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 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
bool refreshCalled = false;
Future<void> refresh() {
refreshCalled = true;
return Future<void>.value();
}
Future<void> holdRefresh() {
refreshCalled = true;
return Completer<void>().future;
}
void main() {
testWidgets('RefreshIndicator', (WidgetTester tester) async {
refreshCalled = false;
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
),
),
);
await tester.fling(find.text('A'), const Offset(0.0, 300.0), 1000.0);
await tester.pump();
expect(tester.getSemantics(find.byType(RefreshProgressIndicator)), matchesSemantics(
label: 'Refresh',
));
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation
expect(refreshCalled, true);
handle.dispose();
});
testWidgets('Refresh Indicator - nested', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
notificationPredicate: (ScrollNotification notification) => notification.depth == 1,
onRefresh: refresh,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(
width: 600.0,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
),
),
),
),
);
await tester.fling(find.text('A'), const Offset(300.0, 0.0), 1000.0); // horizontal fling
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation
expect(refreshCalled, false);
await tester.fling(find.text('A'), const Offset(0.0, 300.0), 1000.0); // vertical fling
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation
expect(refreshCalled, true);
});
testWidgets('RefreshIndicator - reverse', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
reverse: true,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
],
),
),
),
);
await tester.fling(find.text('X'), const Offset(0.0, 600.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation
expect(refreshCalled, true);
});
testWidgets('RefreshIndicator - top - position', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: holdRefresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
],
),
),
),
);
await tester.fling(find.text('X'), const Offset(0.0, 300.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(tester.getCenter(find.byType(RefreshProgressIndicator)).dy, lessThan(300.0));
});
testWidgets('RefreshIndicator - reverse - position', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: holdRefresh,
child: ListView(
reverse: true,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
],
),
),
),
);
await tester.fling(find.text('X'), const Offset(0.0, 600.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(tester.getCenter(find.byType(RefreshProgressIndicator)).dy, lessThan(300.0));
});
testWidgets('RefreshIndicator - no movement', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
],
),
),
),
);
// this fling is horizontal, not up or down
await tester.fling(find.text('X'), const Offset(1.0, 0.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, false);
});
testWidgets('RefreshIndicator - not enough', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
],
),
),
),
);
await tester.fling(find.text('X'), const Offset(0.0, 50.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, false);
});
testWidgets('RefreshIndicator - just enough', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
],
),
),
),
);
await tester.fling(find.text('X'), const Offset(0.0, 200.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, true);
});
testWidgets('RefreshIndicator - drag back not far enough to cancel', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
SizedBox(height: 1000),
],
),
),
),
);
final Offset startLocation = tester.getCenter(find.text('X'), warnIfMissed: true, callee: 'drag');
final TestPointer testPointer = TestPointer();
await tester.sendEventToBinding(testPointer.down(startLocation));
await tester.sendEventToBinding(testPointer.move(startLocation + const Offset(0.0, 175)));
await tester.pump();
await tester.sendEventToBinding(testPointer.move(startLocation + const Offset(0.0, 150)));
await tester.pump();
await tester.sendEventToBinding(testPointer.up());
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, true);
});
testWidgets('RefreshIndicator - drag back far enough to cancel', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
SizedBox(height: 1000),
],
),
),
),
);
final Offset startLocation = tester.getCenter(find.text('X'), warnIfMissed: true, callee: 'drag');
final TestPointer testPointer = TestPointer();
await tester.sendEventToBinding(testPointer.down(startLocation));
await tester.sendEventToBinding(testPointer.move(startLocation + const Offset(0.0, 175)));
await tester.pump();
await tester.sendEventToBinding(testPointer.move(startLocation + const Offset(0.0, 149)));
await tester.pump();
await tester.sendEventToBinding(testPointer.up());
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, false);
});
testWidgets('RefreshIndicator - show - slow', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: holdRefresh, // this one never returns
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
],
),
),
),
);
bool completed = false;
tester.state<RefreshIndicatorState>(find.byType(RefreshIndicator))
.show()
.then<void>((void value) { completed = true; });
await tester.pump();
expect(completed, false);
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, true);
expect(completed, false);
completed = false;
refreshCalled = false;
tester.state<RefreshIndicatorState>(find.byType(RefreshIndicator))
.show()
.then<void>((void value) { completed = true; });
await tester.pump();
expect(completed, false);
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, false);
});
testWidgets('RefreshIndicator - show - fast', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
],
),
),
),
);
bool completed = false;
tester.state<RefreshIndicatorState>(find.byType(RefreshIndicator))
.show()
.then<void>((void value) { completed = true; });
await tester.pump();
expect(completed, false);
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, true);
expect(completed, true);
completed = false;
refreshCalled = false;
tester.state<RefreshIndicatorState>(find.byType(RefreshIndicator))
.show()
.then<void>((void value) { completed = true; });
await tester.pump();
expect(completed, false);
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, true);
expect(completed, true);
});
testWidgets('RefreshIndicator - show - fast - twice', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
],
),
),
),
);
bool completed1 = false;
tester.state<RefreshIndicatorState>(find.byType(RefreshIndicator))
.show()
.then<void>((void value) { completed1 = true; });
bool completed2 = false;
tester.state<RefreshIndicatorState>(find.byType(RefreshIndicator))
.show()
.then<void>((void value) { completed2 = true; });
await tester.pump();
expect(completed1, false);
expect(completed2, false);
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(refreshCalled, true);
expect(completed1, true);
expect(completed2, true);
});
testWidgets('Refresh starts while scroll view moves back to 0.0 after overscroll', (WidgetTester tester) async {
refreshCalled = false;
double lastScrollOffset;
final ScrollController controller = ScrollController();
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
controller: controller,
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
),
),
);
if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) {
await tester.fling(find.text('A'), const Offset(0.0, 1500.0), 10000.0);
}
else {
await tester.fling(find.text('A'), const Offset(0.0, 300.0), 1000.0);
}
await tester.pump(const Duration(milliseconds: 100));
expect(lastScrollOffset = controller.offset, lessThan(0.0));
expect(refreshCalled, isFalse);
await tester.pump(const Duration(milliseconds: 400));
expect(controller.offset, greaterThan(lastScrollOffset));
expect(controller.offset, lessThan(0.0));
expect(refreshCalled, isTrue);
controller.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('RefreshIndicator does not force child to relayout', (WidgetTester tester) async {
int layoutCount = 0;
Widget layoutCallback(BuildContext context, BoxConstraints constraints) {
layoutCount++;
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
);
}
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: LayoutBuilder(builder: layoutCallback),
),
),
);
await tester.fling(find.text('A'), const Offset(0.0, 300.0), 1000.0); // trigger refresh
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation
expect(layoutCount, 1);
});
testWidgets('RefreshIndicator responds to strokeWidth', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: () async {},
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
),
),
);
// Check for the default value
expect(
tester.widget<RefreshIndicator>(find.byType(RefreshIndicator)).strokeWidth,
RefreshProgressIndicator.defaultStrokeWidth,
);
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: () async {},
strokeWidth: 4.0,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
),
),
);
expect(
tester.widget<RefreshIndicator>(find.byType(RefreshIndicator)).strokeWidth,
4.0,
);
});
testWidgets('RefreshIndicator responds to edgeOffset', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: () async {},
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
),
),
);
//By default the value of edgeOffset is 0.0
expect(
tester.widget<RefreshIndicator>(find.byType(RefreshIndicator)).edgeOffset,
0.0,
);
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: () async {},
edgeOffset: kToolbarHeight,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
),
),
);
expect(
tester.widget<RefreshIndicator>(find.byType(RefreshIndicator)).edgeOffset,
kToolbarHeight,
);
});
testWidgets('RefreshIndicator appears at edgeOffset', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: RefreshIndicator(
edgeOffset: kToolbarHeight,
displacement: kToolbarHeight,
onRefresh: () async {
await Future<void>.delayed(const Duration(seconds: 1), () { });
},
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
),
));
await tester.fling(find.byType(ListView), const Offset(0.0, 2.0 * kToolbarHeight), 1000.0);
await tester.pump(const Duration(seconds: 2));
expect(
tester.getTopLeft(find.byType(RefreshProgressIndicator)).dy,
greaterThanOrEqualTo(2.0 * kToolbarHeight),
);
});
testWidgets('Top RefreshIndicator(anywhere mode) should be shown when dragging from non-zero scroll position', (WidgetTester tester) async {
refreshCalled = false;
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
triggerMode: RefreshIndicatorTriggerMode.anywhere,
onRefresh: holdRefresh,
child: ListView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
SizedBox(
height: 800.0,
child: Text('Y'),
),
],
),
),
),
);
scrollController.jumpTo(50.0);
await tester.fling(find.text('X'), const Offset(0.0, 300.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
expect(tester.getCenter(find.byType(RefreshProgressIndicator)).dy, lessThan(300.0));
scrollController.dispose();
});
testWidgets('Reverse RefreshIndicator(anywhere mode) should be shown when dragging from non-zero scroll position', (WidgetTester tester) async {
refreshCalled = false;
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
triggerMode: RefreshIndicatorTriggerMode.anywhere,
onRefresh: holdRefresh,
child: ListView(
reverse: true,
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
SizedBox(
height: 800.0,
child: Text('Y'),
),
],
),
),
),
);
scrollController.jumpTo(50.0);
await tester.fling(find.text('X'), const Offset(0.0, 600.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
expect(tester.getCenter(find.byType(RefreshProgressIndicator)).dy, lessThan(300.0));
scrollController.dispose();
});
// Regression test for https://github.com/flutter/flutter/issues/71936
testWidgets('RefreshIndicator(anywhere mode) should not be shown when overscroll occurs due to inertia', (WidgetTester tester) async {
refreshCalled = false;
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
triggerMode: RefreshIndicatorTriggerMode.anywhere,
onRefresh: holdRefresh,
child: ListView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
SizedBox(
height: 2000.0,
child: Text('Y'),
),
],
),
),
),
);
scrollController.jumpTo(100.0);
// Release finger before reach the edge.
await tester.fling(find.text('X'), const Offset(0.0, 99.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
expect(find.byType(RefreshProgressIndicator), findsNothing);
scrollController.dispose();
});
testWidgets('Top RefreshIndicator(onEdge mode) should not be shown when dragging from non-zero scroll position', (WidgetTester tester) async {
refreshCalled = false;
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: holdRefresh,
child: ListView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
SizedBox(
height: 800.0,
child: Text('Y'),
),
],
),
),
),
);
scrollController.jumpTo(50.0);
await tester.fling(find.text('X'), const Offset(0.0, 300.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
expect(find.byType(RefreshProgressIndicator), findsNothing);
scrollController.dispose();
});
testWidgets('Reverse RefreshIndicator(onEdge mode) should be shown when dragging from non-zero scroll position', (WidgetTester tester) async {
refreshCalled = false;
final ScrollController scrollController = ScrollController();
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: holdRefresh,
child: ListView(
reverse: true,
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
SizedBox(
height: 800.0,
child: Text('Y'),
),
],
),
),
),
);
scrollController.jumpTo(50.0);
await tester.fling(find.text('X'), const Offset(0.0, -300.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
expect(find.byType(RefreshProgressIndicator), findsNothing);
scrollController.dispose();
});
testWidgets('ScrollController.jumpTo should not trigger the refresh indicator', (WidgetTester tester) async {
refreshCalled = false;
final ScrollController scrollController = ScrollController(initialScrollOffset: 500.0);
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 800.0,
child: Text('X'),
),
SizedBox(
height: 800.0,
child: Text('Y'),
),
],
),
),
),
);
scrollController.jumpTo(0.0);
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation
expect(refreshCalled, false);
scrollController.dispose();
});
testWidgets('RefreshIndicator.adaptive', (WidgetTester tester) async {
Widget buildFrame(TargetPlatform platform) {
return MaterialApp(
theme: ThemeData(platform: platform),
home: RefreshIndicator.adaptive(
onRefresh: refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
),
);
}
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) {
await tester.pumpWidget(buildFrame(platform));
await tester.pumpAndSettle(); // Finish the theme change animation.
await tester.fling(find.text('A'), const Offset(0.0, 300.0), 1000.0);
await tester.pump();
expect(find.byType(CupertinoActivityIndicator), findsOneWidget);
expect(find.byType(RefreshProgressIndicator), findsNothing);
}
for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows ]) {
await tester.pumpWidget(buildFrame(platform));
await tester.pumpAndSettle(); // Finish the theme change animation.
await tester.fling(find.text('A'), const Offset(0.0, 300.0), 1000.0);
await tester.pump();
expect(tester.getSemantics(find.byType(RefreshProgressIndicator)), matchesSemantics(
label: 'Refresh',
));
expect(find.byType(CupertinoActivityIndicator), findsNothing);
}
});
testWidgets('RefreshIndicator color defaults to ColorScheme.primary', (WidgetTester tester) async {
const Color primaryColor = Color(0xff4caf50);
final ThemeData theme = ThemeData.from(colorScheme: const ColorScheme.light().copyWith(primary: primaryColor));
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: StatefulBuilder(
builder: (BuildContext context, StateSetter stateSetter) {
return RefreshIndicator(
triggerMode: RefreshIndicatorTriggerMode.anywhere,
onRefresh: holdRefresh,
child: ListView(
reverse: true,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
SizedBox(
height: 800.0,
child: Text('Y'),
),
],
),
);
},
),
),
);
await tester.fling(find.text('X'), const Offset(0.0, 600.0), 1000.0);
await tester.pump();
expect(tester.widget<RefreshProgressIndicator>(find.byType(RefreshProgressIndicator)).valueColor!.value, primaryColor);
});
testWidgets('RefreshIndicator.color can be updated at runtime', (WidgetTester tester) async {
refreshCalled = false;
Color refreshIndicatorColor = Colors.green;
const Color red = Colors.red;
late StateSetter setState;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter stateSetter) {
setState = stateSetter;
return RefreshIndicator(
triggerMode: RefreshIndicatorTriggerMode.anywhere,
onRefresh: holdRefresh,
color: refreshIndicatorColor,
child: ListView(
reverse: true,
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[
SizedBox(
height: 200.0,
child: Text('X'),
),
SizedBox(
height: 800.0,
child: Text('Y'),
),
],
),
);
},
),
),
);
await tester.fling(find.text('X'), const Offset(0.0, 600.0), 1000.0);
await tester.pump();
expect(tester.widget<RefreshProgressIndicator>(find.byType(RefreshProgressIndicator)).valueColor!.value, refreshIndicatorColor.withOpacity(1.0));
setState(() {
refreshIndicatorColor = red;
});
await tester.pump();
expect(tester.widget<RefreshProgressIndicator>(find.byType(RefreshProgressIndicator)).valueColor!.value, red.withOpacity(1.0));
});
testWidgets('RefreshIndicator - reverse - BouncingScrollPhysics', (WidgetTester tester) async {
refreshCalled = false;
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
child: ListView(
reverse: true,
physics: const BouncingScrollPhysics(),
children: <Widget>[
for (int i = 0; i < 4; i++)
SizedBox(
height: 200.0,
child: Text('X - $i'),
),
],
)
),
),
);
// Scroll to top
await tester.fling(find.text('X - 0'), const Offset(0.0, 800.0), 1000.0);
await tester.pumpAndSettle();
// Fling down to show refresh indicator
await tester.fling(find.text('X - 3'), const Offset(0.0, 250.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation
expect(refreshCalled, true);
});
testWidgets('RefreshIndicator disallows indicator - glow', (WidgetTester tester) async {
refreshCalled = false;
bool glowAccepted = true;
ScrollNotification? lastNotification;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: RefreshIndicator(
onRefresh: refresh,
child: Builder(
builder: (BuildContext context) {
return NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
if (notification is OverscrollNotification
&& lastNotification is! OverscrollNotification) {
final OverscrollIndicatorNotification confirmationNotification = OverscrollIndicatorNotification(leading: true);
confirmationNotification.dispatch(context);
glowAccepted = confirmationNotification.accepted;
}
lastNotification = notification;
return false;
},
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
);
}
),
),
),
);
expect(find.byType(StretchingOverscrollIndicator), findsNothing);
expect(find.byType(GlowingOverscrollIndicator), findsOneWidget);
await tester.fling(find.text('A'), const Offset(0.0, 300.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation
expect(refreshCalled, true);
expect(glowAccepted, false);
});
testWidgets('RefreshIndicator disallows indicator - stretch', (WidgetTester tester) async {
refreshCalled = false;
bool stretchAccepted = true;
ScrollNotification? lastNotification;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.light().copyWith(useMaterial3: true),
home: RefreshIndicator(
onRefresh: refresh,
child: Builder(
builder: (BuildContext context) {
return NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
if (notification is OverscrollNotification
&& lastNotification is! OverscrollNotification) {
final OverscrollIndicatorNotification confirmationNotification = OverscrollIndicatorNotification(leading: true);
confirmationNotification.dispatch(context);
stretchAccepted = confirmationNotification.accepted;
}
lastNotification = notification;
return false;
},
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: <String>['A', 'B', 'C', 'D', 'E', 'F'].map<Widget>((String item) {
return SizedBox(
height: 200.0,
child: Text(item),
);
}).toList(),
),
);
}
),
),
),
);
expect(find.byType(StretchingOverscrollIndicator), findsOneWidget);
expect(find.byType(GlowingOverscrollIndicator), findsNothing);
await tester.fling(find.text('A'), const Offset(0.0, 300.0), 1000.0);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the scroll animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator settle animation
await tester.pump(const Duration(seconds: 1)); // finish the indicator hide animation
expect(refreshCalled, true);
expect(stretchAccepted, false);
});
testWidgets('RefreshIndicator manipulates value color opacity correctly', (WidgetTester tester) async {
final List<Color> colors = <Color>[
Colors.black,
Colors.black54,
Colors.white,
Colors.white54,
Colors.transparent,
];
const List<double> positions = <double>[50.0, 100.0, 150.0];
Future<void> testColor(Color color) async {
final AnimationController positionController = AnimationController(vsync: const TestVSync());
addTearDown(positionController.dispose);
// Correspond to [_setupColorTween].
final Animation<Color?> valueColorAnimation = positionController.drive(
ColorTween(
begin: color.withAlpha(0),
end: color.withAlpha(color.alpha),
).chain(
CurveTween(
// Correspond to [_kDragSizeFactorLimit].
curve: const Interval(0.0, 1.0 / 1.5),
),
),
);
await tester.pumpWidget(
MaterialApp(
home: RefreshIndicator(
onRefresh: refresh,
color: color,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const <Widget>[Text('X')],
),
),
),
);
RefreshProgressIndicator getIndicator() {
return tester.widget<RefreshProgressIndicator>(
find.byType(RefreshProgressIndicator),
);
}
// Correspond to [_kDragContainerExtentPercentage].
final double maxPosition = tester.view.physicalSize.height / tester.view.devicePixelRatio * 0.25;
for (final double position in positions) {
await tester.fling(find.text('X'), Offset(0.0, position), 1.0);
await tester.pump();
positionController.value = position / maxPosition;
expect(
getIndicator().valueColor!.value!.alpha,
valueColorAnimation.value!.alpha,
);
// Wait until the fling finishes before starting the next fling.
await tester.pumpAndSettle();
}
}
for (final Color color in colors) {
await testColor(color);
}
});
}
| flutter/packages/flutter/test/material/refresh_indicator_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/refresh_indicator_test.dart",
"repo_id": "flutter",
"token_count": 18169
} | 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('SnackBarThemeData copyWith, ==, hashCode basics', () {
expect(const SnackBarThemeData(), const SnackBarThemeData().copyWith());
expect(const SnackBarThemeData().hashCode, const SnackBarThemeData().copyWith().hashCode);
});
test('SnackBarThemeData lerp special cases', () {
expect(SnackBarThemeData.lerp(null, null, 0), const SnackBarThemeData());
const SnackBarThemeData data = SnackBarThemeData();
expect(identical(SnackBarThemeData.lerp(data, data, 0.5), data), true);
});
test('SnackBarThemeData null fields by default', () {
const SnackBarThemeData snackBarTheme = SnackBarThemeData();
expect(snackBarTheme.backgroundColor, null);
expect(snackBarTheme.actionTextColor, null);
expect(snackBarTheme.disabledActionTextColor, null);
expect(snackBarTheme.contentTextStyle, null);
expect(snackBarTheme.elevation, null);
expect(snackBarTheme.shape, null);
expect(snackBarTheme.behavior, null);
expect(snackBarTheme.width, null);
expect(snackBarTheme.insetPadding, null);
expect(snackBarTheme.showCloseIcon, null);
expect(snackBarTheme.closeIconColor, null);
expect(snackBarTheme.actionOverflowThreshold, null);
});
test(
'SnackBarTheme throws assertion if width is provided with fixed behaviour',
() {
expect(
() => SnackBarThemeData(
behavior: SnackBarBehavior.fixed,
width: 300.0,
),
throwsAssertionError);
});
testWidgets('Default SnackBarThemeData debugFillProperties',
(WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const SnackBarThemeData().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('SnackBarThemeData implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const SnackBarThemeData(
backgroundColor: Color(0xFFFFFFFF),
actionTextColor: Color(0xFF0000AA),
disabledActionTextColor: Color(0xFF00AA00),
contentTextStyle: TextStyle(color: Color(0xFF123456)),
elevation: 2.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))),
behavior: SnackBarBehavior.floating,
width: 400.0,
insetPadding: EdgeInsets.all(10.0),
showCloseIcon: false,
closeIconColor: Color(0xFF0000AA),
actionOverflowThreshold: 0.5,
dismissDirection: DismissDirection.down,
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'backgroundColor: Color(0xffffffff)',
'actionTextColor: Color(0xff0000aa)',
'disabledActionTextColor: Color(0xff00aa00)',
'contentTextStyle: TextStyle(inherit: true, color: Color(0xff123456))',
'elevation: 2.0',
'shape: RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(2.0))',
'behavior: SnackBarBehavior.floating',
'width: 400.0',
'insetPadding: EdgeInsets.all(10.0)',
'showCloseIcon: false',
'closeIconColor: Color(0xff0000aa)',
'actionOverflowThreshold: 0.5',
'dismissDirection: DismissDirection.down',
]);
});
testWidgets('Material2 - Passing no SnackBarThemeData returns defaults', (WidgetTester tester) async {
const String text = 'I am a snack bar.';
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text(text),
duration: const Duration(seconds: 2),
action: SnackBarAction(label: 'ACTION', onPressed: () {}),
));
},
child: const Text('X'),
);
},
),
),
));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final Material material = _getSnackBarMaterial(tester);
final RenderParagraph content = _getSnackBarTextRenderObject(tester, text);
expect(content.text.style, Typography.material2018().white.titleMedium);
expect(material.color, const Color(0xFF333333));
expect(material.elevation, 6.0);
expect(material.shape, null);
});
testWidgets('Material3 - Passing no SnackBarThemeData returns defaults', (WidgetTester tester) async {
const String text = 'I am a snack bar.';
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(MaterialApp(
theme: theme,
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text(text),
duration: const Duration(seconds: 2),
action: SnackBarAction(label: 'ACTION', onPressed: () {}),
));
},
child: const Text('X'),
);
},
),
),
));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final Material material = _getSnackBarMaterial(tester);
final RenderParagraph content = _getSnackBarTextRenderObject(tester, text);
expect(content.text.style, Typography.material2021().englishLike.bodyMedium?.merge(Typography.material2021().black.bodyMedium).copyWith(color: theme.colorScheme.onInverseSurface, decorationColor: theme.colorScheme.onSurface));
expect(material.color, theme.colorScheme.inverseSurface);
expect(material.elevation, 6.0);
expect(material.shape, null);
});
testWidgets('SnackBar uses values from SnackBarThemeData', (WidgetTester tester) async {
const String text = 'I am a snack bar.';
const String action = 'ACTION';
final SnackBarThemeData snackBarTheme = _snackBarTheme(showCloseIcon: true);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(snackBarTheme: snackBarTheme),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text(text),
duration: const Duration(seconds: 2),
action: SnackBarAction(label: action, onPressed: () {}),
));
},
child: const Text('X'),
);
},
),
),
));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final Material material = _getSnackBarMaterial(tester);
final RenderParagraph button = _getSnackBarActionTextRenderObject(tester, action);
final RenderParagraph content = _getSnackBarTextRenderObject(tester, text);
final Icon icon = _getSnackBarIcon(tester);
expect(content.text.style, snackBarTheme.contentTextStyle);
expect(material.color, snackBarTheme.backgroundColor);
expect(material.elevation, snackBarTheme.elevation);
expect(material.shape, snackBarTheme.shape);
expect(button.text.style!.color, snackBarTheme.actionTextColor);
expect(icon.icon, Icons.close);
});
testWidgets('SnackBar widget properties take priority over theme', (WidgetTester tester) async {
const Color backgroundColor = Colors.purple;
const Color textColor = Colors.pink;
const double elevation = 7.0;
const String action = 'ACTION';
const ShapeBorder shape = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(9.0)),
);
const double snackBarWidth = 400.0;
await tester.pumpWidget(MaterialApp(
theme: ThemeData(snackBarTheme: _snackBarTheme(showCloseIcon: true)),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
backgroundColor: backgroundColor,
behavior: SnackBarBehavior.floating,
width: snackBarWidth,
elevation: elevation,
shape: shape,
content: const Text('I am a snack bar.'),
duration: const Duration(seconds: 2),
action: SnackBarAction(
textColor: textColor,
label: action,
onPressed: () {},
),
showCloseIcon: false,
));
},
child: const Text('X'),
);
},
),
),
));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final Finder materialFinder = _getSnackBarMaterialFinder(tester);
final Material material = _getSnackBarMaterial(tester);
final RenderParagraph button =
_getSnackBarActionTextRenderObject(tester, action);
expect(material.color, backgroundColor);
expect(material.elevation, elevation);
expect(material.shape, shape);
expect(button.text.style!.color, textColor);
expect(_getSnackBarIconFinder(tester), findsNothing);
// Assert width.
final Offset snackBarBottomLeft = tester.getBottomLeft(materialFinder.first);
final Offset snackBarBottomRight = tester.getBottomRight(materialFinder.first);
expect(snackBarBottomLeft.dx, (800 - snackBarWidth) / 2); // Device width is 800.
expect(snackBarBottomRight.dx, (800 + snackBarWidth) / 2); // Device width is 800.
});
testWidgets('SnackBarAction uses actionBackgroundColor', (WidgetTester tester) async {
final MaterialStateColor actionBackgroundColor = MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return Colors.blue;
}
return Colors.purple;
});
await tester.pumpWidget(MaterialApp(
theme: ThemeData(snackBarTheme: _createSnackBarTheme(actionBackgroundColor: actionBackgroundColor)),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('I am a snack bar.'),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {},
),
));
},
child: const Text('X'),
);
},
),
),
));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final Material materialBeforeDismissed = tester.widget<Material>(find.descendant(
of: find.widgetWithText(TextButton, 'ACTION'),
matching: find.byType(Material),
));
expect(materialBeforeDismissed.color, Colors.purple);
await tester.tap(find.text('ACTION'));
await tester.pump();
final Material materialAfterDismissed = tester.widget<Material>(find.descendant(
of: find.widgetWithText(TextButton, 'ACTION'),
matching: find.byType(Material),
));
expect(materialAfterDismissed.color, Colors.blue);
});
testWidgets('SnackBarAction backgroundColor overrides SnackBarThemeData actionBackgroundColor', (WidgetTester tester) async {
final MaterialStateColor snackBarActionBackgroundColor = MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return Colors.amber;
}
return Colors.cyan;
});
final MaterialStateColor actionBackgroundColor = MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return Colors.blue;
}
return Colors.purple;
});
await tester.pumpWidget(MaterialApp(
theme: ThemeData(snackBarTheme: _createSnackBarTheme(actionBackgroundColor: actionBackgroundColor)),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('I am a snack bar.'),
action: SnackBarAction(
label: 'ACTION',
backgroundColor: snackBarActionBackgroundColor,
onPressed: () {},
),
));
},
child: const Text('X'),
);
},
),
),
));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final Material materialBeforeDismissed = tester.widget<Material>(find.descendant(
of: find.widgetWithText(TextButton, 'ACTION'),
matching: find.byType(Material),
));
expect(materialBeforeDismissed.color, Colors.cyan);
await tester.tap(find.text('ACTION'));
await tester.pump();
final Material materialAfterDismissed = tester.widget<Material>(find.descendant(
of: find.widgetWithText(TextButton, 'ACTION'),
matching: find.byType(Material),
));
expect(materialAfterDismissed.color, Colors.amber);
});
testWidgets('SnackBarThemeData asserts when actionBackgroundColor is a MaterialStateColor and disabledActionBackgroundColor is also provided', (WidgetTester tester) async {
final MaterialStateColor actionBackgroundColor = MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return Colors.blue;
}
return Colors.purple;
});
expect(() => tester.pumpWidget(MaterialApp(
theme: ThemeData(snackBarTheme: _createSnackBarTheme(actionBackgroundColor: actionBackgroundColor, disabledActionBackgroundColor: Colors.amber)),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('I am a snack bar.'),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {},
),
));
},
child: const Text('X'),
);
},
),
),
)), throwsA(isA<AssertionError>().having(
(AssertionError e) => e.toString(),
'description',
contains('disabledBackgroundColor must not be provided when background color is a MaterialStateColor'))
)
);
});
testWidgets('SnackBar theme behavior is correct for floating', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
snackBarTheme: const SnackBarThemeData(behavior: SnackBarBehavior.floating)),
home: Scaffold(
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.send),
onPressed: () {},
),
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('I am a snack bar.'),
duration: const Duration(seconds: 2),
action: SnackBarAction(label: 'ACTION', onPressed: () {}),
));
},
child: const Text('X'),
);
},
),
),
));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final RenderBox snackBarBox = tester.firstRenderObject(find.byType(SnackBar));
final RenderBox floatingActionButtonBox = tester.firstRenderObject(find.byType(FloatingActionButton));
final Offset snackBarBottomCenter = snackBarBox.localToGlobal(snackBarBox.size.bottomCenter(Offset.zero));
final Offset floatingActionButtonTopCenter = floatingActionButtonBox.localToGlobal(floatingActionButtonBox.size.topCenter(Offset.zero));
// Since padding and margin is handled inside snackBarBox,
// the bottom offset of snackbar should equal with top offset of FAB
expect(snackBarBottomCenter.dy == floatingActionButtonTopCenter.dy, true);
});
testWidgets('SnackBar theme behavior is correct for fixed', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
snackBarTheme: const SnackBarThemeData(behavior: SnackBarBehavior.fixed),
),
home: Scaffold(
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.send),
onPressed: () {},
),
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('I am a snack bar.'),
duration: const Duration(seconds: 2),
action: SnackBarAction(label: 'ACTION', onPressed: () {}),
));
},
child: const Text('X'),
);
},
),
),
));
final RenderBox floatingActionButtonOriginBox= tester.firstRenderObject(find.byType(FloatingActionButton));
final Offset floatingActionButtonOriginBottomCenter = floatingActionButtonOriginBox.localToGlobal(floatingActionButtonOriginBox.size.bottomCenter(Offset.zero));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final RenderBox snackBarBox = tester.firstRenderObject(find.byType(SnackBar));
final RenderBox floatingActionButtonBox = tester.firstRenderObject(find.byType(FloatingActionButton));
final Offset snackBarTopCenter = snackBarBox.localToGlobal(snackBarBox.size.topCenter(Offset.zero));
final Offset floatingActionButtonBottomCenter = floatingActionButtonBox.localToGlobal(floatingActionButtonBox.size.bottomCenter(Offset.zero));
expect(floatingActionButtonOriginBottomCenter.dy > floatingActionButtonBottomCenter.dy, true);
expect(snackBarTopCenter.dy > floatingActionButtonBottomCenter.dy, true);
});
Widget buildApp({
required SnackBarBehavior themedBehavior,
EdgeInsetsGeometry? margin,
double? width,
double? themedActionOverflowThreshold,
}) {
return MaterialApp(
theme: ThemeData(
snackBarTheme: SnackBarThemeData(
behavior: themedBehavior,
actionOverflowThreshold: themedActionOverflowThreshold,
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.send),
onPressed: () {},
),
body: Builder(
builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
margin: margin,
width: width,
content: const Text('I am a snack bar.'),
duration: const Duration(seconds: 2),
action: SnackBarAction(label: 'ACTION', onPressed: () {}),
));
},
child: const Text('X'),
);
},
),
),
);
}
testWidgets('SnackBar theme behavior will assert properly for margin use', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/84935
// SnackBarBehavior.floating set in theme does not assert with margin
await tester.pumpWidget(buildApp(
themedBehavior: SnackBarBehavior.floating,
margin: const EdgeInsets.all(8.0),
));
await tester.tap(find.text('X'));
await tester.pump(); // start animation
await tester.pump(const Duration(milliseconds: 750));
AssertionError? exception = tester.takeException() as AssertionError?;
expect(exception, isNull);
// SnackBarBehavior.fixed set in theme will still assert with margin
await tester.pumpWidget(buildApp(
themedBehavior: SnackBarBehavior.fixed,
margin: const EdgeInsets.all(8.0),
));
await tester.tap(find.text('X'));
await tester.pump(); // start animation
await tester.pump(const Duration(milliseconds: 750));
exception = tester.takeException() as AssertionError;
expect(
exception.message,
'Margin can only be used with floating behavior. SnackBarBehavior.fixed '
'was set by the inherited SnackBarThemeData.',
);
});
for (final double overflowThreshold in <double>[-1.0, -.0001, 1.000001, 5]) {
test('SnackBar theme will assert for actionOverflowThreshold outside of 0-1 range', () {
expect(
() => SnackBarThemeData(
actionOverflowThreshold: overflowThreshold,
),
throwsAssertionError);
});
}
testWidgets('SnackBar theme behavior will assert properly for width use', (WidgetTester tester) async {
// SnackBarBehavior.floating set in theme does not assert with width
await tester.pumpWidget(buildApp(
themedBehavior: SnackBarBehavior.floating,
width: 5.0,
));
await tester.tap(find.text('X'));
await tester.pump(); // start animation
await tester.pump(const Duration(milliseconds: 750));
AssertionError? exception = tester.takeException() as AssertionError?;
expect(exception, isNull);
// SnackBarBehavior.fixed set in theme will still assert with width
await tester.pumpWidget(buildApp(
themedBehavior: SnackBarBehavior.fixed,
width: 5.0,
));
await tester.tap(find.text('X'));
await tester.pump(); // start animation
await tester.pump(const Duration(milliseconds: 750));
exception = tester.takeException() as AssertionError;
expect(
exception.message,
'Width can only be used with floating behavior. SnackBarBehavior.fixed '
'was set by the inherited SnackBarThemeData.',
);
});
}
SnackBarThemeData _snackBarTheme({bool? showCloseIcon}) {
return SnackBarThemeData(
backgroundColor: Colors.orange,
actionTextColor: Colors.green,
contentTextStyle: const TextStyle(color: Colors.blue),
elevation: 12.0,
showCloseIcon: showCloseIcon,
shape: const BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12))),
);
}
SnackBarThemeData _createSnackBarTheme({
Color? backgroundColor,
Color? actionTextColor,
Color? disabledActionTextColor,
TextStyle? contentTextStyle,
double? elevation,
ShapeBorder? shape,
SnackBarBehavior? behavior,
Color? actionBackgroundColor,
Color? disabledActionBackgroundColor,
DismissDirection? dismissDirection
}) {
return SnackBarThemeData(
backgroundColor: backgroundColor,
actionTextColor: actionTextColor,
disabledActionTextColor: disabledActionTextColor,
contentTextStyle: contentTextStyle,
elevation: elevation,
shape: shape,
behavior: behavior,
actionBackgroundColor: actionBackgroundColor,
disabledActionBackgroundColor: disabledActionBackgroundColor,
dismissDirection: dismissDirection
);
}
Material _getSnackBarMaterial(WidgetTester tester) {
return tester.widget<Material>(
_getSnackBarMaterialFinder(tester).first,
);
}
Finder _getSnackBarMaterialFinder(WidgetTester tester) {
return find.descendant(
of: find.byType(SnackBar),
matching: find.byType(Material),
);
}
RenderParagraph _getSnackBarActionTextRenderObject(WidgetTester tester, String text) {
return tester.renderObject(find.descendant(
of: find.byType(TextButton),
matching: find.text(text),
));
}
Icon _getSnackBarIcon(WidgetTester tester) {
return tester.widget<Icon>(_getSnackBarIconFinder(tester));
}
Finder _getSnackBarIconFinder(WidgetTester tester) {
return find.descendant(
of: find.byType(SnackBar),
matching: find.byIcon(Icons.close),
);
}
RenderParagraph _getSnackBarTextRenderObject(WidgetTester tester, String text) {
return tester.renderObject(find.descendant(
of: find.byType(SnackBar),
matching: find.text(text),
));
}
| flutter/packages/flutter/test/material/snack_bar_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/snack_bar_theme_test.dart",
"repo_id": "flutter",
"token_count": 10061
} | 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_test/flutter_test.dart';
const String text = 'Hello World! How are you? Life is good!';
const String alternativeText = 'Everything is awesome!!';
void main() {
testWidgets('TextField restoration', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
restorationScopeId: 'app',
home: TestWidget(),
),
);
await restoreAndVerify(tester);
});
testWidgets('TextField restoration with external controller', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
restorationScopeId: 'root',
home: TestWidget(
useExternal: true,
),
),
);
await restoreAndVerify(tester);
});
}
Future<void> restoreAndVerify(WidgetTester tester) async {
expect(find.text(text), findsNothing);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 0);
await tester.enterText(find.byType(TextField), text);
await skipPastScrollingAnimation(tester);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 0);
await tester.drag(find.byType(Scrollable), const Offset(0, -80));
await skipPastScrollingAnimation(tester);
expect(find.text(text), findsOneWidget);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 60);
await tester.restartAndRestore();
expect(find.text(text), findsOneWidget);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 60);
final TestRestorationData data = await tester.getRestorationData();
await tester.enterText(find.byType(TextField), alternativeText);
await skipPastScrollingAnimation(tester);
await tester.drag(find.byType(Scrollable), const Offset(0, 80));
await skipPastScrollingAnimation(tester);
expect(find.text(text), findsNothing);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, isNot(60));
await tester.restoreFrom(data);
expect(find.text(text), findsOneWidget);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 60);
}
class TestWidget extends StatefulWidget {
const TestWidget({super.key, this.useExternal = false});
final bool useExternal;
@override
TestWidgetState createState() => TestWidgetState();
}
class TestWidgetState extends State<TestWidget> with RestorationMixin {
final RestorableTextEditingController controller = RestorableTextEditingController();
@override
String get restorationId => 'widget';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(controller, 'controller');
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Material(
child: Align(
child: SizedBox(
width: 50,
child: TextField(
restorationId: 'text',
maxLines: 3,
controller: widget.useExternal ? controller.value : null,
),
),
),
);
}
}
Future<void> skipPastScrollingAnimation(WidgetTester tester) async {
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
}
| flutter/packages/flutter/test/material/text_field_restoration_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/text_field_restoration_test.dart",
"repo_id": "flutter",
"token_count": 1178
} | 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.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
const double _defaultBorderWidth = 1.0;
Widget boilerplate({
ThemeData? theme,
MaterialTapTargetSize? tapTargetSize,
required Widget child,
}) {
return Theme(
data: theme ?? ThemeData(
materialTapTargetSize: tapTargetSize,
),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Material(child: child),
),
),
);
}
void main() {
testWidgets('Initial toggle state is reflected', (WidgetTester tester) async {
TextStyle buttonTextStyle(String text) {
return tester.widget<DefaultTextStyle>(find.descendant(
of: find.widgetWithText(TextButton, text),
matching: find.byType(DefaultTextStyle),
)).style;
}
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
onPressed: (int index) {},
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
);
expect(
buttonTextStyle('First child').color,
theme.colorScheme.onSurface.withOpacity(0.87),
);
expect(
buttonTextStyle('Second child').color,
theme.colorScheme.primary,
);
});
testWidgets(
'onPressed is triggered on button tap',
(WidgetTester tester) async {
TextStyle buttonTextStyle(String text) {
return tester.widget<DefaultTextStyle>(find.descendant(
of: find.widgetWithText(TextButton, text),
matching: find.byType(DefaultTextStyle),
)).style;
}
final List<bool> isSelected = <bool>[false, true];
final ThemeData theme = ThemeData();
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return boilerplate(
child: ToggleButtons(
onPressed: (int index) {
setState(() {
isSelected[index] = !isSelected[index];
});
},
isSelected: isSelected,
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
);
},
),
);
expect(isSelected[0], isFalse);
expect(isSelected[1], isTrue);
expect(
buttonTextStyle('First child').color,
theme.colorScheme.onSurface.withOpacity(0.87),
);
expect(
buttonTextStyle('Second child').color,
theme.colorScheme.primary,
);
await tester.tap(find.text('Second child'));
await tester.pumpAndSettle();
expect(isSelected[0], isFalse);
expect(isSelected[1], isFalse);
expect(
buttonTextStyle('First child').color,
theme.colorScheme.onSurface.withOpacity(0.87),
);
expect(
buttonTextStyle('Second child').color,
theme.colorScheme.onSurface.withOpacity(0.87),
);
},
);
testWidgets(
'onPressed that is null disables buttons',
(WidgetTester tester) async {
TextStyle buttonTextStyle(String text) {
return tester.widget<DefaultTextStyle>(find.descendant(
of: find.widgetWithText(TextButton, text),
matching: find.byType(DefaultTextStyle),
)).style;
}
final List<bool> isSelected = <bool>[false, true];
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: isSelected,
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
);
expect(isSelected[0], isFalse);
expect(isSelected[1], isTrue);
expect(
buttonTextStyle('First child').color,
theme.colorScheme.onSurface.withOpacity(0.38),
);
expect(
buttonTextStyle('Second child').color,
theme.colorScheme.onSurface.withOpacity(0.38),
);
await tester.tap(find.text('Second child'));
await tester.pumpAndSettle();
// Nothing should change
expect(isSelected[0], isFalse);
expect(isSelected[1], isTrue);
expect(
buttonTextStyle('First child').color,
theme.colorScheme.onSurface.withOpacity(0.38),
);
expect(
buttonTextStyle('Second child').color,
theme.colorScheme.onSurface.withOpacity(0.38),
);
},
);
testWidgets(
'children and isSelected properties have to be the same length',
(WidgetTester tester) async {
await expectLater(
() => tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false],
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
),
throwsA(isAssertionError.having(
(AssertionError error) => error.toString(),
'.toString()',
allOf(
contains('children.length'),
contains('isSelected.length'),
),
)),
);
},
);
testWidgets('Default text style is applied', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false, true],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
);
TextStyle textStyle;
textStyle = tester.widget<DefaultTextStyle>(find.descendant(
of: find.widgetWithText(TextButton, 'First child'),
matching: find.byType(DefaultTextStyle),
)).style;
expect(textStyle.fontFamily, theme.textTheme.bodyMedium!.fontFamily);
expect(textStyle.decoration, theme.textTheme.bodyMedium!.decoration);
textStyle = tester.widget<DefaultTextStyle>(find.descendant(
of: find.widgetWithText(TextButton, 'Second child'),
matching: find.byType(DefaultTextStyle),
)).style;
expect(textStyle.fontFamily, theme.textTheme.bodyMedium!.fontFamily);
expect(textStyle.decoration, theme.textTheme.bodyMedium!.decoration);
});
testWidgets('Custom text style except color is applied', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false, true],
onPressed: (int index) {},
textStyle: const TextStyle(
textBaseline: TextBaseline.ideographic,
fontSize: 20.0,
color: Colors.orange,
),
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
);
TextStyle textStyle;
textStyle = tester.widget<DefaultTextStyle>(find.descendant(
of: find.widgetWithText(TextButton, 'First child'),
matching: find.byType(DefaultTextStyle),
)).style;
expect(textStyle.textBaseline, TextBaseline.ideographic);
expect(textStyle.fontSize, 20.0);
expect(textStyle.color, isNot(Colors.orange));
textStyle = tester.widget<DefaultTextStyle>(find.descendant(
of: find.widgetWithText(TextButton, 'Second child'),
matching: find.byType(DefaultTextStyle),
)).style;
expect(textStyle.textBaseline, TextBaseline.ideographic);
expect(textStyle.fontSize, 20.0);
expect(textStyle.color, isNot(Colors.orange));
});
testWidgets('Default BoxConstraints', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false, false, false],
onPressed: (int index) {},
children: const <Widget>[
Icon(Icons.check),
Icon(Icons.access_alarm),
Icon(Icons.cake),
],
),
),
);
final Rect firstRect = tester.getRect(find.byType(TextButton).at(0));
expect(firstRect.width, 48.0);
expect(firstRect.height, 48.0);
final Rect secondRect = tester.getRect(find.byType(TextButton).at(1));
expect(secondRect.width, 48.0);
expect(secondRect.height, 48.0);
final Rect thirdRect = tester.getRect(find.byType(TextButton).at(2));
expect(thirdRect.width, 48.0);
expect(thirdRect.height, 48.0);
});
testWidgets('Custom BoxConstraints', (WidgetTester tester) async {
// Test for minimum constraints
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
constraints: const BoxConstraints(
minWidth: 50.0,
minHeight: 60.0,
),
isSelected: const <bool>[false, false, false],
onPressed: (int index) {},
children: const <Widget>[
Icon(Icons.check),
Icon(Icons.access_alarm),
Icon(Icons.cake),
],
),
),
);
Rect firstRect = tester.getRect(find.byType(TextButton).at(0));
expect(firstRect.width, 50.0);
expect(firstRect.height, 60.0);
Rect secondRect = tester.getRect(find.byType(TextButton).at(1));
expect(secondRect.width, 50.0);
expect(secondRect.height, 60.0);
Rect thirdRect = tester.getRect(find.byType(TextButton).at(2));
expect(thirdRect.width, 50.0);
expect(thirdRect.height, 60.0);
// Test for maximum constraints
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
constraints: const BoxConstraints(
maxWidth: 20.0,
maxHeight: 10.0,
),
isSelected: const <bool>[false, false, false],
onPressed: (int index) {},
children: const <Widget>[
Icon(Icons.check),
Icon(Icons.access_alarm),
Icon(Icons.cake),
],
),
),
);
firstRect = tester.getRect(find.byType(TextButton).at(0));
expect(firstRect.width, 20.0);
expect(firstRect.height, 10.0);
secondRect = tester.getRect(find.byType(TextButton).at(1));
expect(secondRect.width, 20.0);
expect(secondRect.height, 10.0);
thirdRect = tester.getRect(find.byType(TextButton).at(2));
expect(thirdRect.width, 20.0);
expect(thirdRect.height, 10.0);
});
testWidgets(
'Default text/icon colors for enabled, selected and disabled states',
(WidgetTester tester) async {
TextStyle buttonTextStyle(String text) {
return tester.widget<DefaultTextStyle>(find.descendant(
of: find.widgetWithText(TextButton, text),
matching: find.byType(DefaultTextStyle),
)).style;
}
IconTheme iconTheme(IconData icon) {
return tester.widget(find.descendant(
of: find.widgetWithIcon(TextButton, icon),
matching: find.byType(IconTheme),
));
}
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false],
onPressed: (int index) {},
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
Icon(Icons.check),
]),
],
),
),
);
// Default enabled color
expect(
buttonTextStyle('First child').color,
theme.colorScheme.onSurface.withOpacity(0.87),
);
expect(
iconTheme(Icons.check).data.color,
theme.colorScheme.onSurface.withOpacity(0.87),
);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
Icon(Icons.check),
]),
],
),
),
);
await tester.pumpAndSettle();
// Default selected color
expect(
buttonTextStyle('First child').color,
theme.colorScheme.primary,
);
expect(
iconTheme(Icons.check).data.color,
theme.colorScheme.primary,
);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[true],
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
Icon(Icons.check),
]),
],
),
),
);
await tester.pumpAndSettle();
// Default disabled color
expect(
buttonTextStyle('First child').color,
theme.colorScheme.onSurface.withOpacity(0.38),
);
expect(
iconTheme(Icons.check).data.color,
theme.colorScheme.onSurface.withOpacity(0.38),
);
},
);
testWidgets(
'Custom text/icon colors for enabled, selected and disabled states',
(WidgetTester tester) async {
TextStyle buttonTextStyle(String text) {
return tester.widget<DefaultTextStyle>(find.descendant(
of: find.widgetWithText(TextButton, text),
matching: find.byType(DefaultTextStyle),
)).style;
}
IconTheme iconTheme(IconData icon) {
return tester.widget(find.descendant(
of: find.widgetWithIcon(TextButton, icon),
matching: find.byType(IconTheme),
));
}
final ThemeData theme = ThemeData();
const Color enabledColor = Colors.lime;
const Color selectedColor = Colors.green;
const Color disabledColor = Colors.yellow;
// Tests are ineffective if the custom colors are the same as the theme's
expect(theme.colorScheme.onSurface, isNot(enabledColor));
expect(theme.colorScheme.primary, isNot(selectedColor));
expect(theme.colorScheme.onSurface.withOpacity(0.38), isNot(disabledColor));
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
color: enabledColor,
isSelected: const <bool>[false],
onPressed: (int index) {},
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
Icon(Icons.check),
]),
],
),
),
);
// Custom enabled color
expect(buttonTextStyle('First child').color, enabledColor);
expect(iconTheme(Icons.check).data.color, enabledColor);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
selectedColor: selectedColor,
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
Icon(Icons.check),
]),
],
),
),
);
await tester.pumpAndSettle();
// Custom selected color
expect(buttonTextStyle('First child').color, selectedColor);
expect(iconTheme(Icons.check).data.color, selectedColor);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
disabledColor: disabledColor,
isSelected: const <bool>[true],
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
Icon(Icons.check),
]),
],
),
),
);
await tester.pumpAndSettle();
// Custom disabled color
expect(buttonTextStyle('First child').color, disabledColor);
expect(iconTheme(Icons.check).data.color, disabledColor);
},
);
testWidgets('Default button fillColor - unselected', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false],
onPressed: (int index) {},
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
]),
],
),
),
);
final Material material = tester.widget<Material>(find.descendant(
of: find.byType(TextButton),
matching: find.byType(Material),
));
expect(
material.color,
theme.colorScheme.surface.withOpacity(0.0),
);
expect(material.type, MaterialType.button);
});
testWidgets('Default button fillColor - selected', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
]),
],
),
),
);
final Material material = tester.widget<Material>(find.descendant(
of: find.byType(TextButton),
matching: find.byType(Material),
));
expect(
material.color,
theme.colorScheme.primary.withOpacity(0.12),
);
expect(material.type, MaterialType.button);
});
testWidgets('Default button fillColor - disabled', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[true],
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
]),
],
),
),
);
final Material material = tester.widget<Material>(find.descendant(
of: find.byType(TextButton),
matching: find.byType(Material),
));
expect(
material.color,
theme.colorScheme.surface.withOpacity(0.0),
);
expect(material.type, MaterialType.button);
});
testWidgets('Custom button fillColor', (WidgetTester tester) async {
const Color customFillColor = Colors.green;
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
fillColor: customFillColor,
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Row(children: <Widget>[
Text('First child'),
]),
],
),
),
);
final Material material = tester.widget<Material>(find.descendant(
of: find.byType(TextButton),
matching: find.byType(Material),
));
expect(material.color, customFillColor);
expect(material.type, MaterialType.button);
});
testWidgets('Custom button fillColor - Non MaterialState', (WidgetTester tester) async {
Material buttonColor(String text) {
return tester.widget<Material>(
find.descendant(
of: find.byType(TextButton),
matching: find.widgetWithText(Material, text),
),
);
}
final ThemeData theme = ThemeData();
const Color selectedFillColor = Colors.yellow;
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
fillColor: selectedFillColor,
isSelected: const <bool>[false, true],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
);
await tester.pumpAndSettle();
expect(buttonColor('First child').color, theme.colorScheme.surface.withOpacity(0.0));
expect(buttonColor('Second child').color, selectedFillColor);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
fillColor: selectedFillColor,
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
);
await tester.pumpAndSettle();
expect(buttonColor('First child').color, theme.colorScheme.surface.withOpacity(0.0));
expect(buttonColor('Second child').color, theme.colorScheme.surface.withOpacity(0.0));
});
testWidgets('Custom button fillColor - MaterialState', (WidgetTester tester) async {
Material buttonColor(String text) {
return tester.widget<Material>(
find.descendant(
of: find.byType(TextButton),
matching: find.widgetWithText(Material, text),
),
);
}
const Color selectedFillColor = Colors.orange;
const Color defaultFillColor = Colors.blue;
Color getFillColor(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return selectedFillColor;
}
return defaultFillColor;
}
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
fillColor: MaterialStateColor.resolveWith(getFillColor),
isSelected: const <bool>[false, true],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
);
await tester.pumpAndSettle();
expect(buttonColor('First child').color, defaultFillColor);
expect(buttonColor('Second child').color, selectedFillColor);
// disabled
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
fillColor: MaterialStateColor.resolveWith(getFillColor),
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
);
await tester.pumpAndSettle();
expect(buttonColor('First child').color, defaultFillColor);
expect(buttonColor('Second child').color, defaultFillColor);
});
testWidgets('Default InkWell colors - unselected', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
final FocusNode focusNode = FocusNode();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false],
onPressed: (int index) {},
focusNodes: <FocusNode>[focusNode],
children: const <Widget>[
Text('First child'),
],
),
),
);
final Offset center = tester.getCenter(find.text('First child'));
// hoverColor
final TestGesture hoverGesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await hoverGesture.addPointer();
await hoverGesture.moveTo(center);
await tester.pumpAndSettle();
await hoverGesture.moveTo(Offset.zero);
RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(
inkFeatures,
paints..rect(color: theme.colorScheme.onSurface.withOpacity(0.04)),
);
// splashColor
final TestGesture touchGesture = await tester.createGesture();
await touchGesture.down(center); // The button is on hovered and pressed
await tester.pumpAndSettle();
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(
inkFeatures,
paints
..circle(color: theme.colorScheme.onSurface.withOpacity(0.16)),
);
await touchGesture.up();
await tester.pumpAndSettle();
await hoverGesture.moveTo(const Offset(0, 50));
await tester.pumpAndSettle();
// focusColor
focusNode.requestFocus();
await tester.pumpAndSettle();
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: theme.colorScheme.onSurface.withOpacity(0.12)));
await hoverGesture.removePointer();
focusNode.dispose();
});
testWidgets('Default InkWell colors - selected', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
final FocusNode focusNode = FocusNode();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[true],
onPressed: (int index) {},
focusNodes: <FocusNode>[focusNode],
children: const <Widget>[
Text('First child'),
],
),
),
);
final Offset center = tester.getCenter(find.text('First child'));
// hoverColor
final TestGesture hoverGesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await hoverGesture.addPointer();
await hoverGesture.moveTo(center);
await tester.pumpAndSettle();
RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(
inkFeatures,
paints..rect(color: theme.colorScheme.primary.withOpacity(0.04)),
);
await hoverGesture.moveTo(Offset.zero);
// splashColor
final TestGesture touchGesture = await tester.createGesture();
await touchGesture.down(center); // The button is on hovered and pressed
await tester.pumpAndSettle();
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(
inkFeatures,
paints
..circle(color: theme.colorScheme.primary.withOpacity(0.16)),
);
await touchGesture.up();
await tester.pumpAndSettle();
await hoverGesture.moveTo(const Offset(0, 50));
await tester.pumpAndSettle();
// focusColor
focusNode.requestFocus();
await tester.pumpAndSettle();
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: theme.colorScheme.primary.withOpacity(0.12)));
await hoverGesture.removePointer();
focusNode.dispose();
});
testWidgets('Custom InkWell colors', (WidgetTester tester) async {
const Color splashColor = Color(0xff4caf50);
const Color highlightColor = Color(0xffcddc39);
const Color hoverColor = Color(0xffffeb3b);
const Color focusColor = Color(0xffffff00);
final FocusNode focusNode = FocusNode();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
splashColor: splashColor,
highlightColor: highlightColor,
hoverColor: hoverColor,
focusColor: focusColor,
isSelected: const <bool>[true],
onPressed: (int index) {},
focusNodes: <FocusNode>[focusNode],
children: const <Widget>[
Text('First child'),
],
),
),
);
final Offset center = tester.getCenter(find.text('First child'));
// splashColor
final TestGesture touchGesture = await tester.createGesture();
await touchGesture.down(center);
await tester.pumpAndSettle();
RenderObject inkFeatures;
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(
inkFeatures,
paints
..circle(color: splashColor),
);
await touchGesture.up();
await tester.pumpAndSettle();
// hoverColor
final TestGesture hoverGesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await hoverGesture.addPointer();
await hoverGesture.moveTo(center);
await tester.pumpAndSettle();
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: hoverColor));
await hoverGesture.moveTo(Offset.zero);
// focusColor
focusNode.requestFocus();
await tester.pumpAndSettle();
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_RenderInkFeatures';
});
expect(inkFeatures, paints..rect(color: focusColor));
await hoverGesture.removePointer();
focusNode.dispose();
});
testWidgets(
'Default border width and border colors for enabled, selected and disabled states',
(WidgetTester tester) async {
final ThemeData theme = ThemeData();
const double defaultBorderWidth = 1.0;
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
],
),
),
);
RenderObject toggleButtonRenderObject;
toggleButtonRenderObject = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
});
expect(
toggleButtonRenderObject,
paints
// physical model
..path()
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: defaultBorderWidth,
),
);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
],
),
),
);
toggleButtonRenderObject = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
});
expect(
toggleButtonRenderObject,
paints
// physical model
..path()
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: defaultBorderWidth,
),
);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false],
children: const <Widget>[
Text('First child'),
],
),
),
);
toggleButtonRenderObject = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
});
expect(
toggleButtonRenderObject,
paints
// physical model
..path()
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: defaultBorderWidth,
),
);
},
);
testWidgets(
'Custom border width and border colors for enabled, selected and disabled states',
(WidgetTester tester) async {
const Color borderColor = Color(0xff4caf50);
const Color selectedBorderColor = Color(0xffcddc39);
const Color disabledBorderColor = Color(0xffffeb3b);
const double customWidth = 2.0;
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
borderColor: borderColor,
borderWidth: customWidth,
isSelected: const <bool>[false],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
],
),
),
);
RenderObject toggleButtonRenderObject;
toggleButtonRenderObject = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
});
expect(
toggleButtonRenderObject,
paints
// physical model
..path()
..path(
style: PaintingStyle.stroke,
color: borderColor,
strokeWidth: customWidth,
),
);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
selectedBorderColor: selectedBorderColor,
borderWidth: customWidth,
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
],
),
),
);
toggleButtonRenderObject = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
});
expect(
toggleButtonRenderObject,
paints
// physical model
..path()
..path(
style: PaintingStyle.stroke,
color: selectedBorderColor,
strokeWidth: customWidth,
),
);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
disabledBorderColor: disabledBorderColor,
borderWidth: customWidth,
isSelected: const <bool>[false],
children: const <Widget>[
Text('First child'),
],
),
),
);
toggleButtonRenderObject = tester.allRenderObjects.firstWhere((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
});
expect(
toggleButtonRenderObject,
paints
// physical model
..path()
..path(
style: PaintingStyle.stroke,
color: disabledBorderColor,
strokeWidth: customWidth,
),
);
},
);
testWidgets('Height of segmented control is determined by tallest widget', (WidgetTester tester) async {
final List<Widget> children = <Widget>[
Container(
constraints: const BoxConstraints.tightFor(height: 100.0),
),
Container(
constraints: const BoxConstraints.tightFor(height: 400.0), // tallest widget
),
Container(
constraints: const BoxConstraints.tightFor(height: 200.0),
),
];
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false, true, false],
children: children,
),
),
);
final List<Widget> toggleButtons = tester.allWidgets.where((Widget widget) {
return widget.runtimeType.toString() == '_SelectToggleButton';
}).toList();
for (int i = 0; i < toggleButtons.length; i++) {
final Rect rect = tester.getRect(find.byWidget(toggleButtons[i]));
expect(rect.height, 400.0 + 2 * _defaultBorderWidth);
}
});
testWidgets('Sizes of toggle buttons rebuilds with the correct dimensions', (WidgetTester tester) async {
final List<Widget> children = <Widget>[
Container(
constraints: const BoxConstraints.tightFor(
width: 100.0,
height: 100.0,
),
),
Container(
constraints: const BoxConstraints.tightFor(
width: 100.0,
height: 100.0,
),
),
Container(
constraints: const BoxConstraints.tightFor(
width: 100.0,
height: 100.0,
),
),
];
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false, true, false],
children: children,
),
),
);
List<Widget> toggleButtons;
toggleButtons = tester.allWidgets.where((Widget widget) {
return widget.runtimeType.toString() == '_SelectToggleButton';
}).toList();
for (int i = 0; i < toggleButtons.length; i++) {
final Rect rect = tester.getRect(find.byWidget(toggleButtons[i]));
expect(rect.height, 100.0 + 2 * _defaultBorderWidth);
// Only the last button paints both leading and trailing borders.
// Other buttons only paint the leading border.
if (i == toggleButtons.length - 1) {
expect(rect.width, 100.0 + 2 * _defaultBorderWidth);
} else {
expect(rect.width, 100.0 + 1 * _defaultBorderWidth);
}
}
final List<Widget> childrenRebuilt = <Widget>[
Container(
constraints: const BoxConstraints.tightFor(
width: 200.0,
height: 200.0,
),
),
Container(
constraints: const BoxConstraints.tightFor(
width: 200.0,
height: 200.0,
),
),
Container(
constraints: const BoxConstraints.tightFor(
width: 200.0,
height: 200.0,
),
),
];
// Update border width and widget sized to verify layout updates correctly
const double customBorderWidth = 5.0;
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
borderWidth: customBorderWidth,
isSelected: const <bool>[false, true, false],
children: childrenRebuilt,
),
),
);
toggleButtons = tester.allWidgets.where((Widget widget) {
return widget.runtimeType.toString() == '_SelectToggleButton';
}).toList();
// Only the last button paints both leading and trailing borders.
// Other buttons only paint the leading border.
for (int i = 0; i < toggleButtons.length; i++) {
final Rect rect = tester.getRect(find.byWidget(toggleButtons[i]));
expect(rect.height, 200.0 + 2 * customBorderWidth);
if (i == toggleButtons.length - 1) {
expect(rect.width, 200.0 + 2 * customBorderWidth);
} else {
expect(rect.width, 200.0 + 1 * customBorderWidth);
}
}
});
testWidgets('Material2 - ToggleButtons text baseline alignment', (WidgetTester tester) async {
// The font size must be a multiple of 4 until
// https://github.com/flutter/flutter/issues/122066 is resolved.
await tester.pumpWidget(
boilerplate(
theme: ThemeData(useMaterial3: false),
child: Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: <Widget>[
ToggleButtons(
borderWidth: 5.0,
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 8.0)),
Text('Second child', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 8.0)),
],
),
ElevatedButton(
onPressed: null,
style: ElevatedButton.styleFrom(textStyle: const TextStyle(
fontFamily: 'FlutterTest',
fontSize: 20.0,
)),
child: const Text('Elevated Button'),
),
const Text('Text', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 28.0)),
],
),
),
);
// The test font extends 0.25 * fontSize below the baseline.
// So the three row elements line up like this:
//
// ToggleButton MaterialButton Text
// ------------------------------------ baseline
// 2.0 5.0 7.0 space below the baseline = 0.25 * fontSize
// ------------------------------------ widget text dy values
final double firstToggleButtonDy = tester.getBottomLeft(find.text('First child')).dy;
final double secondToggleButtonDy = tester.getBottomLeft(find.text('Second child')).dy;
final double elevatedButtonDy = tester.getBottomLeft(find.text('Elevated Button')).dy;
final double textDy = tester.getBottomLeft(find.text('Text')).dy;
expect(firstToggleButtonDy, secondToggleButtonDy);
expect(firstToggleButtonDy, elevatedButtonDy - 3.0);
expect(firstToggleButtonDy, textDy - 5.0);
});
testWidgets('Material3 - ToggleButtons text baseline alignment', (WidgetTester tester) async {
// The point size of the fonts must be a multiple of 4 until
// https://github.com/flutter/flutter/issues/122066 is resolved.
await tester.pumpWidget(
boilerplate(
child: Row(
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: <Widget>[
ToggleButtons(
borderWidth: 5.0,
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 8.0)),
Text('Second child', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 8.0)),
],
),
ElevatedButton(
onPressed: null,
style: ElevatedButton.styleFrom(textStyle: const TextStyle(
fontFamily: 'FlutterTest',
fontSize: 20.0,
)),
child: const Text('Elevated Button'),
),
const Text('Text', style: TextStyle(fontFamily: 'FlutterTest', fontSize: 28.0)),
],
),
),
);
// The test font extends 0.25 * fontSize below the baseline.
// So the three row elements line up like this:
//
// ToggleButton MaterialButton Text
// ------------------------------------ baseline
// 2.0 5.0 7.0 space below the baseline = 0.25 * fontSize
// ------------------------------------ widget text dy values
final double firstToggleButtonDy = tester.getBottomLeft(find.text('First child')).dy;
final double secondToggleButtonDy = tester.getBottomLeft(find.text('Second child')).dy;
final double elevatedButtonDy = tester.getBottomLeft(find.text('Elevated Button')).dy;
final double textDy = tester.getBottomLeft(find.text('Text')).dy;
expect(firstToggleButtonDy, secondToggleButtonDy);
expect(firstToggleButtonDy, closeTo(elevatedButtonDy - 1.7, 0.1));
expect(firstToggleButtonDy, closeTo(textDy - 9.7, 0.1));
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('Directionality test', (WidgetTester tester) async {
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ToggleButtons(
onPressed: (int index) {},
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
),
),
);
expect(
tester.getTopRight(find.text('First child')).dx < tester.getTopRight(find.text('Second child')).dx,
isTrue,
);
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: ToggleButtons(
onPressed: (int index) {},
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
),
),
);
expect(
tester.getTopRight(find.text('First child')).dx > tester.getTopRight(find.text('Second child')).dx,
isTrue,
);
});
testWidgets(
'Properly draws borders based on state',
(WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false, true, false],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
Text('Second child'),
Text('Third child'),
],
),
),
);
final List<RenderObject> toggleButtonRenderObject = tester.allRenderObjects.where((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
}).toSet().toList();
// The first button paints the leading, top and bottom sides with a path
expect(
toggleButtonRenderObject[0],
paints
// physical model
..path()
// leading side, top and bottom - enabled
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
),
);
// The middle buttons paint a leading side path first, followed by a
// top and bottom side path
expect(
toggleButtonRenderObject[1],
paints
// physical model
..path()
// leading side - selected
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
)
// top and bottom - selected
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
),
);
// The last button paints a leading side path first, followed by
// a trailing, top and bottom side path
expect(
toggleButtonRenderObject[2],
paints
// physical model
..path()
// leading side - selected, since previous button is selected
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
)
// trailing side, top and bottom - enabled
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
),
);
},
);
testWidgets(
'Properly draws borders based on state when direction is vertical and verticalDirection is down.',
(WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
direction: Axis.vertical,
isSelected: const <bool>[false, true, false],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
Text('Second child'),
Text('Third child'),
],
),
),
);
// The children should be laid out along vertical and the first child at top.
// The item height is icon height + default border width (48.0 + 1.0) pixels.
expect(tester.getCenter(find.text('First child')), const Offset(400.0, 251.0));
expect(tester.getCenter(find.text('Second child')), const Offset(400.0, 300.0));
expect(tester.getCenter(find.text('Third child')), const Offset(400.0, 349.0));
final List<RenderObject> toggleButtonRenderObject = tester.allRenderObjects.where((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
}).toSet().toList();
// The first button paints the left, top and right sides with a path.
expect(
toggleButtonRenderObject[0],
paints
// physical model
..path()
// left side, top and right - enabled.
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
),
);
// The middle buttons paint a top side path first, followed by a
// left and right side path.
expect(
toggleButtonRenderObject[1],
paints
// physical model
..path()
// top side - selected.
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
)
// left and right - selected.
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
),
);
// The last button paints a top side path first, followed by
// a left, bottom and right side path
expect(
toggleButtonRenderObject[2],
paints
// physical model
..path()
// top side - selected, since previous button is selected.
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
)
// left side, bottom and right - enabled.
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
),
);
},
);
testWidgets(
'VerticalDirection test when direction is vertical.',
(WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
direction: Axis.vertical,
verticalDirection: VerticalDirection.up,
isSelected: const <bool>[false, true, false],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
Text('Second child'),
Text('Third child'),
],
),
),
);
// The children should be laid out along vertical and the last child at top.
expect(tester.getCenter(find.text('Third child')), const Offset(400.0, 251.0));
expect(tester.getCenter(find.text('Second child')), const Offset(400.0, 300.0));
expect(tester.getCenter(find.text('First child')), const Offset(400.0, 349.0));
},
);
testWidgets('Material2 - Tap target size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async {
Widget buildFrame(MaterialTapTargetSize tapTargetSize, Key key) {
return boilerplate(
theme: ThemeData(useMaterial3: false),
tapTargetSize: tapTargetSize,
child: ToggleButtons(
key: key,
constraints: const BoxConstraints(minWidth: 32.0, minHeight: 32.0),
isSelected: const <bool>[false, true, false],
onPressed: (int index) {},
children: const <Widget>[
Text('First'),
Text('Second'),
Text('Third'),
],
),
);
}
final Key key1 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.padded, key1));
expect(tester.getSize(find.byKey(key1)), const Size(228.0, 48.0));
final Key key2 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.shrinkWrap, key2));
expect(tester.getSize(find.byKey(key2)), const Size(228.0, 48.0));
});
testWidgets('Material3 - Tap target size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async {
Widget buildFrame(MaterialTapTargetSize tapTargetSize, Key key) {
return boilerplate(
tapTargetSize: tapTargetSize,
child: ToggleButtons(
key: key,
constraints: const BoxConstraints(minWidth: 32.0, minHeight: 32.0),
isSelected: const <bool>[false, true, false],
onPressed: (int index) {},
children: const <Widget>[
Text('First'),
Text('Second'),
Text('Third'),
],
),
);
}
final Key key1 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.padded, key1));
expect(tester.getSize(find.byKey(key1)), const Size(232.0, 48.0));
final Key key2 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.shrinkWrap, key2));
expect(tester.getSize(find.byKey(key2)), const Size(232.0, 34.0));
});
testWidgets('Material2 - Tap target size is configurable', (WidgetTester tester) async {
Widget buildFrame(MaterialTapTargetSize tapTargetSize, Key key) {
return boilerplate(
theme: ThemeData(useMaterial3: false),
child: ToggleButtons(
key: key,
tapTargetSize: tapTargetSize,
constraints: const BoxConstraints(minWidth: 32.0, minHeight: 32.0),
isSelected: const <bool>[false, true, false],
onPressed: (int index) {},
children: const <Widget>[
Text('First'),
Text('Second'),
Text('Third'),
],
),
);
}
final Key key1 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.padded, key1));
expect(tester.getSize(find.byKey(key1)), const Size(228.0, 48.0));
final Key key2 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.shrinkWrap, key2));
expect(tester.getSize(find.byKey(key2)), const Size(228.0, 34.0));
});
testWidgets('Material3 - Tap target size is configurable', (WidgetTester tester) async {
Widget buildFrame(MaterialTapTargetSize tapTargetSize, Key key) {
return boilerplate(
child: ToggleButtons(
key: key,
tapTargetSize: tapTargetSize,
constraints: const BoxConstraints(minWidth: 32.0, minHeight: 32.0),
isSelected: const <bool>[false, true, false],
onPressed: (int index) {},
children: const <Widget>[
Text('First'),
Text('Second'),
Text('Third'),
],
),
);
}
final Key key1 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.padded, key1));
expect(tester.getSize(find.byKey(key1)), const Size(232.0, 48.0));
final Key key2 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.shrinkWrap, key2));
expect(tester.getSize(find.byKey(key2)), const Size(232.0, 34.0));
});
testWidgets('Tap target size is configurable for vertical axis', (WidgetTester tester) async {
Widget buildFrame(MaterialTapTargetSize tapTargetSize, Key key) {
return boilerplate(
child: ToggleButtons(
key: key,
tapTargetSize: tapTargetSize,
constraints: const BoxConstraints(minWidth: 32.0, minHeight: 32.0),
direction: Axis.vertical,
isSelected: const <bool>[false, true, false],
onPressed: (int index) {},
children: const <Widget>[
Text('1'),
Text('2'),
Text('3'),
],
),
);
}
final Key key1 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.padded, key1));
expect(tester.getSize(find.byKey(key1)), const Size(48.0, 100.0));
final Key key2 = UniqueKey();
await tester.pumpWidget(buildFrame(MaterialTapTargetSize.shrinkWrap, key2));
expect(tester.getSize(find.byKey(key2)), const Size(34.0, 100.0));
});
// Regression test for https://github.com/flutter/flutter/issues/73725
testWidgets('Material2 - Border radius paint test when there is only one button', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
await tester.pumpWidget(
boilerplate(
theme: theme,
child: RepaintBoundary(
child: ToggleButtons(
borderRadius: const BorderRadius.all(Radius.circular(7.0)),
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
],
),
),
),
);
// The only button should be laid out at the center of the screen.
expect(tester.getCenter(find.text('First child')), const Offset(400.0, 300.0));
final List<RenderObject> toggleButtonRenderObject = tester.allRenderObjects.where((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
}).toSet().toList();
// The first button paints the left, top and right sides with a path.
expect(
toggleButtonRenderObject[0],
paints
// physical model paints
..path()
// left side, top and right - enabled.
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
),
);
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('m2_toggle_buttons.oneButton.boardsPaint.png'),
);
});
testWidgets('Material3 - Border radius paint test when there is only one button', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(
boilerplate(
child: RepaintBoundary(
child: ToggleButtons(
borderRadius: const BorderRadius.all(Radius.circular(7.0)),
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
],
),
),
),
);
// The only button should be laid out at the center of the screen.
expect(tester.getCenter(find.text('First child')), const Offset(400.0, 300.0));
final List<RenderObject> toggleButtonRenderObject = tester.allRenderObjects.where((RenderObject object) {
return object.runtimeType.toString() == '_SelectToggleButtonRenderObject';
}).toSet().toList();
// The first button paints the left, top and right sides with a path.
expect(
toggleButtonRenderObject[0],
paints
// physical model paints
..path()
// left side, top and right - enabled.
..path(
style: PaintingStyle.stroke,
color: theme.colorScheme.onSurface.withOpacity(0.12),
strokeWidth: _defaultBorderWidth,
),
);
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('m3_toggle_buttons.oneButton.boardsPaint.png'),
);
});
testWidgets('Material2 - Border radius paint test when Radius.x or Radius.y equal 0.0', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
theme: ThemeData(useMaterial3: false),
child: RepaintBoundary(
child: ToggleButtons(
borderRadius: const BorderRadius.only(
topRight: Radius.elliptical(10, 0),
topLeft: Radius.elliptical(0, 10),
bottomRight: Radius.elliptical(0, 10),
bottomLeft: Radius.elliptical(10, 0),
),
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
],
),
),
),
);
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('m2_toggle_buttons.oneButton.boardsPaint2.png'),
);
});
testWidgets('Material3 - Border radius paint test when Radius.x or Radius.y equal 0.0', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
child: RepaintBoundary(
child: ToggleButtons(
borderRadius: const BorderRadius.only(
topRight: Radius.elliptical(10, 0),
topLeft: Radius.elliptical(0, 10),
bottomRight: Radius.elliptical(0, 10),
bottomLeft: Radius.elliptical(10, 0),
),
isSelected: const <bool>[true],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
],
),
),
),
);
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('m3_toggle_buttons.oneButton.boardsPaint2.png'),
);
});
testWidgets('ToggleButtons implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
ToggleButtons(
direction: Axis.vertical,
verticalDirection: VerticalDirection.up,
borderWidth: 3.0,
color: Colors.green,
selectedBorderColor: Colors.pink,
disabledColor: Colors.blue,
disabledBorderColor: Colors.yellow,
borderRadius: const BorderRadius.all(Radius.circular(7.0)),
isSelected: const <bool>[false, true, false],
onPressed: (int index) {},
children: const <Widget>[
Text('First child'),
Text('Second child'),
Text('Third child'),
],
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString()).toList();
expect(description, <String>[
'Buttons are enabled',
'color: MaterialColor(primary value: Color(0xff4caf50))',
'disabledColor: MaterialColor(primary value: Color(0xff2196f3))',
'selectedBorderColor: MaterialColor(primary value: Color(0xffe91e63))',
'disabledBorderColor: MaterialColor(primary value: Color(0xffffeb3b))',
'borderRadius: BorderRadius.circular(7.0)',
'borderWidth: 3.0',
'direction: Axis.vertical',
'verticalDirection: VerticalDirection.up',
]);
});
testWidgets('ToggleButtons changes mouse cursor when the button is hovered', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: ToggleButtons(
mouseCursor: SystemMouseCursors.text,
onPressed: (int index) {},
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.text('First child')));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test default cursor
await tester.pumpWidget(
boilerplate(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: ToggleButtons(
onPressed: (int index) {},
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test default cursor when disabled
await tester.pumpWidget(
boilerplate(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: ToggleButtons(
isSelected: const <bool>[false, true],
children: const <Widget>[
Text('First child'),
Text('Second child'),
],
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('ToggleButtons focus, hover, and highlight elevations are 0', (WidgetTester tester) async {
final List<FocusNode> focusNodes = <FocusNode>[FocusNode(), FocusNode()];
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[true, false],
onPressed: (int index) { },
focusNodes: focusNodes,
children: const <Widget>[Text('one'), Text('two')],
),
),
);
double toggleButtonElevation(String text) {
return tester.widget<Material>(find.widgetWithText(Material, text).first).elevation;
}
// Default toggle button elevation
expect(toggleButtonElevation('one'), 0); // highlighted
expect(toggleButtonElevation('two'), 0); // not highlighted
// Hovered button elevation
final TestGesture hoverGesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await hoverGesture.addPointer();
await hoverGesture.moveTo(tester.getCenter(find.text('one')));
await tester.pumpAndSettle();
expect(toggleButtonElevation('one'), 0);
await hoverGesture.moveTo(tester.getCenter(find.text('two')));
await tester.pumpAndSettle();
expect(toggleButtonElevation('two'), 0);
// Focused button elevation
focusNodes[0].requestFocus();
await tester.pumpAndSettle();
expect(focusNodes[0].hasFocus, isTrue);
expect(focusNodes[1].hasFocus, isFalse);
expect(toggleButtonElevation('one'), 0);
focusNodes[1].requestFocus();
await tester.pumpAndSettle();
expect(focusNodes[0].hasFocus, isFalse);
expect(focusNodes[1].hasFocus, isTrue);
expect(toggleButtonElevation('two'), 0);
await hoverGesture.removePointer();
for (final FocusNode n in focusNodes) {
n.dispose();
}
});
testWidgets('Toggle buttons height matches MaterialTapTargetSize.padded height', (WidgetTester tester) async {
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false, false, false],
onPressed: (int index) {},
children: const <Widget>[
Icon(Icons.check),
Icon(Icons.access_alarm),
Icon(Icons.cake),
],
),
),
);
final Rect firstRect = tester.getRect(find.byType(TextButton).at(0));
expect(firstRect.height, 48.0);
final Rect secondRect = tester.getRect(find.byType(TextButton).at(1));
expect(secondRect.height, 48.0);
final Rect thirdRect = tester.getRect(find.byType(TextButton).at(2));
expect(thirdRect.height, 48.0);
});
testWidgets('Toggle buttons constraints size does not affect minimum input padding', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/97302
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false, false, false],
onPressed: (int index) {},
constraints: const BoxConstraints.tightFor(
width: 86,
height: 32,
),
children: const <Widget>[
Icon(Icons.check),
Icon(Icons.access_alarm),
Icon(Icons.cake),
],
),
),
);
// Button's height is constrained to `32.0`.
final Rect firstRect = tester.getRect(find.byType(TextButton).at(0));
expect(firstRect.height, 32.0);
final Rect secondRect = tester.getRect(find.byType(TextButton).at(1));
expect(secondRect.height, 32.0);
final Rect thirdRect = tester.getRect(find.byType(TextButton).at(2));
expect(thirdRect.height, 32.0);
// While button's height is constrained to `32.0`, semantic node height
// should remain `48.0`, matching `MaterialTapTargetSize.padded` height (default).
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.hasEnabledState,
SemanticsFlag.hasCheckedState,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[
SemanticsAction.tap,
],
rect: const Rect.fromLTRB(0.0, 0.0, 87.0, 48.0),
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.hasEnabledState,
SemanticsFlag.hasCheckedState,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[
SemanticsAction.tap,
],
rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0)
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.hasEnabledState,
SemanticsFlag.hasCheckedState,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[
SemanticsAction.tap,
],
rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0),
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
),
);
semantics.dispose();
});
testWidgets('Toggle buttons have correct semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
boilerplate(
child: ToggleButtons(
isSelected: const <bool>[false, true],
onPressed: (int index) {},
children: const <Widget>[
Icon(Icons.check),
Icon(Icons.access_alarm),
],
),
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.hasEnabledState,
SemanticsFlag.hasCheckedState,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[
SemanticsAction.tap,
],
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isChecked,
SemanticsFlag.hasCheckedState,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[
SemanticsAction.tap,
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
),
);
semantics.dispose();
});
}
| flutter/packages/flutter/test/material/toggle_buttons_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/toggle_buttons_test.dart",
"repo_id": "flutter",
"token_count": 31309
} | 672 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show DiagnosticLevel, FlutterError;
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
class SillyBorder extends BoxBorder {
const SillyBorder();
@override
dynamic noSuchMethod(Invocation invocation) => null;
}
void main() {
test('BoxBorder.lerp', () {
// names of the form fooAtX are foo, lerped X% of the way to null
const BoxBorder directionalWithMagentaTop5 = BorderDirectional(top: BorderSide(color: Color(0xFFFF00FF), width: 5.0));
const BoxBorder directionalWithMagentaTop5At25 = BorderDirectional(top: BorderSide(color: Color(0x3F3F003F), width: 1.25));
const BoxBorder directionalWithMagentaTop5At75 = BorderDirectional(top: BorderSide(color: Color(0xBFBF00BF), width: 3.75));
const BoxBorder directionalWithSides10 = BorderDirectional(start: BorderSide(width: 10.0), end: BorderSide(width: 20.0));
const BoxBorder directionalWithSides10At25 = BorderDirectional(start: BorderSide(width: 2.5, color: Color(0x3F000000)), end: BorderSide(width: 5.0, color: Color(0x3F000000)));
const BoxBorder directionalWithSides10At50 = BorderDirectional(start: BorderSide(width: 5.0, color: Color(0x7F000000)), end: BorderSide(width: 10.0, color: Color(0x7F000000)));
const BoxBorder directionalWithSides10At75 = BorderDirectional(start: BorderSide(width: 7.5, color: Color(0xBF000000)), end: BorderSide(width: 15.0, color: Color(0xBF000000)));
const BoxBorder directionalWithSides20 = BorderDirectional(start: BorderSide(width: 20.0), end: BorderSide(width: 40.0));
const BoxBorder directionalWithSides30 = BorderDirectional(start: BorderSide(width: 30.0), end: BorderSide(width: 60.0));
const BoxBorder directionalWithTop10 = BorderDirectional(top: BorderSide(width: 10.0));
const BoxBorder directionalWithYellowTop10 = BorderDirectional(top: BorderSide(color: Color(0xFFFFFF00), width: 10.0));
const BoxBorder directionalWithYellowTop5 = BorderDirectional(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0));
const BoxBorder visualWithMagentaTop10 = Border(top: BorderSide(color: Color(0xFFFF00FF), width: 10.0));
const BoxBorder visualWithMagentaTop5 = Border(top: BorderSide(color: Color(0xFFFF00FF), width: 5.0));
const BoxBorder visualWithSides10 = Border(left: BorderSide(width: 10.0), right: BorderSide(width: 20.0));
const BoxBorder visualWithSides10At25 = Border(left: BorderSide(width: 2.5, color: Color(0x3F000000)), right: BorderSide(width: 5.0, color: Color(0x3F000000)));
const BoxBorder visualWithSides10At50 = Border(left: BorderSide(width: 5.0, color: Color(0x7F000000)), right: BorderSide(width: 10.0, color: Color(0x7F000000)));
const BoxBorder visualWithSides10At75 = Border(left: BorderSide(width: 7.5, color: Color(0xBF000000)), right: BorderSide(width: 15.0, color: Color(0xBF000000)));
const BoxBorder visualWithSides20 = Border(left: BorderSide(width: 20.0), right: BorderSide(width: 40.0));
const BoxBorder visualWithSides30 = Border(left: BorderSide(width: 30.0), right: BorderSide(width: 60.0));
const BoxBorder visualWithTop10 = Border(top: BorderSide(width: 10.0));
const BoxBorder visualWithTop100 = Border(top: BorderSide(width: 100.0));
const BoxBorder visualWithTop190 = Border(top: BorderSide(width: 190.0));
const BoxBorder visualWithYellowTop5 = Border(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0));
const BoxBorder visualWithYellowTop5At25 = Border(top: BorderSide(color: Color(0x3F3F3F00), width: 1.25));
const BoxBorder visualWithYellowTop5At75 = Border(top: BorderSide(color: Color(0xBFBFBF00), width: 3.75));
expect(BoxBorder.lerp(null, null, -1.0), null);
expect(BoxBorder.lerp(Border.all(width: 10.0), null, -1.0), Border.all(width: 20.0));
expect(BoxBorder.lerp(null, Border.all(width: 10.0), -1.0), Border.all(width: 0.0, style: BorderStyle.none));
expect(BoxBorder.lerp(directionalWithTop10, null, -1.0), const BorderDirectional(top: BorderSide(width: 20.0)));
expect(BoxBorder.lerp(null, directionalWithTop10, -1.0), const BorderDirectional());
expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, -1.0), const Border());
expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, -1.0), visualWithSides20);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, -1.0), const Border(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0)));
expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, -1.0), visualWithSides30);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, -1.0), directionalWithYellowTop10);
expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), -1.0), throwsFlutterError);
expect(BoxBorder.lerp(null, null, 0.0), null);
expect(BoxBorder.lerp(Border.all(width: 10.0), null, 0.0), Border.all(width: 10.0));
expect(BoxBorder.lerp(null, Border.all(width: 10.0), 0.0), const Border());
expect(BoxBorder.lerp(directionalWithTop10, null, 0.0), const BorderDirectional(top: BorderSide(width: 10.0)));
expect(BoxBorder.lerp(null, directionalWithTop10, 0.0), const BorderDirectional());
expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 0.0), visualWithTop10);
expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 0.0), visualWithSides10);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 0.0), const Border(top: BorderSide(color: Color(0xFFFFFF00), width: 5.0)));
expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 0.0), visualWithSides10);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 0.0), directionalWithYellowTop5);
expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 0.0), throwsFlutterError);
expect(BoxBorder.lerp(null, null, 0.25), null);
expect(BoxBorder.lerp(Border.all(width: 10.0), null, 0.25), Border.all(width: 7.5));
expect(BoxBorder.lerp(null, Border.all(width: 10.0), 0.25), Border.all(width: 2.5));
expect(BoxBorder.lerp(directionalWithTop10, null, 0.25), const BorderDirectional(top: BorderSide(width: 7.5)));
expect(BoxBorder.lerp(null, directionalWithTop10, 0.25), const BorderDirectional(top: BorderSide(width: 2.5)));
expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 0.25), const Border(top: BorderSide(width: 32.5)));
expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 0.25), visualWithSides10At75 + directionalWithMagentaTop5At25);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 0.25), Border(top: BorderSide(width: 5.0, color: Color.lerp(const Color(0xFFFFFF00), const Color(0xFFFF00FF), 0.25)!)));
expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 0.25), visualWithSides10At50);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 0.25), visualWithYellowTop5At75 + directionalWithSides10At25);
expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 0.25), throwsFlutterError);
expect(BoxBorder.lerp(null, null, 0.75), null);
expect(BoxBorder.lerp(Border.all(width: 10.0), null, 0.75), Border.all(width: 2.5));
expect(BoxBorder.lerp(null, Border.all(width: 10.0), 0.75), Border.all(width: 7.5));
expect(BoxBorder.lerp(directionalWithTop10, null, 0.75), const BorderDirectional(top: BorderSide(width: 2.5)));
expect(BoxBorder.lerp(null, directionalWithTop10, 0.75), const BorderDirectional(top: BorderSide(width: 7.5)));
expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 0.75), const Border(top: BorderSide(width: 77.5)));
expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 0.75), visualWithSides10At25 + directionalWithMagentaTop5At75);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 0.75), Border(top: BorderSide(width: 5.0, color: Color.lerp(const Color(0xFFFFFF00), const Color(0xFFFF00FF), 0.75)!)));
expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 0.75), directionalWithSides10At50);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 0.75), visualWithYellowTop5At25 + directionalWithSides10At75);
expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 0.75), throwsFlutterError);
expect(BoxBorder.lerp(null, null, 1.0), null);
expect(BoxBorder.lerp(Border.all(width: 10.0), null, 1.0), Border.all(width: 0.0, style: BorderStyle.none));
expect(BoxBorder.lerp(null, Border.all(width: 10.0), 1.0), Border.all(width: 10.0));
expect(BoxBorder.lerp(directionalWithTop10, null, 1.0), const BorderDirectional());
expect(BoxBorder.lerp(null, directionalWithTop10, 1.0), const BorderDirectional(top: BorderSide(width: 10.0)));
expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 1.0), visualWithTop100);
expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 1.0), visualWithMagentaTop5);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 1.0), visualWithMagentaTop5);
expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 1.0), directionalWithSides10);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 1.0), directionalWithSides10);
expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 1.0), throwsFlutterError);
expect(BoxBorder.lerp(null, null, 2.0), null);
expect(BoxBorder.lerp(Border.all(width: 10.0), null, 2.0), Border.all(width: 0.0, style: BorderStyle.none));
expect(BoxBorder.lerp(null, Border.all(width: 10.0), 2.0), Border.all(width: 20.0));
expect(BoxBorder.lerp(directionalWithTop10, null, 2.0), const BorderDirectional());
expect(BoxBorder.lerp(null, directionalWithTop10, 2.0), const BorderDirectional(top: BorderSide(width: 20.0)));
expect(BoxBorder.lerp(directionalWithTop10, visualWithTop100, 2.0), visualWithTop190);
expect(BoxBorder.lerp(visualWithSides10, directionalWithMagentaTop5, 2.0), visualWithMagentaTop10);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithMagentaTop5, 2.0), visualWithMagentaTop5);
expect(BoxBorder.lerp(visualWithSides10, directionalWithSides10, 2.0), directionalWithSides30);
expect(BoxBorder.lerp(visualWithYellowTop5, directionalWithSides10, 2.0), directionalWithSides20);
expect(() => BoxBorder.lerp(const SillyBorder(), const Border(), 2.0), throwsFlutterError);
});
test('BoxBorder.lerp throws correct FlutterError message', () {
late FlutterError error;
try {
BoxBorder.lerp(const SillyBorder(), const Border(), 2.0);
} on FlutterError catch (e) {
error = e;
}
expect(error, isNotNull);
expect(error.diagnostics.length, 3);
expect(error.diagnostics[2].level, DiagnosticLevel.hint);
expect(
error.diagnostics[2].toStringDeep(),
equalsIgnoringHashCodes(
'For a more general interpolation method, consider using\n'
'ShapeBorder.lerp instead.\n',
),
);
expect(error.toStringDeep(), equalsIgnoringHashCodes(
'FlutterError\n'
' BoxBorder.lerp can only interpolate Border and BorderDirectional\n'
' classes.\n'
' BoxBorder.lerp() was called with two objects of type SillyBorder\n'
' and Border:\n'
' SillyBorder()\n'
' Border.all(BorderSide(width: 0.0, style: none))\n'
' However, only Border and BorderDirectional classes are supported\n'
' by this method.\n'
' For a more general interpolation method, consider using\n'
' ShapeBorder.lerp instead.\n',
));
});
test('BoxBorder.getInnerPath / BoxBorder.getOuterPath', () {
// for Border, BorderDirectional
const Border border = Border(top: BorderSide(width: 10.0), right: BorderSide(width: 20.0));
const BorderDirectional borderDirectional = BorderDirectional(top: BorderSide(width: 10.0), end: BorderSide(width: 20.0));
expect(
border.getOuterPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.rtl),
isPathThat(
includes: <Offset>[
const Offset(50.0, 60.0),
const Offset(60.0, 60.0),
const Offset(60.0, 70.0),
const Offset(80.0, 190.0),
const Offset(109.0, 189.0),
const Offset(110.0, 80.0),
const Offset(110.0, 190.0),
],
excludes: <Offset>[
const Offset(40.0, 60.0),
const Offset(50.0, 50.0),
const Offset(111.0, 190.0),
const Offset(110.0, 191.0),
const Offset(111.0, 191.0),
Offset.zero,
const Offset(-10.0, -10.0),
const Offset(0.0, -10.0),
const Offset(-10.0, 0.0),
const Offset(1000.0, 1000.0),
],
),
);
expect(
border.getInnerPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.rtl),
// inner path is a rect from 50.0,70.0 to 90.0,190.0
isPathThat(
includes: <Offset>[
const Offset(50.0, 70.0),
const Offset(55.0, 70.0),
const Offset(50.0, 75.0),
const Offset(70.0, 70.0),
const Offset(70.0, 71.0),
const Offset(71.0, 70.0),
const Offset(71.0, 71.0),
const Offset(80.0, 180.0),
const Offset(80.0, 190.0),
const Offset(89.0, 189.0),
const Offset(90.0, 190.0),
],
excludes: <Offset>[
const Offset(40.0, 60.0),
const Offset(50.0, 50.0),
const Offset(50.0, 60.0),
const Offset(60.0, 60.0),
Offset.zero,
const Offset(-10.0, -10.0),
const Offset(0.0, -10.0),
const Offset(-10.0, 0.0),
const Offset(110.0, 80.0),
const Offset(89.0, 191.0),
const Offset(90.0, 191.0),
const Offset(91.0, 189.0),
const Offset(91.0, 190.0),
const Offset(91.0, 191.0),
const Offset(109.0, 189.0),
const Offset(110.0, 190.0),
const Offset(1000.0, 1000.0),
],
),
);
expect(
borderDirectional.getOuterPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.rtl),
isPathThat(
includes: <Offset>[
const Offset(50.0, 60.0),
const Offset(60.0, 60.0),
const Offset(60.0, 70.0),
const Offset(80.0, 190.0),
const Offset(109.0, 189.0),
const Offset(110.0, 80.0),
const Offset(110.0, 190.0),
],
excludes: <Offset>[
const Offset(40.0, 60.0),
const Offset(50.0, 50.0),
const Offset(111.0, 190.0),
const Offset(110.0, 191.0),
const Offset(111.0, 191.0),
Offset.zero,
const Offset(-10.0, -10.0),
const Offset(0.0, -10.0),
const Offset(-10.0, 0.0),
const Offset(1000.0, 1000.0),
],
),
);
expect(
borderDirectional.getInnerPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.rtl),
// inner path is a rect from 70.0,70.0 to 110.0,190.0
isPathThat(
includes: <Offset>[
const Offset(70.0, 70.0),
const Offset(70.0, 71.0),
const Offset(71.0, 70.0),
const Offset(71.0, 71.0),
const Offset(80.0, 180.0),
const Offset(80.0, 190.0),
const Offset(89.0, 189.0),
const Offset(90.0, 190.0),
const Offset(91.0, 189.0),
const Offset(91.0, 190.0),
const Offset(109.0, 189.0),
const Offset(110.0, 80.0),
const Offset(110.0, 190.0),
],
excludes: <Offset>[
const Offset(40.0, 60.0),
const Offset(50.0, 50.0),
const Offset(50.0, 60.0),
const Offset(50.0, 70.0),
const Offset(50.0, 75.0),
const Offset(55.0, 70.0),
const Offset(60.0, 60.0),
Offset.zero,
const Offset(-10.0, -10.0),
const Offset(0.0, -10.0),
const Offset(-10.0, 0.0),
const Offset(89.0, 191.0),
const Offset(90.0, 191.0),
const Offset(91.0, 191.0),
const Offset(110.0, 191.0),
const Offset(111.0, 190.0),
const Offset(111.0, 191.0),
const Offset(1000.0, 1000.0),
],
),
);
expect(
borderDirectional.getOuterPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.ltr),
isPathThat(
includes: <Offset>[
const Offset(50.0, 60.0),
const Offset(60.0, 60.0),
const Offset(60.0, 70.0),
const Offset(80.0, 190.0),
const Offset(109.0, 189.0),
const Offset(110.0, 80.0),
const Offset(110.0, 190.0),
],
excludes: <Offset>[
const Offset(40.0, 60.0),
const Offset(50.0, 50.0),
const Offset(111.0, 190.0),
const Offset(110.0, 191.0),
const Offset(111.0, 191.0),
Offset.zero,
const Offset(-10.0, -10.0),
const Offset(0.0, -10.0),
const Offset(-10.0, 0.0),
const Offset(1000.0, 1000.0),
],
),
);
expect(
borderDirectional.getInnerPath(const Rect.fromLTRB(50.0, 60.0, 110.0, 190.0), textDirection: TextDirection.ltr),
// inner path is a rect from 50.0,70.0 to 90.0,190.0
isPathThat(
includes: <Offset>[
const Offset(50.0, 70.0),
const Offset(50.0, 75.0),
const Offset(55.0, 70.0),
const Offset(70.0, 70.0),
const Offset(70.0, 71.0),
const Offset(71.0, 70.0),
const Offset(71.0, 71.0),
const Offset(80.0, 180.0),
const Offset(80.0, 190.0),
const Offset(89.0, 189.0),
const Offset(90.0, 190.0),
],
excludes: <Offset>[
const Offset(50.0, 50.0),
const Offset(40.0, 60.0),
const Offset(50.0, 60.0),
const Offset(60.0, 60.0),
Offset.zero,
const Offset(-10.0, -10.0),
const Offset(0.0, -10.0),
const Offset(-10.0, 0.0),
const Offset(110.0, 80.0),
const Offset(89.0, 191.0),
const Offset(90.0, 191.0),
const Offset(91.0, 189.0),
const Offset(91.0, 190.0),
const Offset(91.0, 191.0),
const Offset(109.0, 189.0),
const Offset(110.0, 190.0),
const Offset(1000.0, 1000.0),
],
),
);
});
test('BorderDirectional.merge', () {
const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0);
const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0);
const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0);
const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none);
expect(
BorderDirectional.merge(
const BorderDirectional(top: yellow2),
const BorderDirectional(end: magenta3),
),
const BorderDirectional(top: yellow2, end: magenta3),
);
expect(
BorderDirectional.merge(
const BorderDirectional(bottom: magenta3),
const BorderDirectional(bottom: magenta3),
),
const BorderDirectional(bottom: magenta6),
);
expect(
BorderDirectional.merge(
const BorderDirectional(start: magenta3, end: yellowNone0),
const BorderDirectional(end: yellow2),
),
const BorderDirectional(start: magenta3, end: yellow2),
);
expect(
BorderDirectional.merge(const BorderDirectional(), const BorderDirectional()),
const BorderDirectional(),
);
expect(
() => BorderDirectional.merge(
const BorderDirectional(start: magenta3),
const BorderDirectional(start: yellow2),
),
throwsAssertionError,
);
});
test('BorderDirectional.dimensions', () {
expect(
const BorderDirectional(
top: BorderSide(width: 3.0),
start: BorderSide(width: 2.0),
end: BorderSide(width: 7.0),
bottom: BorderSide(width: 5.0),
).dimensions,
const EdgeInsetsDirectional.fromSTEB(2.0, 3.0, 7.0, 5.0),
);
});
test('BorderDirectional.isUniform', () {
expect(
const BorderDirectional(
top: BorderSide(width: 3.0),
start: BorderSide(width: 3.0),
end: BorderSide(width: 3.0),
bottom: BorderSide(width: 3.1),
).isUniform,
false,
);
expect(
const BorderDirectional(
top: BorderSide(width: 3.0),
start: BorderSide(width: 3.0),
end: BorderSide(width: 3.0),
bottom: BorderSide(width: 3.0),
).isUniform,
true,
);
expect(
const BorderDirectional(
top: BorderSide(color: Color(0xFFFFFFFF)),
start: BorderSide(color: Color(0xFFFFFFFE)),
end: BorderSide(color: Color(0xFFFFFFFF)),
bottom: BorderSide(color: Color(0xFFFFFFFF)),
).isUniform,
false,
);
expect(
const BorderDirectional(
top: BorderSide(color: Color(0xFFFFFFFF)),
start: BorderSide(color: Color(0xFFFFFFFF)),
end: BorderSide(color: Color(0xFFFFFFFF)),
bottom: BorderSide(color: Color(0xFFFFFFFF)),
).isUniform,
true,
);
expect(
const BorderDirectional(
top: BorderSide(style: BorderStyle.none),
start: BorderSide(style: BorderStyle.none),
end: BorderSide(style: BorderStyle.none),
bottom: BorderSide(width: 0.0),
).isUniform,
false,
);
expect(
const BorderDirectional(
top: BorderSide(style: BorderStyle.none),
start: BorderSide(style: BorderStyle.none),
end: BorderSide(style: BorderStyle.none),
).isUniform,
false,
);
expect(
const BorderDirectional().isUniform,
true,
);
expect(
const BorderDirectional().isUniform,
true,
);
});
test('BorderDirectional.add - all directional', () {
const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0);
const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0);
const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0);
const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none);
expect(
const BorderDirectional(top: yellow2) + const BorderDirectional(end: magenta3),
const BorderDirectional(top: yellow2, end: magenta3),
);
expect(
const BorderDirectional(bottom: magenta3) + const BorderDirectional(bottom: magenta3),
const BorderDirectional(bottom: magenta6),
);
expect(
const BorderDirectional(start: magenta3, end: yellowNone0) + const BorderDirectional(end: yellow2),
const BorderDirectional(start: magenta3, end: yellow2),
);
expect(
const BorderDirectional() + const BorderDirectional(),
const BorderDirectional(),
);
expect(
const BorderDirectional(start: magenta3) + const BorderDirectional(start: yellow2),
isNot(isA<BorderDirectional>()), // see shape_border_test.dart for better tests of this case
);
const BorderDirectional b3 = BorderDirectional(top: magenta3);
const BorderDirectional b6 = BorderDirectional(top: magenta6);
expect(b3 + b3, b6);
const BorderDirectional b0 = BorderDirectional(top: yellowNone0);
const BorderDirectional bZ = BorderDirectional();
expect(b0 + b0, bZ);
expect(bZ + bZ, bZ);
expect(b0 + bZ, bZ);
expect(bZ + b0, bZ);
});
test('BorderDirectional.add', () {
const BorderSide side1 = BorderSide(color: Color(0x11111111));
const BorderSide doubleSide1 = BorderSide(color: Color(0x11111111), width: 2.0);
const BorderSide side2 = BorderSide(color: Color(0x22222222));
const BorderSide doubleSide2 = BorderSide(color: Color(0x22222222), width: 2.0);
// adding tops and sides
expect(const Border(left: side1) + const BorderDirectional(top: side2), const Border(left: side1, top: side2));
expect(const BorderDirectional(start: side1) + const Border(top: side2), const BorderDirectional(start: side1, top: side2));
expect(const Border(top: side2) + const BorderDirectional(start: side1), const BorderDirectional(start: side1, top: side2));
expect(const BorderDirectional(top: side2) + const Border(left: side1), const Border(left: side1, top: side2));
// adding incompatible tops and bottoms
expect((const Border(top: side1) + const BorderDirectional(top: side2)).toString(), contains(' + '));
expect((const BorderDirectional(top: side2) + const Border(top: side1)).toString(), contains(' + '));
expect((const Border(bottom: side1) + const BorderDirectional(bottom: side2)).toString(), contains(' + '));
expect((const BorderDirectional(bottom: side2) + const Border(bottom: side1)).toString(), contains(' + '));
// adding compatible tops and bottoms
expect(const BorderDirectional(top: side1) + const Border(top: side1), const Border(top: doubleSide1));
expect(const Border(top: side1) + const BorderDirectional(top: side1), const Border(top: doubleSide1));
expect(const BorderDirectional(bottom: side1) + const Border(bottom: side1), const Border(bottom: doubleSide1));
expect(const Border(bottom: side1) + const BorderDirectional(bottom: side1), const Border(bottom: doubleSide1));
const Border borderWithLeft = Border(left: side1, top: side2, bottom: side2);
const Border borderWithRight = Border(right: side1, top: side2, bottom: side2);
const Border borderWithoutSides = Border(top: side2, bottom: side2);
const BorderDirectional borderDirectionalWithStart = BorderDirectional(start: side1, top: side2, bottom: side2);
const BorderDirectional borderDirectionalWithEnd = BorderDirectional(end: side1, top: side2, bottom: side2);
const BorderDirectional borderDirectionalWithoutSides = BorderDirectional(top: side2, bottom: side2);
expect((borderWithLeft + borderDirectionalWithStart).toString(), '$borderWithLeft + $borderDirectionalWithStart');
expect((borderWithLeft + borderDirectionalWithEnd).toString(), '$borderWithLeft + $borderDirectionalWithEnd');
expect((borderWithLeft + borderDirectionalWithoutSides).toString(), '${const Border(left: side1, top: doubleSide2, bottom: doubleSide2)}');
expect((borderWithRight + borderDirectionalWithStart).toString(), '$borderWithRight + $borderDirectionalWithStart');
expect((borderWithRight + borderDirectionalWithEnd).toString(), '$borderWithRight + $borderDirectionalWithEnd');
expect((borderWithRight + borderDirectionalWithoutSides).toString(), '${const Border(right: side1, top: doubleSide2, bottom: doubleSide2)}');
expect((borderWithoutSides + borderDirectionalWithStart).toString(), '${const BorderDirectional(start: side1, top: doubleSide2, bottom: doubleSide2)}');
expect((borderWithoutSides + borderDirectionalWithEnd).toString(), '${const BorderDirectional(end: side1, top: doubleSide2, bottom: doubleSide2)}');
expect((borderWithoutSides + borderDirectionalWithoutSides).toString(), '${const Border(top: doubleSide2, bottom: doubleSide2)}');
expect((borderDirectionalWithStart + borderWithLeft).toString(), '$borderDirectionalWithStart + $borderWithLeft');
expect((borderDirectionalWithEnd + borderWithLeft).toString(), '$borderDirectionalWithEnd + $borderWithLeft');
expect((borderDirectionalWithoutSides + borderWithLeft).toString(), '${const Border(left: side1, top: doubleSide2, bottom: doubleSide2)}');
expect((borderDirectionalWithStart + borderWithRight).toString(), '$borderDirectionalWithStart + $borderWithRight');
expect((borderDirectionalWithEnd + borderWithRight).toString(), '$borderDirectionalWithEnd + $borderWithRight');
expect((borderDirectionalWithoutSides + borderWithRight).toString(), '${const Border(right: side1, top: doubleSide2, bottom: doubleSide2)}');
expect((borderDirectionalWithStart + borderWithoutSides).toString(), '${const BorderDirectional(start: side1, top: doubleSide2, bottom: doubleSide2)}');
expect((borderDirectionalWithEnd + borderWithoutSides).toString(), '${const BorderDirectional(end: side1, top: doubleSide2, bottom: doubleSide2)}');
expect((borderDirectionalWithoutSides + borderWithoutSides).toString(), '${const Border(top: doubleSide2, bottom: doubleSide2)}');
});
test('BorderDirectional.scale', () {
const BorderSide magenta3 = BorderSide(color: Color(0xFFFF00FF), width: 3.0);
const BorderSide magenta6 = BorderSide(color: Color(0xFFFF00FF), width: 6.0);
const BorderSide yellow2 = BorderSide(color: Color(0xFFFFFF00), width: 2.0);
const BorderSide yellowNone0 = BorderSide(color: Color(0xFFFFFF00), width: 0.0, style: BorderStyle.none);
const BorderDirectional b3 = BorderDirectional(start: magenta3);
const BorderDirectional b6 = BorderDirectional(start: magenta6);
expect(b3.scale(2.0), b6);
const BorderDirectional bY0 = BorderDirectional(top: yellowNone0);
expect(bY0.scale(3.0), bY0);
const BorderDirectional bY2 = BorderDirectional(top: yellow2);
expect(bY2.scale(0.0), bY0);
});
test('BorderDirectional.lerp', () {
const BorderDirectional directionalWithTop10 = BorderDirectional(top: BorderSide(width: 10.0));
const BorderDirectional atMinus100 = BorderDirectional(start: BorderSide(width: 0.0), end: BorderSide(width: 300.0));
const BorderDirectional at0 = BorderDirectional(start: BorderSide(width: 100.0), end: BorderSide(width: 200.0));
const BorderDirectional at25 = BorderDirectional(start: BorderSide(width: 125.0), end: BorderSide(width: 175.0));
const BorderDirectional at75 = BorderDirectional(start: BorderSide(width: 175.0), end: BorderSide(width: 125.0));
const BorderDirectional at100 = BorderDirectional(start: BorderSide(width: 200.0), end: BorderSide(width: 100.0));
const BorderDirectional at200 = BorderDirectional(start: BorderSide(width: 300.0), end: BorderSide(width: 0.0));
expect(BorderDirectional.lerp(null, null, -1.0), null);
expect(BorderDirectional.lerp(directionalWithTop10, null, -1.0), const BorderDirectional(top: BorderSide(width: 20.0)));
expect(BorderDirectional.lerp(null, directionalWithTop10, -1.0), const BorderDirectional());
expect(BorderDirectional.lerp(at0, at100, -1.0), atMinus100);
expect(BorderDirectional.lerp(null, null, 0.0), null);
expect(BorderDirectional.lerp(directionalWithTop10, null, 0.0), const BorderDirectional(top: BorderSide(width: 10.0)));
expect(BorderDirectional.lerp(null, directionalWithTop10, 0.0), const BorderDirectional());
expect(BorderDirectional.lerp(at0, at100, 0.0), at0);
expect(BorderDirectional.lerp(null, null, 0.25), null);
expect(BorderDirectional.lerp(directionalWithTop10, null, 0.25), const BorderDirectional(top: BorderSide(width: 7.5)));
expect(BorderDirectional.lerp(null, directionalWithTop10, 0.25), const BorderDirectional(top: BorderSide(width: 2.5)));
expect(BorderDirectional.lerp(at0, at100, 0.25), at25);
expect(BorderDirectional.lerp(null, null, 0.75), null);
expect(BorderDirectional.lerp(directionalWithTop10, null, 0.75), const BorderDirectional(top: BorderSide(width: 2.5)));
expect(BorderDirectional.lerp(null, directionalWithTop10, 0.75), const BorderDirectional(top: BorderSide(width: 7.5)));
expect(BorderDirectional.lerp(at0, at100, 0.75), at75);
expect(BorderDirectional.lerp(null, null, 1.0), null);
expect(BorderDirectional.lerp(directionalWithTop10, null, 1.0), const BorderDirectional());
expect(BorderDirectional.lerp(null, directionalWithTop10, 1.0), const BorderDirectional(top: BorderSide(width: 10.0)));
expect(BorderDirectional.lerp(at0, at100, 1.0), at100);
expect(BorderDirectional.lerp(null, null, 2.0), null);
expect(BorderDirectional.lerp(directionalWithTop10, null, 2.0), const BorderDirectional());
expect(BorderDirectional.lerp(null, directionalWithTop10, 2.0), const BorderDirectional(top: BorderSide(width: 20.0)));
expect(BorderDirectional.lerp(at0, at100, 2.0), at200);
});
test('BorderDirectional.paint', () {
expect(
(Canvas canvas) {
const BorderDirectional(end: BorderSide(width: 10.0, color: Color(0xFF00FF00)))
.paint(canvas, const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0), textDirection: TextDirection.rtl);
},
paints
..path(
includes: <Offset>[const Offset(15.0, 30.0)],
excludes: <Offset>[const Offset(25.0, 30.0)],
color: const Color(0xFF00FF00),
),
);
expect(
(Canvas canvas) {
const BorderDirectional(end: BorderSide(width: 10.0, color: Color(0xFF00FF00)))
.paint(canvas, const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0), textDirection: TextDirection.ltr);
},
paints
..path(
includes: <Offset>[const Offset(25.0, 30.0)],
excludes: <Offset>[const Offset(15.0, 30.0)],
color: const Color(0xFF00FF00),
),
);
expect(
(Canvas canvas) {
const BorderDirectional(end: BorderSide(width: 10.0, color: Color(0xFF00FF00)))
.paint(canvas, const Rect.fromLTRB(10.0, 20.0, 30.0, 40.0));
},
paintsAssertion, // no TextDirection
);
});
test('BorderDirectional hashCode', () {
final BorderSide side = BorderSide(width: nonconst(2.0));
expect(BorderDirectional(top: side).hashCode, BorderDirectional(top: side).hashCode);
expect(BorderDirectional(top: side).hashCode, isNot(BorderDirectional(bottom: side).hashCode));
});
test('BoxDecoration.border takes a BorderDirectional', () {
const BoxDecoration decoration2 = BoxDecoration(
border: BorderDirectional(start: BorderSide(width: 2.0)),
);
const BoxDecoration decoration4 = BoxDecoration(
border: BorderDirectional(start: BorderSide(width: 4.0)),
);
const BoxDecoration decoration6 = BoxDecoration(
border: BorderDirectional(start: BorderSide(width: 6.0)),
);
final BoxPainter painter = decoration2.createBoxPainter();
expect(
(Canvas canvas) {
painter.paint(
canvas,
const Offset(30.0, 0.0),
const ImageConfiguration(size: Size(20.0, 20.0), textDirection: TextDirection.rtl),
);
},
paints
..path(
includes: <Offset>[const Offset(49.0, 10.0)],
excludes: <Offset>[const Offset(31.0, 10.0)],
),
);
expect(
(Canvas canvas) {
painter.paint(
canvas,
const Offset(30.0, 0.0),
const ImageConfiguration(size: Size(20.0, 20.0), textDirection: TextDirection.ltr),
);
},
paints
..path(
includes: <Offset>[const Offset(31.0, 10.0)],
excludes: <Offset>[const Offset(49.0, 10.0)],
),
);
expect(decoration2.padding, const EdgeInsetsDirectional.fromSTEB(2.0, 0.0, 0.0, 0.0));
expect(decoration2.scale(2.0), decoration4);
expect(BoxDecoration.lerp(decoration2, decoration6, 0.5), decoration4);
});
}
| flutter/packages/flutter/test/painting/border_rtl_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/border_rtl_test.dart",
"repo_id": "flutter",
"token_count": 14494
} | 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/painting.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('FractionalOffset control test', () {
const FractionalOffset a = FractionalOffset(0.5, 0.25);
const FractionalOffset b = FractionalOffset(1.25, 0.75);
expect(a, hasOneLineDescription);
expect(a.hashCode, equals(const FractionalOffset(0.5, 0.25).hashCode));
expect(a.toString(), equals('FractionalOffset(0.5, 0.3)'));
expect(-a, const FractionalOffset(-0.5, -0.25));
expect(a - b, const FractionalOffset(-0.75, -0.5));
expect(a + b, const FractionalOffset(1.75, 1.0));
expect(a * 2.0, FractionalOffset.centerRight);
expect(a / 2.0, const FractionalOffset(0.25, 0.125));
expect(a ~/ 2.0, FractionalOffset.topLeft);
expect(a % 5.0, const FractionalOffset(0.5, 0.25));
});
test('FractionalOffset.lerp()', () {
const FractionalOffset a = FractionalOffset.topLeft;
const FractionalOffset b = FractionalOffset.topCenter;
expect(FractionalOffset.lerp(a, b, 0.25), equals(const FractionalOffset(0.125, 0.0)));
expect(FractionalOffset.lerp(null, null, 0.25), isNull);
expect(FractionalOffset.lerp(null, b, 0.25), equals(const FractionalOffset(0.5, 0.5 - 0.125)));
expect(FractionalOffset.lerp(a, null, 0.25), equals(const FractionalOffset(0.125, 0.125)));
});
test('FractionalOffset.lerp identical a,b', () {
expect(FractionalOffset.lerp(null, null, 0), null);
const FractionalOffset decoration = FractionalOffset(1, 2);
expect(identical(FractionalOffset.lerp(decoration, decoration, 0.5), decoration), true);
});
test('FractionalOffset.fromOffsetAndSize()', () {
final FractionalOffset a = FractionalOffset.fromOffsetAndSize(const Offset(100.0, 100.0), const Size(200.0, 400.0));
expect(a, const FractionalOffset(0.5, 0.25));
});
test('FractionalOffset.fromOffsetAndRect()', () {
final FractionalOffset a = FractionalOffset.fromOffsetAndRect(const Offset(150.0, 120.0), const Rect.fromLTWH(50.0, 20.0, 200.0, 400.0));
expect(a, const FractionalOffset(0.5, 0.25));
});
}
| flutter/packages/flutter/test/painting/fractional_offset_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/fractional_offset_test.dart",
"repo_id": "flutter",
"token_count": 860
} | 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/painting.dart';
import 'package:flutter_test/flutter_test.dart';
const Rect canvasRect = Rect.fromLTWH(0, 0, 100, 100);
const BorderSide borderSide = BorderSide(width: 4, color: Color(0x0f00ff00));
// Test points for rectangular filled paths based on a BorderSide with width 4 and
// a 100x100 bounding rectangle (canvasRect).
List<Offset> rectIncludes(Rect r) {
return <Offset>[r.topLeft, r.topRight, r.bottomLeft, r.bottomRight, r.center];
}
final List<Offset> leftRectIncludes = rectIncludes(const Rect.fromLTWH(0, 0, 4, 100));
final List<Offset> rightRectIncludes = rectIncludes(const Rect.fromLTWH(96, 0, 4, 100));
final List<Offset> topRectIncludes = rectIncludes(const Rect.fromLTWH(0, 0, 100, 4));
final List<Offset> bottomRectIncludes = rectIncludes(const Rect.fromLTWH(0, 96, 100, 4));
void main() {
test('LinearBorderEdge defaults', () {
expect(const LinearBorderEdge().size, 1);
expect(const LinearBorderEdge().alignment, 0);
});
test('LinearBorder defaults', () {
void expectEmptyBorder(LinearBorder border) {
expect(border.side, BorderSide.none);
expect(border.dimensions, EdgeInsets.zero);
expect(border.preferPaintInterior, false);
expect(border.start, null);
expect(border.end, null);
expect(border.top, null);
expect(border.bottom, null);
}
expectEmptyBorder(LinearBorder.none);
expect(LinearBorder.start().side, BorderSide.none);
expect(LinearBorder.start().start, const LinearBorderEdge());
expect(LinearBorder.start().end, null);
expect(LinearBorder.start().top, null);
expect(LinearBorder.start().bottom, null);
expect(LinearBorder.end().side, BorderSide.none);
expect(LinearBorder.end().start, null);
expect(LinearBorder.end().end, const LinearBorderEdge());
expect(LinearBorder.end().top, null);
expect(LinearBorder.end().bottom, null);
expect(LinearBorder.top().side, BorderSide.none);
expect(LinearBorder.top().start, null);
expect(LinearBorder.top().end, null);
expect(LinearBorder.top().top, const LinearBorderEdge());
expect(LinearBorder.top().bottom, null);
expect(LinearBorder.bottom().side, BorderSide.none);
expect(LinearBorder.bottom().start, null);
expect(LinearBorder.bottom().end, null);
expect(LinearBorder.bottom().top, null);
expect(LinearBorder.bottom().bottom, const LinearBorderEdge());
});
test('LinearBorder copyWith, ==, hashCode', () {
expect(LinearBorder.none, LinearBorder.none.copyWith());
expect(LinearBorder.none.hashCode, LinearBorder.none.copyWith().hashCode);
const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456));
expect(LinearBorder.none.copyWith(side: side), const LinearBorder(side: side));
});
test('LinearBorder lerp identical a,b', () {
expect(OutlinedBorder.lerp(null, null, 0), null);
const LinearBorder border = LinearBorder.none;
expect(identical(OutlinedBorder.lerp(border, border, 0.5), border), true);
});
test('LinearBorderEdge.lerp identical a,b', () {
expect(LinearBorderEdge.lerp(null, null, 0), null);
const LinearBorderEdge edge = LinearBorderEdge();
expect(identical(LinearBorderEdge.lerp(edge, edge, 0.5), edge), true);
});
test('LinearBorderEdge, LinearBorder toString()', () {
expect(const LinearBorderEdge(size: 0.5, alignment: -0.5).toString(), 'LinearBorderEdge(size: 0.5, alignment: -0.5)');
expect(LinearBorder.none.toString(), 'LinearBorder.none');
const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456));
expect(const LinearBorder(side: side).toString(), 'LinearBorder(side: BorderSide(color: Color(0xff123456), width: 10.0))');
expect(
const LinearBorder(
side: side,
start: LinearBorderEdge(size: 0, alignment: -0.75),
end: LinearBorderEdge(size: 0.25, alignment: -0.5),
top: LinearBorderEdge(size: 0.5, alignment: 0.5),
bottom: LinearBorderEdge(size: 0.75, alignment: 0.75),
).toString(),
'LinearBorder('
'side: BorderSide(color: Color(0xff123456), width: 10.0), '
'start: LinearBorderEdge(size: 0.0, alignment: -0.75), '
'end: LinearBorderEdge(size: 0.25, alignment: -0.5), '
'top: LinearBorderEdge(size: 0.5, alignment: 0.5), '
'bottom: LinearBorderEdge(size: 0.75, alignment: 0.75))',
);
},
skip: isBrowser, // [intended] see https://github.com/flutter/flutter/issues/118207
);
test('LinearBorder.start()', () {
final LinearBorder border = LinearBorder.start(side: borderSide);
expect(
(Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.ltr),
paints
..path(
includes: leftRectIncludes,
excludes: rightRectIncludes,
color: borderSide.color,
),
);
expect(
(Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.rtl),
paints
..path(
includes: rightRectIncludes,
excludes: leftRectIncludes,
color: borderSide.color,
),
);
});
test('LinearBorder.end()', () {
final LinearBorder border = LinearBorder.end(side: borderSide);
expect(
(Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.ltr),
paints
..path(
includes: rightRectIncludes,
excludes: leftRectIncludes,
color: borderSide.color,
),
);
expect(
(Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.rtl),
paints
..path(
includes: leftRectIncludes,
excludes: rightRectIncludes,
color: borderSide.color,
),
);
});
test('LinearBorder.top()', () {
final LinearBorder border = LinearBorder.top(side: borderSide);
expect(
(Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.ltr),
paints
..path(
includes: topRectIncludes,
excludes: bottomRectIncludes,
color: borderSide.color,
),
);
});
test('LinearBorder.bottom()', () {
final LinearBorder border = LinearBorder.bottom(side: borderSide);
expect(
(Canvas canvas) => border.paint(canvas, canvasRect, textDirection: TextDirection.ltr),
paints
..path(
includes: bottomRectIncludes,
excludes: topRectIncludes,
color: borderSide.color,
),
);
});
}
| flutter/packages/flutter/test/painting/linear_border_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/linear_border_test.dart",
"repo_id": "flutter",
"token_count": 2516
} | 675 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
const bool skipTestsWithKnownBugs = true;
const bool skipExpectsWithKnownBugs = false;
void main() {
test('TextPainter - basic words', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.ltr;
painter.text = const TextSpan(
text: 'ABC DEF\nGHI',
style: TextStyle(fontSize: 10.0),
);
painter.layout();
expect(
painter.getWordBoundary(const TextPosition(offset: 1)),
const TextRange(start: 0, end: 3),
);
expect(
painter.getWordBoundary(const TextPosition(offset: 5)),
const TextRange(start: 4, end: 7),
);
expect(
painter.getWordBoundary(const TextPosition(offset: 9)),
const TextRange(start: 8, end: 11),
);
painter.dispose();
});
test('TextPainter - bidi overrides in LTR', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.ltr;
painter.text = const TextSpan(
text: '${Unicode.RLO}HEBREW1 ${Unicode.LRO}english2${Unicode.PDF} HEBREW3${Unicode.PDF}',
// 0 12345678 9 101234567 18 90123456 27
style: TextStyle(fontSize: 10.0),
);
TextSpan textSpan = painter.text! as TextSpan;
expect(textSpan.text!.length, 28);
painter.layout();
// The skips here are because the old rendering code considers the bidi formatting characters
// to be part of the word sometimes and not others, which is fine, but we'd mildly prefer if
// we were consistently considering them part of words always.
final TextRange hebrew1 = painter.getWordBoundary(const TextPosition(offset: 4));
expect(hebrew1, const TextRange(start: 0, end: 8), skip: skipExpectsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
final TextRange english2 = painter.getWordBoundary(const TextPosition(offset: 14));
expect(english2, const TextRange(start: 9, end: 19), skip: skipExpectsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
final TextRange hebrew3 = painter.getWordBoundary(const TextPosition(offset: 24));
expect(hebrew3, const TextRange(start: 20, end: 28));
// >>>>>>>>>>>>>>> embedding level 2
// <============================================== embedding level 1
// ------------------------------------------------> embedding level 0
// 0 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 2
// 0 6 5 4 3 2 1 0 9 0 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 7 <- index of character in string
// Paints as: 3 W E R B E H e n g l i s h 2 1 W E R B E H
// 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 <- pixel offset at boundary
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
// 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
expect(
painter.getOffsetForCaret(const TextPosition(offset: 0, affinity: TextAffinity.upstream), Rect.zero),
Offset.zero,
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 0), Rect.zero),
Offset.zero,
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 1, affinity: TextAffinity.upstream), Rect.zero),
const Offset(240.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 1), Rect.zero),
const Offset(240.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 7, affinity: TextAffinity.upstream), Rect.zero),
const Offset(180.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 7), Rect.zero),
const Offset(180.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 8, affinity: TextAffinity.upstream), Rect.zero),
const Offset(170.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 8), Rect.zero),
const Offset(170.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 9, affinity: TextAffinity.upstream), Rect.zero),
const Offset(160.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 9), Rect.zero),
const Offset(160.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 10, affinity: TextAffinity.upstream), Rect.zero),
const Offset(80.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 10), Rect.zero),
const Offset(80.0, 0.0),
);
expect(
painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 27)),
const <TextBox>[
TextBox.fromLTRBD(160.0, 0.0, 240.0, 10.0, TextDirection.rtl), // HEBREW1
TextBox.fromLTRBD( 80.0, 0.0, 160.0, 10.0, TextDirection.ltr), // english2
TextBox.fromLTRBD( 0.0, 0.0, 80.0, 10.0, TextDirection.rtl), // HEBREW3
],
// Horizontal offsets are currently one pixel off in places; vertical offsets are good.
// The list is currently in the wrong order (so selection boxes will paint in the wrong order).
);
textSpan = painter.text! as TextSpan;
final List<List<TextBox>> list = <List<TextBox>>[
for (int index = 0; index < textSpan.text!.length; index += 1)
painter.getBoxesForSelection(TextSelection(baseOffset: index, extentOffset: index + 1)),
];
expect(list, const <List<TextBox>>[
<TextBox>[], // U+202E, non-printing Unicode bidi formatting character
<TextBox>[TextBox.fromLTRBD(230.0, 0.0, 240.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(220.0, 0.0, 230.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(210.0, 0.0, 220.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(200.0, 0.0, 210.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(190.0, 0.0, 200.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(180.0, 0.0, 190.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(170.0, 0.0, 180.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(160.0, 0.0, 170.0, 10.0, TextDirection.rtl)],
<TextBox>[], // U+202D, non-printing Unicode bidi formatting character
<TextBox>[TextBox.fromLTRBD(80.0, 0.0, 90.0, 10.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(90.0, 0.0, 100.0, 10.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(100.0, 0.0, 110.0, 10.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(110.0, 0.0, 120.0, 10.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(120.0, 0.0, 130.0, 10.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(130.0, 0.0, 140.0, 10.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(140.0, 0.0, 150.0, 10.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(150.0, 0.0, 160.0, 10.0, TextDirection.ltr)],
<TextBox>[], // U+202C, non-printing Unicode bidi formatting character
<TextBox>[TextBox.fromLTRBD(70.0, 0.0, 80.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(60.0, 0.0, 70.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(50.0, 0.0, 60.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(40.0, 0.0, 50.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(30.0, 0.0, 40.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(20.0, 0.0, 30.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(10.0, 0.0, 20.0, 10.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(0.0, 0.0, 10.0, 10.0, TextDirection.rtl)],
<TextBox>[], // U+202C, non-printing Unicode bidi formatting character
// The list currently has one extra bogus entry (the last entry, for the
// trailing U+202C PDF, should be empty but is one-pixel-wide instead).
], skip: skipExpectsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
painter.dispose();
}, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
test('TextPainter - bidi overrides in RTL', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.rtl;
painter.text = const TextSpan(
text: '${Unicode.RLO}HEBREW1 ${Unicode.LRO}english2${Unicode.PDF} HEBREW3${Unicode.PDF}',
// 0 12345678 9 101234567 18 90123456 27
style: TextStyle(fontSize: 10.0),
);
final TextSpan textSpan = painter.text! as TextSpan;
expect(textSpan.text!.length, 28);
painter.layout();
final TextRange hebrew1 = painter.getWordBoundary(const TextPosition(offset: 4));
expect(hebrew1, const TextRange(start: 0, end: 8), skip: skipExpectsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
final TextRange english2 = painter.getWordBoundary(const TextPosition(offset: 14));
expect(english2, const TextRange(start: 9, end: 19), skip: skipExpectsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
final TextRange hebrew3 = painter.getWordBoundary(const TextPosition(offset: 24));
expect(hebrew3, const TextRange(start: 20, end: 28));
// >>>>>>>>>>>>>>> embedding level 2
// <================================================== embedding level 1
// 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0
// 7 6 5 4 3 2 1 0 9 0 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 0 <- index of character in string
// Paints as: 3 W E R B E H e n g l i s h 2 1 W E R B E H
// 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 <- pixel offset at boundary
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
// 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
expect(
painter.getOffsetForCaret(const TextPosition(offset: 0, affinity: TextAffinity.upstream), Rect.zero),
const Offset(240.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 0), Rect.zero),
const Offset(240.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 1, affinity: TextAffinity.upstream), Rect.zero),
const Offset(240.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 1), Rect.zero),
const Offset(240.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 7, affinity: TextAffinity.upstream), Rect.zero),
const Offset(180.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 7), Rect.zero),
const Offset(180.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 8, affinity: TextAffinity.upstream), Rect.zero),
const Offset(170.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 8), Rect.zero),
const Offset(170.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 9, affinity: TextAffinity.upstream), Rect.zero),
const Offset(160.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 9), Rect.zero),
const Offset(160.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 10, affinity: TextAffinity.upstream), Rect.zero),
const Offset(80.0, 0.0),
);
expect(
painter.getOffsetForCaret(const TextPosition(offset: 10), Rect.zero),
const Offset(80.0, 0.0),
);
expect(
painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 27)),
const <TextBox>[
TextBox.fromLTRBD(160.0, 0.0, 240.0, 10.0, TextDirection.rtl), // HEBREW1
TextBox.fromLTRBD( 80.0, 0.0, 160.0, 10.0, TextDirection.ltr), // english2
TextBox.fromLTRBD( 0.0, 0.0, 80.0, 10.0, TextDirection.rtl), // HEBREW3
],
// Horizontal offsets are currently one pixel off in places; vertical offsets are good.
// The list is currently in the wrong order (so selection boxes will paint in the wrong order).
skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536
);
painter.dispose();
}, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
test('TextPainter - forced line-wrapping with bidi', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.ltr;
painter.text = const TextSpan(
text: 'A\u05D0', // A, Alef
style: TextStyle(fontSize: 10.0),
);
final TextSpan textSpan = painter.text! as TextSpan;
expect(textSpan.text!.length, 2);
painter.layout(maxWidth: 10.0);
for (int index = 0; index <= 2; index += 1) {
expect(
painter.getWordBoundary(const TextPosition(offset: 0)),
const TextRange(start: 0, end: 2),
);
}
expect( // before the A
painter.getOffsetForCaret(const TextPosition(offset: 0, affinity: TextAffinity.upstream), Rect.zero),
Offset.zero,
);
expect( // before the A
painter.getOffsetForCaret(const TextPosition(offset: 0), Rect.zero),
Offset.zero,
);
expect( // between A and Alef, after the A
painter.getOffsetForCaret(const TextPosition(offset: 1, affinity: TextAffinity.upstream), Rect.zero),
const Offset(10.0, 0.0),
);
expect( // between A and Alef, before the Alef
painter.getOffsetForCaret(const TextPosition(offset: 1), Rect.zero),
const Offset(10.0, 10.0),
);
expect( // after the Alef
painter.getOffsetForCaret(const TextPosition(offset: 2, affinity: TextAffinity.upstream), Rect.zero),
const Offset(0.0, 10.0),
);
expect( // To the right of the Alef
painter.getOffsetForCaret(const TextPosition(offset: 2), Rect.zero),
const Offset(10.0, 10.0),
);
expect(
painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 2)),
const <TextBox>[
TextBox.fromLTRBD(0.0, 0.0, 10.0, 10.0, TextDirection.ltr), // A
TextBox.fromLTRBD(0.0, 10.0, 10.0, 20.0, TextDirection.rtl), // Alef
],
);
expect(
painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 1)),
const <TextBox>[
TextBox.fromLTRBD(0.0, 0.0, 10.0, 10.0, TextDirection.ltr), // A
],
);
expect(
painter.getBoxesForSelection(const TextSelection(baseOffset: 1, extentOffset: 2)),
const <TextBox>[
TextBox.fromLTRBD(0.0, 10.0, 10.0, 20.0, TextDirection.rtl), // Alef
],
);
painter.dispose();
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/32238
test('TextPainter - line wrap mid-word', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.ltr;
painter.text = const TextSpan(
style: TextStyle(fontSize: 10.0),
children: <TextSpan>[
TextSpan(
text: 'hello', // width 50
),
TextSpan(
text: 'lovely', // width 120
style: TextStyle(fontSize: 20.0),
),
TextSpan(
text: 'world', // width 50
),
],
);
painter.layout(maxWidth: 110.0); // half-way through "lovely"
expect(
painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 16)),
const <TextBox>[
TextBox.fromLTRBD( 0.0, 8.0, 50.0, 18.0, TextDirection.ltr),
TextBox.fromLTRBD(50.0, 0.0, 110.0, 20.0, TextDirection.ltr),
TextBox.fromLTRBD( 0.0, 20.0, 60.0, 40.0, TextDirection.ltr),
TextBox.fromLTRBD(60.0, 28.0, 110.0, 38.0, TextDirection.ltr),
],
// horizontal offsets are one pixel off in places; vertical offsets are good
skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536
);
painter.dispose();
}, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
test('TextPainter - line wrap mid-word, bidi - LTR base', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.ltr;
painter.text = const TextSpan(
style: TextStyle(fontSize: 10.0),
children: <TextSpan>[
TextSpan(
text: 'hello', // width 50
),
TextSpan(
text: '\u062C\u0645\u064A\u0644', // width 80
style: TextStyle(fontSize: 20.0),
),
TextSpan(
text: 'world', // width 50
),
],
);
painter.layout(maxWidth: 90.0); // half-way through the Arabic word
expect(
painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 16)),
const <TextBox>[
TextBox.fromLTRBD( 0.0, 8.0, 50.0, 18.0, TextDirection.ltr),
TextBox.fromLTRBD(50.0, 0.0, 90.0, 20.0, TextDirection.rtl),
TextBox.fromLTRBD( 0.0, 20.0, 40.0, 40.0, TextDirection.rtl),
TextBox.fromLTRBD(40.0, 28.0, 90.0, 38.0, TextDirection.ltr),
],
// horizontal offsets are one pixel off in places; vertical offsets are good
skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536
);
final List<List<TextBox>> list = <List<TextBox>>[
for (int index = 0; index < 5+4+5; index += 1)
painter.getBoxesForSelection(TextSelection(baseOffset: index, extentOffset: index + 1)),
];
expect(list, const <List<TextBox>>[
<TextBox>[TextBox.fromLTRBD(0.0, 8.0, 10.0, 18.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(10.0, 8.0, 20.0, 18.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(20.0, 8.0, 30.0, 18.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(30.0, 8.0, 40.0, 18.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(40.0, 8.0, 50.0, 18.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(70.0, 0.0, 90.0, 20.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(50.0, 0.0, 70.0, 20.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(20.0, 20.0, 40.0, 40.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(0.0, 20.0, 20.0, 40.0, TextDirection.rtl)],
<TextBox>[TextBox.fromLTRBD(40.0, 28.0, 50.0, 38.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(50.0, 28.0, 60.0, 38.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(60.0, 28.0, 70.0, 38.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(70.0, 28.0, 80.0, 38.0, TextDirection.ltr)],
<TextBox>[TextBox.fromLTRBD(80.0, 28.0, 90.0, 38.0, TextDirection.ltr)],
]);
painter.dispose();
}, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
test('TextPainter - line wrap mid-word, bidi - RTL base', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.rtl;
painter.text = const TextSpan(
style: TextStyle(fontSize: 10.0),
children: <TextSpan>[
TextSpan(
text: 'hello', // width 50
),
TextSpan(
text: '\u062C\u0645\u064A\u0644', // width 80
style: TextStyle(fontSize: 20.0),
),
TextSpan(
text: 'world', // width 50
),
],
);
painter.layout(maxWidth: 90.0); // half-way through the Arabic word
expect(
painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 16)),
const <TextBox>[
TextBox.fromLTRBD(40.0, 8.0, 90.0, 18.0, TextDirection.ltr),
TextBox.fromLTRBD( 0.0, 0.0, 40.0, 20.0, TextDirection.rtl),
TextBox.fromLTRBD(50.0, 20.0, 90.0, 40.0, TextDirection.rtl),
TextBox.fromLTRBD( 0.0, 28.0, 50.0, 38.0, TextDirection.ltr),
],
// Horizontal offsets are currently one pixel off in places; vertical offsets are good.
// The list is currently in the wrong order (so selection boxes will paint in the wrong order).
skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536
);
painter.dispose();
}, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
test('TextPainter - multiple levels', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.rtl;
final String pyramid = rlo(lro(rlo(lro(rlo('')))));
painter.text = TextSpan(
text: pyramid,
style: const TextStyle(fontSize: 10.0),
);
painter.layout();
expect(
painter.getBoxesForSelection(TextSelection(baseOffset: 0, extentOffset: pyramid.length)),
const <TextBox>[
TextBox.fromLTRBD(90.0, 0.0, 100.0, 10.0, TextDirection.rtl), // outer R, start (right)
TextBox.fromLTRBD(10.0, 0.0, 20.0, 10.0, TextDirection.ltr), // level 1 L, start (left)
TextBox.fromLTRBD(70.0, 0.0, 80.0, 10.0, TextDirection.rtl), // level 2 R, start (right)
TextBox.fromLTRBD(30.0, 0.0, 40.0, 10.0, TextDirection.ltr), // level 3 L, start (left)
TextBox.fromLTRBD(40.0, 0.0, 60.0, 10.0, TextDirection.rtl), // inner-most RR
TextBox.fromLTRBD(60.0, 0.0, 70.0, 10.0, TextDirection.ltr), // lever 3 L, end (right)
TextBox.fromLTRBD(20.0, 0.0, 30.0, 10.0, TextDirection.rtl), // level 2 R, end (left)
TextBox.fromLTRBD(80.0, 0.0, 90.0, 10.0, TextDirection.ltr), // level 1 L, end (right)
TextBox.fromLTRBD( 0.0, 0.0, 10.0, 10.0, TextDirection.rtl), // outer R, end (left)
],
// Horizontal offsets are currently one pixel off in places; vertical offsets are good.
// The list is currently in the wrong order (so selection boxes will paint in the wrong order).
// Also currently there's an extraneous box at the start of the list.
skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536
);
painter.dispose();
}, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
test('TextPainter - getPositionForOffset - RTL in LTR', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.ltr;
painter.text = const TextSpan(
text: 'ABC\u05D0\u05D1\u05D2DEF', // A B C Alef Bet Gimel D E F -- but the Hebrew letters are RTL
style: TextStyle(fontSize: 10.0),
);
painter.layout();
// TODO(ianh): Remove the toString()s once https://github.com/flutter/engine/pull/4283 lands
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(0.0, 5.0)).toString(),
const TextPosition(offset: 0).toString(),
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(-100.0, 5.0)).toString(),
const TextPosition(offset: 0).toString(),
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(4.0, 5.0)).toString(),
const TextPosition(offset: 0).toString(),
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(8.0, 5.0)).toString(),
const TextPosition(offset: 1, affinity: TextAffinity.upstream).toString(),
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(12.0, 5.0)).toString(),
const TextPosition(offset: 1).toString(),
// currently we say upstream instead of downstream
skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(28.0, 5.0)).toString(),
const TextPosition(offset: 3, affinity: TextAffinity.upstream).toString(),
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(32.0, 5.0)).toString(),
const TextPosition(offset: 6, affinity: TextAffinity.upstream).toString(),
skip: skipExpectsWithKnownBugs, // this is part of https://github.com/flutter/flutter/issues/11375
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(58.0, 5.0)).toString(),
const TextPosition(offset: 3).toString(),
skip: skipExpectsWithKnownBugs, // this is part of https://github.com/flutter/flutter/issues/11375
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(62.0, 5.0)).toString(),
const TextPosition(offset: 6).toString(),
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(88.0, 5.0)).toString(),
const TextPosition(offset: 9, affinity: TextAffinity.upstream).toString(),
);
expect(
// Aaa Bbb Ccc Gimel Bet Alef Ddd Eee Fff
// ^
painter.getPositionForOffset(const Offset(100.0, 5.0)).toString(),
const TextPosition(offset: 9, affinity: TextAffinity.upstream).toString(),
);
painter.dispose();
}, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
test('TextPainter - getPositionForOffset - LTR in RTL', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.rtl;
painter.text = const TextSpan(
text: '\u05D0\u05D1\u05D2ABC\u05D3\u05D4\u05D5',
style: TextStyle(fontSize: 10.0),
);
painter.layout();
// TODO(ianh): Remove the toString()s once https://github.com/flutter/engine/pull/4283 lands
expect(
// Vav He Dalet Aaa Bbb Ccc Gimel Bet Alef
// ^
painter.getPositionForOffset(const Offset(-4.0, 5.0)).toString(),
const TextPosition(offset: 9, affinity: TextAffinity.upstream).toString(),
);
expect(
// Vav He Dalet Aaa Bbb Ccc Gimel Bet Alef
// ^
painter.getPositionForOffset(const Offset(28.0, 5.0)).toString(),
const TextPosition(offset: 6).toString(),
);
expect(
// Vav He Dalet Aaa Bbb Ccc Gimel Bet Alef
// ^
painter.getPositionForOffset(const Offset(32.0, 5.0)).toString(),
const TextPosition(offset: 3).toString(),
skip: skipExpectsWithKnownBugs, // this is part of https://github.com/flutter/flutter/issues/11375
);
expect(
// Vav He Dalet Aaa Bbb Ccc Gimel Bet Alef
// ^
painter.getPositionForOffset(const Offset(58.0, 5.0)).toString(),
const TextPosition(offset: 6, affinity: TextAffinity.upstream).toString(),
skip: skipExpectsWithKnownBugs, // this is part of https://github.com/flutter/flutter/issues/11375
);
expect(
// Vav He Dalet Aaa Bbb Ccc Gimel Bet Alef
// ^
painter.getPositionForOffset(const Offset(62.0, 5.0)).toString(),
const TextPosition(offset: 3, affinity: TextAffinity.upstream).toString(),
);
painter.dispose();
}, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
test('TextPainter - Spaces', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.ltr;
painter.text = const TextSpan(
text: ' ',
style: TextStyle(fontSize: 100.0),
children: <TextSpan>[
TextSpan(
text: ' ',
style: TextStyle(fontSize: 10.0),
),
TextSpan(
text: ' ',
style: TextStyle(fontSize: 200.0),
),
// Add a non-whitespace character because the renderer's line breaker
// may strip trailing whitespace on a line.
TextSpan(text: 'A'),
],
);
painter.layout();
// This renders as three (invisible) boxes:
//
// |<--------200------->|
// ____________________
// | ^ |
// | : |
// | : |
// | : |
// | : |
// ___________ | : 160 |
// | ^ | | : |
// |<-+-100--->|10| : |
// | : |__| : |
// | : 80 | |8 : |
// _|__v________|__|________v___________| BASELINE
// | ^20 |__|2 ^ |
// |_____v_____| | | |
// | | 40 |
// | | |
// |________v___________|
expect(painter.width, 410.0);
expect(painter.height, 200.0);
expect(painter.computeDistanceToActualBaseline(TextBaseline.alphabetic), moreOrLessEquals(160.0, epsilon: 0.001));
expect(painter.preferredLineHeight, 100.0);
expect(
painter.getBoxesForSelection(const TextSelection(baseOffset: 0, extentOffset: 3)),
const <TextBox>[
TextBox.fromLTRBD( 0.0, 80.0, 100.0, 180.0, TextDirection.ltr),
TextBox.fromLTRBD(100.0, 152.0, 110.0, 162.0, TextDirection.ltr),
TextBox.fromLTRBD(110.0, 0.0, 310.0, 200.0, TextDirection.ltr),
],
// Horizontal offsets are currently one pixel off in places; vertical offsets are good.
skip: skipExpectsWithKnownBugs, // https://github.com/flutter/flutter/issues/87536
);
painter.dispose();
}, skip: skipTestsWithKnownBugs); // https://github.com/flutter/flutter/issues/87536
test('TextPainter - empty text baseline', () {
final TextPainter painter = TextPainter()
..textDirection = TextDirection.ltr;
painter.text = const TextSpan(
text: '',
style: TextStyle(fontFamily: 'FlutterTest', fontSize: 100.0, height: 1.0),
);
painter.layout();
expect(painter.computeDistanceToActualBaseline(TextBaseline.alphabetic), 75.0);
painter.dispose();
});
}
String lro(String s) => '${Unicode.LRO}L${s}L${Unicode.PDF}';
String rlo(String s) => '${Unicode.RLO}R${s}R${Unicode.PDF}';
| flutter/packages/flutter/test/painting/text_painter_rtl_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/text_painter_rtl_test.dart",
"repo_id": "flutter",
"token_count": 13672
} | 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 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Initializing the RendererBinding does not crash when semantics is enabled', () {
try {
MyRenderingFlutterBinding();
} catch (e) {
fail('Initializing the RenderingBinding threw an unexpected error:\n$e');
}
expect(RendererBinding.instance, isA<MyRenderingFlutterBinding>());
expect(SemanticsBinding.instance.semanticsEnabled, isTrue);
});
}
// Binding that pretends the platform had semantics enabled before the binding
// is initialized.
class MyRenderingFlutterBinding extends RenderingFlutterBinding {
@override
bool get semanticsEnabled => true;
}
| flutter/packages/flutter/test/rendering/binding_pipeline_manifold_init_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/binding_pipeline_manifold_init_test.dart",
"repo_id": "flutter",
"token_count": 267
} | 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/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('Overconstrained flex', () {
final RenderDecoratedBox box = RenderDecoratedBox(decoration: const BoxDecoration());
final RenderFlex flex = RenderFlex(textDirection: TextDirection.ltr, children: <RenderBox>[box]);
layout(flex, constraints: const BoxConstraints(
minWidth: 200.0,
maxWidth: 200.0,
minHeight: 200.0,
maxHeight: 200.0,
));
expect(flex.size.width, equals(200.0), reason: 'flex width');
expect(flex.size.height, equals(200.0), reason: 'flex height');
});
test('Inconsequential overflow is ignored', () {
// These values are meant to simulate slight rounding errors in addition
// or subtraction in the layout code for Flex.
const double slightlyLarger = 438.8571428571429;
const double slightlySmaller = 438.85714285714283;
final List<dynamic> exceptions = <dynamic>[];
final FlutterExceptionHandler? oldHandler = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails details) {
exceptions.add(details.exception);
};
const BoxConstraints square = BoxConstraints.tightFor(width: slightlyLarger, height: 100.0);
final RenderConstrainedBox box1 = RenderConstrainedBox(additionalConstraints: square);
final RenderFlex flex = RenderFlex(
textDirection: TextDirection.ltr,
mainAxisSize: MainAxisSize.min,
);
final RenderConstrainedOverflowBox parent = RenderConstrainedOverflowBox(
minWidth: 0.0,
maxWidth: slightlySmaller,
minHeight: 0.0,
maxHeight: 400.0,
child: flex,
);
flex.add(box1);
layout(parent);
expect(flex.size, const Size(slightlySmaller, 100.0));
pumpFrame(phase: EnginePhase.paint);
expect(exceptions, isEmpty);
FlutterError.onError = oldHandler;
});
test('Clip behavior is respected', () {
const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 100.0);
final TestClipPaintingContext context = TestClipPaintingContext();
bool hadErrors = false;
for (final Clip? clip in <Clip?>[null, ...Clip.values]) {
final RenderFlex flex;
switch (clip) {
case Clip.none:
case Clip.hardEdge:
case Clip.antiAlias:
case Clip.antiAliasWithSaveLayer:
flex = RenderFlex(direction: Axis.vertical, children: <RenderBox>[box200x200], clipBehavior: clip!);
case null:
flex = RenderFlex(direction: Axis.vertical, children: <RenderBox>[box200x200]);
}
layout(flex, constraints: viewport, phase: EnginePhase.composite, onErrors: () {
absorbOverflowedErrors();
hadErrors = true;
});
context.paintChild(flex, Offset.zero);
// By default, clipBehavior should be Clip.none
expect(context.clipBehavior, equals(clip ?? Clip.none));
expect(hadErrors, isTrue);
hadErrors = false;
}
});
test('Vertical Overflow', () {
final RenderConstrainedBox flexible = RenderConstrainedBox(
additionalConstraints: const BoxConstraints.expand(),
);
final RenderFlex flex = RenderFlex(
direction: Axis.vertical,
children: <RenderBox>[
RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(height: 200.0)),
flexible,
],
);
final FlexParentData flexParentData = flexible.parentData! as FlexParentData;
flexParentData.flex = 1;
const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 100.0);
layout(flex, constraints: viewport);
expect(flexible.size.height, equals(0.0));
expect(flex.getMinIntrinsicHeight(100.0), equals(200.0));
expect(flex.getMaxIntrinsicHeight(100.0), equals(200.0));
expect(flex.getMinIntrinsicWidth(100.0), equals(0.0));
expect(flex.getMaxIntrinsicWidth(100.0), equals(0.0));
});
test('Horizontal Overflow', () {
final RenderConstrainedBox flexible = RenderConstrainedBox(
additionalConstraints: const BoxConstraints.expand(),
);
final RenderFlex flex = RenderFlex(
textDirection: TextDirection.ltr,
children: <RenderBox>[
RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 200.0)),
flexible,
],
);
final FlexParentData flexParentData = flexible.parentData! as FlexParentData;
flexParentData.flex = 1;
const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 100.0);
layout(flex, constraints: viewport);
expect(flexible.size.width, equals(0.0));
expect(flex.getMinIntrinsicHeight(100.0), equals(0.0));
expect(flex.getMaxIntrinsicHeight(100.0), equals(0.0));
expect(flex.getMinIntrinsicWidth(100.0), equals(200.0));
expect(flex.getMaxIntrinsicWidth(100.0), equals(200.0));
});
test('Vertical Flipped Constraints', () {
final RenderFlex flex = RenderFlex(
direction: Axis.vertical,
children: <RenderBox>[
RenderAspectRatio(aspectRatio: 1.0),
],
);
const BoxConstraints viewport = BoxConstraints(maxHeight: 200.0, maxWidth: 1000.0);
layout(flex, constraints: viewport);
expect(flex.getMaxIntrinsicWidth(200.0), equals(0.0));
});
// We can't write a horizontal version of the above test due to
// RenderAspectRatio being height-in, width-out.
test('Defaults', () {
final RenderFlex flex = RenderFlex();
expect(flex.crossAxisAlignment, equals(CrossAxisAlignment.center));
expect(flex.direction, equals(Axis.horizontal));
expect(flex, hasAGoodToStringDeep);
expect(
flex.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'RenderFlex#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n'
' parentData: MISSING\n'
' constraints: MISSING\n'
' size: MISSING\n'
' direction: horizontal\n'
' mainAxisAlignment: start\n'
' mainAxisSize: max\n'
' crossAxisAlignment: center\n'
' verticalDirection: down\n',
),
);
});
test('Parent data', () {
final RenderDecoratedBox box1 = RenderDecoratedBox(decoration: const BoxDecoration());
final RenderDecoratedBox box2 = RenderDecoratedBox(decoration: const BoxDecoration());
final RenderFlex flex = RenderFlex(textDirection: TextDirection.ltr, children: <RenderBox>[box1, box2]);
layout(flex, constraints: const BoxConstraints(
maxWidth: 100.0,
maxHeight: 100.0,
));
expect(box1.size.width, equals(0.0));
expect(box1.size.height, equals(0.0));
expect(box2.size.width, equals(0.0));
expect(box2.size.height, equals(0.0));
final FlexParentData box2ParentData = box2.parentData! as FlexParentData;
box2ParentData.flex = 1;
flex.markNeedsLayout();
pumpFrame();
expect(box1.size.width, equals(0.0));
expect(box1.size.height, equals(0.0));
expect(box2.size.width, equals(100.0));
expect(box2.size.height, equals(0.0));
});
test('Stretch', () {
final RenderDecoratedBox box1 = RenderDecoratedBox(decoration: const BoxDecoration());
final RenderDecoratedBox box2 = RenderDecoratedBox(decoration: const BoxDecoration());
final RenderFlex flex = RenderFlex(textDirection: TextDirection.ltr);
flex.setupParentData(box2);
final FlexParentData box2ParentData = box2.parentData! as FlexParentData;
box2ParentData.flex = 2;
flex.addAll(<RenderBox>[box1, box2]);
layout(flex, constraints: const BoxConstraints(
maxWidth: 100.0,
maxHeight: 100.0,
));
expect(box1.size.width, equals(0.0));
expect(box1.size.height, equals(0.0));
expect(box2.size.width, equals(100.0));
expect(box2.size.height, equals(0.0));
flex.crossAxisAlignment = CrossAxisAlignment.stretch;
pumpFrame();
expect(box1.size.width, equals(0.0));
expect(box1.size.height, equals(100.0));
expect(box2.size.width, equals(100.0));
expect(box2.size.height, equals(100.0));
flex.direction = Axis.vertical;
pumpFrame();
expect(box1.size.width, equals(100.0));
expect(box1.size.height, equals(0.0));
expect(box2.size.width, equals(100.0));
expect(box2.size.height, equals(100.0));
});
test('Space evenly', () {
final RenderConstrainedBox box1 = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100.0, height: 100.0));
final RenderConstrainedBox box2 = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100.0, height: 100.0));
final RenderConstrainedBox box3 = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100.0, height: 100.0));
final RenderFlex flex = RenderFlex(textDirection: TextDirection.ltr, mainAxisAlignment: MainAxisAlignment.spaceEvenly);
flex.addAll(<RenderBox>[box1, box2, box3]);
layout(flex, constraints: const BoxConstraints(
maxWidth: 500.0,
maxHeight: 400.0,
));
Offset getOffset(RenderBox box) {
final FlexParentData parentData = box.parentData! as FlexParentData;
return parentData.offset;
}
expect(getOffset(box1).dx, equals(50.0));
expect(box1.size.width, equals(100.0));
expect(getOffset(box2).dx, equals(200.0));
expect(box2.size.width, equals(100.0));
expect(getOffset(box3).dx, equals(350.0));
expect(box3.size.width, equals(100.0));
flex.direction = Axis.vertical;
pumpFrame();
expect(getOffset(box1).dy, equals(25.0));
expect(box1.size.height, equals(100.0));
expect(getOffset(box2).dy, equals(150.0));
expect(box2.size.height, equals(100.0));
expect(getOffset(box3).dy, equals(275.0));
expect(box3.size.height, equals(100.0));
});
test('Fit.loose', () {
final RenderConstrainedBox box1 = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100.0, height: 100.0));
final RenderConstrainedBox box2 = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100.0, height: 100.0));
final RenderConstrainedBox box3 = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100.0, height: 100.0));
final RenderFlex flex = RenderFlex(textDirection: TextDirection.ltr, mainAxisAlignment: MainAxisAlignment.spaceBetween);
flex.addAll(<RenderBox>[box1, box2, box3]);
layout(flex, constraints: const BoxConstraints(
maxWidth: 500.0,
maxHeight: 400.0,
));
Offset getOffset(RenderBox box) {
final FlexParentData parentData = box.parentData! as FlexParentData;
return parentData.offset;
}
expect(getOffset(box1).dx, equals(0.0));
expect(box1.size.width, equals(100.0));
expect(getOffset(box2).dx, equals(200.0));
expect(box2.size.width, equals(100.0));
expect(getOffset(box3).dx, equals(400.0));
expect(box3.size.width, equals(100.0));
void setFit(RenderBox box, FlexFit fit) {
final FlexParentData parentData = box.parentData! as FlexParentData;
parentData.flex = 1;
parentData.fit = fit;
}
setFit(box1, FlexFit.loose);
flex.markNeedsLayout();
pumpFrame();
expect(getOffset(box1).dx, equals(0.0));
expect(box1.size.width, equals(100.0));
expect(getOffset(box2).dx, equals(200.0));
expect(box2.size.width, equals(100.0));
expect(getOffset(box3).dx, equals(400.0));
expect(box3.size.width, equals(100.0));
box1.additionalConstraints = const BoxConstraints.tightFor(width: 1000.0, height: 100.0);
pumpFrame();
expect(getOffset(box1).dx, equals(0.0));
expect(box1.size.width, equals(300.0));
expect(getOffset(box2).dx, equals(300.0));
expect(box2.size.width, equals(100.0));
expect(getOffset(box3).dx, equals(400.0));
expect(box3.size.width, equals(100.0));
});
test('Flexible with MainAxisSize.min', () {
final RenderConstrainedBox box1 = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100.0, height: 100.0));
final RenderConstrainedBox box2 = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100.0, height: 100.0));
final RenderConstrainedBox box3 = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 100.0, height: 100.0));
final RenderFlex flex = RenderFlex(
textDirection: TextDirection.ltr,
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
);
flex.addAll(<RenderBox>[box1, box2, box3]);
layout(flex, constraints: const BoxConstraints(
maxWidth: 500.0,
maxHeight: 400.0,
));
Offset getOffset(RenderBox box) {
final FlexParentData parentData = box.parentData! as FlexParentData;
return parentData.offset;
}
expect(getOffset(box1).dx, equals(0.0));
expect(box1.size.width, equals(100.0));
expect(getOffset(box2).dx, equals(100.0));
expect(box2.size.width, equals(100.0));
expect(getOffset(box3).dx, equals(200.0));
expect(box3.size.width, equals(100.0));
expect(flex.size.width, equals(300.0));
void setFit(RenderBox box, FlexFit fit) {
final FlexParentData parentData = box.parentData! as FlexParentData;
parentData.flex = 1;
parentData.fit = fit;
}
setFit(box1, FlexFit.tight);
flex.markNeedsLayout();
pumpFrame();
expect(getOffset(box1).dx, equals(0.0));
expect(box1.size.width, equals(300.0));
expect(getOffset(box2).dx, equals(300.0));
expect(box2.size.width, equals(100.0));
expect(getOffset(box3).dx, equals(400.0));
expect(box3.size.width, equals(100.0));
expect(flex.size.width, equals(500.0));
setFit(box1, FlexFit.loose);
flex.markNeedsLayout();
pumpFrame();
expect(getOffset(box1).dx, equals(0.0));
expect(box1.size.width, equals(100.0));
expect(getOffset(box2).dx, equals(100.0));
expect(box2.size.width, equals(100.0));
expect(getOffset(box3).dx, equals(200.0));
expect(box3.size.width, equals(100.0));
expect(flex.size.width, equals(300.0));
});
test('MainAxisSize.min inside unconstrained', () {
FlutterError.onError = (FlutterErrorDetails details) => throw details.exception;
const BoxConstraints square = BoxConstraints.tightFor(width: 100.0, height: 100.0);
final RenderConstrainedBox box1 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box2 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box3 = RenderConstrainedBox(additionalConstraints: square);
final RenderFlex flex = RenderFlex(
textDirection: TextDirection.ltr,
mainAxisSize: MainAxisSize.min,
);
final RenderConstrainedOverflowBox parent = RenderConstrainedOverflowBox(
minWidth: 0.0,
maxWidth: double.infinity,
minHeight: 0.0,
maxHeight: 400.0,
child: flex,
);
flex.addAll(<RenderBox>[box1, box2, box3]);
layout(parent);
expect(flex.size, const Size(300.0, 100.0));
final FlexParentData box2ParentData = box2.parentData! as FlexParentData;
box2ParentData.flex = 1;
box2ParentData.fit = FlexFit.loose;
flex.markNeedsLayout();
pumpFrame();
expect(flex.size, const Size(300.0, 100.0));
parent.maxWidth = 500.0; // NOW WITH CONSTRAINED BOUNDARIES
pumpFrame();
expect(flex.size, const Size(300.0, 100.0));
flex.mainAxisSize = MainAxisSize.max;
pumpFrame();
expect(flex.size, const Size(500.0, 100.0));
flex.mainAxisSize = MainAxisSize.min;
box2ParentData.fit = FlexFit.tight;
flex.markNeedsLayout();
pumpFrame();
expect(flex.size, const Size(500.0, 100.0));
parent.maxWidth = 505.0;
pumpFrame();
expect(flex.size, const Size(505.0, 100.0));
});
test('MainAxisSize.min inside unconstrained', () {
const BoxConstraints square = BoxConstraints.tightFor(width: 100.0, height: 100.0);
final RenderConstrainedBox box1 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box2 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box3 = RenderConstrainedBox(additionalConstraints: square);
final RenderFlex flex = RenderFlex(
textDirection: TextDirection.ltr,
mainAxisSize: MainAxisSize.min,
);
final RenderConstrainedOverflowBox parent = RenderConstrainedOverflowBox(
minWidth: 0.0,
maxWidth: double.infinity,
minHeight: 0.0,
maxHeight: 400.0,
child: flex,
);
flex.addAll(<RenderBox>[box1, box2, box3]);
final FlexParentData box2ParentData = box2.parentData! as FlexParentData;
box2ParentData.flex = 1;
final List<dynamic> exceptions = <dynamic>[];
layout(parent, onErrors: () {
exceptions.addAll(TestRenderingFlutterBinding.instance.takeAllFlutterExceptions());
});
expect(exceptions, isNotEmpty);
expect(exceptions.first, isFlutterError);
});
test('MainAxisSize.min inside unconstrained', () {
const BoxConstraints square = BoxConstraints.tightFor(width: 100.0, height: 100.0);
final RenderConstrainedBox box1 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box2 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box3 = RenderConstrainedBox(additionalConstraints: square);
final RenderFlex flex = RenderFlex(
textDirection: TextDirection.ltr,
);
final RenderConstrainedOverflowBox parent = RenderConstrainedOverflowBox(
minWidth: 0.0,
maxWidth: double.infinity,
minHeight: 0.0,
maxHeight: 400.0,
child: flex,
);
flex.addAll(<RenderBox>[box1, box2, box3]);
final FlexParentData box2ParentData = box2.parentData! as FlexParentData;
box2ParentData.flex = 1;
box2ParentData.fit = FlexFit.loose;
final List<dynamic> exceptions = <dynamic>[];
layout(parent, onErrors: () {
exceptions.addAll(TestRenderingFlutterBinding.instance.takeAllFlutterExceptions());
});
expect(exceptions, isNotEmpty);
expect(exceptions.first, isFlutterError);
});
test('MainAxisSize.min inside tightly constrained', () {
const BoxConstraints square = BoxConstraints.tightFor(width: 100.0, height: 100.0);
final RenderConstrainedBox box1 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box2 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box3 = RenderConstrainedBox(additionalConstraints: square);
final RenderFlex flex = RenderFlex(
textDirection: TextDirection.rtl,
mainAxisSize: MainAxisSize.min,
);
flex.addAll(<RenderBox>[box1, box2, box3]);
layout(flex);
expect(flex.constraints.hasTightWidth, isTrue);
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 250.0));
expect(box2.localToGlobal(Offset.zero), const Offset(600.0, 250.0));
expect(box3.localToGlobal(Offset.zero), const Offset(500.0, 250.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
});
test('Flex RTL', () {
const BoxConstraints square = BoxConstraints.tightFor(width: 100.0, height: 100.0);
final RenderConstrainedBox box1 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box2 = RenderConstrainedBox(additionalConstraints: square);
final RenderConstrainedBox box3 = RenderConstrainedBox(additionalConstraints: square);
final RenderFlex flex = RenderFlex(textDirection: TextDirection.ltr, children: <RenderBox>[box1, box2, box3]);
layout(flex);
expect(box1.localToGlobal(Offset.zero), const Offset(0.0, 250.0));
expect(box2.localToGlobal(Offset.zero), const Offset(100.0, 250.0));
expect(box3.localToGlobal(Offset.zero), const Offset(200.0, 250.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.mainAxisAlignment = MainAxisAlignment.end;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(500.0, 250.0));
expect(box2.localToGlobal(Offset.zero), const Offset(600.0, 250.0));
expect(box3.localToGlobal(Offset.zero), const Offset(700.0, 250.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.textDirection = TextDirection.rtl;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(200.0, 250.0));
expect(box2.localToGlobal(Offset.zero), const Offset(100.0, 250.0));
expect(box3.localToGlobal(Offset.zero), const Offset(0.0, 250.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.mainAxisAlignment = MainAxisAlignment.start;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 250.0));
expect(box2.localToGlobal(Offset.zero), const Offset(600.0, 250.0));
expect(box3.localToGlobal(Offset.zero), const Offset(500.0, 250.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.crossAxisAlignment = CrossAxisAlignment.start; // vertical direction is down
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 0.0));
expect(box2.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(box3.localToGlobal(Offset.zero), const Offset(500.0, 0.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.crossAxisAlignment = CrossAxisAlignment.end;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 500.0));
expect(box2.localToGlobal(Offset.zero), const Offset(600.0, 500.0));
expect(box3.localToGlobal(Offset.zero), const Offset(500.0, 500.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.verticalDirection = VerticalDirection.up;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 0.0));
expect(box2.localToGlobal(Offset.zero), const Offset(600.0, 0.0));
expect(box3.localToGlobal(Offset.zero), const Offset(500.0, 0.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.crossAxisAlignment = CrossAxisAlignment.start;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 500.0));
expect(box2.localToGlobal(Offset.zero), const Offset(600.0, 500.0));
expect(box3.localToGlobal(Offset.zero), const Offset(500.0, 500.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.direction = Axis.vertical; // and main=start, cross=start, up, rtl
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 500.0));
expect(box2.localToGlobal(Offset.zero), const Offset(700.0, 400.0));
expect(box3.localToGlobal(Offset.zero), const Offset(700.0, 300.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.crossAxisAlignment = CrossAxisAlignment.end;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(0.0, 500.0));
expect(box2.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(box3.localToGlobal(Offset.zero), const Offset(0.0, 300.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.crossAxisAlignment = CrossAxisAlignment.stretch;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(0.0, 500.0));
expect(box2.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(box3.localToGlobal(Offset.zero), const Offset(0.0, 300.0));
expect(box1.size, const Size(800.0, 100.0));
expect(box2.size, const Size(800.0, 100.0));
expect(box3.size, const Size(800.0, 100.0));
flex.textDirection = TextDirection.ltr;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(0.0, 500.0));
expect(box2.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(box3.localToGlobal(Offset.zero), const Offset(0.0, 300.0));
expect(box1.size, const Size(800.0, 100.0));
expect(box2.size, const Size(800.0, 100.0));
expect(box3.size, const Size(800.0, 100.0));
flex.crossAxisAlignment = CrossAxisAlignment.start;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(0.0, 500.0));
expect(box2.localToGlobal(Offset.zero), const Offset(0.0, 400.0));
expect(box3.localToGlobal(Offset.zero), const Offset(0.0, 300.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.crossAxisAlignment = CrossAxisAlignment.end;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 500.0));
expect(box2.localToGlobal(Offset.zero), const Offset(700.0, 400.0));
expect(box3.localToGlobal(Offset.zero), const Offset(700.0, 300.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.verticalDirection = VerticalDirection.down;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 0.0));
expect(box2.localToGlobal(Offset.zero), const Offset(700.0, 100.0));
expect(box3.localToGlobal(Offset.zero), const Offset(700.0, 200.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
flex.mainAxisAlignment = MainAxisAlignment.end;
pumpFrame();
expect(box1.localToGlobal(Offset.zero), const Offset(700.0, 300.0));
expect(box2.localToGlobal(Offset.zero), const Offset(700.0, 400.0));
expect(box3.localToGlobal(Offset.zero), const Offset(700.0, 500.0));
expect(box1.size, const Size(100.0, 100.0));
expect(box2.size, const Size(100.0, 100.0));
expect(box3.size, const Size(100.0, 100.0));
});
test('Intrinsics throw if alignment is baseline', () {
final RenderDecoratedBox box = RenderDecoratedBox(
decoration: const BoxDecoration(),
);
final RenderFlex flex = RenderFlex(
textDirection: TextDirection.ltr,
children: <RenderBox>[box],
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
);
layout(flex, constraints: const BoxConstraints(
minWidth: 200.0, maxWidth: 200.0, minHeight: 200.0, maxHeight: 200.0,
));
final Matcher cannotCalculateIntrinsics = throwsA(isAssertionError.having(
(AssertionError e) => e.message,
'message',
'Intrinsics are not available for CrossAxisAlignment.baseline.',
));
expect(() => flex.getMaxIntrinsicHeight(100), cannotCalculateIntrinsics);
expect(() => flex.getMinIntrinsicHeight(100), cannotCalculateIntrinsics);
expect(() => flex.getMaxIntrinsicWidth(100), cannotCalculateIntrinsics);
expect(() => flex.getMinIntrinsicWidth(100), cannotCalculateIntrinsics);
});
test('Can call methods that check overflow even if overflow value is not set', () {
final List<dynamic> exceptions = <dynamic>[];
final RenderFlex flex = RenderFlex(children: const <RenderBox>[]);
// This forces a check for _hasOverflow
expect(flex.toStringShort(), isNot(contains('OVERFLOWING')));
layout(flex, phase: EnginePhase.paint, onErrors: () {
exceptions.addAll(TestRenderingFlutterBinding.instance.takeAllFlutterExceptions());
});
// We expect the RenderFlex to throw during performLayout() for not having
// a text direction, thus leaving it with a null overflow value. It'll then
// try to paint(), which also checks _hasOverflow, and it should be able to
// do so without an ancillary error.
expect(exceptions, hasLength(1));
// ignore: avoid_dynamic_calls
expect(exceptions.first.message, isNot(contains('Null check operator')));
});
}
| flutter/packages/flutter/test/rendering/flex_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/flex_test.dart",
"repo_id": "flutter",
"token_count": 11161
} | 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 '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';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('PipelineOwner dispatches memory events', () async {
await expectLater(
await memoryEvents(() => PipelineOwner().dispose(), PipelineOwner),
areCreateAndDispose,
);
});
test('ensure frame is scheduled for markNeedsSemanticsUpdate', () {
// Initialize all bindings because owner.flushSemantics() requires a window
final TestRenderObject renderObject = TestRenderObject();
int onNeedVisualUpdateCallCount = 0;
final PipelineOwner owner = PipelineOwner(
onNeedVisualUpdate: () {
onNeedVisualUpdateCallCount +=1;
},
onSemanticsUpdate: (ui.SemanticsUpdate update) {}
);
owner.ensureSemantics();
renderObject.attach(owner);
renderObject.layout(const BoxConstraints.tightForFinite()); // semantics are only calculated if layout information is up to date.
owner.flushSemantics();
expect(onNeedVisualUpdateCallCount, 1);
renderObject.markNeedsSemanticsUpdate();
expect(onNeedVisualUpdateCallCount, 2);
});
test('onSemanticsUpdate is called during flushSemantics.', () {
int onSemanticsUpdateCallCount = 0;
final PipelineOwner owner = PipelineOwner(
onSemanticsUpdate: (ui.SemanticsUpdate update) {
onSemanticsUpdateCallCount += 1;
},
);
owner.ensureSemantics();
expect(onSemanticsUpdateCallCount, 0);
final TestRenderObject renderObject = TestRenderObject();
renderObject.attach(owner);
renderObject.layout(const BoxConstraints.tightForFinite());
owner.flushSemantics();
expect(onSemanticsUpdateCallCount, 1);
});
test('Enabling semantics without configuring onSemanticsUpdate is invalid.', () {
final PipelineOwner pipelineOwner = PipelineOwner();
expect(() => pipelineOwner.ensureSemantics(), throwsAssertionError);
});
test('onSemanticsUpdate during sendSemanticsUpdate.', () {
int onSemanticsUpdateCallCount = 0;
final SemanticsOwner owner = SemanticsOwner(
onSemanticsUpdate: (ui.SemanticsUpdate update) {
onSemanticsUpdateCallCount += 1;
},
);
final SemanticsNode node = SemanticsNode.root(owner: owner);
node.rect = Rect.largest;
expect(onSemanticsUpdateCallCount, 0);
owner.sendSemanticsUpdate();
expect(onSemanticsUpdateCallCount, 1);
});
test('detached RenderObject does not do semantics', () {
final TestRenderObject renderObject = TestRenderObject();
expect(renderObject.attached, isFalse);
expect(renderObject.describeSemanticsConfigurationCallCount, 0);
renderObject.markNeedsSemanticsUpdate();
expect(renderObject.describeSemanticsConfigurationCallCount, 0);
});
test('ensure errors processing render objects are well formatted', () {
late FlutterErrorDetails errorDetails;
final FlutterExceptionHandler? oldHandler = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails details) {
errorDetails = details;
};
final PipelineOwner owner = PipelineOwner();
final TestThrowingRenderObject renderObject = TestThrowingRenderObject();
try {
renderObject.attach(owner);
renderObject.layout(const BoxConstraints());
} finally {
FlutterError.onError = oldHandler;
}
expect(errorDetails, isNotNull);
expect(errorDetails.stack, isNotNull);
// Check the ErrorDetails without the stack trace
final List<String> lines = errorDetails.toString().split('\n');
// The lines in the middle of the error message contain the stack trace
// which will change depending on where the test is run.
expect(lines.length, greaterThan(8));
expect(
lines.take(4).join('\n'),
equalsIgnoringHashCodes(
'══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞══════════════════════\n'
'The following assertion was thrown during performLayout():\n'
'TestThrowingRenderObject does not support performLayout.\n',
),
);
expect(
lines.getRange(lines.length - 8, lines.length).join('\n'),
equalsIgnoringHashCodes(
'\n'
'The following RenderObject was being processed when the exception was fired:\n'
' TestThrowingRenderObject#00000 NEEDS-PAINT:\n'
' parentData: MISSING\n'
' constraints: BoxConstraints(unconstrained)\n'
'This RenderObject has no descendants.\n'
'═════════════════════════════════════════════════════════════════\n',
),
);
});
test('ContainerParentDataMixin requires nulled out pointers to siblings before detach', () {
expect(() => TestParentData().detach(), isNot(throwsAssertionError));
final TestParentData data1 = TestParentData()
..nextSibling = RenderOpacity()
..previousSibling = RenderOpacity();
expect(() => data1.detach(), throwsAssertionError);
final TestParentData data2 = TestParentData()
..previousSibling = RenderOpacity();
expect(() => data2.detach(), throwsAssertionError);
final TestParentData data3 = TestParentData()
..nextSibling = RenderOpacity();
expect(() => data3.detach(), throwsAssertionError);
});
test('RenderObject.getTransformTo asserts is argument is not descendant', () {
final PipelineOwner owner = PipelineOwner();
final TestRenderObject renderObject1 = TestRenderObject();
renderObject1.attach(owner);
final TestRenderObject renderObject2 = TestRenderObject();
renderObject2.attach(owner);
expect(() => renderObject1.getTransformTo(renderObject2), throwsAssertionError);
});
test('PaintingContext.pushClipRect reuses the layer', () {
_testPaintingContextLayerReuse<ClipRectLayer>((PaintingContextCallback painter, PaintingContext context, Offset offset, Layer? oldLayer) {
return context.pushClipRect(true, offset, Rect.zero, painter, oldLayer: oldLayer as ClipRectLayer?);
});
});
test('PaintingContext.pushClipRRect reuses the layer', () {
_testPaintingContextLayerReuse<ClipRRectLayer>((PaintingContextCallback painter, PaintingContext context, Offset offset, Layer? oldLayer) {
return context.pushClipRRect(true, offset, Rect.zero, RRect.fromRectAndRadius(Rect.zero, const Radius.circular(1.0)), painter, oldLayer: oldLayer as ClipRRectLayer?);
});
});
test('PaintingContext.pushClipPath reuses the layer', () {
_testPaintingContextLayerReuse<ClipPathLayer>((PaintingContextCallback painter, PaintingContext context, Offset offset, Layer? oldLayer) {
return context.pushClipPath(true, offset, Rect.zero, Path(), painter, oldLayer: oldLayer as ClipPathLayer?);
});
});
test('PaintingContext.pushColorFilter reuses the layer', () {
_testPaintingContextLayerReuse<ColorFilterLayer>((PaintingContextCallback painter, PaintingContext context, Offset offset, Layer? oldLayer) {
return context.pushColorFilter(offset, const ColorFilter.mode(Color.fromRGBO(0, 0, 0, 1.0), BlendMode.clear), painter, oldLayer: oldLayer as ColorFilterLayer?);
});
});
test('PaintingContext.pushTransform reuses the layer', () {
_testPaintingContextLayerReuse<TransformLayer>((PaintingContextCallback painter, PaintingContext context, Offset offset, Layer? oldLayer) {
return context.pushTransform(true, offset, Matrix4.identity(), painter, oldLayer: oldLayer as TransformLayer?);
});
});
test('PaintingContext.pushOpacity reuses the layer', () {
_testPaintingContextLayerReuse<OpacityLayer>((PaintingContextCallback painter, PaintingContext context, Offset offset, Layer? oldLayer) {
return context.pushOpacity(offset, 100, painter, oldLayer: oldLayer as OpacityLayer?);
});
});
test('RenderObject.dispose sets debugDisposed to true', () {
final TestRenderObject renderObject = TestRenderObject();
expect(renderObject.debugDisposed, false);
renderObject.dispose();
expect(renderObject.debugDisposed, true);
expect(renderObject.toStringShort(), contains('DISPOSED'));
});
test('Leader layer can switch to a different render object within one frame', () {
List<FlutterErrorDetails?>? caughtErrors;
TestRenderingFlutterBinding.instance.onErrors = () {
caughtErrors = TestRenderingFlutterBinding.instance.takeAllFlutterErrorDetails().toList();
};
final LayerLink layerLink = LayerLink();
// renderObject1 paints the leader layer first.
final LeaderLayerRenderObject renderObject1 = LeaderLayerRenderObject();
renderObject1.layerLink = layerLink;
renderObject1.attach(TestRenderingFlutterBinding.instance.pipelineOwner);
final OffsetLayer rootLayer1 = OffsetLayer();
rootLayer1.attach(renderObject1);
renderObject1.scheduleInitialPaint(rootLayer1);
renderObject1.layout(const BoxConstraints.tightForFinite());
final LeaderLayerRenderObject renderObject2 = LeaderLayerRenderObject();
final OffsetLayer rootLayer2 = OffsetLayer();
rootLayer2.attach(renderObject2);
renderObject2.attach(TestRenderingFlutterBinding.instance.pipelineOwner);
renderObject2.scheduleInitialPaint(rootLayer2);
renderObject2.layout(const BoxConstraints.tightForFinite());
TestRenderingFlutterBinding.instance.pumpCompleteFrame();
// Swap the layer link to renderObject2 in the same frame
renderObject1.layerLink = null;
renderObject1.markNeedsPaint();
renderObject2.layerLink = layerLink;
renderObject2.markNeedsPaint();
TestRenderingFlutterBinding.instance.pumpCompleteFrame();
// Swap the layer link to renderObject1 in the same frame
renderObject1.layerLink = layerLink;
renderObject1.markNeedsPaint();
renderObject2.layerLink = null;
renderObject2.markNeedsPaint();
TestRenderingFlutterBinding.instance.pumpCompleteFrame();
TestRenderingFlutterBinding.instance.onErrors = null;
expect(caughtErrors, isNull);
});
test('Leader layer append to two render objects does crash', () {
List<FlutterErrorDetails?>? caughtErrors;
TestRenderingFlutterBinding.instance.onErrors = () {
caughtErrors = TestRenderingFlutterBinding.instance.takeAllFlutterErrorDetails().toList();
};
final LayerLink layerLink = LayerLink();
// renderObject1 paints the leader layer first.
final LeaderLayerRenderObject renderObject1 = LeaderLayerRenderObject();
renderObject1.layerLink = layerLink;
renderObject1.attach(TestRenderingFlutterBinding.instance.pipelineOwner);
final OffsetLayer rootLayer1 = OffsetLayer();
rootLayer1.attach(renderObject1);
renderObject1.scheduleInitialPaint(rootLayer1);
renderObject1.layout(const BoxConstraints.tightForFinite());
final LeaderLayerRenderObject renderObject2 = LeaderLayerRenderObject();
renderObject2.layerLink = layerLink;
final OffsetLayer rootLayer2 = OffsetLayer();
rootLayer2.attach(renderObject2);
renderObject2.attach(TestRenderingFlutterBinding.instance.pipelineOwner);
renderObject2.scheduleInitialPaint(rootLayer2);
renderObject2.layout(const BoxConstraints.tightForFinite());
TestRenderingFlutterBinding.instance.pumpCompleteFrame();
TestRenderingFlutterBinding.instance.onErrors = null;
expect(caughtErrors!.isNotEmpty, isTrue);
});
test('RenderObject.dispose null the layer on repaint boundaries', () {
final TestRenderObject renderObject = TestRenderObject(allowPaintBounds: true);
// Force a layer to get set.
renderObject.isRepaintBoundary = true;
PaintingContext.repaintCompositedChild(renderObject, debugAlsoPaintedParent: true);
expect(renderObject.debugLayer, isA<OffsetLayer>());
// Dispose with repaint boundary still being true.
renderObject.dispose();
expect(renderObject.debugLayer, null);
});
test('RenderObject.dispose nulls the layer on non-repaint boundaries', () {
final TestRenderObject renderObject = TestRenderObject(allowPaintBounds: true);
// Force a layer to get set.
renderObject.isRepaintBoundary = true;
PaintingContext.repaintCompositedChild(renderObject, debugAlsoPaintedParent: true);
// Dispose with repaint boundary being false.
renderObject.isRepaintBoundary = false;
renderObject.dispose();
expect(renderObject.debugLayer, null);
});
test('Add composition callback works', () {
final ContainerLayer root = ContainerLayer();
final PaintingContext context = PaintingContext(root, Rect.zero);
bool calledBack = false;
final TestObservingRenderObject object = TestObservingRenderObject((Layer layer) {
expect(layer, root);
calledBack = true;
});
expect(calledBack, false);
object.paint(context, Offset.zero);
expect(calledBack, false);
root.buildScene(ui.SceneBuilder()).dispose();
expect(calledBack, true);
});
}
class TestObservingRenderObject extends RenderBox {
TestObservingRenderObject(this.callback);
final CompositionCallback callback;
@override
bool get sizedByParent => true;
@override
void paint(PaintingContext context, Offset offset) {
context.addCompositionCallback(callback);
}
}
// Tests the create-update cycle by pumping two frames. The first frame has no
// prior layer and forces the painting context to create a new one. The second
// frame reuses the layer painted on the first frame.
void _testPaintingContextLayerReuse<L extends Layer>(_LayerTestPaintCallback painter) {
final _TestCustomLayerBox box = _TestCustomLayerBox(painter);
layout(box, phase: EnginePhase.paint);
// Force a repaint. Otherwise, pumpFrame is a noop.
box.markNeedsPaint();
pumpFrame(phase: EnginePhase.paint);
expect(box.paintedLayers, hasLength(2));
expect(box.paintedLayers[0], isA<L>());
expect(box.paintedLayers[0], same(box.paintedLayers[1]));
}
typedef _LayerTestPaintCallback = Layer? Function(PaintingContextCallback painter, PaintingContext context, Offset offset, Layer? oldLayer);
class _TestCustomLayerBox extends RenderBox {
_TestCustomLayerBox(this.painter);
final _LayerTestPaintCallback painter;
final List<Layer> paintedLayers = <Layer>[];
@override
bool get isRepaintBoundary => false;
@override
void performLayout() {
size = constraints.smallest;
}
@override
void paint(PaintingContext context, Offset offset) {
final Layer paintedLayer = painter(super.paint, context, offset, layer)!;
paintedLayers.add(paintedLayer);
layer = paintedLayer as ContainerLayer;
}
}
class TestParentData extends ParentData with ContainerParentDataMixin<RenderBox> { }
class TestRenderObject extends RenderObject {
TestRenderObject({this.allowPaintBounds = false});
final bool allowPaintBounds;
@override
bool isRepaintBoundary = false;
@override
void debugAssertDoesMeetConstraints() { }
@override
Rect get paintBounds {
assert(allowPaintBounds); // For some tests, this should not get called.
return Rect.zero;
}
@override
void performLayout() { }
@override
void performResize() { }
@override
Rect get semanticBounds => const Rect.fromLTWH(0.0, 0.0, 10.0, 20.0);
int describeSemanticsConfigurationCallCount = 0;
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
config.isSemanticBoundary = true;
describeSemanticsConfigurationCallCount++;
}
}
class LeaderLayerRenderObject extends RenderObject {
LeaderLayerRenderObject();
LayerLink? layerLink;
@override
bool isRepaintBoundary = true;
@override
void debugAssertDoesMeetConstraints() { }
@override
Rect get paintBounds {
return Rect.zero;
}
@override
void paint(PaintingContext context, Offset offset) {
if (layerLink != null) {
context.pushLayer(LeaderLayer(link: layerLink!), super.paint, offset);
}
}
@override
void performLayout() { }
@override
void performResize() { }
@override
Rect get semanticBounds => const Rect.fromLTWH(0.0, 0.0, 10.0, 20.0);
}
class TestThrowingRenderObject extends RenderObject {
@override
void performLayout() {
throw FlutterError('TestThrowingRenderObject does not support performLayout.');
}
@override
void debugAssertDoesMeetConstraints() { }
@override
Rect get paintBounds {
assert(false); // The test shouldn't call this.
return Rect.zero;
}
@override
void performResize() { }
@override
Rect get semanticBounds {
assert(false); // The test shouldn't call this.
return Rect.zero;
}
}
| flutter/packages/flutter/test/rendering/object_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/object_test.dart",
"repo_id": "flutter",
"token_count": 5407
} | 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/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('TableBorder constructor', () {
const TableBorder border1 = TableBorder(
left: BorderSide(),
right: BorderSide(color: Color(0xFF00FF00)),
verticalInside: BorderSide(),
);
expect(border1.top, BorderSide.none);
expect(border1.right, const BorderSide(color: Color(0xFF00FF00)));
expect(border1.bottom, BorderSide.none);
expect(border1.left, const BorderSide());
expect(border1.horizontalInside, BorderSide.none);
expect(border1.verticalInside, const BorderSide());
expect(border1.dimensions, const EdgeInsets.symmetric(horizontal: 1.0));
expect(border1.isUniform, isFalse);
expect(border1.scale(2.0), const TableBorder(
left: BorderSide(width: 2.0),
right: BorderSide(width: 2.0, color: Color(0xFF00FF00)),
verticalInside: BorderSide(width: 2.0),
));
});
test('TableBorder.all constructor', () {
final TableBorder border2 = TableBorder.all(
width: 2.0,
color: const Color(0xFF00FFFF),
);
expect(border2.top, const BorderSide(width: 2.0, color: Color(0xFF00FFFF)));
expect(border2.right, const BorderSide(width: 2.0, color: Color(0xFF00FFFF)));
expect(border2.bottom, const BorderSide(width: 2.0, color: Color(0xFF00FFFF)));
expect(border2.left, const BorderSide(width: 2.0, color: Color(0xFF00FFFF)));
expect(border2.horizontalInside, const BorderSide(width: 2.0, color: Color(0xFF00FFFF)));
expect(border2.verticalInside, const BorderSide(width: 2.0, color: Color(0xFF00FFFF)));
expect(border2.dimensions, const EdgeInsets.symmetric(horizontal: 2.0, vertical: 2.0));
expect(border2.isUniform, isTrue);
expect(border2.scale(0.5), TableBorder.all(color: const Color(0xFF00FFFF)));
});
test('TableBorder.symmetric constructor', () {
const TableBorder border3 = TableBorder.symmetric(
inside: BorderSide(width: 3.0),
outside: BorderSide(color: Color(0xFFFF0000)),
);
expect(border3.top, const BorderSide(color: Color(0xFFFF0000)));
expect(border3.right, const BorderSide(color: Color(0xFFFF0000)));
expect(border3.bottom, const BorderSide(color: Color(0xFFFF0000)));
expect(border3.left, const BorderSide(color: Color(0xFFFF0000)));
expect(border3.horizontalInside, const BorderSide(width: 3.0));
expect(border3.verticalInside, const BorderSide(width: 3.0));
expect(border3.dimensions, const EdgeInsets.symmetric(horizontal: 1.0, vertical: 1.0));
expect(border3.isUniform, isFalse);
expect(border3.scale(0.0), const TableBorder.symmetric(
outside: BorderSide(width: 0.0, color: Color(0xFFFF0000), style: BorderStyle.none),
));
});
test('TableBorder.lerp', () {
const BorderSide side1 = BorderSide(color: Color(0x00000001));
const BorderSide side2 = BorderSide(width: 2.0, color: Color(0x00000002));
const BorderSide side3 = BorderSide(width: 3.0, color: Color(0x00000003));
const BorderSide side4 = BorderSide(width: 4.0, color: Color(0x00000004));
const BorderSide side5 = BorderSide(width: 5.0, color: Color(0x00000005));
const BorderSide side6 = BorderSide(width: 6.0, color: Color(0x00000006));
const TableBorder tableA = TableBorder(
top: side1,
right: side2,
bottom: side3,
left: side4,
horizontalInside: side5,
verticalInside: side6,
);
expect(tableA.isUniform, isFalse);
expect(tableA.dimensions, const EdgeInsets.fromLTRB(4.0, 1.0, 2.0, 3.0));
final TableBorder tableB = TableBorder(
top: side1.scale(2.0),
right: side2.scale(2.0),
bottom: side3.scale(2.0),
left: side4.scale(2.0),
horizontalInside: side5.scale(2.0),
verticalInside: side6.scale(2.0),
);
expect(tableB.isUniform, isFalse);
expect(tableB.dimensions, const EdgeInsets.fromLTRB(4.0, 1.0, 2.0, 3.0) * 2.0);
final TableBorder tableC = TableBorder(
top: side1.scale(3.0),
right: side2.scale(3.0),
bottom: side3.scale(3.0),
left: side4.scale(3.0),
horizontalInside: side5.scale(3.0),
verticalInside: side6.scale(3.0),
);
expect(tableC.isUniform, isFalse);
expect(tableC.dimensions, const EdgeInsets.fromLTRB(4.0, 1.0, 2.0, 3.0) * 3.0);
expect(TableBorder.lerp(tableA, tableC, 0.5), tableB);
expect(TableBorder.lerp(tableA, tableB, 2.0), tableC);
expect(TableBorder.lerp(tableB, tableC, -1.0), tableA);
expect(TableBorder.lerp(tableA, tableC, 0.9195)!.isUniform, isFalse);
expect(
TableBorder.lerp(tableA, tableC, 0.9195)!.dimensions,
EdgeInsets.lerp(tableA.dimensions, tableC.dimensions, 0.9195),
);
});
test('TableBorder.lerp identical a,b', () {
expect(TableBorder.lerp(null, null, 0), null);
const TableBorder border = TableBorder();
expect(identical(TableBorder.lerp(border, border, 0.5), border), true);
});
test('TableBorder.lerp with nulls', () {
final TableBorder table2 = TableBorder.all(width: 2.0);
final TableBorder table1 = TableBorder.all();
expect(TableBorder.lerp(table2, null, 0.5), table1);
expect(TableBorder.lerp(null, table2, 0.5), table1);
expect(TableBorder.lerp(null, null, 0.5), null);
});
test('TableBorder Object API', () {
expect(const TableBorder(), isNot(1.0));
expect(const TableBorder().hashCode, isNot(const TableBorder(top: BorderSide(width: 0.0)).hashCode));
});
test('TableBorder Object API', () {
final String none = BorderSide.none.toString();
final String zeroRadius = BorderRadius.zero.toString();
expect(const TableBorder().toString(), 'TableBorder($none, $none, $none, $none, $none, $none, $zeroRadius)');
});
test('TableBorder.all with a borderRadius', () {
final TableBorder tableA = TableBorder.all(borderRadius: const BorderRadius.all(Radius.circular(8.0)));
expect(tableA.borderRadius, const BorderRadius.all(Radius.circular(8.0)));
});
}
| flutter/packages/flutter/test/rendering/table_border_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/table_border_test.dart",
"repo_id": "flutter",
"token_count": 2371
} | 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/scheduler.dart';
@Deprecated('scheduler_tester is not compatible with dart:async') // flutter_ignore: deprecation_syntax (see analyze.dart)
class Future { } // so that people can't import us and dart:async
void tick(Duration duration) {
// We don't bother running microtasks between these two calls
// because we don't use Futures in these tests and so don't care.
SchedulerBinding.instance.handleBeginFrame(duration);
SchedulerBinding.instance.handleDrawFrame();
}
| flutter/packages/flutter/test/scheduler/scheduler_tester.dart/0 | {
"file_path": "flutter/packages/flutter/test/scheduler/scheduler_tester.dart",
"repo_id": "flutter",
"token_count": 188
} | 681 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final List<MethodCall> log = <MethodCall>[];
Future<void> verify(AsyncCallback test, List<Object> expectations) async {
log.clear();
await test();
expect(log, expectations);
}
group('not on web', () {
test('disableContextMenu asserts', () async {
try {
BrowserContextMenu.disableContextMenu();
} catch (error) {
expect(error, isAssertionError);
}
});
test('enableContextMenu asserts', () async {
try {
BrowserContextMenu.enableContextMenu();
} catch (error) {
expect(error, isAssertionError);
}
});
},
skip: kIsWeb, // [intended]
);
group('on web', () {
group('disableContextMenu', () {
// Make sure the context menu is enabled (default) after the test.
tearDown(() async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, (MethodCall methodCall) {
return null;
});
await BrowserContextMenu.enableContextMenu();
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, null);
});
test('disableContextMenu calls its platform channel method', () async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await verify(BrowserContextMenu.disableContextMenu, <Object>[
isMethodCall('disableContextMenu', arguments: null),
]);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, null);
});
});
group('enableContextMenu', () {
test('enableContextMenu calls its platform channel method', () async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await verify(BrowserContextMenu.enableContextMenu, <Object>[
isMethodCall('enableContextMenu', arguments: null),
]);
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.contextMenu, null);
});
});
},
skip: !kIsWeb, // [intended]
);
}
| flutter/packages/flutter/test/services/browser_context_menu_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/browser_context_menu_test.dart",
"repo_id": "flutter",
"token_count": 1010
} | 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/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('MouseTrackerAnnotation has correct toString', () {
final MouseTrackerAnnotation annotation1 = MouseTrackerAnnotation(
onEnter: (_) {},
onExit: (_) {},
);
expect(
annotation1.toString(),
equals('MouseTrackerAnnotation#${shortHash(annotation1)}(callbacks: [enter, exit])'),
);
const MouseTrackerAnnotation annotation2 = MouseTrackerAnnotation();
expect(
annotation2.toString(),
equals('MouseTrackerAnnotation#${shortHash(annotation2)}(callbacks: <none>)'),
);
final MouseTrackerAnnotation annotation3 = MouseTrackerAnnotation(
onEnter: (_) {},
cursor: SystemMouseCursors.grab,
);
expect(
annotation3.toString(),
equals('MouseTrackerAnnotation#${shortHash(annotation3)}(callbacks: [enter], cursor: SystemMouseCursor(grab))'),
);
});
}
| flutter/packages/flutter/test/services/mouse_tracking_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/mouse_tracking_test.dart",
"repo_id": "flutter",
"token_count": 397
} | 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 '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('TextSelection', () {
test('The invalid selection is a singleton', () {
const TextSelection invalidSelection1 = TextSelection(
baseOffset: -1,
extentOffset: 0,
isDirectional: true,
);
const TextSelection invalidSelection2 = TextSelection(baseOffset: 123,
extentOffset: -1,
affinity: TextAffinity.upstream,
);
expect(invalidSelection1, invalidSelection2);
expect(invalidSelection1.hashCode, invalidSelection2.hashCode);
});
test('TextAffinity does not affect equivalence when the selection is not collapsed', () {
const TextSelection selection1 = TextSelection(
baseOffset: 1,
extentOffset: 2,
);
const TextSelection selection2 = TextSelection(
baseOffset: 1,
extentOffset: 2,
affinity: TextAffinity.upstream,
);
expect(selection1, selection2);
expect(selection1.hashCode, selection2.hashCode);
});
});
group('TextEditingValue', () {
group('replaced', () {
const String testText = 'From a false proposition, anything follows.';
test('selection deletion', () {
const TextSelection selection = TextSelection(baseOffset: 5, extentOffset: 13);
expect(
const TextEditingValue(text: testText, selection: selection).replaced(selection, ''),
const TextEditingValue(text: 'From proposition, anything follows.', selection: TextSelection.collapsed(offset: 5)),
);
});
test('reversed selection deletion', () {
const TextSelection selection = TextSelection(baseOffset: 13, extentOffset: 5);
expect(
const TextEditingValue(text: testText, selection: selection).replaced(selection, ''),
const TextEditingValue(text: 'From proposition, anything follows.', selection: TextSelection.collapsed(offset: 5)),
);
});
test('insert', () {
const TextSelection selection = TextSelection.collapsed(offset: 5);
expect(
const TextEditingValue(text: testText, selection: selection).replaced(selection, 'AA'),
const TextEditingValue(
text: 'From AAa false proposition, anything follows.',
// The caret moves to the end of the text inserted.
selection: TextSelection.collapsed(offset: 7),
),
);
});
test('replace before selection', () {
const TextSelection selection = TextSelection(baseOffset: 13, extentOffset: 5);
expect(
// From |a false |proposition, anything follows.
// Replace the first whitespace with "AA".
const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 4, end: 5), 'AA'),
const TextEditingValue(text: 'FromAAa false proposition, anything follows.', selection: TextSelection(baseOffset: 14, extentOffset: 6)),
);
});
test('replace after selection', () {
const TextSelection selection = TextSelection(baseOffset: 13, extentOffset: 5);
expect(
// From |a false |proposition, anything follows.
// replace the first "p" with "AA".
const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 13, end: 14), 'AA'),
const TextEditingValue(text: 'From a false AAroposition, anything follows.', selection: selection),
);
});
test('replace inside selection - start boundary', () {
const TextSelection selection = TextSelection(baseOffset: 13, extentOffset: 5);
expect(
// From |a false |proposition, anything follows.
// replace the first "a" with "AA".
const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 5, end: 6), 'AA'),
const TextEditingValue(text: 'From AA false proposition, anything follows.', selection: TextSelection(baseOffset: 14, extentOffset: 5)),
);
});
test('replace inside selection - end boundary', () {
const TextSelection selection = TextSelection(baseOffset: 13, extentOffset: 5);
expect(
// From |a false |proposition, anything follows.
// replace the second whitespace with "AA".
const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 12, end: 13), 'AA'),
const TextEditingValue(text: 'From a falseAAproposition, anything follows.', selection: TextSelection(baseOffset: 14, extentOffset: 5)),
);
});
test('delete after selection', () {
const TextSelection selection = TextSelection(baseOffset: 13, extentOffset: 5);
expect(
// From |a false |proposition, anything follows.
// Delete the first "p".
const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 13, end: 14), ''),
const TextEditingValue(text: 'From a false roposition, anything follows.', selection: selection),
);
});
test('delete inside selection - start boundary', () {
const TextSelection selection = TextSelection(baseOffset: 13, extentOffset: 5);
expect(
// From |a false |proposition, anything follows.
// Delete the first "a".
const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 5, end: 6), ''),
const TextEditingValue(text: 'From false proposition, anything follows.', selection: TextSelection(baseOffset: 12, extentOffset: 5)),
);
});
test('delete inside selection - end boundary', () {
const TextSelection selection = TextSelection(baseOffset: 13, extentOffset: 5);
expect(
// From |a false |proposition, anything follows.
// Delete the second whitespace.
const TextEditingValue(text: testText, selection: selection).replaced(const TextRange(start: 12, end: 13), ''),
const TextEditingValue(text: 'From a falseproposition, anything follows.', selection: TextSelection(baseOffset: 12, extentOffset: 5)),
);
});
});
});
group('TextInput message channels', () {
late FakeTextChannel fakeTextChannel;
setUp(() {
fakeTextChannel = FakeTextChannel((MethodCall call) async {});
TextInput.setChannel(fakeTextChannel);
});
tearDown(() {
TextInputConnection.debugResetId();
TextInput.setChannel(SystemChannels.textInput);
});
test('text input client handler responds to reattach with setClient', () async {
final FakeTextInputClient client = FakeTextInputClient(const TextEditingValue(text: 'test1'));
TextInput.attach(client, client.configuration);
fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[
MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]),
]);
fakeTextChannel.incoming!(const MethodCall('TextInputClient.requestExistingInputState'));
expect(fakeTextChannel.outgoingCalls.length, 3);
fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[
// From original attach
MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]),
// From requestExistingInputState
MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]),
MethodCall('TextInput.setEditingState', client.currentTextEditingValue.toJSON()),
]);
});
test('text input client handler responds to reattach with setClient (null TextEditingValue)', () async {
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
TextInput.attach(client, client.configuration);
fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[
MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]),
]);
fakeTextChannel.incoming!(const MethodCall('TextInputClient.requestExistingInputState'));
expect(fakeTextChannel.outgoingCalls.length, 3);
fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[
// From original attach
MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]),
// From original attach
MethodCall('TextInput.setClient', <dynamic>[1, client.configuration.toJson()]),
// From requestExistingInputState
const MethodCall(
'TextInput.setEditingState',
<String, dynamic>{
'text': '',
'selectionBase': -1,
'selectionExtent': -1,
'selectionAffinity': 'TextAffinity.downstream',
'selectionIsDirectional': false,
'composingBase': -1,
'composingExtent': -1,
},
),
]);
});
test('Invalid TextRange fails loudly when being converted to JSON', () async {
final List<FlutterErrorDetails> record = <FlutterErrorDetails>[];
FlutterError.onError = (FlutterErrorDetails details) {
record.add(details);
};
final FakeTextInputClient client = FakeTextInputClient(const TextEditingValue(text: 'test3'));
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'method': 'TextInputClient.updateEditingState',
'args': <dynamic>[-1, <String, dynamic>{
'text': '1',
'selectionBase': 2,
'selectionExtent': 3,
}],
});
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'\brange.start >= 0 && range.start <= text.length\b')));
expect(record[0].exception.toString(), matches(RegExp(r'\bRange start 2 is out of text of length 1\b')));
});
test('FloatingCursor coordinates type-casting', () async {
// Regression test for https://github.com/flutter/flutter/issues/109632.
final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[];
FlutterError.onError = errors.add;
final FakeTextInputClient client = FakeTextInputClient(const TextEditingValue(text: 'test3'));
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'method': 'TextInputClient.updateFloatingCursor',
'args': <dynamic>[
-1,
'FloatingCursorDragState.update',
<String, dynamic>{ 'X': 2, 'Y': 3 },
],
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(errors, isEmpty);
});
});
group('TextInputConfiguration', () {
tearDown(() {
TextInputConnection.debugResetId();
});
test('sets expected defaults', () {
const TextInputConfiguration configuration = TextInputConfiguration();
expect(configuration.inputType, TextInputType.text);
expect(configuration.readOnly, false);
expect(configuration.obscureText, false);
expect(configuration.enableDeltaModel, false);
expect(configuration.autocorrect, true);
expect(configuration.actionLabel, null);
expect(configuration.textCapitalization, TextCapitalization.none);
expect(configuration.keyboardAppearance, Brightness.light);
});
test('text serializes to JSON', () async {
const TextInputConfiguration configuration = TextInputConfiguration(
readOnly: true,
obscureText: true,
autocorrect: false,
actionLabel: 'xyzzy',
);
final Map<String, dynamic> json = configuration.toJson();
expect(json['inputType'], <String, dynamic>{
'name': 'TextInputType.text',
'signed': null,
'decimal': null,
});
expect(json['readOnly'], true);
expect(json['obscureText'], true);
expect(json['autocorrect'], false);
expect(json['actionLabel'], 'xyzzy');
});
test('number serializes to JSON', () async {
const TextInputConfiguration configuration = TextInputConfiguration(
inputType: TextInputType.numberWithOptions(decimal: true),
obscureText: true,
autocorrect: false,
actionLabel: 'xyzzy',
);
final Map<String, dynamic> json = configuration.toJson();
expect(json['inputType'], <String, dynamic>{
'name': 'TextInputType.number',
'signed': false,
'decimal': true,
});
expect(json['readOnly'], false);
expect(json['obscureText'], true);
expect(json['autocorrect'], false);
expect(json['actionLabel'], 'xyzzy');
});
test('basic structure', () async {
const TextInputType text = TextInputType.text;
const TextInputType number = TextInputType.number;
const TextInputType number2 = TextInputType.number;
const TextInputType signed = TextInputType.numberWithOptions(signed: true);
const TextInputType signed2 = TextInputType.numberWithOptions(signed: true);
const TextInputType decimal = TextInputType.numberWithOptions(decimal: true);
const TextInputType signedDecimal =
TextInputType.numberWithOptions(signed: true, decimal: true);
expect(text.toString(), 'TextInputType(name: TextInputType.text, signed: null, decimal: null)');
expect(number.toString(), 'TextInputType(name: TextInputType.number, signed: false, decimal: false)');
expect(signed.toString(), 'TextInputType(name: TextInputType.number, signed: true, decimal: false)');
expect(decimal.toString(), 'TextInputType(name: TextInputType.number, signed: false, decimal: true)');
expect(signedDecimal.toString(), 'TextInputType(name: TextInputType.number, signed: true, decimal: true)');
expect(TextInputType.multiline.toString(), 'TextInputType(name: TextInputType.multiline, signed: null, decimal: null)');
expect(TextInputType.phone.toString(), 'TextInputType(name: TextInputType.phone, signed: null, decimal: null)');
expect(TextInputType.datetime.toString(), 'TextInputType(name: TextInputType.datetime, signed: null, decimal: null)');
expect(TextInputType.emailAddress.toString(), 'TextInputType(name: TextInputType.emailAddress, signed: null, decimal: null)');
expect(TextInputType.url.toString(), 'TextInputType(name: TextInputType.url, signed: null, decimal: null)');
expect(TextInputType.visiblePassword.toString(), 'TextInputType(name: TextInputType.visiblePassword, signed: null, decimal: null)');
expect(TextInputType.name.toString(), 'TextInputType(name: TextInputType.name, signed: null, decimal: null)');
expect(TextInputType.streetAddress.toString(), 'TextInputType(name: TextInputType.address, signed: null, decimal: null)');
expect(TextInputType.none.toString(), 'TextInputType(name: TextInputType.none, signed: null, decimal: null)');
expect(text == number, false);
expect(number == number2, true);
expect(number == signed, false);
expect(signed == signed2, true);
expect(signed == decimal, false);
expect(signed == signedDecimal, false);
expect(decimal == signedDecimal, false);
expect(text.hashCode == number.hashCode, false);
expect(number.hashCode == number2.hashCode, true);
expect(number.hashCode == signed.hashCode, false);
expect(signed.hashCode == signed2.hashCode, true);
expect(signed.hashCode == decimal.hashCode, false);
expect(signed.hashCode == signedDecimal.hashCode, false);
expect(decimal.hashCode == signedDecimal.hashCode, false);
expect(TextInputType.text.index, 0);
expect(TextInputType.multiline.index, 1);
expect(TextInputType.number.index, 2);
expect(TextInputType.phone.index, 3);
expect(TextInputType.datetime.index, 4);
expect(TextInputType.emailAddress.index, 5);
expect(TextInputType.url.index, 6);
expect(TextInputType.visiblePassword.index, 7);
expect(TextInputType.name.index, 8);
expect(TextInputType.streetAddress.index, 9);
expect(TextInputType.none.index, 10);
expect(TextEditingValue.empty.toString(),
'TextEditingValue(text: \u2524\u251C, selection: ${const TextSelection.collapsed(offset: -1)}, composing: ${TextRange.empty})');
expect(const TextEditingValue(text: 'Sample Text').toString(),
'TextEditingValue(text: \u2524Sample Text\u251C, selection: ${const TextSelection.collapsed(offset: -1)}, composing: ${TextRange.empty})');
});
test('TextInputClient onConnectionClosed method is called', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(const TextEditingValue(text: 'test3'));
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send onConnectionClosed message.
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[1],
'method': 'TextInputClient.onConnectionClosed',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'connectionClosed');
});
test('TextInputClient insertContent method is called', () async {
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send commitContent message with fake GIF data.
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
1,
'TextInputAction.commitContent',
jsonDecode('{"mimeType": "image/gif", "data": [0,1,0,1,0,1,0,0,0], "uri": "content://com.google.android.inputmethod.latin.fileprovider/test.gif"}'),
],
'method': 'TextInputClient.performAction',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'commitContent');
});
test('TextInputClient performSelectors method is called', () async {
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.performedSelectors, isEmpty);
expect(client.latestMethodCall, isEmpty);
// Send performSelectors message.
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
1,
<dynamic>[
'selector1',
'selector2',
]
],
'method': 'TextInputClient.performSelectors',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'performSelector');
expect(client.performedSelectors, <String>['selector1', 'selector2']);
});
test('TextInputClient performPrivateCommand method is called', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send performPrivateCommand message.
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
1,
jsonDecode('{"action": "actionCommand", "data": {"input_context" : "abcdefg"}}'),
],
'method': 'TextInputClient.performPrivateCommand',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'performPrivateCommand');
});
test('TextInputClient performPrivateCommand method is called with float', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send performPrivateCommand message.
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
1,
jsonDecode('{"action": "actionCommand", "data": {"input_context" : 0.5}}'),
],
'method': 'TextInputClient.performPrivateCommand',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'performPrivateCommand');
});
test('TextInputClient performPrivateCommand method is called with CharSequence array', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send performPrivateCommand message.
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
1,
jsonDecode('{"action": "actionCommand", "data": {"input_context" : ["abc", "efg"]}}'),
],
'method': 'TextInputClient.performPrivateCommand',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'performPrivateCommand');
});
test('TextInputClient performPrivateCommand method is called with CharSequence', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send performPrivateCommand message.
final ByteData? messageBytes =
const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
1,
jsonDecode('{"action": "actionCommand", "data": {"input_context" : "abc"}}'),
],
'method': 'TextInputClient.performPrivateCommand',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'performPrivateCommand');
});
test('TextInputClient performPrivateCommand method is called with float array', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send performPrivateCommand message.
final ByteData? messageBytes =
const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
1,
jsonDecode('{"action": "actionCommand", "data": {"input_context" : [0.5, 0.8]}}'),
],
'method': 'TextInputClient.performPrivateCommand',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'performPrivateCommand');
});
test('TextInputClient performPrivateCommand method is called with no data at all', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send performPrivateCommand message.
final ByteData? messageBytes = const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[
1,
jsonDecode('{"action": "actionCommand"}'), // No `data` parameter.
],
'method': 'TextInputClient.performPrivateCommand',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'performPrivateCommand');
expect(client.latestPrivateCommandData, <String, dynamic>{});
});
test('TextInputClient showAutocorrectionPromptRect method is called', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send onConnectionClosed message.
final ByteData? messageBytes =
const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[1, 0, 1],
'method': 'TextInputClient.showAutocorrectionPromptRect',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'showAutocorrectionPromptRect');
});
test('TextInputClient showToolbar method is called', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
expect(client.latestMethodCall, isEmpty);
// Send showToolbar message.
final ByteData? messageBytes =
const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[1, 0, 1],
'method': 'TextInputClient.showToolbar',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(client.latestMethodCall, 'showToolbar');
});
});
group('Scribble interactions', () {
tearDown(() {
TextInputConnection.debugResetId();
});
test('TextInputClient scribbleInteractionBegan and scribbleInteractionFinished', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
final TextInputConnection connection = TextInput.attach(client, configuration);
expect(connection.scribbleInProgress, false);
// Send scribbleInteractionBegan message.
ByteData? messageBytes =
const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[1, 0, 1],
'method': 'TextInputClient.scribbleInteractionBegan',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(connection.scribbleInProgress, true);
// Send scribbleInteractionFinished message.
messageBytes =
const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[1, 0, 1],
'method': 'TextInputClient.scribbleInteractionFinished',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
expect(connection.scribbleInProgress, false);
});
test('TextInputClient focusElement', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
final FakeScribbleElement targetElement = FakeScribbleElement(elementIdentifier: 'target');
TextInput.registerScribbleElement(targetElement.elementIdentifier, targetElement);
final FakeScribbleElement otherElement = FakeScribbleElement(elementIdentifier: 'other');
TextInput.registerScribbleElement(otherElement.elementIdentifier, otherElement);
expect(targetElement.latestMethodCall, isEmpty);
expect(otherElement.latestMethodCall, isEmpty);
// Send focusElement message.
final ByteData? messageBytes =
const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[targetElement.elementIdentifier, 0.0, 0.0],
'method': 'TextInputClient.focusElement',
});
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? _) {},
);
TextInput.unregisterScribbleElement(targetElement.elementIdentifier);
TextInput.unregisterScribbleElement(otherElement.elementIdentifier);
expect(targetElement.latestMethodCall, 'onScribbleFocus');
expect(otherElement.latestMethodCall, isEmpty);
});
test('TextInputClient requestElementsInRect', () async {
// Assemble a TextInputConnection so we can verify its change in state.
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
const TextInputConfiguration configuration = TextInputConfiguration();
TextInput.attach(client, configuration);
final List<FakeScribbleElement> targetElements = <FakeScribbleElement>[
FakeScribbleElement(elementIdentifier: 'target1', bounds: const Rect.fromLTWH(0.0, 0.0, 100.0, 100.0)),
FakeScribbleElement(elementIdentifier: 'target2', bounds: const Rect.fromLTWH(0.0, 100.0, 100.0, 100.0)),
];
final List<FakeScribbleElement> otherElements = <FakeScribbleElement>[
FakeScribbleElement(elementIdentifier: 'other1', bounds: const Rect.fromLTWH(100.0, 0.0, 100.0, 100.0)),
FakeScribbleElement(elementIdentifier: 'other2', bounds: const Rect.fromLTWH(100.0, 100.0, 100.0, 100.0)),
];
void registerElements(FakeScribbleElement element) => TextInput.registerScribbleElement(element.elementIdentifier, element);
void unregisterElements(FakeScribbleElement element) => TextInput.unregisterScribbleElement(element.elementIdentifier);
<FakeScribbleElement>[...targetElements, ...otherElements].forEach(registerElements);
// Send requestElementsInRect message.
final ByteData? messageBytes =
const JSONMessageCodec().encodeMessage(<String, dynamic>{
'args': <dynamic>[0.0, 50.0, 50.0, 100.0],
'method': 'TextInputClient.requestElementsInRect',
});
ByteData? responseBytes;
await binding.defaultBinaryMessenger.handlePlatformMessage(
'flutter/textinput',
messageBytes,
(ByteData? response) {
responseBytes = response;
},
);
<FakeScribbleElement>[...targetElements, ...otherElements].forEach(unregisterElements);
final List<List<dynamic>> responses = (const JSONMessageCodec().decodeMessage(responseBytes) as List<dynamic>).cast<List<dynamic>>();
expect(responses.first.length, 2);
expect(responses.first.first, containsAllInOrder(<dynamic>[targetElements.first.elementIdentifier, 0.0, 0.0, 100.0, 100.0]));
expect(responses.first.last, containsAllInOrder(<dynamic>[targetElements.last.elementIdentifier, 0.0, 100.0, 100.0, 100.0]));
});
});
test('TextEditingValue.isComposingRangeValid', () async {
// The composing range is empty.
expect(TextEditingValue.empty.isComposingRangeValid, isFalse);
expect(
const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 0)).isComposingRangeValid,
isFalse,
);
// The composing range is out of range for the text.
expect(
const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 5)).isComposingRangeValid,
isFalse,
);
// The composing range is out of range for the text.
expect(
const TextEditingValue(text: 'test', composing: TextRange(start: -1, end: 4)).isComposingRangeValid,
isFalse,
);
expect(
const TextEditingValue(text: 'test', composing: TextRange(start: 1, end: 4)).isComposingRangeValid,
isTrue,
);
});
group('TextInputControl', () {
late FakeTextChannel fakeTextChannel;
setUp(() {
fakeTextChannel = FakeTextChannel((MethodCall call) async {});
TextInput.setChannel(fakeTextChannel);
});
tearDown(() {
TextInput.restorePlatformInputControl();
TextInputConnection.debugResetId();
TextInput.setChannel(SystemChannels.textInput);
});
test('gets attached and detached', () {
final FakeTextInputControl control = FakeTextInputControl();
TextInput.setInputControl(control);
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
final TextInputConnection connection = TextInput.attach(client, const TextInputConfiguration());
final List<String> expectedMethodCalls = <String>['attach'];
expect(control.methodCalls, expectedMethodCalls);
connection.close();
expectedMethodCalls.add('detach');
expect(control.methodCalls, expectedMethodCalls);
});
test('receives text input state changes', () {
final FakeTextInputControl control = FakeTextInputControl();
TextInput.setInputControl(control);
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
final TextInputConnection connection = TextInput.attach(client, const TextInputConfiguration());
control.methodCalls.clear();
final List<String> expectedMethodCalls = <String>[];
connection.updateConfig(const TextInputConfiguration());
expectedMethodCalls.add('updateConfig');
expect(control.methodCalls, expectedMethodCalls);
connection.setEditingState(TextEditingValue.empty);
expectedMethodCalls.add('setEditingState');
expect(control.methodCalls, expectedMethodCalls);
connection.close();
expectedMethodCalls.add('detach');
expect(control.methodCalls, expectedMethodCalls);
});
test('does not interfere with platform text input', () {
final FakeTextInputControl control = FakeTextInputControl();
TextInput.setInputControl(control);
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
TextInput.attach(client, const TextInputConfiguration());
fakeTextChannel.outgoingCalls.clear();
fakeTextChannel.incoming!(MethodCall('TextInputClient.updateEditingState', <dynamic>[1, TextEditingValue.empty.toJSON()]));
expect(client.latestMethodCall, 'updateEditingValue');
expect(control.methodCalls, <String>['attach', 'setEditingState']);
expect(fakeTextChannel.outgoingCalls, isEmpty);
});
test('both input controls receive requests', () async {
final FakeTextInputControl control = FakeTextInputControl();
TextInput.setInputControl(control);
const TextInputConfiguration textConfig = TextInputConfiguration();
const TextInputConfiguration numberConfig = TextInputConfiguration(inputType: TextInputType.number);
const TextInputConfiguration multilineConfig = TextInputConfiguration(inputType: TextInputType.multiline);
const TextInputConfiguration noneConfig = TextInputConfiguration(inputType: TextInputType.none);
// Test for https://github.com/flutter/flutter/issues/125875.
// When there's a custom text input control installed on Web, the platform text
// input control receives TextInputType.none and isMultiline flag.
// isMultiline flag is set to true when the input type is multiline.
// isMultiline flag is set to false when the input type is not multiline.
final Map<String, dynamic> noneIsMultilineFalseJson = noneConfig.toJson();
final Map<String, dynamic> noneInputType = noneIsMultilineFalseJson['inputType'] as Map<String, dynamic>;
if (kIsWeb) {
noneInputType['isMultiline'] = false;
}
final Map<String, dynamic> noneIsMultilineTrueJson = noneConfig.toJson();
final Map<String, dynamic> noneInputType1 = noneIsMultilineTrueJson['inputType'] as Map<String, dynamic>;
if (kIsWeb) {
noneInputType1['isMultiline'] = true;
}
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
final TextInputConnection connection = TextInput.attach(client, textConfig);
final List<String> expectedMethodCalls = <String>['attach'];
expect(control.methodCalls, expectedMethodCalls);
expect(control.inputType, TextInputType.text);
fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[
// When there's a custom text input control installed, the platform text
// input control receives TextInputType.none with isMultiline flag
MethodCall('TextInput.setClient', <dynamic>[1, noneIsMultilineFalseJson]),
]);
connection.show();
expectedMethodCalls.add('show');
expect(control.methodCalls, expectedMethodCalls);
expect(fakeTextChannel.outgoingCalls.length, 2);
expect(fakeTextChannel.outgoingCalls.last.method, 'TextInput.show');
connection.updateConfig(numberConfig);
expectedMethodCalls.add('updateConfig');
expect(control.methodCalls, expectedMethodCalls);
expect(control.inputType, TextInputType.number);
expect(fakeTextChannel.outgoingCalls.length, 3);
fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[
// When there's a custom text input control installed, the platform text
// input control receives TextInputType.none with isMultiline flag
MethodCall('TextInput.setClient', <dynamic>[1, noneIsMultilineFalseJson]),
const MethodCall('TextInput.show'),
MethodCall('TextInput.updateConfig', noneIsMultilineFalseJson),
]);
connection.updateConfig(multilineConfig);
expectedMethodCalls.add('updateConfig');
expect(control.methodCalls, expectedMethodCalls);
expect(control.inputType, TextInputType.multiline);
expect(fakeTextChannel.outgoingCalls.length, 4);
fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[
// When there's a custom text input control installed, the platform text
// input control receives TextInputType.none with isMultiline flag
MethodCall('TextInput.setClient', <dynamic>[1, noneIsMultilineFalseJson]),
const MethodCall('TextInput.show'),
MethodCall('TextInput.updateConfig', noneIsMultilineFalseJson),
MethodCall('TextInput.updateConfig', noneIsMultilineTrueJson),
]);
connection.setComposingRect(Rect.zero);
expectedMethodCalls.add('setComposingRect');
expect(control.methodCalls, expectedMethodCalls);
expect(fakeTextChannel.outgoingCalls.length, 5);
expect(fakeTextChannel.outgoingCalls.last.method, 'TextInput.setMarkedTextRect');
connection.setCaretRect(Rect.zero);
expectedMethodCalls.add('setCaretRect');
expect(control.methodCalls, expectedMethodCalls);
expect(fakeTextChannel.outgoingCalls.length, 6);
expect(fakeTextChannel.outgoingCalls.last.method, 'TextInput.setCaretRect');
connection.setEditableSizeAndTransform(Size.zero, Matrix4.identity());
expectedMethodCalls.add('setEditableSizeAndTransform');
expect(control.methodCalls, expectedMethodCalls);
expect(fakeTextChannel.outgoingCalls.length, 7);
expect(fakeTextChannel.outgoingCalls.last.method, 'TextInput.setEditableSizeAndTransform');
connection.setSelectionRects(const <SelectionRect>[SelectionRect(position: 1, bounds: Rect.fromLTWH(2, 3, 4, 5), direction: TextDirection.rtl)]);
expectedMethodCalls.add('setSelectionRects');
expect(control.methodCalls, expectedMethodCalls);
expect(fakeTextChannel.outgoingCalls.length, 8);
expect(fakeTextChannel.outgoingCalls.last.arguments, const TypeMatcher<List<List<num>>>());
final List<List<num>> sentList = fakeTextChannel.outgoingCalls.last.arguments as List<List<num>>;
expect(sentList.length, 1);
expect(sentList[0].length, 6);
expect(sentList[0][0], 2); // left
expect(sentList[0][1], 3); // top
expect(sentList[0][2], 4); // width
expect(sentList[0][3], 5); // height
expect(sentList[0][4], 1); // position
expect(sentList[0][5], TextDirection.rtl.index); // direction
expect(fakeTextChannel.outgoingCalls.last.method, 'TextInput.setSelectionRects');
connection.setStyle(
fontFamily: null,
fontSize: null,
fontWeight: null,
textDirection: TextDirection.ltr,
textAlign: TextAlign.left,
);
expectedMethodCalls.add('setStyle');
expect(control.methodCalls, expectedMethodCalls);
expect(fakeTextChannel.outgoingCalls.length, 9);
expect(fakeTextChannel.outgoingCalls.last.method, 'TextInput.setStyle');
connection.close();
expectedMethodCalls.add('detach');
expect(control.methodCalls, expectedMethodCalls);
expect(fakeTextChannel.outgoingCalls.length, 10);
expect(fakeTextChannel.outgoingCalls.last.method, 'TextInput.clearClient');
expectedMethodCalls.add('hide');
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
await binding.runAsync(() async {});
await expectLater(control.methodCalls, expectedMethodCalls);
expect(fakeTextChannel.outgoingCalls.length, 11);
expect(fakeTextChannel.outgoingCalls.last.method, 'TextInput.hide');
});
test('the platform input control receives isMultiline true on attach', () async {
final FakeTextInputControl control = FakeTextInputControl();
TextInput.setInputControl(control);
const TextInputConfiguration multilineConfig = TextInputConfiguration(inputType: TextInputType.multiline);
const TextInputConfiguration noneConfig = TextInputConfiguration(inputType: TextInputType.none);
// Test for https://github.com/flutter/flutter/issues/125875.
// When there's a custom text input control installed, the platform text
// input control receives TextInputType.none and isMultiline flag.
// isMultiline flag is set to true when the input type is multiline.
// isMultiline flag is set to false when the input type is not multiline.
final Map<String, dynamic> noneIsMultilineTrueJson = noneConfig.toJson();
final Map<String, dynamic> noneInputType = noneIsMultilineTrueJson['inputType'] as Map<String, dynamic>;
noneInputType['isMultiline'] = true;
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
TextInput.attach(client, multilineConfig);
final List<String> expectedMethodCalls = <String>['attach'];
expect(control.methodCalls, expectedMethodCalls);
expect(control.inputType, TextInputType.multiline);
fakeTextChannel.validateOutgoingMethodCalls(<MethodCall>[
// When there's a custom text input control installed, the platform text
// input control receives TextInputType.none with isMultiline flag
MethodCall('TextInput.setClient', <dynamic>[1, noneIsMultilineTrueJson]),
]);
}, skip: !kIsWeb); // https://github.com/flutter/flutter/issues/125875
test('notifies changes to the attached client', () async {
final FakeTextInputControl control = FakeTextInputControl();
TextInput.setInputControl(control);
final FakeTextInputClient client = FakeTextInputClient(TextEditingValue.empty);
final TextInputConnection connection = TextInput.attach(client, const TextInputConfiguration());
TextInput.setInputControl(null);
expect(client.latestMethodCall, 'didChangeInputControl');
connection.show();
expect(client.latestMethodCall, 'didChangeInputControl');
});
});
}
class FakeTextInputClient with TextInputClient {
FakeTextInputClient(this.currentTextEditingValue);
String latestMethodCall = '';
final List<String> performedSelectors = <String>[];
late Map<String, dynamic>? latestPrivateCommandData;
@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';
latestPrivateCommandData = data;
}
@override
void insertContent(KeyboardInsertedContent content) {
latestMethodCall = 'commitContent';
}
@override
void updateEditingValue(TextEditingValue value) {
latestMethodCall = 'updateEditingValue';
}
@override
void updateFloatingCursor(RawFloatingCursorPoint point) {
latestMethodCall = 'updateFloatingCursor';
}
@override
void connectionClosed() {
latestMethodCall = 'connectionClosed';
}
@override
void showAutocorrectionPromptRect(int start, int end) {
latestMethodCall = 'showAutocorrectionPromptRect';
}
@override
void showToolbar() {
latestMethodCall = 'showToolbar';
}
TextInputConfiguration get configuration => const TextInputConfiguration();
@override
void didChangeInputControl(TextInputControl? oldControl, TextInputControl? newControl) {
latestMethodCall = 'didChangeInputControl';
}
@override
void insertTextPlaceholder(Size size) {
latestMethodCall = 'insertTextPlaceholder';
}
@override
void removeTextPlaceholder() {
latestMethodCall = 'removeTextPlaceholder';
}
@override
void performSelector(String selectorName) {
latestMethodCall = 'performSelector';
performedSelectors.add(selectorName);
}
}
class FakeTextInputControl with TextInputControl {
final List<String> methodCalls = <String>[];
late TextInputType inputType;
@override
void attach(TextInputClient client, TextInputConfiguration configuration) {
methodCalls.add('attach');
inputType = configuration.inputType;
}
@override
void detach(TextInputClient client) {
methodCalls.add('detach');
}
@override
void setEditingState(TextEditingValue value) {
methodCalls.add('setEditingState');
}
@override
void updateConfig(TextInputConfiguration configuration) {
methodCalls.add('updateConfig');
inputType = configuration.inputType;
}
@override
void show() {
methodCalls.add('show');
}
@override
void hide() {
methodCalls.add('hide');
}
@override
void setComposingRect(Rect rect) {
methodCalls.add('setComposingRect');
}
@override
void setCaretRect(Rect rect) {
methodCalls.add('setCaretRect');
}
@override
void setEditableSizeAndTransform(Size editableBoxSize, Matrix4 transform) {
methodCalls.add('setEditableSizeAndTransform');
}
@override
void setSelectionRects(List<SelectionRect> selectionRects) {
methodCalls.add('setSelectionRects');
}
@override
void setStyle({
required String? fontFamily,
required double? fontSize,
required FontWeight? fontWeight,
required TextDirection textDirection,
required TextAlign textAlign,
}) {
methodCalls.add('setStyle');
}
@override
void finishAutofillContext({bool shouldSave = true}) {
methodCalls.add('finishAutofillContext');
}
@override
void requestAutofill() {
methodCalls.add('requestAutofill');
}
}
| flutter/packages/flutter/test/services/text_input_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/text_input_test.dart",
"repo_id": "flutter",
"token_count": 17602
} | 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/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class TestPaintingContext implements PaintingContext {
final List<Invocation> invocations = <Invocation>[];
@override
void noSuchMethod(Invocation invocation) {
invocations.add(invocation);
}
}
void main() {
group('AnimatedSize', () {
testWidgets('animates forwards then backwards with stable-sized children', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
RenderBox box = tester.renderObject(find.byType(AnimatedSize));
expect(box.size.width, equals(100.0));
expect(box.size.height, equals(100.0));
await tester.pumpWidget(
const Center(
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 200.0,
height: 200.0,
),
),
),
);
await tester.pump(const Duration(milliseconds: 100));
box = tester.renderObject(find.byType(AnimatedSize));
expect(box.size.width, equals(150.0));
expect(box.size.height, equals(150.0));
TestPaintingContext context = TestPaintingContext();
box.paint(context, Offset.zero);
expect(context.invocations.first.memberName, equals(#pushClipRect));
await tester.pump(const Duration(milliseconds: 100));
box = tester.renderObject(find.byType(AnimatedSize));
expect(box.size.width, equals(200.0));
expect(box.size.height, equals(200.0));
await tester.pumpWidget(
const Center(
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
await tester.pump(const Duration(milliseconds: 100));
box = tester.renderObject(find.byType(AnimatedSize));
expect(box.size.width, equals(150.0));
expect(box.size.height, equals(150.0));
context = TestPaintingContext();
box.paint(context, Offset.zero);
expect(context.invocations.first.memberName, equals(#paintChild));
await tester.pump(const Duration(milliseconds: 100));
box = tester.renderObject(find.byType(AnimatedSize));
expect(box.size.width, equals(100.0));
expect(box.size.height, equals(100.0));
});
testWidgets('calls onEnd when animation is completed', (WidgetTester tester) async {
int callCount = 0;
void handleEnd() {
callCount++;
}
await tester.pumpWidget(
Center(
child: AnimatedSize(
onEnd: handleEnd,
duration: const Duration(milliseconds: 200),
child: const SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
expect(callCount, equals(0));
await tester.pumpWidget(
Center(
child: AnimatedSize(
onEnd: handleEnd,
duration: const Duration(milliseconds: 200),
child: const SizedBox(
width: 200.0,
height: 200.0,
),
),
),
);
expect(callCount, equals(0));
await tester.pumpAndSettle();
expect(callCount, equals(1));
await tester.pumpWidget(
Center(
child: AnimatedSize(
onEnd: handleEnd,
duration: const Duration(milliseconds: 200),
child: const SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
await tester.pumpAndSettle();
expect(callCount, equals(2));
});
testWidgets('clamps animated size to constraints', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: SizedBox (
width: 100.0,
height: 100.0,
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 100.0,
height: 100.0,
),
),
),
),
);
RenderBox box = tester.renderObject(find.byType(AnimatedSize));
expect(box.size.width, equals(100.0));
expect(box.size.height, equals(100.0));
// Attempt to animate beyond the outer SizedBox.
await tester.pumpWidget(
const Center(
child: SizedBox (
width: 100.0,
height: 100.0,
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 200.0,
height: 200.0,
),
),
),
),
);
// Verify that animated size is the same as the outer SizedBox.
await tester.pump(const Duration(milliseconds: 100));
box = tester.renderObject(find.byType(AnimatedSize));
expect(box.size.width, equals(100.0));
expect(box.size.height, equals(100.0));
});
testWidgets('tracks unstable child, then resumes animation when child stabilizes', (WidgetTester tester) async {
Future<void> pumpMillis(int millis) async {
await tester.pump(Duration(milliseconds: millis));
}
void verify({ double? size, RenderAnimatedSizeState? state }) {
assert(size != null || state != null);
final RenderAnimatedSize box = tester.renderObject(find.byType(AnimatedSize));
if (size != null) {
expect(box.size.width, size);
expect(box.size.height, size);
}
if (state != null) {
expect(box.state, state);
}
}
await tester.pumpWidget(
Center(
child: AnimatedSize(
duration: const Duration(milliseconds: 200),
child: AnimatedContainer(
duration: const Duration(milliseconds: 100),
width: 100.0,
height: 100.0,
),
),
),
);
verify(size: 100.0, state: RenderAnimatedSizeState.stable);
// Animate child size from 100 to 200 slowly (100ms).
await tester.pumpWidget(
Center(
child: AnimatedSize(
duration: const Duration(milliseconds: 200),
child: AnimatedContainer(
duration: const Duration(milliseconds: 100),
width: 200.0,
height: 200.0,
),
),
),
);
// Make sure animation proceeds at child's pace, with AnimatedSize
// tightly tracking the child's size.
verify(state: RenderAnimatedSizeState.stable);
await pumpMillis(1); // register change
verify(state: RenderAnimatedSizeState.changed);
await pumpMillis(49);
verify(size: 150.0, state: RenderAnimatedSizeState.unstable);
await pumpMillis(50);
verify(size: 200.0, state: RenderAnimatedSizeState.unstable);
// Stabilize size
await pumpMillis(50);
verify(size: 200.0, state: RenderAnimatedSizeState.stable);
// Quickly (in 1ms) change size back to 100
await tester.pumpWidget(
Center(
child: AnimatedSize(
duration: const Duration(milliseconds: 200),
child: AnimatedContainer(
duration: const Duration(milliseconds: 1),
width: 100.0,
height: 100.0,
),
),
),
);
verify(size: 200.0, state: RenderAnimatedSizeState.stable);
await pumpMillis(1); // register change
verify(state: RenderAnimatedSizeState.changed);
await pumpMillis(100);
verify(size: 150.0, state: RenderAnimatedSizeState.stable);
await pumpMillis(100);
verify(size: 100.0, state: RenderAnimatedSizeState.stable);
});
testWidgets('resyncs its animation controller', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
await tester.pumpWidget(
const Center(
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 200.0,
height: 100.0,
),
),
),
);
await tester.pump(const Duration(milliseconds: 100));
final RenderBox box = tester.renderObject(find.byType(AnimatedSize));
expect(box.size.width, equals(150.0));
});
testWidgets('does not run animation unnecessarily', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
for (int i = 0; i < 20; i++) {
final RenderAnimatedSize box = tester.renderObject(find.byType(AnimatedSize));
expect(box.size.width, 100.0);
expect(box.size.height, 100.0);
expect(box.state, RenderAnimatedSizeState.stable);
expect(box.isAnimating, false);
await tester.pump(const Duration(milliseconds: 10));
}
});
testWidgets('can set and update clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
// By default, clipBehavior should be Clip.hardEdge
final RenderAnimatedSize renderObject = tester.renderObject(find.byType(AnimatedSize));
expect(renderObject.clipBehavior, equals(Clip.hardEdge));
for (final Clip clip in Clip.values) {
await tester.pumpWidget(
Center(
child: AnimatedSize(
duration: const Duration(milliseconds: 200),
clipBehavior: clip,
child: const SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
expect(renderObject.clipBehavior, clip);
}
});
testWidgets('works wrapped in IntrinsicHeight and Wrap', (WidgetTester tester) async {
Future<void> pumpWidget(Size size, [Duration? duration]) async {
return tester.pumpWidget(
Center(
child: IntrinsicHeight(
child: Wrap(
textDirection: TextDirection.ltr,
children: <Widget>[
AnimatedSize(
duration: const Duration(milliseconds: 200),
curve: Curves.easeInOutBack,
child: SizedBox(
width: size.width,
height: size.height,
),
),
],
),
),
),
duration: duration,
);
}
await pumpWidget(const Size(100, 100));
expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(100, 100));
await pumpWidget(const Size(150, 200));
expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(100, 100));
// Each pump triggers verification of dry layout.
for (int total = 0; total < 200; total += 10) {
await tester.pump(const Duration(milliseconds: 10));
}
expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(150, 200));
// Change every pump
await pumpWidget(const Size(100, 100));
expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(150, 200));
await pumpWidget(const Size(111, 111), const Duration(milliseconds: 10));
expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(111, 111));
await pumpWidget(const Size(222, 222), const Duration(milliseconds: 10));
expect(tester.renderObject<RenderBox>(find.byType(IntrinsicHeight)).size, const Size(222, 222));
});
testWidgets('re-attach with interrupted animation', (WidgetTester tester) async {
const Key key1 = ValueKey<String>('key1');
const Key key2 = ValueKey<String>('key2');
late StateSetter setState;
Size childSize = const Size.square(100);
final Widget animatedSize = Center(
key: GlobalKey(debugLabel: 'animated size'),
// This SizedBox creates a relayout boundary so _cleanRelayoutBoundary
// does not mark the descendant render objects below the relayout boundary
// dirty.
child: SizedBox.fromSize(
size: const Size.square(200),
child: Center(
child: AnimatedSize(
duration: const Duration(seconds: 1),
child: StatefulBuilder(
builder: (BuildContext context, StateSetter stateSetter) {
setState = stateSetter;
return SizedBox.fromSize(size: childSize);
},
),
),
),
),
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Row(
children: <Widget>[
SizedBox(
key: key1,
height: 200,
child: animatedSize,
),
const SizedBox(
key: key2,
height: 200,
),
],
),
)
);
setState(() {
childSize = const Size.square(150);
});
// Kick off the resizing animation.
await tester.pump();
// Immediately reparent the AnimatedSize subtree to a different parent
// with the same incoming constraints.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Row(
children: <Widget>[
const SizedBox(
key: key1,
height: 200,
),
SizedBox(
key: key2,
height: 200,
child: animatedSize,
),
],
),
),
);
expect(
tester.renderObject<RenderBox>(find.byType(AnimatedSize)).size,
const Size.square(100),
);
await tester.pumpAndSettle();
// The animatedSize widget animates to the right size.
expect(
tester.renderObject<RenderBox>(find.byType(AnimatedSize)).size,
const Size.square(150),
);
});
testWidgets('disposes animation and controller', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: AnimatedSize(
duration: Duration(milliseconds: 200),
child: SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
final RenderAnimatedSize box = tester.renderObject(find.byType(AnimatedSize));
await tester.pumpWidget(
const Center(),
);
expect(box.debugAnimation, isNotNull);
expect(box.debugAnimation!.isDisposed, isTrue);
expect(box.debugController, isNotNull);
expect(
() => box.debugController!.dispose(),
throwsA(isA<AssertionError>().having(
(AssertionError error) => error.message,
'message',
equalsIgnoringHashCodes(
'AnimationController.dispose() called more than once.\n'
'A given AnimationController cannot be disposed more than once.\n'
'The following AnimationController object was disposed multiple times:\n'
' AnimationController#00000(⏮ 0.000; paused; DISPOSED)',
),
)),
);
});
});
}
| flutter/packages/flutter/test/widgets/animated_size_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/animated_size_test.dart",
"repo_id": "flutter",
"token_count": 7790
} | 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/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Baseline - control test', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: DefaultTextStyle(
style: TextStyle(
fontSize: 100.0,
),
child: Text('X', textDirection: TextDirection.ltr),
),
),
);
expect(tester.renderObject<RenderBox>(find.text('X')).size, const Size(100.0, 100.0));
});
testWidgets('Baseline - position test', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: Baseline(
baseline: 175.0,
baselineType: TextBaseline.alphabetic,
child: DefaultTextStyle(
style: TextStyle(
fontFamily: 'FlutterTest',
fontSize: 100.0,
),
child: Text('X', textDirection: TextDirection.ltr),
),
),
),
);
expect(tester.renderObject<RenderBox>(find.text('X')).size, const Size(100.0, 100.0));
expect(
tester.renderObject<RenderBox>(find.byType(Baseline)).size,
const Size(100.0, 200),
);
});
testWidgets('Chip caches baseline', (WidgetTester tester) async {
final bool checkIntrinsicSizes = debugCheckIntrinsicSizes;
debugCheckIntrinsicSizes = false;
int calls = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Baseline(
baseline: 100.0,
baselineType: TextBaseline.alphabetic,
child: Chip(
label: BaselineDetector(() {
assert(!debugCheckIntrinsicSizes);
calls += 1;
}),
),
),
),
),
);
expect(calls, 1);
await tester.pump();
expect(calls, 1);
tester.renderObject<RenderBaselineDetector>(find.byType(BaselineDetector)).dirty();
await tester.pump();
expect(calls, 2);
debugCheckIntrinsicSizes = checkIntrinsicSizes;
});
testWidgets('ListTile caches baseline', (WidgetTester tester) async {
final bool checkIntrinsicSizes = debugCheckIntrinsicSizes;
debugCheckIntrinsicSizes = false;
int calls = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Baseline(
baseline: 100.0,
baselineType: TextBaseline.alphabetic,
child: ListTile(
title: BaselineDetector(() {
assert(!debugCheckIntrinsicSizes);
calls += 1;
}),
),
),
),
),
);
expect(calls, 1);
await tester.pump();
expect(calls, 1);
tester.renderObject<RenderBaselineDetector>(find.byType(BaselineDetector)).dirty();
await tester.pump();
expect(calls, 2);
debugCheckIntrinsicSizes = checkIntrinsicSizes;
});
testWidgets("LayoutBuilder returns child's baseline", (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Baseline(
baseline: 180.0,
baselineType: TextBaseline.alphabetic,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return BaselineDetector(() {});
},
),
),
),
),
);
expect(tester.getRect(find.byType(BaselineDetector)).top, 160.0);
});
}
class BaselineDetector extends LeafRenderObjectWidget {
const BaselineDetector(this.callback, { super.key });
final VoidCallback callback;
@override
RenderBaselineDetector createRenderObject(BuildContext context) => RenderBaselineDetector(callback);
@override
void updateRenderObject(BuildContext context, RenderBaselineDetector renderObject) {
renderObject.callback = callback;
}
}
class RenderBaselineDetector extends RenderBox {
RenderBaselineDetector(this.callback);
VoidCallback callback;
@override
bool get sizedByParent => true;
@override
double computeMinIntrinsicWidth(double height) => 0.0;
@override
double computeMaxIntrinsicWidth(double height) => 0.0;
@override
double computeMinIntrinsicHeight(double width) => 0.0;
@override
double computeMaxIntrinsicHeight(double width) => 0.0;
@override
double computeDistanceToActualBaseline(TextBaseline baseline) {
callback();
return 20.0;
}
void dirty() {
markNeedsLayout();
}
@override
Size computeDryLayout(BoxConstraints constraints) {
return constraints.smallest;
}
@override
void paint(PaintingContext context, Offset offset) { }
}
| flutter/packages/flutter/test/widgets/baseline_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/baseline_test.dart",
"repo_id": "flutter",
"token_count": 2070
} | 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
// Assuming that the test container is 800x600. The height of the
// viewport's contents is 650.0, the top and bottom text children
// are 100 pixels high and top/left edge of both widgets are visible.
// The top of the bottom widget is at 550 (the top of the top widget
// is at 0). The top of the bottom widget is 500 when it has been
// scrolled completely into view.
Widget buildFrame(ScrollPhysics physics, { ScrollController? scrollController }) {
return SingleChildScrollView(
key: UniqueKey(),
physics: physics,
controller: scrollController,
child: SizedBox(
height: 650.0,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
textDirection: TextDirection.ltr,
children: <Widget>[
const SizedBox(height: 100.0, child: Text('top', textDirection: TextDirection.ltr)),
Expanded(child: Container()),
const SizedBox(height: 100.0, child: Text('bottom', textDirection: TextDirection.ltr)),
],
),
),
);
}
void main() {
testWidgets('ClampingScrollPhysics', (WidgetTester tester) async {
// Scroll the target text widget by offset and then return its origin
// in global coordinates.
Future<Offset> locationAfterScroll(String target, Offset offset) async {
await tester.dragFrom(tester.getTopLeft(find.text(target)), offset);
await tester.pump();
final RenderBox textBox = tester.renderObject(find.text(target));
final Offset widgetOrigin = textBox.localToGlobal(Offset.zero);
await tester.pump(const Duration(seconds: 1)); // Allow overscroll to settle
return Future<Offset>.value(widgetOrigin);
}
await tester.pumpWidget(buildFrame(const BouncingScrollPhysics()));
Offset origin = await locationAfterScroll('top', const Offset(0.0, 400.0));
expect(origin.dy, greaterThan(0.0));
origin = await locationAfterScroll('bottom', const Offset(0.0, -400.0));
expect(origin.dy, lessThan(500.0));
await tester.pumpWidget(buildFrame(const ClampingScrollPhysics()));
origin = await locationAfterScroll('top', const Offset(0.0, 400.0));
expect(origin.dy, equals(0.0));
origin = await locationAfterScroll('bottom', const Offset(0.0, -400.0));
expect(origin.dy, equals(500.0));
});
testWidgets('ClampingScrollPhysics affects ScrollPosition', (WidgetTester tester) async {
// BouncingScrollPhysics
await tester.pumpWidget(buildFrame(const BouncingScrollPhysics()));
ScrollableState scrollable = tester.state(find.byType(Scrollable));
await tester.dragFrom(tester.getTopLeft(find.text('top')), const Offset(0.0, 400.0));
await tester.pump();
expect(scrollable.position.pixels, lessThan(0.0));
await tester.pump(const Duration(seconds: 1)); // Allow overscroll to settle
await tester.dragFrom(tester.getTopLeft(find.text('bottom')), const Offset(0.0, -400.0));
await tester.pump();
expect(scrollable.position.pixels, greaterThan(0.0));
await tester.pump(const Duration(seconds: 1)); // Allow overscroll to settle
// ClampingScrollPhysics
await tester.pumpWidget(buildFrame(const ClampingScrollPhysics()));
scrollable = scrollable = tester.state(find.byType(Scrollable));
await tester.dragFrom(tester.getTopLeft(find.text('top')), const Offset(0.0, 400.0));
await tester.pump();
expect(scrollable.position.pixels, equals(0.0));
await tester.pump(const Duration(seconds: 1)); // Allow overscroll to settle
await tester.dragFrom(tester.getTopLeft(find.text('bottom')), const Offset(0.0, -400.0));
await tester.pump();
expect(scrollable.position.pixels, equals(50.0));
});
testWidgets('ClampingScrollPhysics handles out of bounds ScrollPosition - initialScrollOffset', (WidgetTester tester) async {
Future<void> testOutOfBounds(ScrollPhysics physics, double initialOffset, double expectedOffset) async {
final ScrollController scrollController = ScrollController(initialScrollOffset: initialOffset);
addTearDown(scrollController.dispose);
await tester.pumpWidget(buildFrame(physics, scrollController: scrollController));
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
// The initialScrollOffset will be corrected during the first frame.
expect(scrollable.position.pixels, equals(expectedOffset));
}
await testOutOfBounds(const ClampingScrollPhysics(), -400.0, 0.0);
await testOutOfBounds(const ClampingScrollPhysics(), 800.0, 50.0);
});
testWidgets('ClampingScrollPhysics handles out of bounds ScrollPosition - jumpTo', (WidgetTester tester) async {
Future<void> testOutOfBounds(ScrollPhysics physics, double targetOffset, double endingOffset) async {
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
await tester.pumpWidget(buildFrame(physics, scrollController: scrollController));
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
expect(scrollable.position.pixels, equals(0.0));
scrollController.jumpTo(targetOffset);
await tester.pump();
expect(scrollable.position.pixels, equals(targetOffset));
await tester.pump(const Duration(seconds: 1)); // Allow overscroll animation to settle
expect(scrollable.position.pixels, equals(endingOffset));
}
await testOutOfBounds(const ClampingScrollPhysics(), -400.0, 0.0);
await testOutOfBounds(const ClampingScrollPhysics(), 800.0, 50.0);
});
}
| flutter/packages/flutter/test/widgets/clamp_overscrolls_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/clamp_overscrolls_test.dart",
"repo_id": "flutter",
"token_count": 1933
} | 687 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('DecoratedSliver creates, paints, and disposes BoxPainter', (WidgetTester tester) async {
final TestDecoration decoration = TestDecoration();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: CustomScrollView(
slivers: <Widget>[
DecoratedSliver(
decoration: decoration,
sliver: const SliverToBoxAdapter(
child: SizedBox(width: 100, height: 100),
),
)
],
)
)
));
expect(decoration.painters, hasLength(1));
expect(decoration.painters.last.lastConfiguration!.size, const Size(800, 100));
expect(decoration.painters.last.lastOffset, Offset.zero);
expect(decoration.painters.last.disposed, false);
await tester.pumpWidget(const SizedBox());
expect(decoration.painters, hasLength(1));
expect(decoration.painters.last.disposed, true);
});
testWidgets('DecoratedSliver can update box painter', (WidgetTester tester) async {
final TestDecoration decorationA = TestDecoration();
final TestDecoration decorationB = TestDecoration();
Decoration activateDecoration = decorationA;
late StateSetter localSetState;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
localSetState = setState;
return CustomScrollView(
slivers: <Widget>[
DecoratedSliver(
decoration: activateDecoration,
sliver: const SliverToBoxAdapter(
child: SizedBox(width: 100, height: 100),
),
)
],
);
},
)
)
));
expect(decorationA.painters, hasLength(1));
expect(decorationA.painters.last.paintCount, 1);
expect(decorationB.painters, hasLength(0));
localSetState(() {
activateDecoration = decorationB;
});
await tester.pump();
expect(decorationA.painters, hasLength(1));
expect(decorationB.painters, hasLength(1));
expect(decorationB.painters.last.paintCount, 1);
});
testWidgets('DecoratedSliver can update DecorationPosition', (WidgetTester tester) async {
final TestDecoration decoration = TestDecoration();
DecorationPosition activePosition = DecorationPosition.foreground;
late StateSetter localSetState;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
localSetState = setState;
return CustomScrollView(
slivers: <Widget>[
DecoratedSliver(
decoration: decoration,
position: activePosition,
sliver: const SliverToBoxAdapter(
child: SizedBox(width: 100, height: 100),
),
)
],
);
},
)
)
));
expect(decoration.painters, hasLength(1));
expect(decoration.painters.last.paintCount, 1);
localSetState(() {
activePosition = DecorationPosition.background;
});
await tester.pump();
expect(decoration.painters, hasLength(1));
expect(decoration.painters.last.paintCount, 2);
});
testWidgets('DecoratedSliver golden test', (WidgetTester tester) async {
const BoxDecoration decoration = BoxDecoration(
color: Colors.blue,
);
final Key backgroundKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: RepaintBoundary(
key: backgroundKey,
child: CustomScrollView(
slivers: <Widget>[
DecoratedSliver(
decoration: decoration,
sliver: SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate.fixed(<Widget>[
Container(
height: 100,
color: Colors.red,
),
Container(
height: 100,
color: Colors.yellow,
),
Container(
height: 100,
color: Colors.red,
),
]),
),
),
),
],
),
),
)
));
await expectLater(find.byKey(backgroundKey), matchesGoldenFile('decorated_sliver.moon.background.png'));
final Key foregroundKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: RepaintBoundary(
key: foregroundKey,
child: CustomScrollView(
slivers: <Widget>[
DecoratedSliver(
decoration: decoration,
position: DecorationPosition.foreground,
sliver: SliverPadding(
padding: const EdgeInsets.all(16),
sliver: SliverList(
delegate: SliverChildListDelegate.fixed(<Widget>[
Container(
height: 100,
color: Colors.red,
),
Container(
height: 100,
color: Colors.yellow,
),
Container(
height: 100,
color: Colors.red,
),
]),
),
),
),
],
),
),
)
));
await expectLater(find.byKey(foregroundKey), matchesGoldenFile('decorated_sliver.moon.foreground.png'));
});
testWidgets('DecoratedSliver paints its border correctly vertically', (WidgetTester tester) async {
const Key key = Key('DecoratedSliver with border');
const Color black = Color(0xFF000000);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: 300,
width: 100,
child: CustomScrollView(
controller: controller,
slivers: <Widget>[
DecoratedSliver(
key: key,
decoration: BoxDecoration(border: Border.all()),
sliver: const SliverToBoxAdapter(
child: SizedBox(width: 100, height: 500),
),
),
],
),
),
),
));
controller.jumpTo(200);
await tester.pumpAndSettle();
expect(find.byKey(key), paints..rect(
rect: const Offset(0.5, -199.5) & const Size(99, 499),
color: black,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
));
});
testWidgets('DecoratedSliver paints its border correctly vertically reverse', (WidgetTester tester) async {
const Key key = Key('DecoratedSliver with border');
const Color black = Color(0xFF000000);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: 300,
width: 100,
child: CustomScrollView(
controller: controller,
reverse: true,
slivers: <Widget>[
DecoratedSliver(
key: key,
decoration: BoxDecoration(border: Border.all()),
sliver: const SliverToBoxAdapter(
child: SizedBox(width: 100, height: 500),
),
),
],
),
),
),
));
controller.jumpTo(200);
await tester.pumpAndSettle();
expect(find.byKey(key), paints..rect(
rect: const Offset(0.5, -199.5) & const Size(99, 499),
color: black,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
));
});
testWidgets('DecoratedSliver paints its border correctly horizontally', (WidgetTester tester) async {
const Key key = Key('DecoratedSliver with border');
const Color black = Color(0xFF000000);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: 100,
width: 300,
child: CustomScrollView(
scrollDirection: Axis.horizontal,
controller: controller,
slivers: <Widget>[
DecoratedSliver(
key: key,
decoration: BoxDecoration(border: Border.all()),
sliver: const SliverToBoxAdapter(
child: SizedBox(width: 500, height: 100),
),
),
],
),
),
),
));
controller.jumpTo(200);
await tester.pumpAndSettle();
expect(find.byKey(key), paints..rect(
rect: const Offset(-199.5, 0.5) & const Size(499, 99),
color: black,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
));
});
testWidgets('DecoratedSliver paints its border correctly horizontally reverse', (WidgetTester tester) async {
const Key key = Key('DecoratedSliver with border');
const Color black = Color(0xFF000000);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: 100,
width: 300,
child: CustomScrollView(
scrollDirection: Axis.horizontal,
reverse: true,
controller: controller,
slivers: <Widget>[
DecoratedSliver(
key: key,
decoration: BoxDecoration(border: Border.all()),
sliver: const SliverToBoxAdapter(
child: SizedBox(width: 500, height: 100),
),
),
],
),
),
),
));
controller.jumpTo(200);
await tester.pumpAndSettle();
expect(find.byKey(key), paints..rect(
rect: const Offset(-199.5, 0.5) & const Size(499, 99),
color: black,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
));
});
testWidgets('DecoratedSliver works with SliverMainAxisGroup', (WidgetTester tester) async {
const Key key = Key('DecoratedSliver with border');
const Color black = Color(0xFF000000);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: 100,
width: 300,
child: CustomScrollView(
controller: controller,
slivers: <Widget>[
DecoratedSliver(
key: key,
decoration: BoxDecoration(border: Border.all()),
sliver: const SliverMainAxisGroup(
slivers: <Widget>[
SliverToBoxAdapter(child: SizedBox(height: 100)),
SliverToBoxAdapter(child: SizedBox(height: 100)),
],
),
),
],
),
),
),
));
await tester.pumpAndSettle();
expect(find.byKey(key), paints..rect(
rect: const Offset(0.5, 0.5) & const Size(299, 199),
color: black,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
));
});
testWidgets('DecoratedSliver works with SliverCrossAxisGroup', (WidgetTester tester) async {
const Key key = Key('DecoratedSliver with border');
const Color black = Color(0xFF000000);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: 100,
width: 300,
child: CustomScrollView(
controller: controller,
slivers: <Widget>[
DecoratedSliver(
key: key,
decoration: BoxDecoration(border: Border.all()),
sliver: const SliverCrossAxisGroup(
slivers: <Widget>[
SliverToBoxAdapter(child: SizedBox(height: 100)),
SliverToBoxAdapter(child: SizedBox(height: 100)),
],
),
),
],
),
),
),
));
await tester.pumpAndSettle();
expect(find.byKey(key), paints..rect(
rect: const Offset(0.5, 0.5) & const Size(299, 99),
color: black,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
));
});
testWidgets('DecoratedSliver draws only up to the bottom cache when sliver has infinite scroll extent', (WidgetTester tester) async {
const Key key = Key('DecoratedSliver with border');
const Color black = Color(0xFF000000);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
height: 100,
width: 300,
child: CustomScrollView(
controller: controller,
slivers: <Widget>[
DecoratedSliver(
key: key,
decoration: BoxDecoration(border: Border.all()),
sliver: SliverList.builder(
itemBuilder: (BuildContext context, int index) => const SizedBox(height: 100),
),
),
],
),
),
),
));
expect(find.byKey(key), paints..rect(
rect: const Offset(0.5, 0.5) & const Size(299, 349),
color: black,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
));
controller.jumpTo(200);
await tester.pumpAndSettle();
// Note that the bottom edge is of the rect is the same as above.
expect(find.byKey(key), paints..rect(
rect: const Offset(0.5, -199.5) & const Size(299, 549),
color: black,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
));
});
}
class TestDecoration extends Decoration {
final List<TestBoxPainter> painters = <TestBoxPainter>[];
@override
BoxPainter createBoxPainter([VoidCallback? onChanged]) {
final TestBoxPainter painter = TestBoxPainter();
painters.add(painter);
return painter;
}
}
class TestBoxPainter extends BoxPainter {
Offset? lastOffset;
ImageConfiguration? lastConfiguration;
bool disposed = false;
int paintCount = 0;
@override
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
lastOffset = offset;
lastConfiguration = configuration;
paintCount += 1;
}
@override
void dispose() {
assert(!disposed);
disposed = true;
super.dispose();
}
}
| flutter/packages/flutter/test/widgets/decorated_sliver_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/decorated_sliver_test.dart",
"repo_id": "flutter",
"token_count": 7622
} | 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'clipboard_utils.dart';
import 'keyboard_utils.dart';
Iterable<SingleActivator> allModifierVariants(LogicalKeyboardKey trigger) {
const Iterable<bool> trueFalse = <bool>[false, true];
return trueFalse.expand((bool shift) {
return trueFalse.expand((bool control) {
return trueFalse.expand((bool alt) {
return trueFalse.map((bool meta) => SingleActivator(trigger, shift: shift, control: control, alt: alt, meta: meta));
});
});
});
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final MockClipboard mockClipboard = MockClipboard();
setUp(() async {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
await Clipboard.setData(const ClipboardData(text: 'empty'));
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
});
const String testText =
'Now is the time for\n' // 20
'all good people\n' // 20 + 16 => 36
'to come to the aid\n' // 36 + 19 => 55
'of their country.'; // 55 + 17 => 72
const String testCluster = '👨👩👦👨👩👦👨👩👦'; // 8 * 3
// Exactly 20 characters each line.
const String testSoftwrapText =
'0123456789ABCDEFGHIJ'
'0123456789ABCDEFGHIJ'
'0123456789ABCDEFGHIJ'
'0123456789ABCDEFGHIJ';
const String testVerticalText = '1\n2\n3\n4\n5\n6\n7\n8\n9';
const String longText =
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. '
'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris '
'nisi ut aliquip ex ea commodo consequat. '
'Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. '
'Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris '
'nisi ut aliquip ex ea commodo consequat. ';
final TextEditingController controller = TextEditingController(text: testText);
final ScrollController scrollController = ScrollController();
final FocusNode focusNode = FocusNode();
Widget buildEditableText({
TextAlign textAlign = TextAlign.left,
bool readOnly = false,
bool obscured = false,
TextStyle style = const TextStyle(fontSize: 10.0),
bool enableInteractiveSelection = true
}) {
return MaterialApp(
home: Align(
alignment: Alignment.topLeft,
child: SizedBox(
// Softwrap at exactly 20 characters.
width: 201,
height: 200,
child: EditableText(
controller: controller,
showSelectionHandles: true,
autofocus: true,
focusNode: focusNode,
style: style,
textScaleFactor: 1,
// Avoid the cursor from taking up width.
cursorWidth: 0,
cursorColor: Colors.blue,
backgroundCursorColor: Colors.grey,
selectionControls: materialTextSelectionControls,
keyboardType: TextInputType.text,
maxLines: obscured ? 1 : null,
readOnly: readOnly,
textAlign: textAlign,
obscureText: obscured,
enableInteractiveSelection: enableInteractiveSelection,
scrollController: scrollController
),
),
),
);
}
group('Common text editing shortcuts: ',
() {
final TargetPlatformVariant allExceptApple = TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.macOS, TargetPlatform.iOS});
group('backspace', () {
const LogicalKeyboardKey trigger = LogicalKeyboardKey.backspace;
testWidgets('backspace', (WidgetTester tester) async {
controller.text = testText;
// Move the selection to the beginning of the 2nd line (after the newline
// character).
controller.selection = const TextSelection.collapsed(
offset: 20,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'Now is the time forall good people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 19),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('backspace readonly', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 20,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText(readOnly: true));
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 20, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all());
testWidgets('backspace at start', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'Now is the time for\n'
'all good people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all());
testWidgets('backspace at end', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 72,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'Now is the time for\n'
'all good people\n'
'to come to the aid\n'
'of their country',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 71),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('backspace inside of a cluster', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 1,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('backspace at cluster boundary', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 8,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
});
group('delete: ', () {
const LogicalKeyboardKey trigger = LogicalKeyboardKey.delete;
testWidgets('delete', (WidgetTester tester) async {
controller.text = testText;
// Move the selection to the beginning of the 2nd line (after the newline
// character).
controller.selection = const TextSelection.collapsed(
offset: 20,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'Now is the time for\n'
'll good people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 20),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('delete readonly', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 20,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText(readOnly: true));
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 20, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('delete at start', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'ow is the time for\n'
'all good people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('delete at end', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 72,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'Now is the time for\n'
'all good people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 72, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all());
testWidgets('delete inside of a cluster', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 1,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('delete at cluster boundary', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 8,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 8),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
});
group('Non-collapsed delete', () {
// This shares the same logic as backspace.
const LogicalKeyboardKey trigger = LogicalKeyboardKey.delete;
testWidgets('inside of a cluster', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection(
baseOffset: 9,
extentOffset: 12,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 8),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('at the boundaries of a cluster', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection(
baseOffset: 8,
extentOffset: 16,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 8),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('cross-cluster', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection(
baseOffset: 1,
extentOffset: 9,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
expect(
controller.text,
'👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('cross-cluster obscured text', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection(
baseOffset: 1,
extentOffset: 9,
);
await tester.pumpWidget(buildEditableText(obscured: true));
await sendKeyCombination(tester, const SingleActivator(trigger));
// Both emojis that were partially selected are deleted entirely.
expect(
controller.text,
'👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
});
group('word modifier + backspace', () {
const LogicalKeyboardKey trigger = LogicalKeyboardKey.backspace;
SingleActivator wordModifierBackspace() {
final bool isApple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS;
return SingleActivator(trigger, control: !isApple, alt: isApple);
}
testWidgets('WordModifier-backspace', (WidgetTester tester) async {
controller.text = testText;
// Place the caret before "people".
controller.selection = const TextSelection.collapsed(
offset: 29,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierBackspace());
expect(
controller.text,
'Now is the time for\n'
'all people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 24),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('readonly', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 29,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText(readOnly: true));
await sendKeyCombination(tester, wordModifierBackspace());
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 29, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all());
testWidgets('at start', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierBackspace());
expect(
controller.text,
'Now is the time for\n'
'all good people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all());
testWidgets('at end', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 72,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierBackspace());
expect(
controller.text,
'Now is the time for\n'
'all good people\n'
'to come to the aid\n'
'of their ',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 64),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('inside of a cluster', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 1,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierBackspace());
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('at cluster boundary', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 8,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierBackspace());
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
});
group('word modifier + delete', () {
const LogicalKeyboardKey trigger = LogicalKeyboardKey.delete;
SingleActivator wordModifierDelete() {
final bool isApple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS;
return SingleActivator(trigger, control: !isApple, alt: isApple);
}
testWidgets('WordModifier-delete', (WidgetTester tester) async {
controller.text = testText;
// Place the caret after "all".
controller.selection = const TextSelection.collapsed(
offset: 23,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierDelete());
expect(
controller.text,
'Now is the time for\n'
'all people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 23),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('readonly', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 23,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText(readOnly: true));
await sendKeyCombination(tester, wordModifierDelete());
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 23, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all());
testWidgets('at start', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierDelete());
expect(
controller.text,
' is the time for\n'
'all good people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('at end', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 72,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierDelete());
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 72, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all());
testWidgets('inside of a cluster', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 1,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierDelete());
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
testWidgets('at cluster boundary', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 8,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, wordModifierDelete());
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 8),
);
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS }));
});
group('line modifier + backspace', () {
const LogicalKeyboardKey trigger = LogicalKeyboardKey.backspace;
SingleActivator lineModifierBackspace() {
final bool isApple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS;
return SingleActivator(trigger, meta: isApple, alt: !isApple);
}
testWidgets('alt-backspace', (WidgetTester tester) async {
controller.text = testText;
// Place the caret before "people".
controller.selection = const TextSelection.collapsed(
offset: 29,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierBackspace());
expect(
controller.text,
'Now is the time for\n'
'people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 20),
);
}, variant: TargetPlatformVariant.all());
testWidgets('softwrap line boundary, upstream', (WidgetTester tester) async {
controller.text = testSoftwrapText;
// Place the caret at the end of the 2nd line.
controller.selection = const TextSelection.collapsed(
offset: 40,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierBackspace());
expect(
controller.text,
'0123456789ABCDEFGHIJ'
'0123456789ABCDEFGHIJ'
'0123456789ABCDEFGHIJ'
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 20),
);
}, variant: TargetPlatformVariant.all());
testWidgets('softwrap line boundary, downstream', (WidgetTester tester) async {
controller.text = testSoftwrapText;
// Place the caret at the beginning of the 3rd line.
controller.selection = const TextSelection.collapsed(
offset: 40,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierBackspace());
expect(
controller.selection,
const TextSelection.collapsed(offset: 40),
);
expect(controller.text, testSoftwrapText);
}, variant: TargetPlatformVariant.all());
testWidgets('readonly', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 29,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText(readOnly: true));
await sendKeyCombination(tester, lineModifierBackspace());
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 29, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all());
testWidgets('at start', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierBackspace());
expect(
controller.text,
'Now is the time for\n'
'all good people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all());
testWidgets('at end', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 72,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierBackspace());
expect(
controller.text,
'Now is the time for\n'
'all good people\n'
'to come to the aid\n'
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 55),
);
}, variant: TargetPlatformVariant.all());
testWidgets('inside of a cluster', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 1,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierBackspace());
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all());
testWidgets('at cluster boundary', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 8,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierBackspace());
expect(
controller.text,
'👨👩👦👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all());
});
group('line modifier + delete', () {
const LogicalKeyboardKey trigger = LogicalKeyboardKey.delete;
SingleActivator lineModifierDelete() {
final bool isApple = defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.iOS;
return SingleActivator(trigger, meta: isApple, alt: !isApple);
}
testWidgets('alt-delete', (WidgetTester tester) async {
controller.text = testText;
// Place the caret after "all".
controller.selection = const TextSelection.collapsed(
offset: 23,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierDelete());
expect(
controller.text,
'Now is the time for\n'
'all\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 23),
);
}, variant: TargetPlatformVariant.all());
testWidgets('softwrap line boundary, upstream', (WidgetTester tester) async {
controller.text = testSoftwrapText;
// Place the caret at the end of the 2nd line.
controller.selection = const TextSelection.collapsed(
offset: 40,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierDelete());
expect(controller.text, testSoftwrapText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 40, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all());
testWidgets('softwrap line boundary, downstream', (WidgetTester tester) async {
controller.text = testSoftwrapText;
// Place the caret at the beginning of the 3rd line.
controller.selection = const TextSelection.collapsed(
offset: 40,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierDelete());
expect(
controller.text,
'0123456789ABCDEFGHIJ'
'0123456789ABCDEFGHIJ'
'0123456789ABCDEFGHIJ'
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 40),
);
}, variant: TargetPlatformVariant.all());
testWidgets('readonly', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 23,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText(readOnly: true));
await sendKeyCombination(tester, lineModifierDelete());
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 23, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all());
testWidgets('at start', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierDelete());
expect(
controller.text,
'\n'
'all good people\n'
'to come to the aid\n'
'of their country.',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all());
testWidgets('at end', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 72,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierDelete());
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 72, affinity: TextAffinity.upstream),
);
}, variant: TargetPlatformVariant.all());
testWidgets('inside of a cluster', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 1,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierDelete());
expect(
controller.text,
isEmpty,
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
);
}, variant: TargetPlatformVariant.all());
testWidgets('at cluster boundary', (WidgetTester tester) async {
controller.text = testCluster;
controller.selection = const TextSelection.collapsed(
offset: 8,
affinity: TextAffinity.upstream,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, lineModifierDelete());
expect(
controller.text,
'👨👩👦',
);
expect(
controller.selection,
const TextSelection.collapsed(offset: 8),
);
}, variant: TargetPlatformVariant.all());
});
group('Arrow Movement', () {
group('left', () {
const LogicalKeyboardKey trigger = LogicalKeyboardKey.arrowLeft;
testWidgets('at start', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
for (final SingleActivator activator in allModifierVariants(trigger)) {
await sendKeyCombination(tester, activator);
await tester.pump();
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
reason: activator.toString(),
);
}
}, variant: TargetPlatformVariant.all());
testWidgets('base arrow key movement', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 20,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 19,
));
}, variant: TargetPlatformVariant.all());
testWidgets('word modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 7, // Before the first "the"
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger, control: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 4,
));
}, variant: allExceptApple);
testWidgets('line modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 24, // Before the "good".
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 20,
));
}, variant: allExceptApple);
});
group('right', () {
const LogicalKeyboardKey trigger = LogicalKeyboardKey.arrowRight;
testWidgets('at end', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 72,
);
await tester.pumpWidget(buildEditableText());
for (final SingleActivator activator in allModifierVariants(trigger)) {
await sendKeyCombination(tester, activator);
await tester.pump();
expect(controller.selection.isCollapsed, isTrue, reason: activator.toString());
expect(controller.selection.baseOffset, 72, reason: activator.toString());
}
}, variant: TargetPlatformVariant.all());
testWidgets('base arrow key movement', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 20,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 21,
));
}, variant: TargetPlatformVariant.all());
testWidgets('word modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 7, // Before the first "the"
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger, control: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 10,
));
}, variant: allExceptApple);
testWidgets('line modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 24, // Before the "good".
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(trigger, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 35, // Before the newline character.
affinity: TextAffinity.upstream,
));
}, variant: allExceptApple);
});
group('With initial non-collapsed selection', () {
testWidgets('base arrow key movement', (WidgetTester tester) async {
controller.text = testText;
// The word "all" is selected.
controller.selection = const TextSelection(
baseOffset: 20,
extentOffset: 23,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 20,
));
// The word "all" is selected.
controller.selection = const TextSelection(
baseOffset: 23,
extentOffset: 20,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 20,
));
// The word "all" is selected.
controller.selection = const TextSelection(
baseOffset: 20,
extentOffset: 23,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 23,
));
// The word "all" is selected.
controller.selection = const TextSelection(
baseOffset: 23,
extentOffset: 20,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 23,
));
}, variant: TargetPlatformVariant.all());
testWidgets('word modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, control: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 39, // Before "come".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, control: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 20, // Before "all".
//offset: 39, // Before "come".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, control: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 46, // After "to".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, control: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 28, // After "good".
));
}, variant: allExceptApple);
testWidgets('line modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 36, // Before "to".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 20, // Before "all".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 54, // After "aid".
affinity: TextAffinity.upstream,
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 35, // After "people".
affinity: TextAffinity.upstream,
));
}, variant: allExceptApple);
});
group('vertical movement', () {
testWidgets('at start', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
for (final SingleActivator activator in allModifierVariants(LogicalKeyboardKey.arrowUp)) {
await sendKeyCombination(tester, activator);
await tester.pump();
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
reason: activator.toString(),
);
}
for (final SingleActivator activator in allModifierVariants(LogicalKeyboardKey.pageUp)) {
await sendKeyCombination(tester, activator);
await tester.pump();
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
reason: activator.toString(),
);
}
}, variant: TargetPlatformVariant.all());
testWidgets('at end', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 72,
);
await tester.pumpWidget(buildEditableText());
for (final SingleActivator activator in allModifierVariants(LogicalKeyboardKey.arrowDown)) {
await sendKeyCombination(tester, activator);
await tester.pump();
expect(controller.text, testText);
expect(controller.selection.baseOffset, 72, reason: activator.toString());
expect(controller.selection.extentOffset, 72, reason: activator.toString());
}
for (final SingleActivator activator in allModifierVariants(LogicalKeyboardKey.pageDown)) {
await sendKeyCombination(tester, activator);
await tester.pump();
expect(controller.text, testText);
expect(controller.selection.baseOffset, 72, reason: activator.toString());
expect(controller.selection.extentOffset, 72, reason: activator.toString());
}
}, variant: TargetPlatformVariant.all());
testWidgets('run', (WidgetTester tester) async {
controller.text =
'aa\n' // 3
'a\n' // 3 + 2 = 5
'aa\n' // 5 + 3 = 8
'aaa\n' // 8 + 4 = 12
'aaaa'; // 12 + 4 = 16
controller.selection = const TextSelection.collapsed(
offset: 2,
);
await tester.pumpWidget(buildEditableText());
await tester.pump(); // Wait for autofocus to take effect.
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 4,
affinity: TextAffinity.upstream,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 7,
affinity: TextAffinity.upstream,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 10,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 14,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 16,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 10,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 7,
affinity: TextAffinity.upstream,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 4,
affinity: TextAffinity.upstream,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 2,
affinity: TextAffinity.upstream,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 0,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 4,
affinity: TextAffinity.upstream,
));
}, variant: TargetPlatformVariant.all());
testWidgets('run with page down/up', (WidgetTester tester) async {
controller.text =
'aa\n' // 3
'a\n' // 3 + 2 = 5
'aa\n' // 5 + 3 = 8
'aaa\n' // 8 + 4 = 12
'${"aaa\n" * 50}'
'aaaa';
controller.selection = const TextSelection.collapsed(offset: 2);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 4,
affinity: TextAffinity.upstream,
));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.pageDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(offset: 82));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(offset: 78));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.pageUp));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 2,
affinity: TextAffinity.upstream,
));
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{TargetPlatform.iOS, TargetPlatform.macOS})); // intended: on macOS Page Up/Down only scrolls
testWidgets('run can be interrupted by layout changes', (WidgetTester tester) async {
controller.text =
'aa\n' // 3
'a\n' // 3 + 2 = 5
'aa\n' // 5 + 3 = 8
'aaa\n' // 8 + 4 = 12
'aaaa'; // 12 + 4 = 16
controller.selection = const TextSelection.collapsed(
offset: 2,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 0,
));
// Layout changes.
await tester.pumpWidget(buildEditableText(textAlign: TextAlign.right));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 3,
));
}, variant: TargetPlatformVariant.all());
testWidgets('run can be interrupted by selection changes', (WidgetTester tester) async {
controller.text =
'aa\n' // 3
'a\n' // 3 + 2 = 5
'aa\n' // 5 + 3 = 8
'aaa\n' // 8 + 4 = 12
'aaaa'; // 12 + 4 = 16
controller.selection = const TextSelection.collapsed(
offset: 2,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 0,
));
controller.selection = const TextSelection.collapsed(
offset: 1,
);
await tester.pump();
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 3, // Would have been 4 if the run wasn't interrupted.
));
}, variant: TargetPlatformVariant.all());
testWidgets('long run with fractional text height', (WidgetTester tester) async {
controller.text = "${'źdźbło\n' * 49}źdźbło";
controller.selection = const TextSelection.collapsed(offset: 2);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 13.0, height: 1.17)));
for (int i = 1; i <= 49; i++) {
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
await tester.pump();
expect(
controller.selection,
TextSelection.collapsed(offset: 2 + i * 7),
reason: 'line $i',
);
}
for (int i = 49; i >= 1; i--) {
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp));
await tester.pump();
expect(
controller.selection,
TextSelection.collapsed(offset: 2 + (i - 1) * 7),
reason: 'line $i',
);
}
}, variant: TargetPlatformVariant.all());
// Regression test for https://github.com/flutter/flutter/issues/139196.
testWidgets('does not create invalid selection', (WidgetTester tester) async {
controller.value = const TextEditingValue(text: 'A', selection: TextSelection.collapsed(offset: 1));
await tester.pumpWidget(buildEditableText());
controller.value = const TextEditingValue(text: 'AA', selection: TextSelection.collapsed(offset: 2));
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown));
}, variant: TargetPlatformVariant.all());
});
});
},
skip: kIsWeb, // [intended] on web these keys are handled by the browser.
);
group('macOS shortcuts', () {
final TargetPlatformVariant macOSOnly = TargetPlatformVariant.only(TargetPlatform.macOS);
testWidgets('word modifier + arrowLeft', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 7, // Before the first "the"
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 4,
));
}, variant: macOSOnly);
testWidgets('word modifier + arrowRight', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 7, // Before the first "the"
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 10, // after the first "the"
));
}, variant: macOSOnly);
testWidgets('line modifier + arrowLeft', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 24, // Before the "good".
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 20,
));
}, variant: macOSOnly);
testWidgets('line modifier + arrowRight', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 24, // Before the "good".
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 35, // Before the newline character.
affinity: TextAffinity.upstream,
));
}, variant: macOSOnly);
testWidgets('word modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 39, // Before "come".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 20, // Before "all".
//offset: 39, // Before "come".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 46, // After "to".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 28, // After "good".
));
}, variant: macOSOnly);
testWidgets('line modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 36, // Before "to".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 20, // Before "all".
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 54, // After "aid".
affinity: TextAffinity.upstream,
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 35, // After "people".
affinity: TextAffinity.upstream,
));
}, variant: macOSOnly);
}, skip: kIsWeb); // [intended] on web these keys are handled by the browser.
group('Web does not accept', () {
final TargetPlatformVariant allExceptApple = TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS });
const TargetPlatformVariant appleOnly = TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.iOS });
group('macOS shortcuts', () {
testWidgets('word modifier + arrowLeft', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 7, // Before the first "the"
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(offset: 7));
}, variant: appleOnly);
testWidgets('word modifier + arrowRight', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 7, // Before the first "the"
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(offset: 7));
}, variant: appleOnly);
testWidgets('line modifier + arrowLeft', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 24, // Before the "good".
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(offset: 24,));
}, variant: appleOnly);
testWidgets('line modifier + arrowRight', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 24, // Before the "good".
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(
offset: 24, // Before the newline character.
));
}, variant: appleOnly);
testWidgets('word modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection(
baseOffset: 24,
extentOffset: 43,
));
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection(
baseOffset: 43,
extentOffset: 24,
));
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection(
baseOffset: 24,
extentOffset: 43,
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true));
await tester.pump();
expect(controller.selection, const TextSelection(
baseOffset: 43,
extentOffset: 24,
));
}, variant: appleOnly);
testWidgets('line modifier + arrow key movement', (WidgetTester tester) async {
controller.text = testText;
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection(
baseOffset: 24,
extentOffset: 43,
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection(
baseOffset: 43,
extentOffset: 24,
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 24,
extentOffset: 43,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection(
baseOffset: 24,
extentOffset: 43,
));
// "good" to "come" is selected.
controller.selection = const TextSelection(
baseOffset: 43,
extentOffset: 24,
);
await tester.pump();
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection(
baseOffset: 43,
extentOffset: 24,
));
}, variant: appleOnly);
});
testWidgets('vertical movement outside of selection',
(WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
for (final SingleActivator activator in allModifierVariants(LogicalKeyboardKey.arrowDown)) {
// Skip for the shift shortcut since web accepts it.
if (activator.shift) {
continue;
}
await sendKeyCombination(tester, activator);
await tester.pump();
expect(controller.text, testText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0),
reason: activator.toString(),
);
}
}, variant: TargetPlatformVariant.all());
testWidgets('select all non apple', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(offset: 0));
}, variant: allExceptApple);
testWidgets('select all apple', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(
offset: 0,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(offset: 0));
}, variant: appleOnly);
testWidgets('copy non apple', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection(
baseOffset: 0,
extentOffset: 4,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true));
await tester.pump();
final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
expect(clipboardData['text'], 'empty');
}, variant: allExceptApple);
testWidgets('copy apple', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection(
baseOffset: 0,
extentOffset: 4,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, meta: true));
await tester.pump();
final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
expect(clipboardData['text'], 'empty');
}, variant: appleOnly);
testWidgets('cut non apple', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection(
baseOffset: 0,
extentOffset: 4,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyX, control: true));
await tester.pump();
final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
expect(clipboardData['text'], 'empty');
expect(controller.selection, const TextSelection(
baseOffset: 0,
extentOffset: 4,
));
}, variant: allExceptApple);
testWidgets('cut apple', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection(
baseOffset: 0,
extentOffset: 4,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyX, meta: true));
await tester.pump();
final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>;
expect(clipboardData['text'], 'empty');
expect(controller.selection, const TextSelection(
baseOffset: 0,
extentOffset: 4,
));
}, variant: appleOnly);
testWidgets('paste non apple', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(offset: 0);
mockClipboard.clipboardData = <String, dynamic>{
'text': 'some text',
};
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyV, control: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(offset: 0));
expect(controller.text, testText);
}, variant: allExceptApple);
testWidgets('paste apple', (WidgetTester tester) async {
controller.text = testText;
controller.selection = const TextSelection.collapsed(offset: 0);
mockClipboard.clipboardData = <String, dynamic>{
'text': 'some text',
};
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyV, meta: true));
await tester.pump();
expect(controller.selection, const TextSelection.collapsed(offset: 0));
expect(controller.text, testText);
}, variant: appleOnly);
}, skip: !kIsWeb);// [intended] specific tests target web.
group('Web does accept', () {
final TargetPlatformVariant macOSOnly = TargetPlatformVariant.only(TargetPlatform.macOS);
const TargetPlatformVariant desktopExceptMacOS = TargetPlatformVariant(<TargetPlatform>{
TargetPlatform.linux,
TargetPlatform.windows,
});
testWidgets('select up', (WidgetTester tester) async {
const SingleActivator selectUp =
SingleActivator(LogicalKeyboardKey.arrowUp, shift: true);
controller.text = testVerticalText;
controller.selection = const TextSelection.collapsed(
offset: 5,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, selectUp);
await tester.pump();
expect(controller.text, testVerticalText);
expect(
controller.selection,
const TextSelection(
baseOffset: 5,
extentOffset: 3), // selection extends upwards from 5
reason: selectUp.toString(),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets('select down', (WidgetTester tester) async {
const SingleActivator selectDown =
SingleActivator(LogicalKeyboardKey.arrowDown, shift: true);
controller.text = testVerticalText;
controller.selection = const TextSelection.collapsed(
offset: 5,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, selectDown);
await tester.pump();
expect(controller.text, testVerticalText);
expect(
controller.selection,
const TextSelection(
baseOffset: 5,
extentOffset: 7), // selection extends downwards from 5
reason: selectDown.toString(),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets('select all up', (WidgetTester tester) async {
final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS;
final SingleActivator selectAllUp = isMacOS
? const SingleActivator(LogicalKeyboardKey.arrowUp,
shift: true, meta: true)
: const SingleActivator(LogicalKeyboardKey.arrowUp,
shift: true, alt: true);
controller.text = testVerticalText;
controller.selection = const TextSelection.collapsed(
offset: 5,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, selectAllUp);
await tester.pump();
expect(controller.text, testVerticalText);
expect(
controller.selection,
const TextSelection(
baseOffset: 5,
extentOffset: 0), // selection extends all the way up
reason: selectAllUp.toString(),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets('select all down', (WidgetTester tester) async {
final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS;
final SingleActivator selectAllDown = isMacOS
? const SingleActivator(LogicalKeyboardKey.arrowDown,
shift: true, meta: true)
: const SingleActivator(LogicalKeyboardKey.arrowDown,
shift: true, alt: true);
controller.text = testVerticalText;
controller.selection = const TextSelection.collapsed(
offset: 5,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, selectAllDown);
await tester.pump();
expect(controller.text, testVerticalText);
expect(
controller.selection,
const TextSelection(
baseOffset: 5,
extentOffset: 17), // selection extends all the way down
reason: selectAllDown.toString(),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets('select left', (WidgetTester tester) async {
const SingleActivator selectLeft =
SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true);
controller.text = 'testing';
controller.selection = const TextSelection.collapsed(
offset: 5,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, selectLeft);
await tester.pump();
expect(controller.text, 'testing');
expect(
controller.selection,
const TextSelection(baseOffset: 5, extentOffset: 4),
reason: selectLeft.toString(),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets('select right', (WidgetTester tester) async {
const SingleActivator selectRight =
SingleActivator(LogicalKeyboardKey.arrowRight, shift: true);
controller.text = 'testing';
controller.selection = const TextSelection.collapsed(
offset: 5,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, selectRight);
await tester.pump();
expect(controller.text, 'testing');
expect(
controller.selection,
const TextSelection(baseOffset: 5, extentOffset: 6),
reason: selectRight.toString(),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets(
'select left should not expand selection if selection is disabled',
(WidgetTester tester) async {
const SingleActivator selectLeft =
SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true);
controller.text = 'testing';
controller.selection = const TextSelection.collapsed(
offset: 5,
);
await tester
.pumpWidget(buildEditableText(enableInteractiveSelection: false));
await sendKeyCombination(tester, selectLeft);
await tester.pump();
expect(controller.text, 'testing');
expect(
controller.selection,
const TextSelection.collapsed(offset: 4), // should not expand selection
reason: selectLeft.toString(),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets(
'select right should not expand selection if selection is disabled',
(WidgetTester tester) async {
const SingleActivator selectRight =
SingleActivator(LogicalKeyboardKey.arrowRight, shift: true);
controller.text = 'testing';
controller.selection = const TextSelection.collapsed(offset: 5);
await tester
.pumpWidget(buildEditableText(enableInteractiveSelection: false));
await sendKeyCombination(tester, selectRight);
await tester.pump();
expect(controller.text, 'testing');
expect(
controller.selection,
const TextSelection.collapsed(offset: 6), // should not expand selection
reason: selectRight.toString(),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets('select all left', (WidgetTester tester) async {
final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS;
final SingleActivator selectAllLeft = isMacOS
? const SingleActivator(LogicalKeyboardKey.arrowLeft,
shift: true, meta: true)
: const SingleActivator(LogicalKeyboardKey.arrowLeft,
shift: true, alt: true);
controller.text = 'testing';
controller.selection = const TextSelection.collapsed(
offset: 5,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, selectAllLeft);
await tester.pump();
expect(controller.text, 'testing');
expect(
controller.selection,
const TextSelection(baseOffset: 5, extentOffset: 0),
reason: selectAllLeft.toString(),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets('select all right', (WidgetTester tester) async {
final bool isMacOS = defaultTargetPlatform == TargetPlatform.macOS;
final SingleActivator selectAllRight = isMacOS
? const SingleActivator(LogicalKeyboardKey.arrowRight,
shift: true, meta: true)
: const SingleActivator(LogicalKeyboardKey.arrowRight,
shift: true, alt: true);
controller.text = 'testing';
controller.selection = const TextSelection.collapsed(
offset: 5,
);
await tester.pumpWidget(buildEditableText());
await sendKeyCombination(tester, selectAllRight);
await tester.pump();
expect(controller.text, 'testing');
expect(
controller.selection,
const TextSelection(baseOffset: 5, extentOffset: 7),
reason: selectAllRight.toString(),
);
}, variant: TargetPlatformVariant.desktop());
group('macOS only', () {
testWidgets('pageUp scrolls 80% of viewport dimension upwards', (WidgetTester tester) async {
const SingleActivator pageUp = SingleActivator(LogicalKeyboardKey.pageUp);
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: controller.text.length);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, pageUp);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
TextSelection.collapsed(offset: controller.text.length), // selection stays the same.
reason: pageUp.toString(),
);
// default page up/down scroll increment is 80% of viewport dimension.
final double newOffset = initialScrollOffset - (0.8 * scrollController.position.viewportDimension);
expect(scrollController.offset, newOffset);
}, variant: macOSOnly);
testWidgets('pageUp + shift scrolls upwards and modifies selection', (WidgetTester tester) async {
const SingleActivator pageUp = SingleActivator(LogicalKeyboardKey.pageUp, shift: true);
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: controller.text.length);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, pageUp);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
TextSelection(baseOffset: controller.text.length, extentOffset: 232),
reason: pageUp.toString(),
);
expect(scrollController.offset, lessThan(initialScrollOffset));
}, variant: macOSOnly);
testWidgets('pageDown scrolls 80% of viewport dimension downwards', (WidgetTester tester) async {
const SingleActivator pageDown = SingleActivator(LogicalKeyboardKey.pageDown);
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: 0);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, pageDown);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0), // selection stays the same.
reason: pageDown.toString(),
);
// default page up/down scroll increment is 80% of viewport dimension.
final double newOffset = initialScrollOffset + (0.8 * scrollController.position.viewportDimension);
expect(scrollController.offset, newOffset);
}, variant: macOSOnly);
testWidgets('pageDown + shift scrolls downwards and modifies selection', (WidgetTester tester) async {
const SingleActivator pageDown = SingleActivator(LogicalKeyboardKey.pageDown, shift: true);
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: 0);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, pageDown);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
const TextSelection(baseOffset: 0, extentOffset: 238),
reason: pageDown.toString(),
);
expect(scrollController.offset, greaterThan(initialScrollOffset));
}, variant: macOSOnly);
testWidgets('end scrolls to the end of the text field', (WidgetTester tester) async {
const SingleActivator end = SingleActivator(LogicalKeyboardKey.end);
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: 0);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, end);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0), // selection stays the same.
reason: end.toString(),
);
// scrolls to end.
final double newOffset = scrollController.position.maxScrollExtent;
expect(scrollController.offset, newOffset);
}, variant: macOSOnly);
testWidgets('end + shift scrolls to the end of the text field and selects everything', (WidgetTester tester) async {
const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, shift: true);
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: 0);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, end);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
TextSelection(baseOffset: 0, extentOffset: controller.text.length), // selection changes.
reason: end.toString(),
);
// scrolls to end.
final double newOffset = scrollController.position.maxScrollExtent;
expect(scrollController.offset, newOffset);
}, variant: macOSOnly);
testWidgets('home scrolls to the beginning of the text field', (WidgetTester tester) async {
const SingleActivator home = SingleActivator(LogicalKeyboardKey.home);
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: controller.text.length);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, home);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
TextSelection.collapsed(offset: controller.text.length), // selection stays the same.
reason: home.toString(),
);
// scrolls to beginning.
const double newOffset = 0;
expect(scrollController.offset, newOffset);
}, variant: macOSOnly);
testWidgets('home + shift scrolls to the beginning of text field and selects everything', (WidgetTester tester) async {
const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, shift: true);
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: controller.text.length);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, home);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
TextSelection(baseOffset: controller.text.length, extentOffset: 0), // selection changes.
reason: home.toString(),
);
// scrolls to beginning.
const double newOffset = 0;
expect(scrollController.offset, newOffset);
}, variant: macOSOnly);
});
group('non-macOS', () {
testWidgets('pageUp scrolls up and modifies selection', (WidgetTester tester) async {
const SingleActivator pageUp = SingleActivator(LogicalKeyboardKey.pageUp);
final int initialSelectionOffset = controller.text.length;
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: initialSelectionOffset);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, pageUp);
await tester.pump();
expect(controller.text, longText);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, lessThan(initialSelectionOffset));
expect(scrollController.offset, lessThan(initialScrollOffset));
}, variant: desktopExceptMacOS);
testWidgets('pageUp + shift scrolls up and modifies selection', (WidgetTester tester) async {
const SingleActivator pageUp = SingleActivator(LogicalKeyboardKey.pageUp, shift: true);
final int initialSelectionOffset = controller.text.length;
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: initialSelectionOffset);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, pageUp);
await tester.pump();
expect(controller.text, longText);
expect(controller.selection.isCollapsed, isFalse);
expect(controller.selection.baseOffset, initialSelectionOffset);
expect(controller.selection.extentOffset, lessThan(initialSelectionOffset));
expect(scrollController.offset, lessThan(initialScrollOffset));
}, variant: desktopExceptMacOS);
testWidgets('pageDown scrolls down and modifies selection', (WidgetTester tester) async {
const SingleActivator pageDown = SingleActivator(LogicalKeyboardKey.pageDown);
const int initialSelectionOffset = 0;
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: initialSelectionOffset);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, pageDown);
await tester.pump();
expect(controller.text, longText);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, greaterThan(initialSelectionOffset));
expect(scrollController.offset, greaterThan(initialScrollOffset));
}, variant: desktopExceptMacOS);
testWidgets('pageDown + shift scrolls down and modifies selection', (WidgetTester tester) async {
const SingleActivator pageDown = SingleActivator(LogicalKeyboardKey.pageDown, shift: true);
const int initialSelectionOffset = 0;
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: initialSelectionOffset);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, pageDown);
await tester.pump();
expect(controller.text, longText);
expect(controller.selection.isCollapsed, isFalse);
expect(controller.selection.baseOffset, initialSelectionOffset);
expect(controller.selection.extentOffset, greaterThan(initialSelectionOffset));
expect(scrollController.offset, greaterThan(initialScrollOffset));
}, variant: desktopExceptMacOS);
testWidgets('end moves selection to the end of the line, no scroll', (WidgetTester tester) async {
const SingleActivator end = SingleActivator(LogicalKeyboardKey.end);
const int initialSelectionOffset = 0;
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: initialSelectionOffset);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, end);
await tester.pump();
expect(controller.text, longText);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, greaterThan(initialSelectionOffset));
expect(scrollController.offset, initialScrollOffset); // no scroll.
}, variant: desktopExceptMacOS);
testWidgets('end + shift highlights selection to the end of the line, no scroll', (WidgetTester tester) async {
const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, shift: true);
const int initialSelectionOffset = 0;
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: initialSelectionOffset);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, end);
await tester.pump();
expect(controller.text, longText);
expect(controller.selection.isCollapsed, isFalse);
expect(controller.selection.baseOffset, initialSelectionOffset);
expect(controller.selection.extentOffset, greaterThan(initialSelectionOffset));
expect(scrollController.offset, initialScrollOffset); // no scroll.
}, variant: desktopExceptMacOS);
testWidgets('home moves selection to the beginning of the line, no scroll', (WidgetTester tester) async {
const SingleActivator home = SingleActivator(LogicalKeyboardKey.home);
final int initialSelectionOffset = controller.text.length;
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: initialSelectionOffset);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, home);
await tester.pump();
expect(controller.text, longText);
expect(controller.selection.isCollapsed, isTrue);
expect(controller.selection.baseOffset, lessThan(initialSelectionOffset));
expect(scrollController.offset, initialScrollOffset); // no scroll.
}, variant: desktopExceptMacOS);
testWidgets('home + shift highlights selection to the beginning of the line, no scroll', (WidgetTester tester) async {
const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, shift: true);
final int initialSelectionOffset = controller.text.length;
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: initialSelectionOffset);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, home);
await tester.pump();
expect(controller.text, longText);
expect(controller.selection.isCollapsed, isFalse);
expect(controller.selection.baseOffset, initialSelectionOffset);
expect(controller.selection.extentOffset, lessThan(initialSelectionOffset));
expect(scrollController.offset, initialScrollOffset); // no scroll.
}, variant: desktopExceptMacOS);
testWidgets('end + ctrl scrolls to the end of the text field and changes selection on Windows', (WidgetTester tester) async {
const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, control: true);
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: 0);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, end);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
TextSelection.collapsed(offset: controller.text.length), // selection goes to end.
reason: end.toString(),
);
// scrolls to end.
final double newOffset = scrollController.position.maxScrollExtent;
expect(scrollController.offset, newOffset);
}, variant: TargetPlatformVariant.only(TargetPlatform.windows));
testWidgets('end + shift + ctrl scrolls to the end of the text field and highlights everything on Windows', (WidgetTester tester) async {
const SingleActivator end = SingleActivator(LogicalKeyboardKey.end, control: true, shift: true);
controller.text = longText;
controller.selection = const TextSelection.collapsed(offset: 0);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, 0);
await sendKeyCombination(tester, end);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
TextSelection(baseOffset: 0, extentOffset: controller.text.length), // selection goes to end.
reason: end.toString(),
);
// scrolls to end.
final double newOffset = scrollController.position.maxScrollExtent;
expect(scrollController.offset, newOffset);
}, variant: TargetPlatformVariant.only(TargetPlatform.windows));
testWidgets('home + ctrl scrolls to the beginning of the text field and changes selection on Windows', (WidgetTester tester) async {
const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, control: true);
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: controller.text.length);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, home);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
const TextSelection.collapsed(offset: 0), // selection goes to beginning.
reason: home.toString(),
);
// scrolls to beginning.
const double newOffset = 0;
expect(scrollController.offset, newOffset);
}, variant: TargetPlatformVariant.only(TargetPlatform.windows));
testWidgets('home + shift + ctrl scrolls to the beginning of the text field and highlights everything on Windows', (WidgetTester tester) async {
const SingleActivator home = SingleActivator(LogicalKeyboardKey.home, control: true, shift: true);
controller.text = longText;
controller.selection = TextSelection.collapsed(offset: controller.text.length);
await tester.pumpWidget(buildEditableText(style: const TextStyle(fontSize: 12)));
await tester.pumpAndSettle();
final double initialScrollOffset = scrollController.offset;
expect(initialScrollOffset, scrollController.position.maxScrollExtent);
await sendKeyCombination(tester, home);
await tester.pump();
expect(controller.text, longText);
expect(
controller.selection,
TextSelection(baseOffset: controller.text.length, extentOffset: 0), // selection goes to beginning.
reason: home.toString(),
);
// scrolls to beginning.
const double newOffset = 0;
expect(scrollController.offset, newOffset);
}, variant: TargetPlatformVariant.only(TargetPlatform.windows));
});
}, skip: !kIsWeb); // [intended] specific tests target web.
}
| flutter/packages/flutter/test/widgets/editable_text_shortcuts_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/editable_text_shortcuts_test.dart",
"repo_id": "flutter",
"token_count": 46031
} | 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('FractionallySizedBox', (WidgetTester tester) async {
final GlobalKey inner = GlobalKey();
await tester.pumpWidget(OverflowBox(
minWidth: 0.0,
maxWidth: 100.0,
minHeight: 0.0,
maxHeight: 100.0,
alignment: Alignment.topLeft,
child: Center(
child: FractionallySizedBox(
widthFactor: 0.5,
heightFactor: 0.25,
child: Container(
key: inner,
),
),
),
));
final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox;
expect(box.size, equals(const Size(50.0, 25.0)));
expect(box.localToGlobal(Offset.zero), equals(const Offset(25.0, 37.5)));
});
testWidgets('FractionallySizedBox alignment', (WidgetTester tester) async {
final GlobalKey inner = GlobalKey();
await tester.pumpWidget(Directionality(
textDirection: TextDirection.rtl,
child: FractionallySizedBox(
widthFactor: 0.5,
heightFactor: 0.5,
alignment: Alignment.topRight,
child: Placeholder(key: inner),
),
));
final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox;
expect(box.size, equals(const Size(400.0, 300.0)));
expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(800.0 - 400.0 / 2.0, 0.0 + 300.0 / 2.0)));
});
testWidgets('FractionallySizedBox alignment (direction-sensitive)', (WidgetTester tester) async {
final GlobalKey inner = GlobalKey();
await tester.pumpWidget(Directionality(
textDirection: TextDirection.rtl,
child: FractionallySizedBox(
widthFactor: 0.5,
heightFactor: 0.5,
alignment: AlignmentDirectional.topEnd,
child: Placeholder(key: inner),
),
));
final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox;
expect(box.size, equals(const Size(400.0, 300.0)));
expect(box.localToGlobal(box.size.center(Offset.zero)), equals(const Offset(0.0 + 400.0 / 2.0, 0.0 + 300.0 / 2.0)));
});
testWidgets('OverflowBox alignment with FractionallySizedBox', (WidgetTester tester) async {
final GlobalKey inner = GlobalKey();
await tester.pumpWidget(Directionality(
textDirection: TextDirection.rtl,
child: OverflowBox(
minWidth: 0.0,
maxWidth: 100.0,
minHeight: 0.0,
maxHeight: 100.0,
alignment: AlignmentDirectional.topEnd,
child: Center(
child: FractionallySizedBox(
widthFactor: 0.5,
heightFactor: 0.25,
child: Container(
key: inner,
),
),
),
),
));
final RenderBox box = inner.currentContext!.findRenderObject()! as RenderBox;
expect(box.size, equals(const Size(50.0, 25.0)));
expect(box.localToGlobal(Offset.zero), equals(const Offset(25.0, 37.5)));
});
}
| flutter/packages/flutter/test/widgets/fractionally_sized_box_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/fractionally_sized_box_test.dart",
"repo_id": "flutter",
"token_count": 1328
} | 690 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Can set opacity for an Icon', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
color: Color(0xFF666666),
opacity: 0.5,
),
child: Icon(IconData(0xd0a0, fontFamily: 'Arial')),
),
),
);
final RichText text = tester.widget(find.byType(RichText));
expect(text.text.style!.color, const Color(0xFF666666).withOpacity(0.5));
});
testWidgets('Icon sizing - no theme, default size', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(null),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(24.0)));
});
testWidgets('Icon sizing - no theme, explicit size', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(
null,
size: 96.0,
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(96.0)));
});
testWidgets('Icon sizing - sized theme', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconTheme(
data: IconThemeData(size: 36.0),
child: Icon(null),
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(36.0)));
});
testWidgets('Icon sizing - sized theme, explicit size', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconTheme(
data: IconThemeData(size: 36.0),
child: Icon(
null,
size: 48.0,
),
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(48.0)));
});
testWidgets('Icon sizing - sizeless theme, default size', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconTheme(
data: IconThemeData(),
child: Icon(null),
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(24.0)));
});
testWidgets('Icon sizing - no theme, default size, considering text scaler', (WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(
textScaler: _TextDoubler(),
),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(
null,
applyTextScaling: true,
),
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(48.0)));
});
testWidgets('Icon sizing - no theme, explicit size, considering text scaler', (WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(
textScaler: _TextDoubler(),
),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(
null,
size: 96.0,
applyTextScaling: true,
),
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(192.0)));
});
testWidgets('Icon sizing - sized theme, considering text scaler', (WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(
textScaler: _TextDoubler(),
),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconTheme(
data: IconThemeData(
size: 36.0,
applyTextScaling: true,
),
child: Icon(null),
),
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(72.0)));
});
testWidgets('Icon sizing - sized theme, explicit size, considering text scale', (WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(
textScaler: _TextDoubler(),
),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconTheme(
data: IconThemeData(
size: 36.0,
applyTextScaling: true,
),
child: Icon(
null,
size: 48.0,
applyTextScaling: false,
),
),
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(48.0)));
});
testWidgets('Icon sizing - sizeless theme, default size, default consideration for text scaler', (WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(
textScaler: _TextDoubler(),
),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IconTheme(
data: IconThemeData(),
child: Icon(null),
),
),
),
),
);
final RenderBox renderObject = tester.renderObject(find.byType(Icon));
expect(renderObject.size, equals(const Size.square(24.0)));
});
testWidgets('Icon with custom font', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(IconData(0x41, fontFamily: 'Roboto')),
),
),
);
final RichText richText = tester.firstWidget(find.byType(RichText));
expect(richText.text.style!.fontFamily, equals('Roboto'));
});
testWidgets("Icon's TextStyle makes sure the font body is vertically center-aligned", (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/138592.
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(IconData(0x41)),
),
),
);
final RichText richText = tester.firstWidget(find.byType(RichText));
expect(richText.text.style?.height, 1.0);
expect(richText.text.style?.leadingDistribution, TextLeadingDistribution.even);
});
testWidgets('Icon with custom fontFamilyFallback', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(IconData(0x41, fontFamilyFallback: <String>['FallbackFont'])),
),
),
);
final RichText richText = tester.firstWidget(find.byType(RichText));
expect(richText.text.style!.fontFamilyFallback, equals(<String>['FallbackFont']));
});
testWidgets('Icon with semantic label', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(
Icons.title,
semanticLabel: 'a label',
),
),
),
);
expect(semantics, includesNodeWith(label: 'a label'));
semantics.dispose();
});
testWidgets('Null icon with semantic label', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(
null,
semanticLabel: 'a label',
),
),
),
);
expect(semantics, includesNodeWith(label: 'a label'));
semantics.dispose();
});
testWidgets("Changing semantic label from null doesn't rebuild tree ", (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(Icons.time_to_leave),
),
),
);
final Element richText1 = tester.element(find.byType(RichText));
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Icon(
Icons.time_to_leave,
semanticLabel: 'a label',
),
),
),
);
final Element richText2 = tester.element(find.byType(RichText));
// Compare a leaf Element in the Icon subtree before and after changing the
// semanticLabel to make sure the subtree was not rebuilt.
expect(richText2, same(richText1));
});
testWidgets('IconData comparison', (WidgetTester tester) async {
expect(const IconData(123), const IconData(123));
expect(const IconData(123), isNot(const IconData(123, matchTextDirection: true)));
expect(const IconData(123), isNot(const IconData(123, fontFamily: 'f')));
expect(const IconData(123), isNot(const IconData(123, fontPackage: 'p')));
expect(const IconData(123).hashCode, const IconData(123).hashCode);
expect(const IconData(123).hashCode, isNot(const IconData(123, matchTextDirection: true).hashCode));
expect(const IconData(123).hashCode, isNot(const IconData(123, fontFamily: 'f').hashCode));
expect(const IconData(123).hashCode, isNot(const IconData(123, fontPackage: 'p').hashCode));
expect(const IconData(123).toString(), 'IconData(U+0007B)');
});
testWidgets('Fill, weight, grade, and optical size variations are passed', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Icon(Icons.abc),
),
);
RichText text = tester.widget(find.byType(RichText));
expect(text.text.style!.fontVariations, <FontVariation>[
const FontVariation('FILL', 0.0),
const FontVariation('wght', 400.0),
const FontVariation('GRAD', 0.0),
const FontVariation('opsz', 48.0)
]);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Icon(Icons.abc, fill: 0.5, weight: 300, grade: 200, opticalSize: 48),
),
);
text = tester.widget(find.byType(RichText));
expect(text.text.style!.fontVariations, isNotNull);
expect(text.text.style!.fontVariations, <FontVariation>[
const FontVariation('FILL', 0.5),
const FontVariation('wght', 300.0),
const FontVariation('GRAD', 200.0),
const FontVariation('opsz', 48.0)
]);
});
testWidgets('Fill, weight, grade, and optical size can be set at the theme-level', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
fill: 0.2,
weight: 3.0,
grade: 4.0,
opticalSize: 5.0,
),
child: Icon(Icons.abc),
),
),
);
final RichText text = tester.widget(find.byType(RichText));
expect(text.text.style!.fontVariations, <FontVariation>[
const FontVariation('FILL', 0.2),
const FontVariation('wght', 3.0),
const FontVariation('GRAD', 4.0),
const FontVariation('opsz', 5.0)
]);
});
testWidgets('Theme-level fill, weight, grade, and optical size can be overridden', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: IconTheme(
data: IconThemeData(
fill: 0.2,
weight: 3.0,
grade: 4.0,
opticalSize: 5.0,
),
child: Icon(Icons.abc, fill: 0.6, weight: 7.0, grade: 8.0, opticalSize: 9.0),
),
),
);
final RichText text = tester.widget(find.byType(RichText));
expect(text.text.style!.fontVariations, isNotNull);
expect(text.text.style!.fontVariations, <FontVariation>[
const FontVariation('FILL', 0.6),
const FontVariation('wght', 7.0),
const FontVariation('GRAD', 8.0),
const FontVariation('opsz', 9.0)
]);
});
test('Throws if given invalid values', () {
expect(() => Icon(Icons.abc, fill: -0.1), throwsAssertionError);
expect(() => Icon(Icons.abc, fill: 1.1), throwsAssertionError);
expect(() => Icon(Icons.abc, weight: -0.1), throwsAssertionError);
expect(() => Icon(Icons.abc, weight: 0.0), throwsAssertionError);
expect(() => Icon(Icons.abc, opticalSize: -0.1), throwsAssertionError);
expect(() => Icon(Icons.abc, opticalSize: 0), throwsAssertionError);
});
}
final class _TextDoubler extends TextScaler {
const _TextDoubler();
@override
double scale(double fontSize) => fontSize * 2.0;
@override
double get textScaleFactor => 2.0;
}
| flutter/packages/flutter/test/widgets/icon_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/icon_test.dart",
"repo_id": "flutter",
"token_count": 6170
} | 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class TestRoute extends PageRouteBuilder<void> {
TestRoute(Widget child) : super(
pageBuilder: (BuildContext _, Animation<double> __, Animation<double> ___) => child,
);
}
class IconTextBox extends StatelessWidget {
const IconTextBox(this.text, { super.key });
final String text;
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.center,
child: Row(
children: <Widget>[const Icon(IconData(0x41, fontFamily: 'Roboto')), Text(text)],
),
);
}
}
void main() {
testWidgets('InheritedTheme.captureAll()', (WidgetTester tester) async {
const double fontSize = 32;
const double iconSize = 48;
const Color textColor = Color(0xFF00FF00);
const Color iconColor = Color(0xFF0000FF);
bool useCaptureAll = false;
late BuildContext navigatorContext;
Widget buildFrame() {
return WidgetsApp(
color: const Color(0xFFFFFFFF),
onGenerateRoute: (RouteSettings settings) {
return TestRoute(
// The outer DefaultTextStyle and IconTheme widgets must have
// no effect on the test because InheritedTheme.captureAll()
// is required to only save the closest InheritedTheme ancestors.
DefaultTextStyle(
style: const TextStyle(fontSize: iconSize, color: iconColor),
child: IconTheme(
data: const IconThemeData(size: fontSize, color: textColor),
// The inner DefaultTextStyle and IconTheme widgets define
// InheritedThemes that captureAll() will wrap() around
// TestRoute's IconTextBox child.
child: DefaultTextStyle(
style: const TextStyle(fontSize: fontSize, color: textColor),
child: IconTheme(
data: const IconThemeData(size: iconSize, color: iconColor),
child: Builder(
builder: (BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
navigatorContext = context;
Navigator.of(context).push(
TestRoute(
useCaptureAll
? InheritedTheme.captureAll(context, const IconTextBox('Hello'))
: const IconTextBox('Hello'),
),
);
},
child: const IconTextBox('Tap'),
);
},
),
),
),
),
),
);
},
);
}
TextStyle getIconStyle() {
return tester.widget<RichText>(
find.descendant(
of: find.byType(Icon),
matching: find.byType(RichText),
),
).text.style!;
}
TextStyle getTextStyle(String text) {
return tester.widget<RichText>(
find.descendant(
of: find.text(text),
matching: find.byType(RichText),
),
).text.style!;
}
useCaptureAll = false;
await tester.pumpWidget(buildFrame());
expect(find.text('Tap'), findsOneWidget);
expect(find.text('Hello'), findsNothing);
expect(getTextStyle('Tap').color, textColor);
expect(getTextStyle('Tap').fontSize, fontSize);
expect(getIconStyle().color, iconColor);
expect(getIconStyle().fontSize, iconSize);
// Tap to show the TestRoute
await tester.tap(find.text('Tap'));
await tester.pumpAndSettle(); // route transition
expect(find.text('Tap'), findsNothing);
expect(find.text('Hello'), findsOneWidget);
// The new route's text and icons will NOT inherit the DefaultTextStyle or
// IconTheme values.
expect(getTextStyle('Hello').color, isNot(textColor));
expect(getTextStyle('Hello').fontSize, isNot(fontSize));
expect(getIconStyle().color, isNot(iconColor));
expect(getIconStyle().fontSize, isNot(iconSize));
// Return to the home route
useCaptureAll = true;
Navigator.of(navigatorContext).pop();
await tester.pumpAndSettle(); // route transition
// Verify that all is the same as it was when the test started
expect(find.text('Tap'), findsOneWidget);
expect(find.text('Hello'), findsNothing);
expect(getTextStyle('Tap').color, textColor);
expect(getTextStyle('Tap').fontSize, fontSize);
expect(getIconStyle().color, iconColor);
expect(getIconStyle().fontSize, iconSize);
// Tap to show the TestRoute. The test route's IconTextBox will have been
// wrapped with InheritedTheme.captureAll().
await tester.tap(find.text('Tap'));
await tester.pumpAndSettle(); // route transition
expect(find.text('Tap'), findsNothing);
expect(find.text('Hello'), findsOneWidget);
// The new route's text and icons will inherit the DefaultTextStyle or
// IconTheme values because captureAll.
expect(getTextStyle('Hello').color, textColor);
expect(getTextStyle('Hello').fontSize, fontSize);
expect(getIconStyle().color, iconColor);
expect(getIconStyle().fontSize, iconSize);
});
testWidgets('InheritedTheme.captureAll() multiple IconTheme ancestors', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/39087
const Color outerColor = Color(0xFF0000FF);
const Color innerColor = Color(0xFF00FF00);
const double iconSize = 48;
final Key icon1 = UniqueKey();
final Key icon2 = UniqueKey();
await tester.pumpWidget(
WidgetsApp(
color: const Color(0xFFFFFFFF),
onGenerateRoute: (RouteSettings settings) {
return TestRoute(
IconTheme(
data: const IconThemeData(color: outerColor),
child: IconTheme(
data: const IconThemeData(size: iconSize, color: innerColor),
child: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Icon(const IconData(0x41, fontFamily: 'Roboto'), key: icon1),
Builder(
builder: (BuildContext context) {
// The same IconThemes are visible from this context
// and the context that the widget returned by captureAll()
// is built in. So only the inner green IconTheme should
// apply to the icon, i.e. both icons will be big and green.
return InheritedTheme.captureAll(
context,
Icon(const IconData(0x41, fontFamily: 'Roboto'), key: icon2),
);
},
),
],
),
),
),
),
);
},
),
);
TextStyle getIconStyle(Key key) {
return tester.widget<RichText>(
find.descendant(
of: find.byKey(key),
matching: find.byType(RichText),
),
).text.style!;
}
expect(getIconStyle(icon1).color, innerColor);
expect(getIconStyle(icon1).fontSize, iconSize);
expect(getIconStyle(icon2).color, innerColor);
expect(getIconStyle(icon2).fontSize, iconSize);
});
testWidgets('InheritedTheme.captureAll() multiple DefaultTextStyle ancestors', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/39087
const Color textColor = Color(0xFF00FF00);
await tester.pumpWidget(
WidgetsApp(
color: const Color(0xFFFFFFFF),
onGenerateRoute: (RouteSettings settings) {
return TestRoute(
DefaultTextStyle(
style: const TextStyle(fontSize: 48),
child: DefaultTextStyle(
style: const TextStyle(color: textColor),
child: Row(
children: <Widget>[
const Text('Hello'),
Builder(
builder: (BuildContext context) {
return InheritedTheme.captureAll(context, const Text('World'));
},
),
],
),
),
),
);
},
),
);
TextStyle getTextStyle(String text) {
return tester.widget<RichText>(
find.descendant(
of: find.text(text),
matching: find.byType(RichText),
),
).text.style!;
}
expect(getTextStyle('Hello').fontSize, null);
expect(getTextStyle('Hello').color, textColor);
expect(getTextStyle('World').fontSize, null);
expect(getTextStyle('World').color, textColor);
});
}
| flutter/packages/flutter/test/widgets/inherited_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/inherited_theme_test.dart",
"repo_id": "flutter",
"token_count": 4234
} | 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'test_widgets.dart';
void main() {
testWidgets('ListView.builder mount/dismount smoke test', (WidgetTester tester) async {
final List<int> callbackTracker = <int>[];
// the root view is 800x600 in the test environment
// so if our widget is 100 pixels tall, it should fit exactly 6 times.
Widget builder() {
return Directionality(
textDirection: TextDirection.ltr,
child: FlipWidget(
left: ListView.builder(
itemExtent: 100.0,
itemBuilder: (BuildContext context, int index) {
callbackTracker.add(index);
return SizedBox(
key: ValueKey<int>(index),
height: 100.0,
child: Text('$index'),
);
},
),
right: const Text('Not Today'),
),
);
}
await tester.pumpWidget(builder());
final FlipWidgetState testWidget = tester.state(find.byType(FlipWidget));
expect(callbackTracker, equals(<int>[
0, 1, 2, 3, 4, 5, // visible in viewport
6, 7, 8, // in caching area
]));
check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[ 6, 7, 8]);
callbackTracker.clear();
testWidget.flip();
await tester.pump();
expect(callbackTracker, equals(<int>[]));
callbackTracker.clear();
testWidget.flip();
await tester.pump();
expect(callbackTracker, equals(<int>[
0, 1, 2, 3, 4, 5,
6, 7, 8, // in caching area
]));
check(visible: <int>[0, 1, 2, 3, 4, 5], hidden: <int>[ 6, 7, 8]);
});
testWidgets('ListView.builder vertical', (WidgetTester tester) async {
final List<int> callbackTracker = <int>[];
// the root view is 800x600 in the test environment
// so if our widget is 200 pixels tall, it should fit exactly 3 times.
// but if we are offset by 300 pixels, there will be 4, numbered 1-4.
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return SizedBox(
key: ValueKey<int>(index),
width: 500.0, // this should be ignored
height: 400.0, // should be overridden by itemExtent
child: Text('$index', textDirection: TextDirection.ltr),
);
}
Widget buildWidget() {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
return Directionality(
textDirection: TextDirection.ltr,
child: FlipWidget(
left: ListView.builder(
controller: controller,
itemExtent: 200.0,
itemBuilder: itemBuilder,
),
right: const Text('Not Today'),
),
);
}
void jumpTo(double newScrollOffset) {
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
scrollable.position.jumpTo(newScrollOffset);
}
await tester.pumpWidget(buildWidget());
expect(callbackTracker, equals(<int>[
0, // in caching area
1, 2, 3, 4,
5, // in caching area
]));
check(visible: <int>[1, 2, 3, 4], hidden: <int>[0, 5]);
callbackTracker.clear();
jumpTo(400.0);
// now only 3 should fit, numbered 2-4.
await tester.pumpWidget(buildWidget());
expect(callbackTracker, equals(<int>[
0, 1, // in caching area
2, 3, 4,
5, 6, // in caching area
]));
check(visible: <int>[2, 3, 4], hidden: <int>[0, 1, 5, 6]);
callbackTracker.clear();
jumpTo(500.0);
// now 4 should fit, numbered 2-5.
await tester.pumpWidget(buildWidget());
expect(callbackTracker, equals(<int>[
0, 1, // in caching area
2, 3, 4, 5,
6, // in caching area
]));
check(visible: <int>[2, 3, 4, 5], hidden: <int>[0, 1, 6]);
callbackTracker.clear();
});
testWidgets('ListView.builder horizontal', (WidgetTester tester) async {
final List<int> callbackTracker = <int>[];
// the root view is 800x600 in the test environment
// so if our widget is 200 pixels wide, it should fit exactly 4 times.
// but if we are offset by 300 pixels, there will be 5, numbered 1-5.
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return SizedBox(
key: ValueKey<int>(index),
width: 400.0, // this should be overridden by itemExtent
height: 500.0, // this should be ignored
child: Text('$index'),
);
}
Widget buildWidget() {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
return Directionality(
textDirection: TextDirection.ltr,
child: FlipWidget(
left: ListView.builder(
controller: controller,
itemBuilder: itemBuilder,
itemExtent: 200.0,
scrollDirection: Axis.horizontal,
),
right: const Text('Not Today'),
),
);
}
void jumpTo(double newScrollOffset) {
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
scrollable.position.jumpTo(newScrollOffset);
}
await tester.pumpWidget(buildWidget());
expect(callbackTracker, equals(<int>[
0, // in caching area
1, 2, 3, 4, 5,
6, // in caching area
]));
check(visible: <int>[1, 2, 3, 4, 5], hidden: <int>[0, 6]);
callbackTracker.clear();
jumpTo(400.0);
// now only 4 should fit, numbered 2-5.
await tester.pumpWidget(buildWidget());
expect(callbackTracker, equals(<int>[
0, 1, // in caching area
2, 3, 4, 5,
6, 7, // in caching area
]));
check(visible: <int>[2, 3, 4, 5], hidden: <int>[0, 1, 6, 7]);
callbackTracker.clear();
jumpTo(500.0);
// now only 5 should fit, numbered 2-6.
await tester.pumpWidget(buildWidget());
expect(callbackTracker, equals(<int>[
0, 1, // in caching area
2, 3, 4, 5, 6,
7, // in caching area
]));
check(visible: <int>[2, 3, 4, 5, 6], hidden: <int>[0, 1, 7]);
callbackTracker.clear();
});
testWidgets('ListView.builder 10 items, 2-3 items visible', (WidgetTester tester) async {
final List<int> callbackTracker = <int>[];
// The root view is 800x600 in the test environment and our list
// items are 300 tall. Scrolling should cause two or three items
// to be built.
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return Text('$index', key: ValueKey<int>(index), textDirection: TextDirection.ltr);
}
final Widget testWidget = Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
itemBuilder: itemBuilder,
itemExtent: 300.0,
itemCount: 10,
),
);
void jumpTo(double newScrollOffset) {
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
scrollable.position.jumpTo(newScrollOffset);
}
await tester.pumpWidget(testWidget);
expect(callbackTracker, equals(<int>[0, 1, 2]));
check(visible: <int>[0, 1], hidden: <int>[2]);
callbackTracker.clear();
jumpTo(150.0);
await tester.pump();
expect(callbackTracker, equals(<int>[3]));
check(visible: <int>[0, 1, 2], hidden: <int>[3]);
callbackTracker.clear();
jumpTo(600.0);
await tester.pump();
expect(callbackTracker, equals(<int>[4]));
check(visible: <int>[2, 3], hidden: <int>[0, 1, 4]);
callbackTracker.clear();
jumpTo(750.0);
await tester.pump();
expect(callbackTracker, equals(<int>[5]));
check(visible: <int>[2, 3, 4], hidden: <int>[0, 1, 5]);
callbackTracker.clear();
});
testWidgets('ListView.builder 30 items with big jump, using prototypeItem', (WidgetTester tester) async {
final List<int> callbackTracker = <int>[];
// The root view is 800x600 in the test environment and our list
// items are 300 tall. Scrolling should cause two or three items
// to be built.
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return Text('$index', key: ValueKey<int>(index), textDirection: TextDirection.ltr);
}
final Widget testWidget = Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
itemBuilder: itemBuilder,
prototypeItem: const SizedBox(
width: 800,
height: 300,
),
itemCount: 30,
),
);
void jumpTo(double newScrollOffset) {
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
scrollable.position.jumpTo(newScrollOffset);
}
await tester.pumpWidget(testWidget);
// 2 is in the cache area, but not visible.
expect(callbackTracker, equals(<int>[0, 1, 2]));
final List<int> initialExpectedHidden = List<int>.generate(28, (int i) => i + 2);
check(visible: <int>[0, 1], hidden: initialExpectedHidden);
callbackTracker.clear();
// Jump to the end of the ListView.
jumpTo(8400);
await tester.pump();
// 27 is in the cache area, but not visible.
expect(callbackTracker, equals(<int>[27, 28, 29]));
final List<int> finalExpectedHidden = List<int>.generate(28, (int i) => i);
check(visible: <int>[28, 29], hidden: finalExpectedHidden);
callbackTracker.clear();
});
testWidgets('ListView.separated', (WidgetTester tester) async {
Widget buildFrame({ required int itemCount }) {
return Directionality(
textDirection: TextDirection.ltr,
child: ListView.separated(
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: 100.0,
child: Text('i$index'),
);
},
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 10.0,
child: Text('s$index'),
);
},
),
);
}
await tester.pumpWidget(buildFrame(itemCount: 0));
expect(find.text('i0'), findsNothing);
expect(find.text('s0'), findsNothing);
await tester.pumpWidget(buildFrame(itemCount: 1));
expect(find.text('i0'), findsOneWidget);
expect(find.text('s0'), findsNothing);
await tester.pumpWidget(buildFrame(itemCount: 2));
expect(find.text('i0'), findsOneWidget);
expect(find.text('s0'), findsOneWidget);
expect(find.text('i1'), findsOneWidget);
expect(find.text('s1'), findsNothing);
// ListView's height is 600, so items i0-i5 and s0-s4 fit.
await tester.pumpWidget(buildFrame(itemCount: 25));
for (final String s in <String>['i0', 's0', 'i1', 's1', 'i2', 's2', 'i3', 's3', 'i4', 's4', 'i5']) {
expect(find.text(s), findsOneWidget);
}
expect(find.text('s5'), findsNothing);
expect(find.text('i6'), findsNothing);
});
testWidgets('ListView.separated uses correct semanticChildCount', (WidgetTester tester) async {
Widget buildFrame({ required int itemCount}) {
return Directionality(
textDirection: TextDirection.ltr,
child: ListView.separated(
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: 100.0,
child: Text('i$index'),
);
},
separatorBuilder: (BuildContext context, int index) {
return SizedBox(
height: 10.0,
child: Text('s$index'),
);
},
),
);
}
Scrollable scrollable() {
return tester.widget<Scrollable>(
find.descendant(
of: find.byType(ListView),
matching: find.byType(Scrollable),
),
);
}
await tester.pumpWidget(buildFrame(itemCount: 0));
expect(scrollable().semanticChildCount, 0);
await tester.pumpWidget(buildFrame(itemCount: 1));
expect(scrollable().semanticChildCount, 1);
await tester.pumpWidget(buildFrame(itemCount: 2));
expect(scrollable().semanticChildCount, 2);
await tester.pumpWidget(buildFrame(itemCount: 3));
expect(scrollable().semanticChildCount, 3);
await tester.pumpWidget(buildFrame(itemCount: 4));
expect(scrollable().semanticChildCount, 4);
});
// Regression test for https://github.com/flutter/flutter/issues/72292
testWidgets('ListView.builder and SingleChildScrollView can work well together', (WidgetTester tester) async {
Widget builder(int itemCount) {
return Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
child: ListView.builder(
shrinkWrap: true,
itemExtent: 35,
itemCount: itemCount,
itemBuilder: (BuildContext context, int index) {
return const Text('I love Flutter.');
},
),
),
);
}
await tester.pumpWidget(builder(1));
// Trigger relayout and garbage collect.
await tester.pumpWidget(builder(2));
});
}
void check({ List<int> visible = const <int>[], List<int> hidden = const <int>[] }) {
for (final int i in visible) {
expect(find.text('$i'), findsOneWidget);
}
for (final int i in hidden) {
expect(find.text('$i'), findsNothing);
}
}
| flutter/packages/flutter/test/widgets/list_view_builder_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/list_view_builder_test.dart",
"repo_id": "flutter",
"token_count": 5545
} | 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/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('LookupBoundary.dependOnInheritedWidgetOfExactType', () {
testWidgets('respects boundary', (WidgetTester tester) async {
InheritedWidget? containerThroughBoundary;
InheritedWidget? containerStoppedAtBoundary;
final Key inheritedKey = UniqueKey();
await tester.pumpWidget(MyInheritedWidget(
value: 2,
key: inheritedKey,
child: LookupBoundary(
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
containerStoppedAtBoundary = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context);
return const SizedBox.expand();
},
),
),
));
expect(containerThroughBoundary, equals(tester.widget(find.byKey(inheritedKey))));
expect(containerStoppedAtBoundary, isNull);
});
testWidgets('ignores ancestor boundary', (WidgetTester tester) async {
InheritedWidget? inheritedWidget;
final Key inheritedKey = UniqueKey();
await tester.pumpWidget(LookupBoundary(
child: MyInheritedWidget(
value: 2,
key: inheritedKey,
child: Builder(
builder: (BuildContext context) {
inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context);
return const SizedBox.expand();
},
),
),
));
expect(inheritedWidget, equals(tester.widget(find.byKey(inheritedKey))));
});
testWidgets('finds widget before boundary', (WidgetTester tester) async {
InheritedWidget? containerThroughBoundary;
InheritedWidget? containerStoppedAtBoundary;
final Key inheritedKey = UniqueKey();
await tester.pumpWidget(MyInheritedWidget(
value: 2,
child: LookupBoundary(
child: MyInheritedWidget(
key: inheritedKey,
value: 1,
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.dependOnInheritedWidgetOfExactType<MyInheritedWidget>();
containerStoppedAtBoundary = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context);
return const SizedBox.expand();
},
),
),
),
));
expect(containerThroughBoundary, equals(tester.widget(find.byKey(inheritedKey))));
expect(containerStoppedAtBoundary, equals(tester.widget(find.byKey(inheritedKey))));
});
testWidgets('creates dependency', (WidgetTester tester) async {
MyInheritedWidget? inheritedWidget;
final Widget widgetTree = DidChangeDependencySpy(
onDidChangeDependencies: (BuildContext context) {
inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context);
},
);
await tester.pumpWidget(
MyInheritedWidget(
value: 1,
child: widgetTree,
),
);
expect(inheritedWidget!.value, 1);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
await tester.pumpWidget(
MyInheritedWidget(
value: 2,
child: widgetTree,
),
);
expect(inheritedWidget!.value, 2);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 2);
});
testWidgets('causes didChangeDependencies to be called on move even if dependency was not fulfilled due to boundary', (WidgetTester tester) async {
MyInheritedWidget? inheritedWidget;
final Key globalKey = GlobalKey();
final Widget widgetTree = DidChangeDependencySpy(
key: globalKey,
onDidChangeDependencies: (BuildContext context) {
inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context);
},
);
await tester.pumpWidget(
MyInheritedWidget(
value: 1,
child: LookupBoundary(
child: widgetTree,
),
),
);
expect(inheritedWidget, isNull);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
// Value of inherited widget changes, but there should be no dependency due to boundary.
await tester.pumpWidget(
MyInheritedWidget(
value: 2,
child: LookupBoundary(
child: widgetTree,
),
),
);
expect(inheritedWidget, isNull);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
// Widget is moved, didChangeDependencies is called, but dependency is still not found due to boundary.
await tester.pumpWidget(
SizedBox(
child: MyInheritedWidget(
value: 2,
child: LookupBoundary(
child: widgetTree,
),
),
),
);
expect(inheritedWidget, isNull);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 2);
await tester.pumpWidget(
SizedBox(
child: MyInheritedWidget(
value: 2,
child: LookupBoundary(
child: MyInheritedWidget(
value: 4,
child: widgetTree,
),
),
),
),
);
expect(inheritedWidget!.value, 4);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 3);
});
testWidgets('causes didChangeDependencies to be called on move even if dependency was non-existent', (WidgetTester tester) async {
MyInheritedWidget? inheritedWidget;
final Key globalKey = GlobalKey();
final Widget widgetTree = DidChangeDependencySpy(
key: globalKey,
onDidChangeDependencies: (BuildContext context) {
inheritedWidget = LookupBoundary.dependOnInheritedWidgetOfExactType<MyInheritedWidget>(context);
},
);
await tester.pumpWidget(widgetTree);
expect(inheritedWidget, isNull);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
// Widget moved, didChangeDependencies must be called.
await tester.pumpWidget(
SizedBox(
child: widgetTree,
),
);
expect(inheritedWidget, isNull);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 2);
// Widget moved, didChangeDependencies must be called.
await tester.pumpWidget(
MyInheritedWidget(
value: 6,
child: SizedBox(
child: widgetTree,
),
),
);
expect(inheritedWidget!.value, 6);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 3);
});
});
group('LookupBoundary.getElementForInheritedWidgetOfExactType', () {
testWidgets('respects boundary', (WidgetTester tester) async {
InheritedElement? containerThroughBoundary;
InheritedElement? containerStoppedAtBoundary;
final Key inheritedKey = UniqueKey();
await tester.pumpWidget(MyInheritedWidget(
value: 2,
key: inheritedKey,
child: LookupBoundary(
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.getElementForInheritedWidgetOfExactType<MyInheritedWidget>();
containerStoppedAtBoundary = LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context);
return const SizedBox.expand();
},
),
),
));
expect(containerThroughBoundary, equals(tester.element(find.byKey(inheritedKey))));
expect(containerStoppedAtBoundary, isNull);
});
testWidgets('ignores ancestor boundary', (WidgetTester tester) async {
InheritedElement? inheritedWidget;
final Key inheritedKey = UniqueKey();
await tester.pumpWidget(LookupBoundary(
child: MyInheritedWidget(
value: 2,
key: inheritedKey,
child: Builder(
builder: (BuildContext context) {
inheritedWidget = LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context);
return const SizedBox.expand();
},
),
),
));
expect(inheritedWidget, equals(tester.element(find.byKey(inheritedKey))));
});
testWidgets('finds widget before boundary', (WidgetTester tester) async {
InheritedElement? containerThroughBoundary;
InheritedElement? containerStoppedAtBoundary;
final Key inheritedKey = UniqueKey();
await tester.pumpWidget(MyInheritedWidget(
value: 2,
child: LookupBoundary(
child: MyInheritedWidget(
key: inheritedKey,
value: 1,
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.getElementForInheritedWidgetOfExactType<MyInheritedWidget>();
containerStoppedAtBoundary = LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context);
return const SizedBox.expand();
},
),
),
),
));
expect(containerThroughBoundary, equals(tester.element(find.byKey(inheritedKey))));
expect(containerStoppedAtBoundary, equals(tester.element(find.byKey(inheritedKey))));
});
testWidgets('does not creates dependency', (WidgetTester tester) async {
final Widget widgetTree = DidChangeDependencySpy(
onDidChangeDependencies: (BuildContext context) {
LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context);
},
);
await tester.pumpWidget(
MyInheritedWidget(
value: 1,
child: widgetTree,
),
);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
await tester.pumpWidget(
MyInheritedWidget(
value: 2,
child: widgetTree,
),
);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
});
testWidgets('does not cause didChangeDependencies to be called on move when found', (WidgetTester tester) async {
final Key globalKey = GlobalKey();
final Widget widgetTree = DidChangeDependencySpy(
key: globalKey,
onDidChangeDependencies: (BuildContext context) {
LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context);
},
);
await tester.pumpWidget(
MyInheritedWidget(
value: 1,
child: LookupBoundary(
child: widgetTree,
),
),
);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
// Value of inherited widget changes, but there should be no dependency due to boundary.
await tester.pumpWidget(
MyInheritedWidget(
value: 2,
child: LookupBoundary(
child: widgetTree,
),
),
);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
// Widget is moved, didChangeDependencies is called, but dependency is still not found due to boundary.
await tester.pumpWidget(
SizedBox(
child: MyInheritedWidget(
value: 2,
child: LookupBoundary(
child: widgetTree,
),
),
),
);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
await tester.pumpWidget(
SizedBox(
child: MyInheritedWidget(
value: 2,
child: LookupBoundary(
child: MyInheritedWidget(
value: 4,
child: widgetTree,
),
),
),
),
);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
});
testWidgets('does not cause didChangeDependencies to be called on move when nothing was found', (WidgetTester tester) async {
final Key globalKey = GlobalKey();
final Widget widgetTree = DidChangeDependencySpy(
key: globalKey,
onDidChangeDependencies: (BuildContext context) {
LookupBoundary.getElementForInheritedWidgetOfExactType<MyInheritedWidget>(context);
},
);
await tester.pumpWidget(widgetTree);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
// Widget moved, didChangeDependencies must be called.
await tester.pumpWidget(
SizedBox(
child: widgetTree,
),
);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
// Widget moved, didChangeDependencies must be called.
await tester.pumpWidget(
MyInheritedWidget(
value: 6,
child: SizedBox(
child: widgetTree,
),
),
);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
});
});
group('LookupBoundary.findAncestorWidgetOfExactType', () {
testWidgets('respects boundary', (WidgetTester tester) async {
Widget? containerThroughBoundary;
Widget? containerStoppedAtBoundary;
Widget? boundaryThroughBoundary;
Widget? boundaryStoppedAtBoundary;
final Key containerKey = UniqueKey();
final Key boundaryKey = UniqueKey();
await tester.pumpWidget(Container(
key: containerKey,
child: LookupBoundary(
key: boundaryKey,
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.findAncestorWidgetOfExactType<Container>();
containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>(context);
boundaryThroughBoundary = context.findAncestorWidgetOfExactType<LookupBoundary>();
boundaryStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<LookupBoundary>(context);
return const SizedBox.expand();
},
),
),
));
expect(containerThroughBoundary, equals(tester.widget(find.byKey(containerKey))));
expect(containerStoppedAtBoundary, isNull);
expect(boundaryThroughBoundary, equals(tester.widget(find.byKey(boundaryKey))));
expect(boundaryStoppedAtBoundary, equals(tester.widget(find.byKey(boundaryKey))));
});
testWidgets('finds right widget before boundary', (WidgetTester tester) async {
Widget? containerThroughBoundary;
Widget? containerStoppedAtBoundary;
final Key outerContainerKey = UniqueKey();
final Key innerContainerKey = UniqueKey();
await tester.pumpWidget(Container(
key: outerContainerKey,
child: LookupBoundary(
child: Container(
padding: const EdgeInsets.all(10),
color: Colors.blue,
child: Container(
key: innerContainerKey,
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.findAncestorWidgetOfExactType<Container>();
containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>(context);
return const SizedBox.expand();
},
),
),
),
),
));
expect(containerThroughBoundary, equals(tester.widget(find.byKey(innerContainerKey))));
expect(containerStoppedAtBoundary, equals(tester.widget(find.byKey(innerContainerKey))));
});
testWidgets('works if nothing is found', (WidgetTester tester) async {
Widget? containerStoppedAtBoundary;
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>(context);
return const SizedBox.expand();
},
));
expect(containerStoppedAtBoundary, isNull);
});
testWidgets('does not establish a dependency', (WidgetTester tester) async {
Widget? containerThroughBoundary;
Widget? containerStoppedAtBoundary;
Widget? containerStoppedAtBoundaryUnfulfilled;
final Key innerContainerKey = UniqueKey();
final Key globalKey = GlobalKey();
final Widget widgetTree = LookupBoundary(
child: Container(
key: innerContainerKey,
child: DidChangeDependencySpy(
key: globalKey,
onDidChangeDependencies: (BuildContext context) {
containerThroughBoundary = context.findAncestorWidgetOfExactType<Container>();
containerStoppedAtBoundary = LookupBoundary.findAncestorWidgetOfExactType<Container>(context);
containerStoppedAtBoundaryUnfulfilled = LookupBoundary.findAncestorWidgetOfExactType<Material>(context);
},
),
),
);
await tester.pumpWidget(widgetTree);
expect(containerThroughBoundary, equals(tester.widget(find.byKey(innerContainerKey))));
expect(containerStoppedAtBoundary, equals(tester.widget(find.byKey(innerContainerKey))));
expect(containerStoppedAtBoundaryUnfulfilled, isNull);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
await tester.pumpWidget(
SizedBox( // Changes tree structure, triggers global key move of DidChangeDependencySpy.
child: widgetTree,
),
);
// Tree restructuring above would have called didChangeDependencies if dependency had been established.
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
});
});
group('LookupBoundary.findAncestorStateOfType', () {
testWidgets('respects boundary', (WidgetTester tester) async {
State? containerThroughBoundary;
State? containerStoppedAtBoundary;
final Key containerKey = UniqueKey();
await tester.pumpWidget(MyStatefulContainer(
key: containerKey,
child: LookupBoundary(
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.findAncestorStateOfType<MyStatefulContainerState>();
containerStoppedAtBoundary = LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context);
return const SizedBox.expand();
},
),
),
));
expect(containerThroughBoundary, equals(tester.state(find.byKey(containerKey))));
expect(containerStoppedAtBoundary, isNull);
});
testWidgets('finds right widget before boundary', (WidgetTester tester) async {
State? containerThroughBoundary;
State? containerStoppedAtBoundary;
final Key outerContainerKey = UniqueKey();
final Key innerContainerKey = UniqueKey();
await tester.pumpWidget(MyStatefulContainer(
key: outerContainerKey,
child: LookupBoundary(
child: MyStatefulContainer(
child: MyStatefulContainer(
key: innerContainerKey,
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.findAncestorStateOfType<MyStatefulContainerState>();
containerStoppedAtBoundary = LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context);
return const SizedBox.expand();
},
),
),
),
),
));
expect(containerThroughBoundary, equals(tester.state(find.byKey(innerContainerKey))));
expect(containerStoppedAtBoundary, equals(tester.state(find.byKey(innerContainerKey))));
});
testWidgets('works if nothing is found', (WidgetTester tester) async {
State? containerStoppedAtBoundary;
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
containerStoppedAtBoundary = LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context);
return const SizedBox.expand();
},
));
expect(containerStoppedAtBoundary, isNull);
});
testWidgets('does not establish a dependency', (WidgetTester tester) async {
State? containerThroughBoundary;
State? containerStoppedAtBoundary;
State? containerStoppedAtBoundaryUnfulfilled;
final Key innerContainerKey = UniqueKey();
final Key globalKey = GlobalKey();
final Widget widgetTree = LookupBoundary(
child: MyStatefulContainer(
key: innerContainerKey,
child: DidChangeDependencySpy(
key: globalKey,
onDidChangeDependencies: (BuildContext context) {
containerThroughBoundary = context.findAncestorStateOfType<MyStatefulContainerState>();
containerStoppedAtBoundary = LookupBoundary.findAncestorStateOfType<MyStatefulContainerState>(context);
containerStoppedAtBoundaryUnfulfilled = LookupBoundary.findAncestorStateOfType<MyOtherStatefulContainerState>(context);
},
),
),
);
await tester.pumpWidget(widgetTree);
expect(containerThroughBoundary, equals(tester.state(find.byKey(innerContainerKey))));
expect(containerStoppedAtBoundary, equals(tester.state(find.byKey(innerContainerKey))));
expect(containerStoppedAtBoundaryUnfulfilled, isNull);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
await tester.pumpWidget(
SizedBox( // Changes tree structure, triggers global key move of DidChangeDependencySpy.
child: widgetTree,
),
);
// Tree restructuring above would have called didChangeDependencies if dependency had been established.
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
});
});
group('LookupBoundary.findRootAncestorStateOfType', () {
testWidgets('respects boundary', (WidgetTester tester) async {
State? containerThroughBoundary;
State? containerStoppedAtBoundary;
final Key containerKey = UniqueKey();
await tester.pumpWidget(MyStatefulContainer(
key: containerKey,
child: LookupBoundary(
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.findRootAncestorStateOfType<MyStatefulContainerState>();
containerStoppedAtBoundary = LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context);
return const SizedBox.expand();
},
),
),
));
expect(containerThroughBoundary, equals(tester.state(find.byKey(containerKey))));
expect(containerStoppedAtBoundary, isNull);
});
testWidgets('finds right widget before boundary', (WidgetTester tester) async {
State? containerThroughBoundary;
State? containerStoppedAtBoundary;
final Key outerContainerKey = UniqueKey();
final Key innerContainerKey = UniqueKey();
await tester.pumpWidget(MyStatefulContainer(
key: outerContainerKey,
child: LookupBoundary(
child: MyStatefulContainer(
key: innerContainerKey,
child: MyStatefulContainer(
child: Builder(
builder: (BuildContext context) {
containerThroughBoundary = context.findRootAncestorStateOfType<MyStatefulContainerState>();
containerStoppedAtBoundary = LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context);
return const SizedBox.expand();
},
),
),
),
),
));
expect(containerThroughBoundary, equals(tester.state(find.byKey(outerContainerKey))));
expect(containerStoppedAtBoundary, equals(tester.state(find.byKey(innerContainerKey))));
});
testWidgets('works if nothing is found', (WidgetTester tester) async {
State? containerStoppedAtBoundary;
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
containerStoppedAtBoundary = LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context);
return const SizedBox.expand();
},
));
expect(containerStoppedAtBoundary, isNull);
});
testWidgets('does not establish a dependency', (WidgetTester tester) async {
State? containerThroughBoundary;
State? containerStoppedAtBoundary;
State? containerStoppedAtBoundaryUnfulfilled;
final Key innerContainerKey = UniqueKey();
final Key globalKey = GlobalKey();
final Widget widgetTree = LookupBoundary(
child: MyStatefulContainer(
key: innerContainerKey,
child: DidChangeDependencySpy(
key: globalKey,
onDidChangeDependencies: (BuildContext context) {
containerThroughBoundary = context.findRootAncestorStateOfType<MyStatefulContainerState>();
containerStoppedAtBoundary = LookupBoundary.findRootAncestorStateOfType<MyStatefulContainerState>(context);
containerStoppedAtBoundaryUnfulfilled = LookupBoundary.findRootAncestorStateOfType<MyOtherStatefulContainerState>(context);
},
),
),
);
await tester.pumpWidget(widgetTree);
expect(containerThroughBoundary, equals(tester.state(find.byKey(innerContainerKey))));
expect(containerStoppedAtBoundary, equals(tester.state(find.byKey(innerContainerKey))));
expect(containerStoppedAtBoundaryUnfulfilled, isNull);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
await tester.pumpWidget(
SizedBox( // Changes tree structure, triggers global key move of DidChangeDependencySpy.
child: widgetTree,
),
);
// Tree restructuring above would have called didChangeDependencies if dependency had been established.
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
});
});
group('LookupBoundary.findAncestorRenderObjectOfType', () {
testWidgets('respects boundary', (WidgetTester tester) async {
RenderPadding? paddingThroughBoundary;
RenderPadding? passingStoppedAtBoundary;
final Key paddingKey = UniqueKey();
await tester.pumpWidget(Padding(
padding: EdgeInsets.zero,
key: paddingKey,
child: LookupBoundary(
child: Builder(
builder: (BuildContext context) {
paddingThroughBoundary = context.findAncestorRenderObjectOfType<RenderPadding>();
passingStoppedAtBoundary = LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context);
return const SizedBox.expand();
},
),
),
));
expect(paddingThroughBoundary, equals(tester.renderObject(find.byKey(paddingKey))));
expect(passingStoppedAtBoundary, isNull);
});
testWidgets('finds right widget before boundary', (WidgetTester tester) async {
RenderPadding? paddingThroughBoundary;
RenderPadding? paddingStoppedAtBoundary;
final Key outerPaddingKey = UniqueKey();
final Key innerPaddingKey = UniqueKey();
await tester.pumpWidget(Padding(
padding: EdgeInsets.zero,
key: outerPaddingKey,
child: LookupBoundary(
child: Padding(
padding: EdgeInsets.zero,
child: Padding(
padding: EdgeInsets.zero,
key: innerPaddingKey,
child: Builder(
builder: (BuildContext context) {
paddingThroughBoundary = context.findAncestorRenderObjectOfType<RenderPadding>();
paddingStoppedAtBoundary = LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context);
return const SizedBox.expand();
},
),
),
),
),
));
expect(paddingThroughBoundary, equals(tester.renderObject(find.byKey(innerPaddingKey))));
expect(paddingStoppedAtBoundary, equals(tester.renderObject(find.byKey(innerPaddingKey))));
});
testWidgets('works if nothing is found', (WidgetTester tester) async {
RenderPadding? paddingStoppedAtBoundary;
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
paddingStoppedAtBoundary = LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context);
return const SizedBox.expand();
},
));
expect(paddingStoppedAtBoundary, isNull);
});
testWidgets('does not establish a dependency', (WidgetTester tester) async {
RenderPadding? paddingThroughBoundary;
RenderPadding? paddingStoppedAtBoundary;
RenderWrap? wrapStoppedAtBoundaryUnfulfilled;
final Key innerPaddingKey = UniqueKey();
final Key globalKey = GlobalKey();
final Widget widgetTree = LookupBoundary(
child: Padding(
padding: EdgeInsets.zero,
key: innerPaddingKey,
child: DidChangeDependencySpy(
key: globalKey,
onDidChangeDependencies: (BuildContext context) {
paddingThroughBoundary = context.findAncestorRenderObjectOfType<RenderPadding>();
paddingStoppedAtBoundary = LookupBoundary.findAncestorRenderObjectOfType<RenderPadding>(context);
wrapStoppedAtBoundaryUnfulfilled = LookupBoundary.findAncestorRenderObjectOfType<RenderWrap>(context);
},
),
),
);
await tester.pumpWidget(widgetTree);
expect(paddingThroughBoundary, equals(tester.renderObject(find.byKey(innerPaddingKey))));
expect(paddingStoppedAtBoundary, equals(tester.renderObject(find.byKey(innerPaddingKey))));
expect(wrapStoppedAtBoundaryUnfulfilled, isNull);
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
await tester.pumpWidget(
SizedBox( // Changes tree structure, triggers global key move of DidChangeDependencySpy.
child: widgetTree,
),
);
// Tree restructuring above would have called didChangeDependencies if dependency had been established.
expect(tester.state<_DidChangeDependencySpyState>(find.byType(DidChangeDependencySpy)).didChangeDependenciesCount, 1);
});
});
group('LookupBoundary.visitAncestorElements', () {
testWidgets('respects boundary', (WidgetTester tester) async {
final List<Element> throughBoundary = <Element>[];
final List<Element> stoppedAtBoundary = <Element>[];
final List<Element> stoppedAtBoundaryTerminatedEarly = <Element>[];
final Key level0 = UniqueKey();
final Key level1 = UniqueKey();
final Key level2 = UniqueKey();
final Key level3 = UniqueKey();
final Key level4 = UniqueKey();
await tester.pumpWidget(Container(
key: level0,
child: Container(
key: level1,
child: LookupBoundary(
key: level2,
child: Container(
key: level3,
child: Container(
key: level4,
child: Builder(
builder: (BuildContext context) {
context.visitAncestorElements((Element element) {
throughBoundary.add(element);
return element.widget.key != level0;
});
LookupBoundary.visitAncestorElements(context, (Element element) {
stoppedAtBoundary.add(element);
return element.widget.key != level0;
});
LookupBoundary.visitAncestorElements(context, (Element element) {
stoppedAtBoundaryTerminatedEarly.add(element);
return element.widget.key != level3;
});
return const SizedBox();
}
)
)
)
)
),
));
expect(throughBoundary, <Element>[
tester.element(find.byKey(level4)),
tester.element(find.byKey(level3)),
tester.element(find.byKey(level2)),
tester.element(find.byKey(level1)),
tester.element(find.byKey(level0)),
]);
expect(stoppedAtBoundary, <Element>[
tester.element(find.byKey(level4)),
tester.element(find.byKey(level3)),
tester.element(find.byKey(level2)),
]);
expect(stoppedAtBoundaryTerminatedEarly, <Element>[
tester.element(find.byKey(level4)),
tester.element(find.byKey(level3)),
]);
});
});
group('LookupBoundary.visitChildElements', () {
testWidgets('respects boundary', (WidgetTester tester) async {
final Key root = UniqueKey();
final Key child1 = UniqueKey();
final Key child2 = UniqueKey();
final Key child3 = UniqueKey();
await tester.pumpWidget(Column(
key: root,
children: <Widget>[
LookupBoundary(
key: child1,
child: Container(),
),
Container(
key: child2,
child: LookupBoundary(
child: Container(),
),
),
Container(
key: child3,
),
],
));
final List<Element> throughBoundary = <Element>[];
final List<Element> stoppedAtBoundary = <Element>[];
final BuildContext context = tester.element(find.byKey(root));
context.visitChildElements((Element element) {
throughBoundary.add(element);
});
LookupBoundary.visitChildElements(context, (Element element) {
stoppedAtBoundary.add(element);
});
expect(throughBoundary, <Element>[
tester.element(find.byKey(child1)),
tester.element(find.byKey(child2)),
tester.element(find.byKey(child3)),
]);
expect(stoppedAtBoundary, <Element>[
tester.element(find.byKey(child2)),
tester.element(find.byKey(child3)),
]);
});
});
group('LookupBoundary.debugIsHidingAncestorWidgetOfExactType', () {
testWidgets('is hiding', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(Container(
padding: const EdgeInsets.all(10),
color: Colors.blue,
child: LookupBoundary(
child: Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context);
return Container();
},
),
),
));
expect(isHidden, isTrue);
});
testWidgets('is not hiding entity within boundary', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(Container(
padding: const EdgeInsets.all(10),
color: Colors.blue,
child: LookupBoundary(
child: Container(
padding: const EdgeInsets.all(10),
color: Colors.red,
child: Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context);
return Container();
},
),
),
),
));
expect(isHidden, isFalse);
});
testWidgets('is not hiding if no boundary exists', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(Container(
padding: const EdgeInsets.all(10),
color: Colors.blue,
child: Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context);
return Container();
},
),
));
expect(isHidden, isFalse);
});
testWidgets('is not hiding if no boundary and no entity exists', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<Container>(context);
return Container();
},
));
expect(isHidden, isFalse);
});
});
group('LookupBoundary.debugIsHidingAncestorStateOfType', () {
testWidgets('is hiding', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(MyStatefulContainer(
child: LookupBoundary(
child: Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>(context);
return Container();
},
),
),
));
expect(isHidden, isTrue);
});
testWidgets('is not hiding entity within boundary', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(MyStatefulContainer(
child: LookupBoundary(
child: MyStatefulContainer(
child: Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>(context);
return Container();
},
),
),
),
));
expect(isHidden, isFalse);
});
testWidgets('is not hiding if no boundary exists', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(MyStatefulContainer(
child: Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>(context);
return Container();
},
),
));
expect(isHidden, isFalse);
});
testWidgets('is not hiding if no boundary and no entity exists', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorStateOfType<MyStatefulContainerState>(context);
return Container();
},
));
expect(isHidden, isFalse);
});
});
group('LookupBoundary.debugIsHidingAncestorRenderObjectOfType', () {
testWidgets('is hiding', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(Padding(
padding: EdgeInsets.zero,
child: LookupBoundary(
child: Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>(context);
return Container();
},
),
),
));
expect(isHidden, isTrue);
});
testWidgets('is not hiding entity within boundary', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(Padding(
padding: EdgeInsets.zero,
child: LookupBoundary(
child: Padding(
padding: EdgeInsets.zero,
child: Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>(context);
return Container();
},
),
),
),
));
expect(isHidden, isFalse);
});
testWidgets('is not hiding if no boundary exists', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(Padding(
padding: EdgeInsets.zero,
child: Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>(context);
return Container();
},
),
));
expect(isHidden, isFalse);
});
testWidgets('is not hiding if no boundary and no entity exists', (WidgetTester tester) async {
bool? isHidden;
await tester.pumpWidget(Builder(
builder: (BuildContext context) {
isHidden = LookupBoundary.debugIsHidingAncestorRenderObjectOfType<RenderPadding>(context);
return Container();
},
));
expect(isHidden, isFalse);
});
});
}
class MyStatefulContainer extends StatefulWidget {
const MyStatefulContainer({super.key, required this.child});
final Widget child;
@override
State<MyStatefulContainer> createState() => MyStatefulContainerState();
}
class MyStatefulContainerState extends State<MyStatefulContainer> {
@override
Widget build(BuildContext context) {
return widget.child;
}
}
class MyOtherStatefulContainerState extends State<MyStatefulContainer> {
@override
Widget build(BuildContext context) {
return widget.child;
}
}
class MyInheritedWidget extends InheritedWidget {
const MyInheritedWidget({super.key, required this.value, required super.child});
final int value;
@override
bool updateShouldNotify(MyInheritedWidget oldWidget) => oldWidget.value != value;
}
class DidChangeDependencySpy extends StatefulWidget {
const DidChangeDependencySpy({super.key, required this.onDidChangeDependencies});
final OnDidChangeDependencies onDidChangeDependencies;
@override
State<DidChangeDependencySpy> createState() => _DidChangeDependencySpyState();
}
class _DidChangeDependencySpyState extends State<DidChangeDependencySpy> {
int didChangeDependenciesCount = 0;
@override
void didChangeDependencies() {
super.didChangeDependencies();
didChangeDependenciesCount += 1;
widget.onDidChangeDependencies(context);
}
@override
Widget build(BuildContext context) {
return Container();
}
}
typedef OnDidChangeDependencies = void Function(BuildContext context);
| flutter/packages/flutter/test/widgets/lookup_boundary_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/lookup_boundary_test.dart",
"repo_id": "flutter",
"token_count": 18169
} | 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 'dart:ui' show FlutterView;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'navigator_utils.dart';
import 'observer_tester.dart';
import 'semantics_tester.dart';
class FirstWidget extends StatelessWidget {
const FirstWidget({ super.key });
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, '/second');
},
child: const ColoredBox(
color: Color(0xFFFFFF00),
child: Text('X'),
),
);
}
}
class SecondWidget extends StatefulWidget {
const SecondWidget({ super.key });
@override
SecondWidgetState createState() => SecondWidgetState();
}
class SecondWidgetState extends State<SecondWidget> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => Navigator.pop(context),
child: const ColoredBox(
color: Color(0xFFFF00FF),
child: Text('Y'),
),
);
}
}
typedef ExceptionCallback = void Function(dynamic exception);
class ThirdWidget extends StatelessWidget {
const ThirdWidget({ super.key, required this.targetKey, required this.onException });
final Key targetKey;
final ExceptionCallback onException;
@override
Widget build(BuildContext context) {
return GestureDetector(
key: targetKey,
onTap: () {
try {
Navigator.of(context);
} catch (e) {
onException(e);
}
},
behavior: HitTestBehavior.opaque,
);
}
}
class OnTapPage extends StatelessWidget {
const OnTapPage({ super.key, required this.id, this.onTap });
final String id;
final VoidCallback? onTap;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Page $id')),
body: GestureDetector(
onTap: onTap,
behavior: HitTestBehavior.opaque,
child: Center(
child: Text(id, style: Theme.of(context).textTheme.displaySmall),
),
),
);
}
}
class SlideInOutPageRoute<T> extends PageRouteBuilder<T> {
SlideInOutPageRoute({required WidgetBuilder bodyBuilder, super.settings}) : super(
pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) => bodyBuilder(context),
transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
return SlideTransition(
position: Tween<Offset>(
begin: const Offset(1.0, 0),
end: Offset.zero,
).animate(animation),
child: SlideTransition(
position: Tween<Offset>(
begin: Offset.zero,
end: const Offset(-1.0, 0),
).animate(secondaryAnimation),
child: child,
),
);
},
);
@override
AnimationController? get controller => super.controller;
}
void main() {
testWidgets('Can navigator navigate to and from a stateful widget', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const FirstWidget(), // X
'/second': (BuildContext context) => const SecondWidget(), // Y
};
await tester.pumpWidget(MaterialApp(routes: routes));
expect(find.text('X'), findsOneWidget);
expect(find.text('Y', skipOffstage: false), findsNothing);
await tester.tap(find.text('X'));
await tester.pump();
expect(find.text('X'), findsOneWidget);
expect(find.text('Y', skipOffstage: false), isOffstage);
await tester.pump(const Duration(milliseconds: 10));
expect(find.text('X'), findsOneWidget);
expect(find.text('Y'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 10));
expect(find.text('X'), findsOneWidget);
expect(find.text('Y'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 10));
expect(find.text('X'), findsOneWidget);
expect(find.text('Y'), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
expect(find.text('X'), findsNothing);
expect(find.text('X', skipOffstage: false), findsOneWidget);
expect(find.text('Y'), findsOneWidget);
await tester.tap(find.text('Y'));
expect(find.text('X'), findsNothing);
expect(find.text('Y'), findsOneWidget);
await tester.pump();
await tester.pump();
expect(find.text('X'), findsOneWidget);
expect(find.text('Y'), findsOneWidget);
await tester.pump(const Duration(milliseconds: 10));
expect(find.text('X'), findsOneWidget);
expect(find.text('Y'), findsOneWidget);
await tester.pump(const Duration(seconds: 1));
expect(find.text('X'), findsOneWidget);
expect(find.text('Y', skipOffstage: false), findsNothing);
});
testWidgets('Navigator.of fails gracefully when not found in context', (WidgetTester tester) async {
const Key targetKey = Key('foo');
dynamic exception;
final Widget widget = ThirdWidget(
targetKey: targetKey,
onException: (dynamic e) {
exception = e;
},
);
await tester.pumpWidget(widget);
await tester.tap(find.byKey(targetKey));
expect(exception, isFlutterError);
expect('$exception', startsWith('Navigator operation requested with a context'));
});
testWidgets('Navigator can push Route created through page class as Pageless route', (WidgetTester tester) async {
final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: nav,
home: const Scaffold(
body: Text('home'),
)
)
);
const MaterialPage<void> page = MaterialPage<void>(child: Text('page'));
nav.currentState!.push<void>(page.createRoute(nav.currentContext!));
await tester.pumpAndSettle();
expect(find.text('page'), findsOneWidget);
nav.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('home'), findsOneWidget);
});
testWidgets('Navigator can set clip behavior', (WidgetTester tester) async {
const MaterialPage<void> page = MaterialPage<void>(child: Text('page'));
await tester.pumpWidget(
MediaQuery(
data: MediaQueryData.fromView(tester.view),
child: Directionality(
textDirection: TextDirection.ltr,
child: Navigator(
pages: const <Page<void>>[page],
onPopPage: (_, __) => false,
),
),
),
);
// Default to hard edge.
expect(tester.widget<Overlay>(find.byType(Overlay)).clipBehavior, Clip.hardEdge);
await tester.pumpWidget(
MediaQuery(
data: MediaQueryData.fromView(tester.view),
child: Directionality(
textDirection: TextDirection.ltr,
child: Navigator(
pages: const <Page<void>>[page],
clipBehavior: Clip.none,
onPopPage: (_, __) => false,
),
),
),
);
expect(tester.widget<Overlay>(find.byType(Overlay)).clipBehavior, Clip.none);
});
testWidgets('Zero transition page-based route correctly notifies observers when it is popped', (WidgetTester tester) async {
final List<Page<void>> pages = <Page<void>>[
const ZeroTransitionPage(name: 'Page 1'),
const ZeroTransitionPage(name: 'Page 2'),
];
final List<NavigatorObservation> observations = <NavigatorObservation>[];
final TestObserver observer = TestObserver()
..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observations.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'pop',
),
);
};
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
await tester.pumpWidget(
TestDependencies(
child: Navigator(
key: navigator,
pages: pages,
observers: <NavigatorObserver>[observer],
onPopPage: (Route<dynamic> route, dynamic result) {
pages.removeLast();
return route.didPop(result);
},
),
),
);
navigator.currentState!.pop();
await tester.pump();
expect(observations.length, 1);
expect(observations[0].current, 'Page 2');
expect(observations[0].previous, 'Page 1');
});
testWidgets('Navigator.of rootNavigator finds root Navigator', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: Material(
child: Column(
children: <Widget>[
const SizedBox(
height: 300.0,
child: Text('Root page'),
),
SizedBox(
height: 300.0,
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
if (settings.name == '/') {
return MaterialPageRoute<void>(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('Next'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('Inner page'),
onPressed: () {
Navigator.of(context, rootNavigator: true).push(
MaterialPageRoute<void>(
builder: (BuildContext context) {
return const Text('Dialog');
},
),
);
},
);
},
),
);
},
);
},
);
}
return null;
},
),
),
],
),
),
));
await tester.tap(find.text('Next'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
// Both elements are on screen.
expect(tester.getTopLeft(find.text('Root page')).dy, 0.0);
expect(tester.getTopLeft(find.text('Inner page')).dy, greaterThan(300.0));
await tester.tap(find.text('Inner page'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
// Dialog is pushed to the whole page and is at the top of the screen, not
// inside the inner page.
expect(tester.getTopLeft(find.text('Dialog')).dy, 0.0);
});
testWidgets('Gestures between push and build are ignored', (WidgetTester tester) async {
final List<String> log = <String>[];
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) {
return Row(
children: <Widget>[
GestureDetector(
onTap: () {
log.add('left');
Navigator.pushNamed(context, '/second');
},
child: const Text('left'),
),
GestureDetector(
onTap: () { log.add('right'); },
child: const Text('right'),
),
],
);
},
'/second': (BuildContext context) => Container(),
};
await tester.pumpWidget(MaterialApp(routes: routes));
expect(log, isEmpty);
await tester.tap(find.text('left'));
expect(log, equals(<String>['left']));
await tester.tap(find.text('right'), warnIfMissed: false);
expect(log, equals(<String>['left']));
});
testWidgets('pushnamed can handle Object as type', (WidgetTester tester) async {
final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>();
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const Text('/'),
'/second': (BuildContext context) => const Text('/second'),
};
await tester.pumpWidget(MaterialApp(navigatorKey: nav, routes: routes));
expect(find.text('/'), findsOneWidget);
Error? error;
try {
nav.currentState!.pushNamed<Object>('/second');
} on Error catch (e) {
error = e;
}
expect(error, isNull);
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('/second'), findsOneWidget);
});
testWidgets('Pending gestures are rejected', (WidgetTester tester) async {
final List<String> log = <String>[];
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) {
return Row(
children: <Widget>[
GestureDetector(
onTap: () {
log.add('left');
Navigator.pushNamed(context, '/second');
},
child: const Text('left'),
),
GestureDetector(
onTap: () { log.add('right'); },
child: const Text('right'),
),
],
);
},
'/second': (BuildContext context) => Container(),
};
await tester.pumpWidget(MaterialApp(routes: routes));
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('right')), pointer: 23);
expect(log, isEmpty);
await tester.tap(find.text('left'), pointer: 1);
expect(log, equals(<String>['left']));
await gesture.up();
expect(log, equals(<String>['left']));
});
testWidgets('popAndPushNamed', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.popAndPushNamed(context, '/B'); }),
'/B': (BuildContext context) => OnTapPage(id: 'B', onTap: () { Navigator.pop(context); }),
};
await tester.pumpWidget(MaterialApp(routes: routes));
expect(find.text('/'), findsOneWidget);
expect(find.text('A', skipOffstage: false), findsNothing);
expect(find.text('B', skipOffstage: false), findsNothing);
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
});
testWidgets('popAndPushNamed with explicit void type parameter', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed<void>(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.popAndPushNamed<void, void>(context, '/B'); }),
'/B': (BuildContext context) => OnTapPage(id: 'B', onTap: () { Navigator.pop<void>(context); }),
};
await tester.pumpWidget(MaterialApp(routes: routes));
expect(find.text('/'), findsOneWidget);
expect(find.text('A', skipOffstage: false), findsNothing);
expect(find.text('B', skipOffstage: false), findsNothing);
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
});
testWidgets('Push and pop should trigger the observers', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context); }),
};
bool isPushed = false;
bool isPopped = false;
final TestObserver observer = TestObserver()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
// Pushes the initial route.
expect(route is PageRoute && route.settings.name == '/', isTrue);
expect(previousRoute, isNull);
isPushed = true;
}
..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
isPopped = true;
};
await tester.pumpWidget(MaterialApp(
routes: routes,
navigatorObservers: <NavigatorObserver>[observer],
));
expect(find.text('/'), findsOneWidget);
expect(find.text('A'), findsNothing);
expect(isPushed, isTrue);
expect(isPopped, isFalse);
isPushed = false;
isPopped = false;
observer.onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
expect(route is PageRoute && route.settings.name == '/A', isTrue);
expect(previousRoute is PageRoute && previousRoute.settings.name == '/', isTrue);
isPushed = true;
};
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsOneWidget);
expect(isPushed, isTrue);
expect(isPopped, isFalse);
isPushed = false;
isPopped = false;
observer.onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
expect(route is PageRoute && route.settings.name == '/A', isTrue);
expect(previousRoute is PageRoute && previousRoute.settings.name == '/', isTrue);
isPopped = true;
};
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsOneWidget);
expect(find.text('A'), findsNothing);
expect(isPushed, isFalse);
expect(isPopped, isTrue);
});
testWidgets('Add and remove an observer should work', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context); }),
};
bool isPushed = false;
bool isPopped = false;
final TestObserver observer1 = TestObserver();
final TestObserver observer2 = TestObserver()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
isPushed = true;
}
..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
isPopped = true;
};
await tester.pumpWidget(MaterialApp(
routes: routes,
navigatorObservers: <NavigatorObserver>[observer1],
));
expect(isPushed, isFalse);
expect(isPopped, isFalse);
await tester.pumpWidget(MaterialApp(
routes: routes,
navigatorObservers: <NavigatorObserver>[observer1, observer2],
));
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(isPushed, isTrue);
expect(isPopped, isFalse);
isPushed = false;
isPopped = false;
await tester.pumpWidget(MaterialApp(
routes: routes,
navigatorObservers: <NavigatorObserver>[observer1],
));
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(isPushed, isFalse);
expect(isPopped, isFalse);
});
testWidgets('initial route trigger observer in the right order', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => const Text('/'),
'/A': (BuildContext context) => const Text('A'),
'/A/B': (BuildContext context) => const Text('B'),
};
final List<NavigatorObservation> observations = <NavigatorObservation>[];
final TestObserver observer = TestObserver()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
// Pushes the initial route.
observations.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'push',
),
);
};
await tester.pumpWidget(MaterialApp(
routes: routes,
initialRoute: '/A/B',
navigatorObservers: <NavigatorObserver>[observer],
));
expect(observations.length, 3);
expect(observations[0].operation, 'push');
expect(observations[0].current, '/');
expect(observations[0].previous, isNull);
expect(observations[1].operation, 'push');
expect(observations[1].current, '/A');
expect(observations[1].previous, '/');
expect(observations[2].operation, 'push');
expect(observations[2].current, '/A/B');
expect(observations[2].previous, '/A');
});
testWidgets('$Route dispatches memory events', (WidgetTester tester) async {
Future<void> createAndDisposeRoute() async {
final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: nav,
home: const Scaffold(
body: Text('home'),
)
)
);
nav.currentState!.push(MaterialPageRoute<void>(builder: (_) => const Placeholder())); // This should create a route
await tester.pumpAndSettle();
nav.currentState!.pop();
await tester.pumpAndSettle(); // this should dispose the route.
}
final List<ObjectEvent> events = <ObjectEvent>[];
void listener(ObjectEvent event) {
if (event.object.runtimeType == MaterialPageRoute<void>) {
events.add(event);
}
}
FlutterMemoryAllocations.instance.addListener(listener);
await createAndDisposeRoute();
expect(events, hasLength(2));
expect(events.first, isA<ObjectCreated>());
expect(events.last, isA<ObjectDisposed>());
FlutterMemoryAllocations.instance.removeListener(listener);
});
testWidgets('Route didAdd and dispose in same frame work', (WidgetTester tester) async {
// Regression Test for https://github.com/flutter/flutter/issues/61346.
Widget buildNavigator() {
return Navigator(
pages: const <Page<void>>[
MaterialPage<void>(
child: Placeholder(),
),
],
onPopPage: (Route<dynamic> route, dynamic result) => false,
);
}
final TabController controller = TabController(length: 3, vsync: tester);
addTearDown(controller.dispose);
await tester.pumpWidget(
TestDependencies(
child: TabBarView(
controller: controller,
children: <Widget>[
buildNavigator(),
buildNavigator(),
buildNavigator(),
],
),
),
);
// This test should finish without crashing.
controller.index = 2;
await tester.pumpAndSettle();
});
testWidgets('Page-based route pop before push finishes', (WidgetTester tester) async {
List<Page<void>> pages = <Page<void>>[const MaterialPage<void>(child: Text('Page 1'))];
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
Widget buildNavigator() {
return Navigator(
key: navigator,
pages: pages,
onPopPage: (Route<dynamic> route, dynamic result) {
pages.removeLast();
return route.didPop(result);
},
);
}
await tester.pumpWidget(
TestDependencies(
child: buildNavigator(),
),
);
expect(find.text('Page 1'), findsOneWidget);
pages = pages.toList();
pages.add(const MaterialPage<void>(child: Text('Page 2')));
await tester.pumpWidget(
TestDependencies(
child: buildNavigator(),
),
);
// This test should finish without crashing.
await tester.pump();
await tester.pump();
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('Page 1'), findsOneWidget);
});
testWidgets('Pages update does update overlay correctly', (WidgetTester tester) async {
// Regression Test for https://github.com/flutter/flutter/issues/64941.
List<Page<void>> pages = const <Page<void>>[
MaterialPage<void>(
key: ValueKey<int>(0),
child: Text('page 0'),
),
MaterialPage<void>(
key: ValueKey<int>(1),
child: Text('page 1'),
),
];
Widget buildNavigator() {
return Navigator(
pages: pages,
onPopPage: (Route<dynamic> route, dynamic result) => false,
);
}
await tester.pumpWidget(
TestDependencies(
child: buildNavigator(),
),
);
expect(find.text('page 1'), findsOneWidget);
expect(find.text('page 0'), findsNothing);
// Removes the first page.
pages = const <Page<void>>[
MaterialPage<void>(
key: ValueKey<int>(1),
child: Text('page 1'),
),
];
await tester.pumpWidget(
TestDependencies(
child: buildNavigator(),
),
);
// Overlay updates correctly.
expect(find.text('page 1'), findsOneWidget);
expect(find.text('page 0'), findsNothing);
await tester.pumpAndSettle();
expect(find.text('page 1'), findsOneWidget);
expect(find.text('page 0'), findsNothing);
});
testWidgets('replaceNamed replaces', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushReplacementNamed(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pushReplacementNamed(context, '/B'); }),
'/B': (BuildContext context) => const OnTapPage(id: 'B'),
};
await tester.pumpWidget(MaterialApp(routes: routes));
await tester.tap(find.text('/')); // replaceNamed('/A')
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsOneWidget);
await tester.tap(find.text('A')); // replaceNamed('/B')
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
});
testWidgets('pushReplacement sets secondaryAnimation after transition, with history change during transition', (WidgetTester tester) async {
final Map<String, SlideInOutPageRoute<dynamic>> routes = <String, SlideInOutPageRoute<dynamic>>{};
final Map<String, WidgetBuilder> builders = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(
id: '/',
onTap: () {
Navigator.pushNamed(context, '/A');
},
),
'/A': (BuildContext context) => OnTapPage(
id: 'A',
onTap: () {
Navigator.pushNamed(context, '/B');
},
),
'/B': (BuildContext context) => OnTapPage(
id: 'B',
onTap: () {
Navigator.pushReplacementNamed(context, '/C');
},
),
'/C': (BuildContext context) => OnTapPage(
id: 'C',
onTap: () {
Navigator.removeRoute(context, routes['/']!);
},
),
};
await tester.pumpWidget(MaterialApp(
onGenerateRoute: (RouteSettings settings) {
final SlideInOutPageRoute<dynamic> ret = SlideInOutPageRoute<dynamic>(bodyBuilder: builders[settings.name]!, settings: settings);
routes[settings.name!] = ret;
return ret;
},
));
await tester.pumpAndSettle();
await tester.tap(find.text('/'));
await tester.pumpAndSettle();
final double a2 = routes['/A']!.secondaryAnimation!.value;
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 16));
expect(routes['/A']!.secondaryAnimation!.value, greaterThan(a2));
await tester.pumpAndSettle();
await tester.tap(find.text('B'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(routes['/A']!.secondaryAnimation!.value, equals(1.0));
await tester.tap(find.text('C'));
await tester.pumpAndSettle();
expect(find.text('C'), isOnstage);
expect(routes['/A']!.secondaryAnimation!.value, equals(routes['/C']!.animation!.value));
final AnimationController controller = routes['/C']!.controller!;
controller.value = 1 - controller.value;
expect(routes['/A']!.secondaryAnimation!.value, equals(routes['/C']!.animation!.value));
});
testWidgets('new route removed from navigator history during pushReplacement transition', (WidgetTester tester) async {
final Map<String, SlideInOutPageRoute<dynamic>> routes = <String, SlideInOutPageRoute<dynamic>>{};
final Map<String, WidgetBuilder> builders = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(
id: '/',
onTap: () {
Navigator.pushNamed(context, '/A');
},
),
'/A': (BuildContext context) => OnTapPage(
id: 'A',
onTap: () {
Navigator.pushReplacementNamed(context, '/B');
},
),
'/B': (BuildContext context) => OnTapPage(
id: 'B',
onTap: () {
Navigator.removeRoute(context, routes['/B']!);
},
),
};
await tester.pumpWidget(MaterialApp(
onGenerateRoute: (RouteSettings settings) {
final SlideInOutPageRoute<dynamic> ret = SlideInOutPageRoute<dynamic>(bodyBuilder: builders[settings.name]!, settings: settings);
routes[settings.name!] = ret;
return ret;
},
));
await tester.pumpAndSettle();
await tester.tap(find.text('/'));
await tester.pumpAndSettle();
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(find.text('A'), isOnstage);
expect(find.text('B'), isOnstage);
await tester.tap(find.text('B'));
await tester.pumpAndSettle();
expect(find.text('/'), isOnstage);
expect(find.text('B'), findsNothing);
expect(find.text('A'), findsNothing);
expect(routes['/']!.secondaryAnimation!.value, equals(0.0));
expect(routes['/']!.animation!.value, equals(1.0));
});
testWidgets('pushReplacement triggers secondaryAnimation', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(
id: '/',
onTap: () {
Navigator.pushReplacementNamed(context, '/A');
},
),
'/A': (BuildContext context) => OnTapPage(
id: 'A',
onTap: () {
Navigator.pushReplacementNamed(context, '/B');
},
),
'/B': (BuildContext context) => const OnTapPage(id: 'B'),
};
await tester.pumpWidget(MaterialApp(
onGenerateRoute: (RouteSettings settings) {
return SlideInOutPageRoute<dynamic>(bodyBuilder: routes[settings.name]!);
},
));
await tester.pumpAndSettle();
final Offset rootOffsetOriginal = tester.getTopLeft(find.text('/'));
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 16));
expect(find.text('/'), isOnstage);
expect(find.text('A'), isOnstage);
expect(find.text('B'), findsNothing);
final Offset rootOffset = tester.getTopLeft(find.text('/'));
expect(rootOffset.dx, lessThan(rootOffsetOriginal.dx));
Offset aOffsetOriginal = tester.getTopLeft(find.text('A'));
await tester.pumpAndSettle();
Offset aOffset = tester.getTopLeft(find.text('A'));
expect(aOffset.dx, lessThan(aOffsetOriginal.dx));
aOffsetOriginal = aOffset;
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 16));
expect(find.text('/'), findsNothing);
expect(find.text('A'), isOnstage);
expect(find.text('B'), isOnstage);
aOffset = tester.getTopLeft(find.text('A'));
expect(aOffset.dx, lessThan(aOffsetOriginal.dx));
});
testWidgets('pushReplacement correctly reports didReplace to the observer', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/56892.
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => const OnTapPage(
id: '/',
),
'/A': (BuildContext context) => const OnTapPage(
id: 'A',
),
'/A/B': (BuildContext context) => OnTapPage(
id: 'B',
onTap: () {
Navigator.of(context).popUntil((Route<dynamic> route) => route.isFirst);
Navigator.of(context).pushReplacementNamed('/C');
},
),
'/C': (BuildContext context) => const OnTapPage(id: 'C',
),
};
final List<NavigatorObservation> observations = <NavigatorObservation>[];
final TestObserver observer = TestObserver()
..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observations.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'didPop',
),
);
}
..onReplaced = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observations.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'didReplace',
),
);
};
await tester.pumpWidget(
MaterialApp(
routes: routes,
navigatorObservers: <NavigatorObserver>[observer],
initialRoute: '/A/B',
),
);
await tester.pumpAndSettle();
expect(find.text('B'), isOnstage);
await tester.tap(find.text('B'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 16));
expect(observations.length, 3);
expect(observations[0].current, '/A/B');
expect(observations[0].previous, '/A');
expect(observations[0].operation, 'didPop');
expect(observations[1].current, '/A');
expect(observations[1].previous, '/');
expect(observations[1].operation, 'didPop');
expect(observations[2].current, '/C');
expect(observations[2].previous, '/');
expect(observations[2].operation, 'didReplace');
await tester.pumpAndSettle();
expect(find.text('C'), isOnstage);
});
testWidgets('Able to pop all routes', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => const OnTapPage(
id: '/',
),
'/A': (BuildContext context) => const OnTapPage(
id: 'A',
),
'/A/B': (BuildContext context) => OnTapPage(
id: 'B',
onTap: () {
// Pops all routes with bad predicate.
Navigator.of(context).popUntil((Route<dynamic> route) => false);
},
),
};
await tester.pumpWidget(
MaterialApp(
routes: routes,
initialRoute: '/A/B',
),
);
await tester.tap(find.text('B'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
});
testWidgets('pushAndRemoveUntil triggers secondaryAnimation', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(
id: '/',
onTap: () {
Navigator.pushNamed(context, '/A');
},
),
'/A': (BuildContext context) => OnTapPage(
id: 'A',
onTap: () {
Navigator.pushNamedAndRemoveUntil(context, '/B', (Route<dynamic> route) => false);
},
),
'/B': (BuildContext context) => const OnTapPage(id: 'B'),
};
await tester.pumpWidget(MaterialApp(
onGenerateRoute: (RouteSettings settings) {
return SlideInOutPageRoute<dynamic>(bodyBuilder: routes[settings.name]!);
},
));
await tester.pumpAndSettle();
final Offset rootOffsetOriginal = tester.getTopLeft(find.text('/'));
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 16));
expect(find.text('/'), isOnstage);
expect(find.text('A'), isOnstage);
expect(find.text('B'), findsNothing);
final Offset rootOffset = tester.getTopLeft(find.text('/'));
expect(rootOffset.dx, lessThan(rootOffsetOriginal.dx));
Offset aOffsetOriginal = tester.getTopLeft(find.text('A'));
await tester.pumpAndSettle();
Offset aOffset = tester.getTopLeft(find.text('A'));
expect(aOffset.dx, lessThan(aOffsetOriginal.dx));
aOffsetOriginal = aOffset;
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 16));
expect(find.text('/'), findsNothing);
expect(find.text('A'), isOnstage);
expect(find.text('B'), isOnstage);
aOffset = tester.getTopLeft(find.text('A'));
expect(aOffset.dx, lessThan(aOffsetOriginal.dx));
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsNothing);
expect(find.text('B'), isOnstage);
});
testWidgets('pushAndRemoveUntil does not remove routes below the first route that pass the predicate', (WidgetTester tester) async {
// Regression https://github.com/flutter/flutter/issues/56688
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => const Text('home'),
'/A': (BuildContext context) => const Text('page A'),
'/A/B': (BuildContext context) => OnTapPage(
id: 'B',
onTap: () {
Navigator.of(context).pushNamedAndRemoveUntil('/D', ModalRoute.withName('/A'));
},
),
'/D': (BuildContext context) => const Text('page D'),
};
await tester.pumpWidget(
MaterialApp(
navigatorKey: navigator,
routes: routes,
initialRoute: '/A/B',
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('B'));
await tester.pumpAndSettle();
expect(find.text('page D'), isOnstage);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('page A'), isOnstage);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('home'), isOnstage);
});
testWidgets('replaceNamed returned value', (WidgetTester tester) async {
late Future<String?> value;
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { value = Navigator.pushReplacementNamed(context, '/B', result: 'B'); }),
'/B': (BuildContext context) => OnTapPage(id: 'B', onTap: () { Navigator.pop(context, 'B'); }),
};
await tester.pumpWidget(MaterialApp(
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<String>(
settings: settings,
pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) {
return routes[settings.name]!(context);
},
);
},
));
expect(find.text('/'), findsOneWidget);
expect(find.text('A', skipOffstage: false), findsNothing);
expect(find.text('B', skipOffstage: false), findsNothing);
await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
await tester.tap(find.text('A')); // replaceNamed('/B'), stack becomes /, /B
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
await tester.tap(find.text('B')); // pop, stack becomes /
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsOneWidget);
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsNothing);
final String? replaceNamedValue = await value; // replaceNamed result was 'B'
expect(replaceNamedValue, 'B');
});
testWidgets('removeRoute', (WidgetTester tester) async {
final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pushNamed(context, '/B'); }),
'/B': (BuildContext context) => const OnTapPage(id: 'B'),
};
final Map<String, Route<String>> routes = <String, Route<String>>{};
late Route<String> removedRoute;
late Route<String> previousRoute;
final TestObserver observer = TestObserver()
..onRemoved = (Route<dynamic>? route, Route<dynamic>? previous) {
removedRoute = route! as Route<String>;
previousRoute = previous! as Route<String>;
};
await tester.pumpWidget(MaterialApp(
navigatorObservers: <NavigatorObserver>[observer],
onGenerateRoute: (RouteSettings settings) {
routes[settings.name!] = PageRouteBuilder<String>(
settings: settings,
pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) {
return pageBuilders[settings.name!]!(context);
},
);
return routes[settings.name];
},
));
expect(find.text('/'), findsOneWidget);
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsNothing);
await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
await tester.tap(find.text('A')); // pushNamed('/B'), stack becomes /, /A, /B
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsOneWidget);
// Verify that the navigator's stack is ordered as expected.
expect(routes['/']!.isActive, true);
expect(routes['/A']!.isActive, true);
expect(routes['/B']!.isActive, true);
expect(routes['/']!.isFirst, true);
expect(routes['/B']!.isCurrent, true);
final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator));
navigator.removeRoute(routes['/B']!); // stack becomes /, /A
await tester.pump();
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsOneWidget);
expect(find.text('B'), findsNothing);
// Verify that the navigator's stack no longer includes /B
expect(routes['/']!.isActive, true);
expect(routes['/A']!.isActive, true);
expect(routes['/B']!.isActive, false);
expect(routes['/']!.isFirst, true);
expect(routes['/A']!.isCurrent, true);
expect(removedRoute, routes['/B']);
expect(previousRoute, routes['/A']);
navigator.removeRoute(routes['/A']!); // stack becomes just /
await tester.pump();
expect(find.text('/'), findsOneWidget);
expect(find.text('A'), findsNothing);
expect(find.text('B'), findsNothing);
// Verify that the navigator's stack no longer includes /A
expect(routes['/']!.isActive, true);
expect(routes['/A']!.isActive, false);
expect(routes['/B']!.isActive, false);
expect(routes['/']!.isFirst, true);
expect(routes['/']!.isCurrent, true);
expect(removedRoute, routes['/A']);
expect(previousRoute, routes['/']);
});
testWidgets('remove a route whose value is awaited', (WidgetTester tester) async {
late Future<String?> pageValue;
final Map<String, WidgetBuilder> pageBuilders = <String, WidgetBuilder>{
'/': (BuildContext context) => OnTapPage(id: '/', onTap: () { pageValue = Navigator.pushNamed(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context, 'A'); }),
};
final Map<String, Route<String>> routes = <String, Route<String>>{};
await tester.pumpWidget(MaterialApp(
onGenerateRoute: (RouteSettings settings) {
routes[settings.name!] = PageRouteBuilder<String>(
settings: settings,
pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) {
return pageBuilders[settings.name!]!(context);
},
);
return routes[settings.name];
},
));
await tester.tap(find.text('/')); // pushNamed('/A'), stack becomes /, /A
await tester.pumpAndSettle();
pageValue.then((String? value) { assert(false); });
final NavigatorState navigator = tester.state<NavigatorState>(find.byType(Navigator));
navigator.removeRoute(routes['/A']!); // stack becomes /, pageValue will not complete
});
testWidgets('replacing route can be observed', (WidgetTester tester) async {
final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>();
final List<String> log = <String>[];
final TestObserver observer = TestObserver()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
log.add('pushed ${route!.settings.name} (previous is ${previousRoute == null ? "<none>" : previousRoute.settings.name})');
}
..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
log.add('popped ${route!.settings.name} (previous is ${previousRoute == null ? "<none>" : previousRoute.settings.name})');
}
..onRemoved = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
log.add('removed ${route!.settings.name} (previous is ${previousRoute == null ? "<none>" : previousRoute.settings.name})');
}
..onReplaced = (Route<dynamic>? newRoute, Route<dynamic>? oldRoute) {
log.add('replaced ${oldRoute!.settings.name} with ${newRoute!.settings.name}');
};
late Route<void> routeB;
await tester.pumpWidget(MaterialApp(
navigatorKey: key,
navigatorObservers: <NavigatorObserver>[observer],
home: TextButton(
child: const Text('A'),
onPressed: () {
key.currentState!.push<void>(routeB = MaterialPageRoute<void>(
settings: const RouteSettings(name: 'B'),
builder: (BuildContext context) {
return TextButton(
child: const Text('B'),
onPressed: () {
key.currentState!.push<void>(MaterialPageRoute<int>(
settings: const RouteSettings(name: 'C'),
builder: (BuildContext context) {
return TextButton(
child: const Text('C'),
onPressed: () {
key.currentState!.replace(
oldRoute: routeB,
newRoute: MaterialPageRoute<int>(
settings: const RouteSettings(name: 'D'),
builder: (BuildContext context) {
return const Text('D');
},
),
);
},
);
},
));
},
);
},
));
},
),
));
expect(log, <String>['pushed / (previous is <none>)']);
await tester.tap(find.text('A'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(log, <String>['pushed / (previous is <none>)', 'pushed B (previous is /)']);
await tester.tap(find.text('B'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(log, <String>['pushed / (previous is <none>)', 'pushed B (previous is /)', 'pushed C (previous is B)']);
await tester.tap(find.text('C'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(log, <String>['pushed / (previous is <none>)', 'pushed B (previous is /)', 'pushed C (previous is B)', 'replaced B with D']);
});
testWidgets('didStartUserGesture observable', (WidgetTester tester) async {
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(id: '/', onTap: () { Navigator.pushNamed(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context); }),
};
late Route<dynamic> observedRoute;
late Route<dynamic> observedPreviousRoute;
final TestObserver observer = TestObserver()
..onStartUserGesture = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observedRoute = route!;
observedPreviousRoute = previousRoute!;
};
await tester.pumpWidget(MaterialApp(
routes: routes,
navigatorObservers: <NavigatorObserver>[observer],
));
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsNothing);
expect(find.text('A'), findsOneWidget);
tester.state<NavigatorState>(find.byType(Navigator)).didStartUserGesture();
expect(observedRoute.settings.name, '/A');
expect(observedPreviousRoute.settings.name, '/');
});
testWidgets('ModalRoute.of sets up a route to rebuild if its state changes', (WidgetTester tester) async {
final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>();
final List<String> log = <String>[];
late Route<void> routeB;
await tester.pumpWidget(MaterialApp(
navigatorKey: key,
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
},
),
),
home: TextButton(
child: const Text('A'),
onPressed: () {
key.currentState!.push<void>(routeB = MaterialPageRoute<void>(
settings: const RouteSettings(name: 'B'),
builder: (BuildContext context) {
log.add('building B');
return TextButton(
child: const Text('B'),
onPressed: () {
key.currentState!.push<void>(MaterialPageRoute<int>(
settings: const RouteSettings(name: 'C'),
builder: (BuildContext context) {
log.add('building C');
log.add('found ${ModalRoute.of(context)!.settings.name}');
return TextButton(
child: const Text('C'),
onPressed: () {
key.currentState!.replace(
oldRoute: routeB,
newRoute: MaterialPageRoute<int>(
settings: const RouteSettings(name: 'D'),
builder: (BuildContext context) {
log.add('building D');
return const Text('D');
},
),
);
},
);
},
));
},
);
},
));
},
),
));
expect(log, <String>[]);
await tester.tap(find.text('A'));
await tester.pumpAndSettle(const Duration(milliseconds: 10));
expect(log, <String>['building B']);
await tester.tap(find.text('B'));
await tester.pumpAndSettle(const Duration(milliseconds: 10));
expect(log, <String>['building B', 'building C', 'found C']);
await tester.tap(find.text('C'));
await tester.pumpAndSettle(const Duration(milliseconds: 10));
expect(log, <String>['building B', 'building C', 'found C', 'building D']);
key.currentState!.pop<void>();
await tester.pumpAndSettle(const Duration(milliseconds: 10));
expect(log, <String>['building B', 'building C', 'found C', 'building D']);
});
testWidgets("Routes don't rebuild just because their animations ended", (WidgetTester tester) async {
final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>();
final List<String> log = <String>[];
Route<dynamic>? nextRoute = PageRouteBuilder<int>(
pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
log.add('building page 1 - ${ModalRoute.of(context)!.canPop}');
return const Placeholder();
},
);
await tester.pumpWidget(MaterialApp(
navigatorKey: key,
onGenerateRoute: (RouteSettings settings) {
assert(nextRoute != null);
final Route<dynamic> result = nextRoute!;
nextRoute = null;
return result;
},
));
final List<String> expected = <String>['building page 1 - false'];
expect(log, expected);
key.currentState!.pushReplacement(PageRouteBuilder<int>(
pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
log.add('building page 2 - ${ModalRoute.of(context)!.canPop}');
return const Placeholder();
},
));
expect(log, expected);
await tester.pump();
expected.add('building page 2 - false');
expected.add('building page 1 - false'); // page 1 is rebuilt again because isCurrent changed.
expect(log, expected);
await tester.pump(const Duration(milliseconds: 150));
expect(log, expected);
key.currentState!.pushReplacement(PageRouteBuilder<int>(
pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
log.add('building page 3 - ${ModalRoute.of(context)!.canPop}');
return const Placeholder();
},
));
expect(log, expected);
await tester.pump();
expected.add('building page 3 - false');
expected.add('building page 2 - false'); // page 2 is rebuilt again because isCurrent changed.
expect(log, expected);
await tester.pump(const Duration(milliseconds: 200));
expect(log, expected);
});
testWidgets('route semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/': (BuildContext context) => OnTapPage(id: '1', onTap: () { Navigator.pushNamed(context, '/A'); }),
'/A': (BuildContext context) => OnTapPage(id: '2', onTap: () { Navigator.pushNamed(context, '/B/C'); }),
'/B/C': (BuildContext context) => const OnTapPage(id: '3'),
};
await tester.pumpWidget(MaterialApp(routes: routes));
expect(semantics, includesNodeWith(
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
));
expect(semantics, includesNodeWith(
label: 'Page 1',
flags: <SemanticsFlag>[
SemanticsFlag.namesRoute,
SemanticsFlag.isHeader,
],
));
await tester.tap(find.text('1')); // pushNamed('/A')
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(semantics, includesNodeWith(
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
));
expect(semantics, includesNodeWith(
label: 'Page 2',
flags: <SemanticsFlag>[
SemanticsFlag.namesRoute,
SemanticsFlag.isHeader,
],
));
await tester.tap(find.text('2')); // pushNamed('/B/C')
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(semantics, includesNodeWith(
flags: <SemanticsFlag>[
SemanticsFlag.scopesRoute,
],
));
expect(semantics, includesNodeWith(
label: 'Page 3',
flags: <SemanticsFlag>[
SemanticsFlag.namesRoute,
SemanticsFlag.isHeader,
],
));
semantics.dispose();
});
testWidgets('arguments for named routes on Navigator', (WidgetTester tester) async {
late GlobalKey currentRouteKey;
final List<Object?> arguments = <Object?>[];
await tester.pumpWidget(MaterialApp(
onGenerateRoute: (RouteSettings settings) {
arguments.add(settings.arguments);
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) => Center(key: currentRouteKey = GlobalKey(), child: Text(settings.name!)),
);
},
));
expect(find.text('/'), findsOneWidget);
expect(arguments.single, isNull);
arguments.clear();
Navigator.pushNamed(
currentRouteKey.currentContext!,
'/A',
arguments: 'pushNamed',
);
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('/A'), findsOneWidget);
expect(arguments.single, 'pushNamed');
arguments.clear();
Navigator.popAndPushNamed(
currentRouteKey.currentContext!,
'/B',
arguments: 'popAndPushNamed',
);
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('/A'), findsNothing);
expect(find.text('/B'), findsOneWidget);
expect(arguments.single, 'popAndPushNamed');
arguments.clear();
Navigator.pushNamedAndRemoveUntil(
currentRouteKey.currentContext!,
'/C',
(Route<dynamic> route) => route.isFirst,
arguments: 'pushNamedAndRemoveUntil',
);
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('/A'), findsNothing);
expect(find.text('/B'), findsNothing);
expect(find.text('/C'), findsOneWidget);
expect(arguments.single, 'pushNamedAndRemoveUntil');
arguments.clear();
Navigator.pushReplacementNamed(
currentRouteKey.currentContext!,
'/D',
arguments: 'pushReplacementNamed',
);
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('/A'), findsNothing);
expect(find.text('/B'), findsNothing);
expect(find.text('/C'), findsNothing);
expect(find.text('/D'), findsOneWidget);
expect(arguments.single, 'pushReplacementNamed');
arguments.clear();
});
testWidgets('arguments for named routes on NavigatorState', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
final List<Object?> arguments = <Object?>[];
await tester.pumpWidget(MaterialApp(
navigatorKey: navigatorKey,
onGenerateRoute: (RouteSettings settings) {
arguments.add(settings.arguments);
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) => Center(child: Text(settings.name!)),
);
},
));
expect(find.text('/'), findsOneWidget);
expect(arguments.single, isNull);
arguments.clear();
navigatorKey.currentState!.pushNamed(
'/A',
arguments:'pushNamed',
);
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('/A'), findsOneWidget);
expect(arguments.single, 'pushNamed');
arguments.clear();
navigatorKey.currentState!.popAndPushNamed(
'/B',
arguments: 'popAndPushNamed',
);
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('/A'), findsNothing);
expect(find.text('/B'), findsOneWidget);
expect(arguments.single, 'popAndPushNamed');
arguments.clear();
navigatorKey.currentState!.pushNamedAndRemoveUntil(
'/C',
(Route<dynamic> route) => route.isFirst,
arguments: 'pushNamedAndRemoveUntil',
);
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('/A'), findsNothing);
expect(find.text('/B'), findsNothing);
expect(find.text('/C'), findsOneWidget);
expect(arguments.single, 'pushNamedAndRemoveUntil');
arguments.clear();
navigatorKey.currentState!.pushReplacementNamed(
'/D',
arguments: 'pushReplacementNamed',
);
await tester.pumpAndSettle();
expect(find.text('/'), findsNothing);
expect(find.text('/A'), findsNothing);
expect(find.text('/B'), findsNothing);
expect(find.text('/C'), findsNothing);
expect(find.text('/D'), findsOneWidget);
expect(arguments.single, 'pushReplacementNamed');
arguments.clear();
});
testWidgets('Initial route can have gaps', (WidgetTester tester) async {
final GlobalKey<NavigatorState> keyNav = GlobalKey<NavigatorState>();
const Key keyRoot = Key('Root');
const Key keyA = Key('A');
const Key keyABC = Key('ABC');
await tester.pumpWidget(
MaterialApp(
navigatorKey: keyNav,
initialRoute: '/A/B/C',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => Container(key: keyRoot),
'/A': (BuildContext context) => Container(key: keyA),
// The route /A/B is intentionally left out.
'/A/B/C': (BuildContext context) => Container(key: keyABC),
},
),
);
// The initial route /A/B/C should've been pushed successfully.
expect(find.byKey(keyRoot, skipOffstage: false), findsOneWidget);
expect(find.byKey(keyA, skipOffstage: false), findsOneWidget);
expect(find.byKey(keyABC), findsOneWidget);
keyNav.currentState!.pop();
await tester.pumpAndSettle();
expect(find.byKey(keyRoot, skipOffstage: false), findsOneWidget);
expect(find.byKey(keyA), findsOneWidget);
expect(find.byKey(keyABC, skipOffstage: false), findsNothing);
});
testWidgets('The full initial route has to be matched', (WidgetTester tester) async {
final GlobalKey<NavigatorState> keyNav = GlobalKey<NavigatorState>();
const Key keyRoot = Key('Root');
const Key keyA = Key('A');
const Key keyAB = Key('AB');
await tester.pumpWidget(
MaterialApp(
navigatorKey: keyNav,
initialRoute: '/A/B/C',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => Container(key: keyRoot),
'/A': (BuildContext context) => Container(key: keyA),
'/A/B': (BuildContext context) => Container(key: keyAB),
// The route /A/B/C is intentionally left out.
},
),
);
final dynamic exception = tester.takeException();
expect(exception, isA<String>());
// ignore: avoid_dynamic_calls
expect(exception.startsWith('Could not navigate to initial route.'), isTrue);
// Only the root route should've been pushed.
expect(find.byKey(keyRoot), findsOneWidget);
expect(find.byKey(keyA), findsNothing);
expect(find.byKey(keyAB), findsNothing);
});
testWidgets("Popping immediately after pushing doesn't crash", (WidgetTester tester) async {
// Added this test to protect against regression of https://github.com/flutter/flutter/issues/45539
final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
'/' : (BuildContext context) => OnTapPage(id: '/', onTap: () {
Navigator.pushNamed(context, '/A');
Navigator.of(context).pop();
}),
'/A': (BuildContext context) => OnTapPage(id: 'A', onTap: () { Navigator.pop(context); }),
};
bool isPushed = false;
bool isPopped = false;
final TestObserver observer = TestObserver()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
// Pushes the initial route.
expect(route is PageRoute && route.settings.name == '/', isTrue);
expect(previousRoute, isNull);
isPushed = true;
}
..onPopped = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
isPopped = true;
};
await tester.pumpWidget(MaterialApp(
routes: routes,
navigatorObservers: <NavigatorObserver>[observer],
));
expect(find.text('/'), findsOneWidget);
expect(find.text('A'), findsNothing);
expect(isPushed, isTrue);
expect(isPopped, isFalse);
isPushed = false;
isPopped = false;
observer.onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
expect(route is PageRoute && route.settings.name == '/A', isTrue);
expect(previousRoute is PageRoute && previousRoute.settings.name == '/', isTrue);
isPushed = true;
};
await tester.tap(find.text('/'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('/'), findsOneWidget);
expect(find.text('A'), findsNothing);
expect(isPushed, isTrue);
expect(isPopped, isTrue);
});
group('error control test', () {
testWidgets('onUnknownRoute null and onGenerateRoute returns null', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(Navigator(
key: navigatorKey,
onGenerateRoute: (_) => null,
));
final dynamic exception = tester.takeException();
expect(exception, isNotNull);
expect(exception, isFlutterError);
final FlutterError error = exception as FlutterError;
expect(error, isNotNull);
expect(error.diagnostics.last, isA<DiagnosticsProperty<NavigatorState>>());
expect(
error.toStringDeep(),
equalsIgnoringHashCodes(
'FlutterError\n'
' Navigator.onGenerateRoute returned null when requested to build\n'
' route "/".\n'
' The onGenerateRoute callback must never return null, unless an\n'
' onUnknownRoute callback is provided as well.\n'
' The Navigator was:\n'
' NavigatorState#00000(lifecycle state: initialized)\n',
),
);
});
testWidgets('onUnknownRoute null and onGenerateRoute returns null', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(Navigator(
key: navigatorKey,
onGenerateRoute: (_) => null,
onUnknownRoute: (_) => null,
));
final dynamic exception = tester.takeException();
expect(exception, isNotNull);
expect(exception, isFlutterError);
final FlutterError error = exception as FlutterError;
expect(error, isNotNull);
expect(error.diagnostics.last, isA<DiagnosticsProperty<NavigatorState>>());
expect(
error.toStringDeep(),
equalsIgnoringHashCodes(
'FlutterError\n'
' Navigator.onUnknownRoute returned null when requested to build\n'
' route "/".\n'
' The onUnknownRoute callback must never return null.\n'
' The Navigator was:\n'
' NavigatorState#00000(lifecycle state: initialized)\n',
),
);
});
});
testWidgets('OverlayEntry of topmost initial route is marked as opaque', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/38038.
final Key root = UniqueKey();
final Key intermediate = UniqueKey();
final GlobalKey topmost = GlobalKey();
await tester.pumpWidget(
MaterialApp(
initialRoute: '/A/B',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => Container(key: root),
'/A': (BuildContext context) => Container(key: intermediate),
'/A/B': (BuildContext context) => Container(key: topmost),
},
),
);
expect(ModalRoute.of(topmost.currentContext!)!.overlayEntries.first.opaque, isTrue);
expect(find.byKey(root), findsNothing); // hidden by opaque Route
expect(find.byKey(intermediate), findsNothing); // hidden by opaque Route
expect(find.byKey(topmost), findsOneWidget);
});
testWidgets('OverlayEntry of topmost route is set to opaque after Push', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/38038.
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: navigator,
initialRoute: '/',
onGenerateRoute: (RouteSettings settings) {
return NoAnimationPageRoute(
pageBuilder: (_) => Container(key: ValueKey<String>(settings.name!)),
);
},
),
);
expect(find.byKey(const ValueKey<String>('/')), findsOneWidget);
navigator.currentState!.pushNamed('/A');
await tester.pump();
final BuildContext topMostContext = tester.element(find.byKey(const ValueKey<String>('/A')));
expect(ModalRoute.of(topMostContext)!.overlayEntries.first.opaque, isTrue);
expect(find.byKey(const ValueKey<String>('/')), findsNothing); // hidden by /A
expect(find.byKey(const ValueKey<String>('/A')), findsOneWidget);
});
testWidgets('OverlayEntry of topmost route is set to opaque after Replace', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/38038.
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: navigator,
initialRoute: '/A/B',
onGenerateRoute: (RouteSettings settings) {
return NoAnimationPageRoute(
pageBuilder: (_) => Container(key: ValueKey<String>(settings.name!)),
);
},
),
);
expect(find.byKey(const ValueKey<String>('/')), findsNothing);
expect(find.byKey(const ValueKey<String>('/A')), findsNothing);
expect(find.byKey(const ValueKey<String>('/A/B')), findsOneWidget);
final Route<dynamic> oldRoute = ModalRoute.of(
tester.element(find.byKey(const ValueKey<String>('/A'), skipOffstage: false)),
)!;
final Route<void> newRoute = NoAnimationPageRoute(
pageBuilder: (_) => Container(key: const ValueKey<String>('/C')),
);
navigator.currentState!.replace<void>(oldRoute: oldRoute, newRoute: newRoute);
await tester.pump();
expect(newRoute.overlayEntries.first.opaque, isTrue);
expect(find.byKey(const ValueKey<String>('/')), findsNothing); // hidden by /A/B
expect(find.byKey(const ValueKey<String>('/A')), findsNothing); // replaced
expect(find.byKey(const ValueKey<String>('/C')), findsNothing); // hidden by /A/B
expect(find.byKey(const ValueKey<String>('/A/B')), findsOneWidget);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.byKey(const ValueKey<String>('/')), findsNothing); // hidden by /C
expect(find.byKey(const ValueKey<String>('/A')), findsNothing); // replaced
expect(find.byKey(const ValueKey<String>('/A/B')), findsNothing); // popped
expect(find.byKey(const ValueKey<String>('/C')), findsOneWidget);
});
testWidgets('Pushing opaque Route does not rebuild routes below', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/45797.
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
final Key bottomRoute = UniqueKey();
final Key topRoute = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(
builders: <TargetPlatform, PageTransitionsBuilder>{
TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(),
},
),
),
navigatorKey: navigator,
routes: <String, WidgetBuilder>{
'/' : (BuildContext context) => StatefulTestWidget(key: bottomRoute),
'/a': (BuildContext context) => StatefulTestWidget(key: topRoute),
},
),
);
expect(tester.state<StatefulTestState>(find.byKey(bottomRoute)).rebuildCount, 1);
navigator.currentState!.pushNamed('/a');
await tester.pumpAndSettle();
// Bottom route is offstage and did not rebuild.
expect(find.byKey(bottomRoute), findsNothing);
expect(tester.state<StatefulTestState>(find.byKey(bottomRoute, skipOffstage: false)).rebuildCount, 1);
expect(tester.state<StatefulTestState>(find.byKey(topRoute)).rebuildCount, 1);
});
testWidgets('initial routes below opaque route are offstage', (WidgetTester tester) async {
final GlobalKey<NavigatorState> testKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(
TestDependencies(
child: Navigator(
key: testKey,
initialRoute: '/a/b',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return Text('+${s.name}+');
},
settings: s,
);
},
),
),
);
expect(find.text('+/+'), findsNothing);
expect(find.text('+/+', skipOffstage: false), findsOneWidget);
expect(find.text('+/a+'), findsNothing);
expect(find.text('+/a+', skipOffstage: false), findsOneWidget);
expect(find.text('+/a/b+'), findsOneWidget);
testKey.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('+/+'), findsNothing);
expect(find.text('+/+', skipOffstage: false), findsOneWidget);
expect(find.text('+/a+'), findsOneWidget);
expect(find.text('+/a/b+'), findsNothing);
testKey.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('+/+'), findsOneWidget);
expect(find.text('+/a+'), findsNothing);
expect(find.text('+/a/b+'), findsNothing);
});
testWidgets('Can provide custom onGenerateInitialRoutes', (WidgetTester tester) async {
bool onGenerateInitialRoutesCalled = false;
final GlobalKey<NavigatorState> testKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(
TestDependencies(
child: Navigator(
key: testKey,
initialRoute: 'Hello World',
onGenerateInitialRoutes: (NavigatorState navigator, String initialRoute) {
onGenerateInitialRoutesCalled = true;
final List<Route<void>> result = <Route<void>>[];
for (final String route in initialRoute.split(' ')) {
result.add(MaterialPageRoute<void>(builder: (BuildContext context) {
return Text(route);
}));
}
return result;
},
),
),
);
expect(onGenerateInitialRoutesCalled, true);
expect(find.text('Hello'), findsNothing);
expect(find.text('World'), findsOneWidget);
testKey.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('Hello'), findsOneWidget);
expect(find.text('World'), findsNothing);
});
testWidgets('Navigator.of able to handle input context is a navigator context', (WidgetTester tester) async {
final GlobalKey<NavigatorState> testKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: testKey,
home: const Text('home'),
),
);
final NavigatorState state = Navigator.of(testKey.currentContext!);
expect(state, testKey.currentState);
});
testWidgets('Navigator.of able to handle input context is a navigator context - root navigator', (WidgetTester tester) async {
final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> sub = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: root,
home: Navigator(
key: sub,
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) => const Text('dummy'),
);
},
),
),
);
final NavigatorState state = Navigator.of(sub.currentContext!, rootNavigator: true);
expect(state, root.currentState);
});
testWidgets('Navigator.maybeOf throws when there is no navigator', (WidgetTester tester) async {
final GlobalKey<NavigatorState> testKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(SizedBox(key: testKey));
expect(() async {
Navigator.of(testKey.currentContext!);
}, throwsFlutterError);
});
testWidgets('Navigator.maybeOf works when there is no navigator', (WidgetTester tester) async {
final GlobalKey<NavigatorState> testKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(SizedBox(key: testKey));
final NavigatorState? state = Navigator.maybeOf(testKey.currentContext!);
expect(state, isNull);
});
testWidgets('Navigator.maybeOf able to handle input context is a navigator context', (WidgetTester tester) async {
final GlobalKey<NavigatorState> testKey = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: testKey,
home: const Text('home'),
),
);
final NavigatorState? state = Navigator.maybeOf(testKey.currentContext!);
expect(state, isNotNull);
expect(state, testKey.currentState);
});
testWidgets('Navigator.maybeOf able to handle input context is a navigator context - root navigator', (WidgetTester tester) async {
final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> sub = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: root,
home: Navigator(
key: sub,
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) => const Text('dummy'),
);
},
),
),
);
final NavigatorState? state = Navigator.maybeOf(sub.currentContext!, rootNavigator: true);
expect(state, isNotNull);
expect(state, root.currentState);
});
testWidgets('pushAndRemove until animates the push', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/25080.
const Duration kFourTenthsOfTheTransitionDuration = Duration(milliseconds: 120);
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
final Map<String, MaterialPageRoute<dynamic>> routeNameToContext = <String, MaterialPageRoute<dynamic>>{};
await tester.pumpWidget(
TestDependencies(
child: Navigator(
key: navigator,
initialRoute: 'root',
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) {
routeNameToContext[settings.name!] = ModalRoute.of(context)! as MaterialPageRoute<dynamic>;
return Text('Route: ${settings.name}');
},
);
},
),
),
);
expect(find.text('Route: root'), findsOneWidget);
navigator.currentState!.pushNamed('1');
await tester.pumpAndSettle();
expect(find.text('Route: 1'), findsOneWidget);
navigator.currentState!.pushNamed('2');
await tester.pumpAndSettle();
expect(find.text('Route: 2'), findsOneWidget);
navigator.currentState!.pushNamed('3');
await tester.pumpAndSettle();
expect(find.text('Route: 3'), findsOneWidget);
expect(find.text('Route: 2', skipOffstage: false), findsOneWidget);
expect(find.text('Route: 1', skipOffstage: false), findsOneWidget);
expect(find.text('Route: root', skipOffstage: false), findsOneWidget);
navigator.currentState!.pushNamedAndRemoveUntil('4', (Route<dynamic> route) => route.isFirst);
await tester.pump();
expect(find.text('Route: 3'), findsOneWidget);
expect(find.text('Route: 4'), findsOneWidget);
final Animation<double> route4Entry = routeNameToContext['4']!.animation!;
expect(route4Entry.value, 0.0); // Entry animation has not started.
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(find.text('Route: 3'), findsOneWidget);
expect(find.text('Route: 4'), findsOneWidget);
expect(route4Entry.value, 0.4);
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(find.text('Route: 3'), findsOneWidget);
expect(find.text('Route: 4'), findsOneWidget);
expect(route4Entry.value, 0.8);
expect(find.text('Route: 2', skipOffstage: false), findsOneWidget);
expect(find.text('Route: 1', skipOffstage: false), findsOneWidget);
expect(find.text('Route: root', skipOffstage: false), findsOneWidget);
// When we hit 1.0 all but root and current have been removed.
await tester.pump(kFourTenthsOfTheTransitionDuration);
expect(find.text('Route: 3', skipOffstage: false), findsNothing);
expect(find.text('Route: 4'), findsOneWidget);
expect(route4Entry.value, 1.0);
expect(find.text('Route: 2', skipOffstage: false), findsNothing);
expect(find.text('Route: 1', skipOffstage: false), findsNothing);
expect(find.text('Route: root', skipOffstage: false), findsOneWidget);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('Route: root'), findsOneWidget);
expect(find.text('Route: 4', skipOffstage: false), findsNothing);
});
testWidgets('Wrapping TickerMode can turn off ticking in routes', (WidgetTester tester) async {
int tickCount = 0;
Widget widgetUnderTest({required bool enabled}) {
return TickerMode(
enabled: enabled,
child: TestDependencies(
child: Navigator(
initialRoute: 'root',
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) {
return _TickingWidget(
onTick: () {
tickCount++;
},
);
},
);
},
),
),
);
}
await tester.pumpWidget(widgetUnderTest(enabled: false));
expect(tickCount, 0);
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(tickCount, 0);
await tester.pumpWidget(widgetUnderTest(enabled: true));
expect(tickCount, 0);
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(tickCount, 4);
});
testWidgets('Route announce correctly for first route and last route', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/57133.
Route<void>? previousOfFirst = NotAnnounced();
Route<void>? nextOfFirst = NotAnnounced();
Route<void>? popNextOfFirst = NotAnnounced();
Route<void>? firstRoute;
Route<void>? previousOfSecond = NotAnnounced();
Route<void>? nextOfSecond = NotAnnounced();
Route<void>? popNextOfSecond = NotAnnounced();
Route<void>? secondRoute;
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
await tester.pumpWidget(
MaterialApp(
navigatorKey: navigator,
initialRoute: '/second',
onGenerateRoute: (RouteSettings settings) {
if (settings.name == '/') {
firstRoute = RouteAnnouncementSpy(
onDidChangeNext: (Route<void>? next) => nextOfFirst = next,
onDidChangePrevious: (Route<void>? previous) => previousOfFirst = previous,
onDidPopNext: (Route<void>? next) => popNextOfFirst = next,
settings: settings,
);
return firstRoute;
}
secondRoute = RouteAnnouncementSpy(
onDidChangeNext: (Route<void>? next) => nextOfSecond = next,
onDidChangePrevious: (Route<void>? previous) => previousOfSecond = previous,
onDidPopNext: (Route<void>? next) => popNextOfSecond = next,
settings: settings,
);
return secondRoute;
},
),
);
await tester.pumpAndSettle();
expect(previousOfFirst, isNull);
expect(nextOfFirst, secondRoute);
expect(popNextOfFirst, isA<NotAnnounced>());
expect(previousOfSecond, firstRoute);
expect(nextOfSecond, isNull);
expect(popNextOfSecond, isA<NotAnnounced>());
navigator.currentState!.pop();
expect(popNextOfFirst, secondRoute);
});
testWidgets('hero controller scope works', (WidgetTester tester) async {
final GlobalKey<NavigatorState> top = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> sub = GlobalKey<NavigatorState>();
final List<NavigatorObservation> observations = <NavigatorObservation>[];
final HeroControllerSpy spy = HeroControllerSpy()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observations.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'didPush',
),
);
};
addTearDown(spy.dispose);
await tester.pumpWidget(
HeroControllerScope(
controller: spy,
child: TestDependencies(
child: Navigator(
key: top,
initialRoute: 'top1',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return Navigator(
key: sub,
initialRoute: 'sub1',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
);
},
settings: s,
);
},
),
),
),
);
// It should only observe the top navigator.
expect(observations.length, 1);
expect(observations[0].current, 'top1');
expect(observations[0].previous, isNull);
sub.currentState!.push(MaterialPageRoute<void>(
settings: const RouteSettings(name:'sub2'),
builder: (BuildContext context) => const Text('sub2'),
));
await tester.pumpAndSettle();
expect(find.text('sub2'), findsOneWidget);
// It should not record sub navigator.
expect(observations.length, 1);
top.currentState!.push(MaterialPageRoute<void>(
settings: const RouteSettings(name:'top2'),
builder: (BuildContext context) => const Text('top2'),
));
await tester.pumpAndSettle();
expect(observations.length, 2);
expect(observations[1].current, 'top2');
expect(observations[1].previous, 'top1');
});
testWidgets('hero controller can correctly transfer subscription - replacing navigator', (WidgetTester tester) async {
final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>();
final List<NavigatorObservation> observations = <NavigatorObservation>[];
final HeroControllerSpy spy = HeroControllerSpy()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observations.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'didPush',
),
);
};
addTearDown(spy.dispose);
await tester.pumpWidget(
HeroControllerScope(
controller: spy,
child: TestDependencies(
child: Navigator(
key: key1,
initialRoute: 'navigator1',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
),
),
);
// Transfer the subscription to another navigator
await tester.pumpWidget(
HeroControllerScope(
controller: spy,
child: TestDependencies(
child: Navigator(
key: key2,
initialRoute: 'navigator2',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
),
),
);
observations.clear();
key2.currentState!.push(MaterialPageRoute<void>(
settings: const RouteSettings(name:'new route'),
builder: (BuildContext context) => const Text('new route'),
));
await tester.pumpAndSettle();
expect(find.text('new route'), findsOneWidget);
// It should record from the new navigator.
expect(observations.length, 1);
expect(observations[0].current, 'new route');
expect(observations[0].previous, 'navigator2');
});
testWidgets('hero controller can correctly transfer subscription - swapping navigator', (WidgetTester tester) async {
final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>();
final List<NavigatorObservation> observations1 = <NavigatorObservation>[];
final HeroControllerSpy spy1 = HeroControllerSpy()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observations1.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'didPush',
),
);
};
addTearDown(spy1.dispose);
final List<NavigatorObservation> observations2 = <NavigatorObservation>[];
final HeroControllerSpy spy2 = HeroControllerSpy()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observations2.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'didPush',
),
);
};
addTearDown(spy2.dispose);
await tester.pumpWidget(
TestDependencies(
child: Stack(
children: <Widget>[
HeroControllerScope(
controller: spy1,
child: Navigator(
key: key1,
initialRoute: 'navigator1',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
),
HeroControllerScope(
controller: spy2,
child: Navigator(
key: key2,
initialRoute: 'navigator2',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
),
],
),
),
);
expect(observations1.length, 1);
expect(observations1[0].current, 'navigator1');
expect(observations1[0].previous, isNull);
expect(observations2.length, 1);
expect(observations2[0].current, 'navigator2');
expect(observations2[0].previous, isNull);
// Swaps the spies.
await tester.pumpWidget(
TestDependencies(
child: Stack(
children: <Widget>[
HeroControllerScope(
controller: spy2,
child: Navigator(
key: key1,
initialRoute: 'navigator1',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
),
HeroControllerScope(
controller: spy1,
child: Navigator(
key: key2,
initialRoute: 'navigator2',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
),
],
),
),
);
// Pushes a route to navigator2.
key2.currentState!.push(MaterialPageRoute<void>(
settings: const RouteSettings(name:'new route2'),
builder: (BuildContext context) => const Text('new route2'),
));
await tester.pumpAndSettle();
expect(find.text('new route2'), findsOneWidget);
// The spy1 should record the push in navigator2.
expect(observations1.length, 2);
expect(observations1[1].current, 'new route2');
expect(observations1[1].previous, 'navigator2');
// The spy2 should not record anything.
expect(observations2.length, 1);
// Pushes a route to navigator1
key1.currentState!.push(MaterialPageRoute<void>(
settings: const RouteSettings(name:'new route1'),
builder: (BuildContext context) => const Text('new route1'),
));
await tester.pumpAndSettle();
expect(find.text('new route1'), findsOneWidget);
// The spy1 should not record anything.
expect(observations1.length, 2);
// The spy2 should record the push in navigator1.
expect(observations2.length, 2);
expect(observations2[1].current, 'new route1');
expect(observations2[1].previous, 'navigator1');
});
testWidgets('hero controller subscribes to multiple navigators does throw', (WidgetTester tester) async {
final HeroControllerSpy spy = HeroControllerSpy();
addTearDown(spy.dispose);
await tester.pumpWidget(
HeroControllerScope(
controller: spy,
child: TestDependencies(
child: Stack(
children: <Widget>[
Navigator(
initialRoute: 'navigator1',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
Navigator(
initialRoute: 'navigator2',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
],
),
),
),
);
expect(tester.takeException(), isAssertionError);
});
testWidgets('hero controller throws has correct error message', (WidgetTester tester) async {
final HeroControllerSpy spy = HeroControllerSpy();
addTearDown(spy.dispose);
await tester.pumpWidget(
HeroControllerScope(
controller: spy,
child: TestDependencies(
child: Stack(
children: <Widget>[
Navigator(
initialRoute: 'navigator1',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
Navigator(
initialRoute: 'navigator2',
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(
builder: (BuildContext c) {
return const Placeholder();
},
settings: s,
);
},
),
],
),
),
),
);
final dynamic exception = tester.takeException();
expect(exception, isFlutterError);
final FlutterError error = exception as FlutterError;
expect(
error.toStringDeep(),
equalsIgnoringHashCodes(
'FlutterError\n'
' A HeroController can not be shared by multiple Navigators. The\n'
' Navigators that share the same HeroController are:\n'
' - NavigatorState#00000(tickers: tracking 1 ticker)\n'
' - NavigatorState#00000(tickers: tracking 1 ticker)\n'
' Please create a HeroControllerScope for each Navigator or use a\n'
' HeroControllerScope.none to prevent subtree from receiving a\n'
' HeroController.\n',
),
);
});
group('Page api', () {
Widget buildNavigator({
required FlutterView view,
required List<Page<dynamic>> pages,
required PopPageCallback onPopPage,
GlobalKey<NavigatorState>? key,
TransitionDelegate<dynamic>? transitionDelegate,
List<NavigatorObserver> observers = const <NavigatorObserver>[],
}) {
return MediaQuery(
data: MediaQueryData.fromView(view),
child: Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: TestDependencies(
child: Navigator(
key: key,
pages: pages,
onPopPage: onPopPage,
observers: observers,
transitionDelegate: transitionDelegate ?? const DefaultTransitionDelegate<dynamic>(),
),
),
),
);
}
testWidgets('can initialize with pages list', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
final List<TestPage> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name:'initial'),
const TestPage(key: ValueKey<String>('2'), name:'second'),
const TestPage(key: ValueKey<String>('3'), name:'third'),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
expect(find.text('third'), findsOneWidget);
expect(find.text('second'), findsNothing);
expect(find.text('initial'), findsNothing);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('third'), findsNothing);
expect(find.text('second'), findsOneWidget);
expect(find.text('initial'), findsNothing);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('third'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('initial'), findsOneWidget);
});
testWidgets('can handle duplicate page key if update before transition finishes', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/97363.
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
final List<TestPage> myPages1 = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name:'initial'),
];
final List<TestPage> myPages2 = <TestPage>[
const TestPage(key: ValueKey<String>('2'), name:'second'),
];
bool onPopPage(Route<dynamic> route, dynamic result) => false;
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages1,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pump();
expect(find.text('initial'), findsOneWidget);
// Update multiple times without waiting for pop to finish to leave
// multiple popping route entries in route stack with the same page key.
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages2,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pump();
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages1,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pump();
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages2,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pumpAndSettle();
expect(find.text('second'), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('throw if onPopPage callback is not provided', (WidgetTester tester) async {
final List<TestPage> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name:'initial'),
const TestPage(key: ValueKey<String>('2'), name:'second'),
const TestPage(key: ValueKey<String>('3'), name:'third'),
];
await tester.pumpWidget(
MediaQuery(
data: MediaQueryData.fromView(tester.view),
child: Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: TestDependencies(
child: Navigator(
pages: myPages,
),
),
),
),
);
final dynamic exception = tester.takeException();
expect(exception, isFlutterError);
final FlutterError error = exception as FlutterError;
expect(
error.toStringDeep(),
equalsIgnoringHashCodes(
'FlutterError\n'
' The Navigator.onPopPage must be provided to use the\n'
' Navigator.pages API\n',
),
);
});
testWidgets('throw if page list is empty', (WidgetTester tester) async {
final List<TestPage> myPages = <TestPage>[];
final FlutterExceptionHandler? originalOnError = FlutterError.onError;
FlutterErrorDetails? firstError;
FlutterError.onError = (FlutterErrorDetails? detail) {
// We only care about the first error;
firstError ??= detail;
};
await tester.pumpWidget(
MediaQuery(
data: MediaQueryData.fromView(tester.view),
child: Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: TestDependencies(
child: Navigator(
pages: myPages,
),
),
),
),
);
FlutterError.onError = originalOnError;
expect(
firstError!.exception.toString(),
'The Navigator.pages must not be empty to use the Navigator.pages API',
);
});
testWidgets('Can pop route with local history entries using page api', (WidgetTester tester) async {
List<Page<void>> myPages = const <Page<void>>[
MaterialPage<void>(child: Text('page1')),
MaterialPage<void>(child: Text('page2')),
];
await tester.pumpWidget(
MediaQuery(
data: MediaQueryData.fromView(tester.view),
child: Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: Navigator(
pages: myPages,
onPopPage: (_, __) => false,
),
),
),
);
expect(find.text('page2'), findsOneWidget);
final ModalRoute<void> route = ModalRoute.of(tester.element(find.text('page2')))!;
bool entryRemoved = false;
route.addLocalHistoryEntry(LocalHistoryEntry(onRemove: () => entryRemoved = true));
expect(route.willHandlePopInternally, true);
myPages = const <Page<void>>[
MaterialPage<void>(child: Text('page1')),
];
await tester.pumpWidget(
MediaQuery(
data: MediaQueryData.fromView(tester.view),
child: Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: Navigator(
pages: myPages,
onPopPage: (_, __) => false,
),
),
),
);
expect(find.text('page1'), findsOneWidget);
expect(entryRemoved, isTrue);
});
testWidgets('ModalRoute must comply with willHandlePopInternally when there is a PopScope', (WidgetTester tester) async {
const List<Page<void>> myPages = <Page<void>>[
MaterialPage<void>(child: Text('page1')),
MaterialPage<void>(
child: PopScope(
canPop: false,
child: Text('page2'),
),
),
];
await tester.pumpWidget(
MediaQuery(
data: MediaQueryData.fromView(tester.view),
child: Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultMaterialLocalizations.delegate,
DefaultWidgetsLocalizations.delegate,
],
child: Navigator(
pages: myPages,
onPopPage: (_, __) => false,
),
),
),
);
final ModalRoute<void> route = ModalRoute.of(tester.element(find.text('page2')))!;
// PopScope only prevents user trigger action, e.g. Navigator.maybePop.
// The page can still be popped by the system if it needs to.
expect(route.willHandlePopInternally, false);
expect(route.didPop(null), true);
});
testWidgets('can push and pop pages using page api', (WidgetTester tester) async {
late Animation<double> secondaryAnimationOfRouteOne;
late Animation<double> primaryAnimationOfRouteOne;
late Animation<double> secondaryAnimationOfRouteTwo;
late Animation<double> primaryAnimationOfRouteTwo;
late Animation<double> secondaryAnimationOfRouteThree;
late Animation<double> primaryAnimationOfRouteThree;
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
List<Page<dynamic>> myPages = <Page<dynamic>>[
BuilderPage(
key: const ValueKey<String>('1'),
name:'initial',
pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) {
secondaryAnimationOfRouteOne = secondaryAnimation;
primaryAnimationOfRouteOne = animation;
return const Text('initial');
},
),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
expect(find.text('initial'), findsOneWidget);
myPages = <Page<dynamic>>[
BuilderPage(
key: const ValueKey<String>('1'),
name:'initial',
pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) {
secondaryAnimationOfRouteOne = secondaryAnimation;
primaryAnimationOfRouteOne = animation;
return const Text('initial');
},
),
BuilderPage(
key: const ValueKey<String>('2'),
name:'second',
pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) {
secondaryAnimationOfRouteTwo = secondaryAnimation;
primaryAnimationOfRouteTwo = animation;
return const Text('second');
},
),
BuilderPage(
key: const ValueKey<String>('3'),
name:'third',
pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) {
secondaryAnimationOfRouteThree = secondaryAnimation;
primaryAnimationOfRouteThree = animation;
return const Text('third');
},
),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// The third page is transitioning, and the secondary animation of first
// page should chain with the third page. The animation of second page
// won't start until the third page finishes transition.
expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteThree.value);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.dismissed);
expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteThree.status, AnimationStatus.forward);
await tester.pump(const Duration(milliseconds: 30));
expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteThree.value);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.dismissed);
expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteThree.value, 0.1);
await tester.pumpAndSettle();
// After transition finishes, the routes' animations are correctly chained.
expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteThree.value);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteThree.status, AnimationStatus.completed);
expect(find.text('third'), findsOneWidget);
expect(find.text('second'), findsNothing);
expect(find.text('initial'), findsNothing);
// Starts pops the pages using page api and verify the animations chain
// correctly.
myPages = <Page<dynamic>>[
BuilderPage(
key: const ValueKey<String>('1'),
name:'initial',
pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) {
secondaryAnimationOfRouteOne = secondaryAnimation;
primaryAnimationOfRouteOne = animation;
return const Text('initial');
},
),
BuilderPage(
key: const ValueKey<String>('2'),
name:'second',
pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) {
secondaryAnimationOfRouteTwo = secondaryAnimation;
primaryAnimationOfRouteTwo = animation;
return const Text('second');
},
),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pump(const Duration(milliseconds: 30));
expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteThree.value);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteThree.value, 0.9);
await tester.pumpAndSettle();
expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteThree.value);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteThree.status, AnimationStatus.dismissed);
});
testWidgets('can modify routes history and secondary animation still works', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
late Animation<double> secondaryAnimationOfRouteOne;
late Animation<double> primaryAnimationOfRouteOne;
late Animation<double> secondaryAnimationOfRouteTwo;
late Animation<double> primaryAnimationOfRouteTwo;
late Animation<double> secondaryAnimationOfRouteThree;
late Animation<double> primaryAnimationOfRouteThree;
List<Page<dynamic>> myPages = <Page<void>>[
BuilderPage(
key: const ValueKey<String>('1'),
name:'initial',
pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) {
secondaryAnimationOfRouteOne = secondaryAnimation;
primaryAnimationOfRouteOne = animation;
return const Text('initial');
},
),
BuilderPage(
key: const ValueKey<String>('2'),
name:'second',
pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) {
secondaryAnimationOfRouteTwo = secondaryAnimation;
primaryAnimationOfRouteTwo = animation;
return const Text('second');
},
),
BuilderPage(
key: const ValueKey<String>('3'),
name:'third',
pageBuilder: (_, Animation<double> animation, Animation<double> secondaryAnimation) {
secondaryAnimationOfRouteThree = secondaryAnimation;
primaryAnimationOfRouteThree = animation;
return const Text('third');
},
),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
expect(find.text('third'), findsOneWidget);
expect(find.text('second'), findsNothing);
expect(find.text('initial'), findsNothing);
expect(secondaryAnimationOfRouteOne.value, primaryAnimationOfRouteTwo.value);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteThree.value);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteThree.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteThree.status, AnimationStatus.completed);
myPages = myPages.reversed.toList();
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// Reversed routes are still chained up correctly.
expect(secondaryAnimationOfRouteThree.value, primaryAnimationOfRouteTwo.value);
expect(primaryAnimationOfRouteThree.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteOne.value);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteOne.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.completed);
navigator.currentState!.pop();
await tester.pump();
await tester.pump(const Duration(milliseconds: 30));
expect(secondaryAnimationOfRouteThree.value, primaryAnimationOfRouteTwo.value);
expect(primaryAnimationOfRouteThree.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteOne.value);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteOne.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteOne.value, 0.9);
await tester.pumpAndSettle();
expect(secondaryAnimationOfRouteThree.value, primaryAnimationOfRouteTwo.value);
expect(primaryAnimationOfRouteThree.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteOne.value);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteOne.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.dismissed);
navigator.currentState!.pop();
await tester.pump();
await tester.pump(const Duration(milliseconds: 30));
expect(secondaryAnimationOfRouteThree.value, primaryAnimationOfRouteTwo.value);
expect(primaryAnimationOfRouteThree.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteOne.value);
expect(primaryAnimationOfRouteTwo.value, 0.9);
expect(secondaryAnimationOfRouteOne.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.dismissed);
await tester.pumpAndSettle();
expect(secondaryAnimationOfRouteThree.value, primaryAnimationOfRouteTwo.value);
expect(primaryAnimationOfRouteThree.status, AnimationStatus.completed);
expect(secondaryAnimationOfRouteTwo.value, primaryAnimationOfRouteOne.value);
expect(primaryAnimationOfRouteTwo.status, AnimationStatus.dismissed);
expect(secondaryAnimationOfRouteOne.status, AnimationStatus.dismissed);
expect(primaryAnimationOfRouteOne.status, AnimationStatus.dismissed);
});
testWidgets('Pop no animation page does not crash', (WidgetTester tester) async {
// Regression Test for https://github.com/flutter/flutter/issues/86604.
Widget buildNavigator(bool secondPage) {
return TestDependencies(
child: Navigator(
pages: <Page<void>>[
const ZeroDurationPage(
child: Text('page1'),
),
if (secondPage)
const ZeroDurationPage(
child: Text('page2'),
),
],
onPopPage: (Route<dynamic> route, dynamic result) => false,
),
);
}
await tester.pumpWidget(buildNavigator(true));
expect(find.text('page2'), findsOneWidget);
await tester.pumpWidget(buildNavigator(false));
expect(find.text('page1'), findsOneWidget);
});
testWidgets('can work with pageless route', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
List<TestPage> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name:'initial'),
const TestPage(key: ValueKey<String>('2'), name:'second'),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
expect(find.text('second'), findsOneWidget);
expect(find.text('initial'), findsNothing);
// Pushes two pageless routes to second page route
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('second-pageless1'),
),
);
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('second-pageless2'),
),
);
await tester.pumpAndSettle();
// Now the history should look like
// [initial, second, second-pageless1, second-pageless2].
expect(find.text('initial'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsNothing);
expect(find.text('second-pageless2'), findsOneWidget);
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name:'initial'),
const TestPage(key: ValueKey<String>('2'), name:'second'),
const TestPage(key: ValueKey<String>('3'), name:'third'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pumpAndSettle();
expect(find.text('initial'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsNothing);
expect(find.text('second-pageless2'), findsNothing);
expect(find.text('third'), findsOneWidget);
// Pushes one pageless routes to third page route
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('third-pageless1'),
),
);
await tester.pumpAndSettle();
// Now the history should look like
// [initial, second, second-pageless1, second-pageless2, third, third-pageless1].
expect(find.text('initial'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsNothing);
expect(find.text('second-pageless2'), findsNothing);
expect(find.text('third'), findsNothing);
expect(find.text('third-pageless1'), findsOneWidget);
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name:'initial'),
const TestPage(key: ValueKey<String>('3'), name:'third'),
const TestPage(key: ValueKey<String>('2'), name:'second'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// Swaps the order without any adding or removing should not trigger any
// transition. The routes should update without a pumpAndSettle
// Now the history should look like
// [initial, third, third-pageless1, second, second-pageless1, second-pageless2].
expect(find.text('initial'), findsNothing);
expect(find.text('third'), findsNothing);
expect(find.text('third-pageless1'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsNothing);
expect(find.text('second-pageless2'), findsOneWidget);
// Pops the route one by one to make sure the order is correct.
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('initial'), findsNothing);
expect(find.text('third'), findsNothing);
expect(find.text('third-pageless1'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsOneWidget);
expect(find.text('second-pageless2'), findsNothing);
expect(myPages.length, 3);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('initial'), findsNothing);
expect(find.text('third'), findsNothing);
expect(find.text('third-pageless1'), findsNothing);
expect(find.text('second'), findsOneWidget);
expect(find.text('second-pageless1'), findsNothing);
expect(find.text('second-pageless2'), findsNothing);
expect(myPages.length, 3);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('initial'), findsNothing);
expect(find.text('third'), findsNothing);
expect(find.text('third-pageless1'), findsOneWidget);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsNothing);
expect(find.text('second-pageless2'), findsNothing);
expect(myPages.length, 2);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('initial'), findsNothing);
expect(find.text('third'), findsOneWidget);
expect(find.text('third-pageless1'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsNothing);
expect(find.text('second-pageless2'), findsNothing);
expect(myPages.length, 2);
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(find.text('initial'), findsOneWidget);
expect(find.text('third'), findsNothing);
expect(find.text('third-pageless1'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsNothing);
expect(find.text('second-pageless2'), findsNothing);
expect(myPages.length, 1);
});
testWidgets('complex case 1', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
List<TestPage> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
// Add initial page route with one pageless route.
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
bool initialPageless1Completed = false;
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('initial-pageless1'),
),
).then((_) => initialPageless1Completed = true);
await tester.pumpAndSettle();
// Pushes second page route with two pageless routes.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pumpAndSettle();
bool secondPageless1Completed = false;
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('second-pageless1'),
),
).then((_) => secondPageless1Completed = true);
await tester.pumpAndSettle();
bool secondPageless2Completed = false;
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('second-pageless2'),
),
).then((_) => secondPageless2Completed = true);
await tester.pumpAndSettle();
// Pushes third page route with one pageless route.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
const TestPage(key: ValueKey<String>('3'), name: 'third'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pumpAndSettle();
bool thirdPageless1Completed = false;
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('third-pageless1'),
),
).then((_) => thirdPageless1Completed = true);
await tester.pumpAndSettle();
// Nothing has been popped.
expect(initialPageless1Completed, false);
expect(secondPageless1Completed, false);
expect(secondPageless2Completed, false);
expect(thirdPageless1Completed, false);
// Switches order and removes the initial page route.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('3'), name: 'third'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// The pageless route of initial page route should be completed.
expect(initialPageless1Completed, true);
expect(secondPageless1Completed, false);
expect(secondPageless2Completed, false);
expect(thirdPageless1Completed, false);
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('3'), name: 'third'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pumpAndSettle();
expect(secondPageless1Completed, true);
expect(secondPageless2Completed, true);
expect(thirdPageless1Completed, false);
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('4'), name: 'forth'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
expect(thirdPageless1Completed, true);
await tester.pumpAndSettle();
expect(find.text('forth'), findsOneWidget);
});
//Regression test for https://github.com/flutter/flutter/issues/115887
testWidgets('Complex case 2', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
List<TestPage> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name:'initial'),
const TestPage(key: ValueKey<String>('2'), name:'second'),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
expect(find.text('second'), findsOneWidget);
expect(find.text('initial'), findsNothing);
// Push pageless route to second page route
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('second-pageless1'),
),
);
await tester.pumpAndSettle();
// Now the history should look like [initial, second, second-pageless1].
expect(find.text('initial'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsOneWidget);
expect(myPages.length, 2);
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('2'), name:'second'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
await tester.pumpAndSettle();
// Now the history should look like [second, second-pageless1].
expect(find.text('initial'), findsNothing);
expect(find.text('second'), findsNothing);
expect(find.text('second-pageless1'), findsOneWidget);
expect(myPages.length, 1);
// Pop the pageless route.
navigator.currentState!.pop();
await tester.pumpAndSettle();
expect(myPages.length, 1);
expect(find.text('initial'), findsNothing);
expect(find.text('second'), findsOneWidget);
expect(find.text('second-pageless1'), findsNothing);
});
testWidgets('complex case 1 - with always remove transition delegate', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
final AlwaysRemoveTransitionDelegate transitionDelegate = AlwaysRemoveTransitionDelegate();
List<TestPage> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
// Add initial page route with one pageless route.
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
transitionDelegate: transitionDelegate,
),
);
bool initialPageless1Completed = false;
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('initial-pageless1'),
),
).then((_) => initialPageless1Completed = true);
await tester.pumpAndSettle();
// Pushes second page route with two pageless routes.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
transitionDelegate: transitionDelegate,
),
);
bool secondPageless1Completed = false;
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('second-pageless1'),
),
).then((_) => secondPageless1Completed = true);
await tester.pumpAndSettle();
bool secondPageless2Completed = false;
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('second-pageless2'),
),
).then((_) => secondPageless2Completed = true);
await tester.pumpAndSettle();
// Pushes third page route with one pageless route.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
const TestPage(key: ValueKey<String>('3'), name: 'third'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
transitionDelegate: transitionDelegate,
),
);
bool thirdPageless1Completed = false;
navigator.currentState!.push(
MaterialPageRoute<void>(
builder: (BuildContext context) => const Text('third-pageless1'),
),
).then((_) => thirdPageless1Completed = true);
await tester.pumpAndSettle();
// Nothing has been popped.
expect(initialPageless1Completed, false);
expect(secondPageless1Completed, false);
expect(secondPageless2Completed, false);
expect(thirdPageless1Completed, false);
// Switches order and removes the initial page route.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('3'), name: 'third'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
transitionDelegate: transitionDelegate,
),
);
// The pageless route of initial page route should be removed without complete.
expect(initialPageless1Completed, false);
expect(secondPageless1Completed, false);
expect(secondPageless2Completed, false);
expect(thirdPageless1Completed, false);
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('3'), name: 'third'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
transitionDelegate: transitionDelegate,
),
);
await tester.pumpAndSettle();
expect(initialPageless1Completed, false);
expect(secondPageless1Completed, false);
expect(secondPageless2Completed, false);
expect(thirdPageless1Completed, false);
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('4'), name: 'forth'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
transitionDelegate: transitionDelegate,
),
);
await tester.pump();
expect(initialPageless1Completed, false);
expect(secondPageless1Completed, false);
expect(secondPageless2Completed, false);
expect(thirdPageless1Completed, false);
expect(find.text('forth'), findsOneWidget);
});
testWidgets('can repush a page that was previously popped before it has finished popping', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
List<Page<dynamic>> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// Pops the second page route.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// Re-push the second page again before it finishes popping.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// It should not crash the app.
expect(tester.takeException(), isNull);
await tester.pumpAndSettle();
expect(find.text('second'), findsOneWidget);
});
testWidgets('can update pages before a route has finished popping', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
List<Page<dynamic>> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// Pops the second page route.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// Updates the pages again before second page finishes popping.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// It should not crash the app.
expect(tester.takeException(), isNull);
await tester.pumpAndSettle();
expect(find.text('initial'), findsOneWidget);
});
testWidgets('can update pages before a pageless route has finished popping', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/68162.
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
List<Page<dynamic>> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
const TestPage(key: ValueKey<String>('2'), name: 'second'),
];
bool onPopPage(Route<dynamic> route, dynamic result) {
myPages.removeWhere((Page<dynamic> page) => route.settings == page);
return route.didPop(result);
}
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// Pushes a pageless route.
showDialog<void>(
useRootNavigator: false,
context: navigator.currentContext!,
builder: (BuildContext context) => const Text('dialog'),
);
await tester.pumpAndSettle();
expect(find.text('dialog'), findsOneWidget);
// Pops the pageless route.
navigator.currentState!.pop();
// Before the pop finishes, updates the page list.
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name: 'initial'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
),
);
// It should not crash the app.
expect(tester.takeException(), isNull);
await tester.pumpAndSettle();
expect(find.text('initial'), findsOneWidget);
});
testWidgets('pages remove and add trigger observer in the right order', (WidgetTester tester) async {
final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>();
List<TestPage> myPages = <TestPage>[
const TestPage(key: ValueKey<String>('1'), name:'first'),
const TestPage(key: ValueKey<String>('2'), name:'second'),
const TestPage(key: ValueKey<String>('3'), name:'third'),
];
final List<NavigatorObservation> observations = <NavigatorObservation>[];
final TestObserver observer = TestObserver()
..onPushed = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observations.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'push',
),
);
}
..onRemoved = (Route<dynamic>? route, Route<dynamic>? previousRoute) {
observations.add(
NavigatorObservation(
current: route?.settings.name,
previous: previousRoute?.settings.name,
operation: 'remove',
),
);
};
bool onPopPage(Route<dynamic> route, dynamic result) => false;
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
observers: <NavigatorObserver>[observer],
),
);
myPages = <TestPage>[
const TestPage(key: ValueKey<String>('4'), name:'forth'),
const TestPage(key: ValueKey<String>('5'), name:'fifth'),
];
await tester.pumpWidget(
buildNavigator(
view: tester.view,
pages: myPages,
onPopPage: onPopPage,
key: navigator,
observers: <NavigatorObserver>[observer],
),
);
await tester.pumpAndSettle();
expect(observations.length, 8);
// Initial routes are pushed.
expect(observations[0].operation, 'push');
expect(observations[0].current, 'first');
expect(observations[0].previous, isNull);
expect(observations[1].operation, 'push');
expect(observations[1].current, 'second');
expect(observations[1].previous, 'first');
expect(observations[2].operation, 'push');
expect(observations[2].current, 'third');
expect(observations[2].previous, 'second');
// Pages are updated.
// New routes are pushed before removing the initial routes.
expect(observations[3].operation, 'push');
expect(observations[3].current, 'forth');
expect(observations[3].previous, 'third');
expect(observations[4].operation, 'push');
expect(observations[4].current, 'fifth');
expect(observations[4].previous, 'forth');
// Initial routes are removed.
expect(observations[5].operation, 'remove');
expect(observations[5].current, 'third');
expect(observations[5].previous, isNull);
expect(observations[6].operation, 'remove');
expect(observations[6].current, 'second');
expect(observations[6].previous, isNull);
expect(observations[7].operation, 'remove');
expect(observations[7].current, 'first');
expect(observations[7].previous, isNull);
});
});
testWidgets('Can reuse NavigatorObserver in rebuilt tree', (WidgetTester tester) async {
final NavigatorObserver observer = NavigatorObserver();
Widget build([Key? key]) {
return TestDependencies(
child: Navigator(
key: key,
observers: <NavigatorObserver>[observer],
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<void>(
settings: settings,
pageBuilder: (BuildContext _, Animation<double> __, Animation<double> ___) {
return Container();
},
);
},
),
);
}
// Test without reinsertion
await tester.pumpWidget(build());
await tester.pumpWidget(Container(child: build()));
expect(observer.navigator, tester.state<NavigatorState>(find.byType(Navigator)));
// Clear the tree
await tester.pumpWidget(Container());
expect(observer.navigator, isNull);
// Test with reinsertion
final GlobalKey key = GlobalKey();
await tester.pumpWidget(build(key));
await tester.pumpWidget(Container(child: build(key)));
expect(observer.navigator, tester.state<NavigatorState>(find.byType(Navigator)));
});
testWidgets('Navigator requests focus if requestFocus is true', (WidgetTester tester) async {
final GlobalKey navigatorKey = GlobalKey();
final GlobalKey innerKey = GlobalKey();
final Map<String, Widget> routes = <String, Widget>{
'/': const Text('A'),
'/second': Text('B', key: innerKey),
};
late final NavigatorState navigator = navigatorKey.currentState! as NavigatorState;
final FocusScopeNode focusNode = FocusScopeNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(Column(
children: <Widget>[
FocusScope(node: focusNode, child: Container()),
Expanded(
child: MaterialApp(
home: Navigator(
key: navigatorKey,
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<void>(
settings: settings,
pageBuilder: (BuildContext _, Animation<double> __,
Animation<double> ___) {
return routes[settings.name!]!;
},
);
},
),
),
),
],
));
expect(navigator.widget.requestFocus, true);
expect(find.text('A'), findsOneWidget);
expect(find.text('B', skipOffstage: false), findsNothing);
expect(focusNode.hasFocus, false);
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(focusNode.hasFocus, true);
navigator.pushNamed('/second');
await tester.pumpAndSettle();
expect(find.text('A', skipOffstage: false), findsOneWidget);
expect(find.text('B'), findsOneWidget);
expect(focusNode.hasFocus, false);
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(focusNode.hasFocus, true);
navigator.pop();
await tester.pumpAndSettle();
expect(find.text('A'), findsOneWidget);
expect(find.text('B', skipOffstage: false), findsNothing);
// Pop does not take focus.
expect(focusNode.hasFocus, true);
navigator.pushReplacementNamed('/second');
await tester.pumpAndSettle();
expect(find.text('A', skipOffstage: false), findsNothing);
expect(find.text('B'), findsOneWidget);
expect(focusNode.hasFocus, false);
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(focusNode.hasFocus, true);
ModalRoute.of(innerKey.currentContext!)!.addLocalHistoryEntry(
LocalHistoryEntry(),
);
await tester.pumpAndSettle();
// addLocalHistoryEntry does not take focus.
expect(focusNode.hasFocus, true);
});
testWidgets('Navigator does not request focus if requestFocus is false', (WidgetTester tester) async {
final GlobalKey navigatorKey = GlobalKey();
final GlobalKey innerKey = GlobalKey();
final Map<String, Widget> routes = <String, Widget>{
'/': const Text('A'),
'/second': Text('B', key: innerKey),
};
late final NavigatorState navigator =
navigatorKey.currentState! as NavigatorState;
final FocusScopeNode focusNode = FocusScopeNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(Column(
children: <Widget>[
FocusScope(node: focusNode, child: Container()),
Expanded(
child: MaterialApp(
home: Navigator(
key: navigatorKey,
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<void>(
settings: settings,
pageBuilder: (BuildContext _, Animation<double> __,
Animation<double> ___) {
return routes[settings.name!]!;
},
);
},
requestFocus: false,
),
),
),
],
));
expect(find.text('A'), findsOneWidget);
expect(find.text('B', skipOffstage: false), findsNothing);
expect(focusNode.hasFocus, false);
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(focusNode.hasFocus, true);
navigator.pushNamed('/second');
await tester.pumpAndSettle();
expect(find.text('A', skipOffstage: false), findsOneWidget);
expect(find.text('B'), findsOneWidget);
expect(focusNode.hasFocus, true);
navigator.pop();
await tester.pumpAndSettle();
expect(find.text('A'), findsOneWidget);
expect(find.text('B', skipOffstage: false), findsNothing);
expect(focusNode.hasFocus, true);
navigator.pushReplacementNamed('/second');
await tester.pumpAndSettle();
expect(find.text('A', skipOffstage: false), findsNothing);
expect(find.text('B'), findsOneWidget);
expect(focusNode.hasFocus, true);
ModalRoute.of(innerKey.currentContext!)!.addLocalHistoryEntry(
LocalHistoryEntry(),
);
await tester.pumpAndSettle();
expect(focusNode.hasFocus, true);
});
testWidgets('class implementing NavigatorObserver can be used without problems', (WidgetTester tester) async {
final _MockNavigatorObserver observer = _MockNavigatorObserver();
Widget build([Key? key]) {
return TestDependencies(
child: Navigator(
key: key,
observers: <NavigatorObserver>[observer],
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<void>(
settings: settings,
pageBuilder: (BuildContext _, Animation<double> __, Animation<double> ___) {
return Container();
},
);
},
),
);
}
await tester.pumpWidget(build());
observer._checkInvocations(<Symbol>[#navigator, #didPush]);
await tester.pumpWidget(Container(child: build()));
observer._checkInvocations(<Symbol>[#navigator, #didPush, #navigator]);
await tester.pumpWidget(Container());
observer._checkInvocations(<Symbol>[#navigator]);
final GlobalKey key = GlobalKey();
await tester.pumpWidget(build(key));
observer._checkInvocations(<Symbol>[#navigator, #didPush]);
await tester.pumpWidget(Container(child: build(key)));
observer._checkInvocations(<Symbol>[#navigator, #navigator]);
});
testWidgets("Navigator doesn't override FocusTraversalPolicy of ancestors", (WidgetTester tester) async {
FocusTraversalPolicy? policy;
await tester.pumpWidget(
TestDependencies(
child: FocusTraversalGroup(
policy: WidgetOrderTraversalPolicy(),
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<void>(
settings: settings,
pageBuilder: (BuildContext context, Animation<double> __, Animation<double> ___) {
policy = FocusTraversalGroup.of(context);
return const SizedBox();
},
);
},
),
),
),
);
expect(policy, isA<WidgetOrderTraversalPolicy>());
});
testWidgets('Navigator inserts ReadingOrderTraversalPolicy if no ancestor has a policy', (WidgetTester tester) async {
FocusTraversalPolicy? policy;
await tester.pumpWidget(
TestDependencies(
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<void>(
settings: settings,
pageBuilder: (BuildContext context, Animation<double> __, Animation<double> ___) {
policy = FocusTraversalGroup.of(context);
return const SizedBox();
},
);
},
),
),
);
expect(policy, isA<ReadingOrderTraversalPolicy>());
});
testWidgets(
'Send semantic event to move a11y focus to the last focused item when pop next page',
(WidgetTester tester) async {
dynamic semanticEvent;
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(
SystemChannels.accessibility, (dynamic message) async {
semanticEvent = message;
});
final Key openSheetKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(primarySwatch: Colors.blue),
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => _LinksPage(
title: 'Home page',
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one');
},
child: const Text('Go to one'),
),
],
),
'/one': (BuildContext context) => Scaffold(
body: Column(
children: <Widget>[
const ListTile(title: Text('Title 1')),
const ListTile(title: Text('Title 2')),
const ListTile(title: Text('Title 3')),
ElevatedButton(
key: openSheetKey,
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return Center(
child: ElevatedButton(
onPressed: () => Navigator.pop(context),
child: const Text('Close Sheet'),
),
);
},
);
},
child: const Text('Open Sheet'),
)
],
),
),
},
),
);
expect(find.text('Home page'), findsOneWidget);
await tester.tap(find.text('Go to one'));
await tester.pumpAndSettle();
// The focused node before opening the sheet.
final ByteData? fakeMessage =
SystemChannels.accessibility.codec.encodeMessage(<String, dynamic>{
'type': 'didGainFocus',
'nodeId': 5,
});
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
SystemChannels.accessibility.name,
fakeMessage,
(ByteData? data) {},
);
await tester.pumpAndSettle();
await tester.tap(find.text('Open Sheet'));
await tester.pumpAndSettle();
expect(find.text('Close Sheet'), findsOneWidget);
await tester.tap(find.text('Close Sheet'));
await tester.pumpAndSettle(const Duration(milliseconds: 500));
// The focused node before opening the sheet regains the focus;
expect(semanticEvent, <String, dynamic>{
'type': 'focus',
'nodeId': 5,
'data': <String, dynamic>{},
});
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, null);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS}),
skip: isBrowser, // [intended] only non-web supports move a11y focus back to last item.
);
group('RouteSettings.toString', () {
test('when name is not null, should have double quote', () {
expect(const RouteSettings(name: '/home').toString(), 'RouteSettings("/home", null)');
});
test('when name is null, should not have double quote', () {
expect(const RouteSettings().toString(), 'RouteSettings(none, null)');
});
});
group('Android Predictive Back', () {
bool? lastFrameworkHandlesBack;
setUp(() async {
lastFrameworkHandlesBack = null;
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
if (methodCall.method == 'SystemNavigator.setFrameworkHandlesBack') {
expect(methodCall.arguments, isA<bool>());
lastFrameworkHandlesBack = methodCall.arguments as bool;
}
return;
});
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.handlePlatformMessage(
'flutter/lifecycle',
const StringCodec().encodeMessage(AppLifecycleState.resumed.toString()),
(ByteData? data) {},
);
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(SystemChannels.platform, null);
});
testWidgets('a single route is already defaulted to false', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: Text('home'),
)
)
);
expect(lastFrameworkHandlesBack, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
testWidgets('navigating around a single Navigator with .pop', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => _LinksPage(
title: 'Home page',
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one');
},
child: const Text('Go to one'),
),
],
),
'/one': (BuildContext context) => _LinksPage(
title: 'Page one',
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one/one');
},
child: const Text('Go to one/one'),
),
],
),
'/one/one': (BuildContext context) => const _LinksPage(
title: 'Page one - one',
),
},
),
);
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to one'));
await tester.pumpAndSettle();
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await tester.tap(find.text('Go back'));
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to one'));
await tester.pumpAndSettle();
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await tester.tap(find.text('Go to one/one'));
await tester.pumpAndSettle();
expect(find.text('Page one - one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await tester.tap(find.text('Go back'));
await tester.pumpAndSettle();
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await tester.tap(find.text('Go back'));
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
testWidgets('navigating around a single Navigator with system back', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => _LinksPage(
title: 'Home page',
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one');
},
child: const Text('Go to one'),
),
],
),
'/one': (BuildContext context) => _LinksPage(
title: 'Page one',
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one/one');
},
child: const Text('Go to one/one'),
),
],
),
'/one/one': (BuildContext context) => const _LinksPage(
title: 'Page one - one',
),
},
),
);
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to one'));
await tester.pumpAndSettle();
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to one'));
await tester.pumpAndSettle();
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await tester.tap(find.text('Go to one/one'));
await tester.pumpAndSettle();
expect(find.text('Page one - one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
testWidgets('a single Navigator with a PopScope that defaults to enabled', (WidgetTester tester) async {
bool canPop = true;
late StateSetter setState;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setter) {
setState = setter;
return MaterialApp(
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => _LinksPage(
title: 'Home page',
canPop: canPop,
),
},
);
},
),
);
expect(lastFrameworkHandlesBack, isFalse);
setState(() {
canPop = false;
});
await tester.pump();
expect(lastFrameworkHandlesBack, isTrue);
setState(() {
canPop = true;
});
await tester.pump();
expect(lastFrameworkHandlesBack, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
testWidgets('a single Navigator with a PopScope that defaults to disabled', (WidgetTester tester) async {
bool canPop = false;
late StateSetter setState;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setter) {
setState = setter;
return MaterialApp(
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => _LinksPage(
title: 'Home page',
canPop: canPop,
),
},
);
},
),
);
expect(lastFrameworkHandlesBack, isTrue);
setState(() {
canPop = true;
});
await tester.pump();
expect(lastFrameworkHandlesBack, isFalse);
setState(() {
canPop = false;
});
await tester.pump();
expect(lastFrameworkHandlesBack, isTrue);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
// Test both system back gestures and Navigator.pop.
for (final _BackType backType in _BackType.values) {
testWidgets('navigating around nested Navigators', (WidgetTester tester) async {
final GlobalKey<NavigatorState> nav = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> nestedNav = GlobalKey<NavigatorState>();
Future<void> goBack() async {
switch (backType) {
case _BackType.systemBack:
return simulateSystemBack();
case _BackType.navigatorPop:
if (nestedNav.currentState != null) {
if (nestedNav.currentState!.mounted && nestedNav.currentState!.canPop()) {
return nestedNav.currentState?.pop();
}
}
return nav.currentState?.pop();
}
}
await tester.pumpWidget(
MaterialApp(
navigatorKey: nav,
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => _LinksPage(
title: 'Home page',
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one');
},
child: const Text('Go to one'),
),
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/nested');
},
child: const Text('Go to nested'),
),
],
),
'/one': (BuildContext context) => _LinksPage(
title: 'Page one',
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one/one');
},
child: const Text('Go to one/one'),
),
],
),
'/nested': (BuildContext context) => _NestedNavigatorsPage(
navigatorKey: nestedNav,
),
},
),
);
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to one'));
await tester.pumpAndSettle();
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await goBack();
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to nested'));
await tester.pumpAndSettle();
expect(find.text('Nested - home'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await tester.tap(find.text('Go to nested/one'));
await tester.pumpAndSettle();
expect(find.text('Nested - page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await goBack();
await tester.pumpAndSettle();
expect(find.text('Nested - home'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await goBack();
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
}
testWidgets('nested Navigators with a nested PopScope', (WidgetTester tester) async {
bool canPop = true;
late StateSetter setState;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setter) {
setState = setter;
return MaterialApp(
initialRoute: '/',
routes: <String, WidgetBuilder>{
'/': (BuildContext context) => _LinksPage(
title: 'Home page',
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one');
},
child: const Text('Go to one'),
),
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/nested');
},
child: const Text('Go to nested'),
),
],
),
'/one': (BuildContext context) => _LinksPage(
title: 'Page one',
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one/one');
},
child: const Text('Go to one/one'),
),
],
),
'/nested': (BuildContext context) => _NestedNavigatorsPage(
popScopePageEnabled: canPop,
),
},
);
},
),
);
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to one'));
await tester.pumpAndSettle();
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to nested'));
await tester.pumpAndSettle();
expect(find.text('Nested - home'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await tester.tap(find.text('Go to nested/popscope'));
await tester.pumpAndSettle();
expect(find.text('Nested - PopScope'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
// Going back works because canPop is true.
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Nested - home'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await tester.tap(find.text('Go to nested/popscope'));
await tester.pumpAndSettle();
expect(find.text('Nested - PopScope'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
setState(() {
canPop = false;
});
await tester.pumpAndSettle();
expect(lastFrameworkHandlesBack, isTrue);
// Now going back doesn't work because canPop is false, but it still
// has no effect on the system navigator due to all of the other routes.
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Nested - PopScope'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
setState(() {
canPop = true;
});
await tester.pump();
expect(lastFrameworkHandlesBack, isTrue);
// And going back works again after switching canPop back to true.
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Nested - home'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
group('Navigator page API', () {
testWidgets('starting with one route as usual', (WidgetTester tester) async {
late StateSetter builderSetState;
final List<_Page> pages = <_Page>[_Page.home];
bool canPop() => pages.length <= 1;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
builderSetState = setState;
return PopScope(
canPop: canPop(),
onPopInvoked: (bool success) {
if (success || pages.last == _Page.noPop) {
return;
}
setState(() {
pages.removeLast();
});
},
child: Navigator(
onPopPage: (Route<void> route, void result) {
if (!route.didPop(null)) {
return false;
}
setState(() {
pages.removeLast();
});
return true;
},
pages: pages.map((_Page page) {
switch (page) {
case _Page.home:
return MaterialPage<void>(
child: _LinksPage(
title: 'Home page',
buttons: <Widget>[
TextButton(
onPressed: () {
setState(() {
pages.add(_Page.one);
});
},
child: const Text('Go to _Page.one'),
),
TextButton(
onPressed: () {
setState(() {
pages.add(_Page.noPop);
});
},
child: const Text('Go to _Page.noPop'),
),
],
),
);
case _Page.one:
return const MaterialPage<void>(
child: _LinksPage(
title: 'Page one',
),
);
case _Page.noPop:
return const MaterialPage<void>(
child: _LinksPage(
title: 'Cannot pop page',
canPop: false,
),
);
}
}).toList(),
),
);
},
),
),
);
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to _Page.one'));
await tester.pumpAndSettle();
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
await tester.tap(find.text('Go to _Page.noPop'));
await tester.pumpAndSettle();
expect(find.text('Cannot pop page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Cannot pop page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
// Circumvent "Cannot pop page" by directly modifying pages.
builderSetState(() {
pages.removeLast();
});
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
testWidgets('starting with existing route history', (WidgetTester tester) async {
final List<_Page> pages = <_Page>[_Page.home, _Page.one];
bool canPop() => pages.length <= 1;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return PopScope(
canPop: canPop(),
onPopInvoked: (bool success) {
if (success || pages.last == _Page.noPop) {
return;
}
setState(() {
pages.removeLast();
});
},
child: Navigator(
onPopPage: (Route<void> route, void result) {
if (!route.didPop(null)) {
return false;
}
setState(() {
pages.removeLast();
});
return true;
},
pages: pages.map((_Page page) {
switch (page) {
case _Page.home:
return MaterialPage<void>(
child: _LinksPage(
title: 'Home page',
buttons: <Widget>[
TextButton(
onPressed: () {
setState(() {
pages.add(_Page.one);
});
},
child: const Text('Go to _Page.one'),
),
TextButton(
onPressed: () {
setState(() {
pages.add(_Page.noPop);
});
},
child: const Text('Go to _Page.noPop'),
),
],
),
);
case _Page.one:
return const MaterialPage<void>(
child: _LinksPage(
title: 'Page one',
),
);
case _Page.noPop:
return const MaterialPage<void>(
child: _LinksPage(
title: 'Cannot pop page',
canPop: false,
),
);
}
}).toList(),
),
);
},
),
),
);
expect(find.text('Home page'), findsNothing);
expect(find.text('Page one'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(find.text('Page one'), findsNothing);
expect(lastFrameworkHandlesBack, isFalse);
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
testWidgets('popping a page with canPop true still calls onPopInvoked', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/141189.
final List<_PageWithYesPop> pages = <_PageWithYesPop>[_PageWithYesPop.home];
bool canPop() => pages.length <= 1;
int onPopInvokedCallCount = 0;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return PopScope(
canPop: canPop(),
onPopInvoked: (bool success) {
if (success || pages.last == _PageWithYesPop.noPop) {
return;
}
setState(() {
pages.removeLast();
});
},
child: Navigator(
onPopPage: (Route<void> route, void result) {
if (!route.didPop(null)) {
return false;
}
setState(() {
pages.removeLast();
});
return true;
},
pages: pages.map((_PageWithYesPop page) {
switch (page) {
case _PageWithYesPop.home:
return MaterialPage<void>(
child: _LinksPage(
title: 'Home page',
buttons: <Widget>[
TextButton(
onPressed: () {
setState(() {
pages.add(_PageWithYesPop.one);
});
},
child: const Text('Go to _PageWithYesPop.one'),
),
TextButton(
onPressed: () {
setState(() {
pages.add(_PageWithYesPop.noPop);
});
},
child: const Text('Go to _PageWithYesPop.noPop'),
),
TextButton(
onPressed: () {
setState(() {
pages.add(_PageWithYesPop.yesPop);
});
},
child: const Text('Go to _PageWithYesPop.yesPop'),
),
],
),
);
case _PageWithYesPop.one:
return const MaterialPage<void>(
child: _LinksPage(
title: 'Page one',
),
);
case _PageWithYesPop.noPop:
return const MaterialPage<void>(
child: _LinksPage(
title: 'Cannot pop page',
canPop: false,
),
);
case _PageWithYesPop.yesPop:
return MaterialPage<void>(
child: _LinksPage(
title: 'Can pop page',
canPop: true,
onPopInvoked: (bool didPop) {
onPopInvokedCallCount += 1;
},
),
);
}
}).toList(),
),
);
},
),
),
);
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
expect(onPopInvokedCallCount, equals(0));
await tester.tap(find.text('Go to _PageWithYesPop.yesPop'));
await tester.pumpAndSettle();
expect(find.text('Can pop page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
expect(onPopInvokedCallCount, equals(0));
// A system back calls onPopInvoked.
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
expect(onPopInvokedCallCount, equals(1));
await tester.tap(find.text('Go to _PageWithYesPop.yesPop'));
await tester.pumpAndSettle();
expect(find.text('Can pop page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isTrue);
expect(onPopInvokedCallCount, equals(1));
// Tapping a back button also calls onPopInvoked.
await tester.tap(find.text('Go back'));
await tester.pumpAndSettle();
expect(find.text('Home page'), findsOneWidget);
expect(lastFrameworkHandlesBack, isFalse);
expect(onPopInvokedCallCount, equals(2));
},
variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android }),
skip: isBrowser, // [intended] only non-web Android supports predictive back.
);
});
});
}
typedef AnnouncementCallBack = void Function(Route<dynamic>?);
class NotAnnounced extends Route<void> { /* A place holder for not announced route*/ }
class RouteAnnouncementSpy extends Route<void> {
RouteAnnouncementSpy({
this.onDidChangePrevious,
this.onDidChangeNext,
this.onDidPopNext,
super.settings,
});
final AnnouncementCallBack? onDidChangePrevious;
final AnnouncementCallBack? onDidChangeNext;
final AnnouncementCallBack? onDidPopNext;
@override
final List<OverlayEntry> overlayEntries = <OverlayEntry>[
OverlayEntry(
builder: (BuildContext context) => const Placeholder(),
),
];
@override
void didChangeNext(Route<dynamic>? nextRoute) {
super.didChangeNext(nextRoute);
onDidChangeNext?.call(nextRoute);
}
@override
void didChangePrevious(Route<dynamic>? previousRoute) {
super.didChangePrevious(previousRoute);
onDidChangePrevious?.call(previousRoute);
}
@override
void didPopNext(Route<dynamic> nextRoute) {
super.didPopNext(nextRoute);
onDidPopNext?.call(nextRoute);
}
}
class _TickingWidget extends StatefulWidget {
const _TickingWidget({required this.onTick});
final VoidCallback onTick;
@override
State<_TickingWidget> createState() => _TickingWidgetState();
}
class _TickingWidgetState extends State<_TickingWidget> with SingleTickerProviderStateMixin {
late Ticker _ticker;
@override
void initState() {
super.initState();
_ticker = createTicker((Duration _) {
widget.onTick();
})..start();
}
@override
Widget build(BuildContext context) {
return Container();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
}
class AlwaysRemoveTransitionDelegate extends TransitionDelegate<void> {
@override
Iterable<RouteTransitionRecord> resolve({
required List<RouteTransitionRecord> newPageRouteHistory,
required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
}) {
final List<RouteTransitionRecord> results = <RouteTransitionRecord>[];
void handleExitingRoute(RouteTransitionRecord? location) {
if (!locationToExitingPageRoute.containsKey(location)) {
return;
}
final RouteTransitionRecord exitingPageRoute = locationToExitingPageRoute[location]!;
if (exitingPageRoute.isWaitingForExitingDecision) {
final bool hasPagelessRoute = pageRouteToPagelessRoutes.containsKey(exitingPageRoute);
exitingPageRoute.markForRemove();
if (hasPagelessRoute) {
final List<RouteTransitionRecord> pagelessRoutes = pageRouteToPagelessRoutes[exitingPageRoute]!;
for (final RouteTransitionRecord pagelessRoute in pagelessRoutes) {
pagelessRoute.markForRemove();
}
}
}
results.add(exitingPageRoute);
handleExitingRoute(exitingPageRoute);
}
handleExitingRoute(null);
for (final RouteTransitionRecord pageRoute in newPageRouteHistory) {
if (pageRoute.isWaitingForEnteringDecision) {
pageRoute.markForAdd();
}
results.add(pageRoute);
handleExitingRoute(pageRoute);
}
return results;
}
}
class ZeroTransitionPage extends Page<void> {
const ZeroTransitionPage({
super.key,
super.arguments,
required String super.name,
});
@override
Route<void> createRoute(BuildContext context) {
return NoAnimationPageRoute(
settings: this,
pageBuilder: (BuildContext context) => Text(name!),
);
}
}
class TestPage extends Page<void> {
const TestPage({
super.key,
required String super.name,
super.arguments,
});
@override
Route<void> createRoute(BuildContext context) {
return MaterialPageRoute<void>(
builder: (BuildContext context) => Text(name!),
settings: this,
);
}
}
class NoAnimationPageRoute extends PageRouteBuilder<void> {
NoAnimationPageRoute({
super.settings,
required WidgetBuilder pageBuilder
}) : super(
transitionDuration: Duration.zero,
reverseTransitionDuration: Duration.zero,
pageBuilder: (BuildContext context, __, ___) {
return pageBuilder(context);
}
);
}
class StatefulTestWidget extends StatefulWidget {
const StatefulTestWidget({super.key});
@override
State<StatefulTestWidget> createState() => StatefulTestState();
}
class StatefulTestState extends State<StatefulTestWidget> {
int rebuildCount = 0;
@override
Widget build(BuildContext context) {
rebuildCount += 1;
return Container();
}
}
class HeroControllerSpy extends HeroController {
OnObservation? onPushed;
@override
void didPush(Route<dynamic>? route, Route<dynamic>? previousRoute) {
onPushed?.call(route, previousRoute);
}
}
class NavigatorObservation {
const NavigatorObservation({this.previous, this.current, required this.operation});
final String? previous;
final String? current;
final String operation;
@override
String toString() => 'NavigatorObservation($operation, $current, $previous)';
}
class BuilderPage extends Page<void> {
const BuilderPage({super.key, super.name, required this.pageBuilder});
final RoutePageBuilder pageBuilder;
@override
Route<void> createRoute(BuildContext context) {
return PageRouteBuilder<void>(
settings: this,
pageBuilder: pageBuilder,
);
}
}
class ZeroDurationPage extends Page<void> {
const ZeroDurationPage({required this.child});
final Widget child;
@override
Route<void> createRoute(BuildContext context) {
return ZeroDurationPageRoute(page: this);
}
}
class ZeroDurationPageRoute extends PageRoute<void> {
ZeroDurationPageRoute({required ZeroDurationPage page})
: super(settings: page, allowSnapshotting: false);
@override
Duration get transitionDuration => Duration.zero;
ZeroDurationPage get _page => settings as ZeroDurationPage;
@override
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
return _page.child;
}
@override
Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
return child;
}
@override
bool get maintainState => false;
@override
Color? get barrierColor => null;
@override
String? get barrierLabel => null;
}
class _MockNavigatorObserver implements NavigatorObserver {
final List<Symbol> _invocations = <Symbol>[];
void _checkInvocations(List<Symbol> expected) {
expect(_invocations, expected);
_invocations.clear();
}
@override
Object? noSuchMethod(Invocation invocation) {
_invocations.add(invocation.memberName);
return null;
}
}
class TestDependencies extends StatelessWidget {
const TestDependencies({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return MediaQuery(
data: MediaQueryData.fromView(View.of(context)),
child: Directionality(
textDirection: TextDirection.ltr,
child: child,
)
);
}
}
enum _BackType {
systemBack,
navigatorPop,
}
enum _Page {
home,
one,
noPop,
}
enum _PageWithYesPop {
home,
one,
noPop,
yesPop,
}
class _LinksPage extends StatelessWidget {
const _LinksPage ({
this.buttons = const <Widget>[],
this.canPop,
required this.title,
this.onBack,
this.onPopInvoked,
});
final List<Widget> buttons;
final bool? canPop;
final VoidCallback? onBack;
final String title;
final PopInvokedCallback? onPopInvoked;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(title),
...buttons,
if (Navigator.of(context).canPop())
TextButton(
onPressed: onBack ?? () {
Navigator.of(context).pop();
},
child: const Text('Go back'),
),
if (canPop != null)
PopScope(
canPop: canPop!,
onPopInvoked: onPopInvoked,
child: const SizedBox.shrink(),
),
],
),
),
);
}
}
class _NestedNavigatorsPage extends StatefulWidget {
const _NestedNavigatorsPage({
this.popScopePageEnabled,
this.navigatorKey,
});
/// Whether the PopScope on the /popscope page is enabled.
///
/// If null, then no PopScope is built at all.
final bool? popScopePageEnabled;
final GlobalKey<NavigatorState>? navigatorKey;
@override
State<_NestedNavigatorsPage> createState() => _NestedNavigatorsPageState();
}
class _NestedNavigatorsPageState extends State<_NestedNavigatorsPage> {
late final GlobalKey<NavigatorState> _navigatorKey;
@override
void initState() {
super.initState();
_navigatorKey = widget.navigatorKey ?? GlobalKey<NavigatorState>();
}
@override
Widget build(BuildContext context) {
final BuildContext rootContext = context;
return NavigatorPopHandler(
onPop: () {
if (widget.popScopePageEnabled == false) {
return;
}
_navigatorKey.currentState!.pop();
},
child: Navigator(
key: _navigatorKey,
initialRoute: '/',
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute<void>(
builder: (BuildContext context) {
return _LinksPage(
title: 'Nested - home',
onBack: () {
Navigator.of(rootContext).pop();
},
buttons: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/one');
},
child: const Text('Go to nested/one'),
),
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/popscope');
},
child: const Text('Go to nested/popscope'),
),
TextButton(
onPressed: () {
Navigator.of(rootContext).pop();
},
child: const Text('Go back out of nested nav'),
),
],
);
},
);
case '/one':
return MaterialPageRoute<void>(
builder: (BuildContext context) {
return const _LinksPage(
title: 'Nested - page one',
);
},
);
case '/popscope':
return MaterialPageRoute<void>(
builder: (BuildContext context) {
return _LinksPage(
canPop: widget.popScopePageEnabled,
title: 'Nested - PopScope',
);
},
);
default:
throw Exception('Invalid route: ${settings.name}');
}
},
),
);
}
}
| flutter/packages/flutter/test/widgets/navigator_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/navigator_test.dart",
"repo_id": "flutter",
"token_count": 88050
} | 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/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('PageStorage read and write', (WidgetTester tester) async {
const Key builderKey = PageStorageKey<String>('builderKey');
late StateSetter setState;
int storedValue = 0;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
key: builderKey,
builder: (BuildContext context, StateSetter setter) {
PageStorage.of(context).writeState(context, storedValue);
setState = setter;
return Center(
child: Text('storedValue: $storedValue'),
);
},
),
),
);
final Element builderElement = tester.element(find.byKey(builderKey));
expect(PageStorage.of(builderElement), isNotNull);
expect(PageStorage.of(builderElement).readState(builderElement), equals(storedValue));
setState(() {
storedValue = 1;
});
await tester.pump();
expect(PageStorage.of(builderElement).readState(builderElement), equals(storedValue));
});
testWidgets('PageStorage read and write by identifier', (WidgetTester tester) async {
late StateSetter setState;
int storedValue = 0;
Widget buildWidthKey(Key key) {
return MaterialApp(
home: StatefulBuilder(
key: key,
builder: (BuildContext context, StateSetter setter) {
PageStorage.of(context).writeState(context, storedValue, identifier: 123);
setState = setter;
return Center(
child: Text('storedValue: $storedValue'),
);
},
),
);
}
Key key = const Key('Key one');
await tester.pumpWidget(buildWidthKey(key));
Element builderElement = tester.element(find.byKey(key));
expect(PageStorage.of(builderElement), isNotNull);
expect(PageStorage.of(builderElement).readState(builderElement), isNull);
expect(PageStorage.of(builderElement).readState(builderElement, identifier: 123), equals(storedValue));
// New StatefulBuilder widget - different key - but the same PageStorage identifier.
key = const Key('Key two');
await tester.pumpWidget(buildWidthKey(key));
builderElement = tester.element(find.byKey(key));
expect(PageStorage.of(builderElement), isNotNull);
expect(PageStorage.of(builderElement).readState(builderElement), isNull);
expect(PageStorage.of(builderElement).readState(builderElement, identifier: 123), equals(storedValue));
setState(() {
storedValue = 1;
});
await tester.pump();
expect(PageStorage.of(builderElement).readState(builderElement, identifier: 123), equals(storedValue));
});
}
| flutter/packages/flutter/test/widgets/page_storage_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/page_storage_test.dart",
"repo_id": "flutter",
"token_count": 1070
} | 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/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
@immutable
class Pair<T> {
const Pair(this.first, this.second);
final T? first;
final T second;
@override
bool operator ==(Object other) {
return other is Pair<T> && other.first == first && other.second == second;
}
@override
int get hashCode => Object.hash(first, second);
@override
String toString() => '($first,$second)';
}
/// Widget that will layout one child in the top half of this widget's size
/// and the other child in the bottom half. It will swap which child is on top
/// and which is on bottom every time the widget is rendered.
abstract class Swapper extends RenderObjectWidget {
const Swapper({ super.key, this.stable, this.swapper });
final Widget? stable;
final Widget? swapper;
@override
SwapperElement createElement();
@override
RenderObject createRenderObject(BuildContext context) => RenderSwapper();
}
class SwapperWithProperOverrides extends Swapper {
const SwapperWithProperOverrides({
super.key,
super.stable,
super.swapper,
});
@override
SwapperElement createElement() => SwapperElementWithProperOverrides(this);
}
abstract class SwapperElement extends RenderObjectElement {
SwapperElement(Swapper super.widget);
Element? stable;
Element? swapper;
bool swapperIsOnTop = true;
List<dynamic> insertSlots = <dynamic>[];
List<Pair<dynamic>> moveSlots = <Pair<dynamic>>[];
List<dynamic> removeSlots = <dynamic>[];
@override
Swapper get widget => super.widget as Swapper;
@override
RenderSwapper get renderObject => super.renderObject as RenderSwapper;
@override
void visitChildren(ElementVisitor visitor) {
if (stable != null) {
visitor(stable!);
}
if (swapper != null) {
visitor(swapper!);
}
}
@override
void update(Swapper newWidget) {
super.update(newWidget);
_updateChildren(newWidget);
}
@override
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
_updateChildren(widget);
}
void _updateChildren(Swapper widget) {
stable = updateChild(stable, widget.stable, 'stable');
swapper = updateChild(swapper, widget.swapper, swapperIsOnTop);
swapperIsOnTop = !swapperIsOnTop;
}
@override
void insertRenderObjectChild(covariant RenderObject child, covariant Object? slot) { }
@override
void moveRenderObjectChild(covariant RenderObject child, covariant Object? oldSlot, covariant Object? newSlot) { }
@override
void removeRenderObjectChild(covariant RenderObject child, covariant Object? slot) { }
}
class SwapperElementWithProperOverrides extends SwapperElement {
SwapperElementWithProperOverrides(super.widget);
@override
void insertRenderObjectChild(RenderBox child, Object? slot) {
insertSlots.add(slot);
if (slot == 'stable') {
renderObject.stable = child;
} else {
renderObject.setSwapper(child, slot! as bool);
}
}
@override
void moveRenderObjectChild(RenderBox child, bool oldIsOnTop, bool newIsOnTop) {
moveSlots.add(Pair<bool>(oldIsOnTop, newIsOnTop));
assert(oldIsOnTop == !newIsOnTop);
renderObject.setSwapper(child, newIsOnTop);
}
@override
void removeRenderObjectChild(RenderBox child, Object? slot) {
removeSlots.add(slot);
if (slot == 'stable') {
renderObject.stable = null;
} else {
renderObject.setSwapper(null, slot! as bool);
}
}
}
class RenderSwapper extends RenderBox {
RenderBox? get stable => _stable;
RenderBox? _stable;
set stable(RenderBox? child) {
if (child == _stable) {
return;
}
if (_stable != null) {
dropChild(_stable!);
}
_stable = child;
if (child != null) {
adoptChild(child);
}
}
bool? _swapperIsOnTop;
RenderBox? get swapper => _swapper;
RenderBox? _swapper;
void setSwapper(RenderBox? child, bool isOnTop) {
if (isOnTop != _swapperIsOnTop) {
_swapperIsOnTop = isOnTop;
markNeedsLayout();
}
if (child == _swapper) {
return;
}
if (_swapper != null) {
dropChild(_swapper!);
}
_swapper = child;
if (child != null) {
adoptChild(child);
}
}
@override
void visitChildren(RenderObjectVisitor visitor) {
if (stable != null) {
visitor(stable!);
}
if (swapper != null) {
visitor(swapper!);
}
}
@override
void attach(PipelineOwner owner) {
super.attach(owner);
visitChildren((RenderObject child) => child.attach(owner));
}
@override
void detach() {
super.detach();
visitChildren((RenderObject child) => child.detach());
}
@override
Size computeDryLayout(BoxConstraints constraints) {
return constraints.biggest;
}
@override
void performLayout() {
assert(constraints.hasBoundedWidth);
assert(constraints.hasTightHeight);
size = constraints.biggest;
const Offset topOffset = Offset.zero;
final Offset bottomOffset = Offset(0, size.height / 2);
final BoxConstraints childConstraints = constraints.copyWith(
minHeight: constraints.minHeight / 2,
maxHeight: constraints.maxHeight / 2,
);
if (stable != null) {
final BoxParentData stableParentData = stable!.parentData! as BoxParentData;
stable!.layout(childConstraints);
stableParentData.offset = _swapperIsOnTop! ? bottomOffset : topOffset;
}
if (swapper != null) {
final BoxParentData swapperParentData = swapper!.parentData! as BoxParentData;
swapper!.layout(childConstraints);
swapperParentData.offset = _swapperIsOnTop! ? topOffset : bottomOffset;
}
}
@override
void paint(PaintingContext context, Offset offset) {
visitChildren((RenderObject child) {
final BoxParentData childParentData = child.parentData! as BoxParentData;
context.paintChild(child, offset + childParentData.offset);
});
}
@override
void redepthChildren() {
visitChildren((RenderObject child) => redepthChild(child));
}
}
BoxParentData parentDataFor(RenderObject renderObject) => renderObject.parentData! as BoxParentData;
void main() {
testWidgets('RenderObjectElement *RenderObjectChild methods get called with correct arguments', (WidgetTester tester) async {
const Key redKey = ValueKey<String>('red');
const Key blueKey = ValueKey<String>('blue');
Widget widget() {
return SwapperWithProperOverrides(
stable: ColoredBox(
key: redKey,
color: Color(nonconst(0xffff0000)),
),
swapper: ColoredBox(
key: blueKey,
color: Color(nonconst(0xff0000ff)),
),
);
}
await tester.pumpWidget(widget());
final SwapperElement swapper = tester.element<SwapperElement>(find.byType(SwapperWithProperOverrides));
final RenderBox redBox = tester.renderObject<RenderBox>(find.byKey(redKey));
final RenderBox blueBox = tester.renderObject<RenderBox>(find.byKey(blueKey));
expect(swapper.insertSlots.length, 2);
expect(swapper.insertSlots, contains('stable'));
expect(swapper.insertSlots, contains(true));
expect(swapper.moveSlots, isEmpty);
expect(swapper.removeSlots, isEmpty);
expect(parentDataFor(redBox).offset, const Offset(0, 300));
expect(parentDataFor(blueBox).offset, Offset.zero);
await tester.pumpWidget(widget());
expect(swapper.insertSlots.length, 2);
expect(swapper.moveSlots.length, 1);
expect(swapper.moveSlots, contains(const Pair<bool>(true, false)));
expect(swapper.removeSlots, isEmpty);
expect(parentDataFor(redBox).offset, Offset.zero);
expect(parentDataFor(blueBox).offset, const Offset(0, 300));
await tester.pumpWidget(const SwapperWithProperOverrides());
expect(redBox.attached, false);
expect(blueBox.attached, false);
expect(swapper.insertSlots.length, 2);
expect(swapper.moveSlots.length, 1);
expect(swapper.removeSlots.length, 2);
expect(swapper.removeSlots, contains('stable'));
expect(swapper.removeSlots, contains(false));
});
}
| flutter/packages/flutter/test/widgets/render_object_element_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/render_object_element_test.dart",
"repo_id": "flutter",
"token_count": 2948
} | 697 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
void main() {
testWidgets('Simple router basic functionality - synchronized', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
return Text(Uri.decodeComponent(information!.uri.toString()));
},
);
addTearDown(delegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
),
));
expect(find.text('initial'), findsOneWidget);
provider.value = RouteInformation(
uri: Uri.parse('update'),
);
await tester.pump();
expect(find.text('initial'), findsNothing);
expect(find.text('update'), findsOneWidget);
});
testWidgets('Simple router basic functionality - asynchronized', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final SimpleAsyncRouteInformationParser parser = SimpleAsyncRouteInformationParser();
final SimpleAsyncRouterDelegate delegate = SimpleAsyncRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
return Text(information?.uri.toString() ?? 'waiting');
},
);
addTearDown(delegate.dispose);
await tester.runAsync(() async {
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: parser,
routerDelegate: delegate,
),
));
// Future has not yet completed.
expect(find.text('waiting'), findsOneWidget);
await parser.parsingFuture;
await delegate.setNewRouteFuture;
await tester.pump();
expect(find.text('initial'), findsOneWidget);
provider.value = RouteInformation(
uri: Uri.parse('update'),
);
await tester.pump();
// Future has not yet completed.
expect(find.text('initial'), findsOneWidget);
await parser.parsingFuture;
await delegate.setNewRouteFuture;
await tester.pump();
expect(find.text('update'), findsOneWidget);
});
});
testWidgets('Interrupts route parsing should not crash', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final CompleterRouteInformationParser parser = CompleterRouteInformationParser();
final SimpleAsyncRouterDelegate delegate = SimpleAsyncRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
return Text(information?.uri.toString() ?? 'waiting');
},
);
addTearDown(delegate.dispose);
await tester.runAsync(() async {
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: parser,
routerDelegate: delegate,
),
));
// Future has not yet completed.
expect(find.text('waiting'), findsOneWidget);
final Completer<void> firstTransactionCompleter = parser.completer;
// Start a new parsing transaction before the previous one complete.
provider.value = RouteInformation(
uri: Uri.parse('update'),
);
await tester.pump();
expect(find.text('waiting'), findsOneWidget);
// Completing the previous transaction does not cause an update.
firstTransactionCompleter.complete();
await firstTransactionCompleter.future;
await tester.pump();
expect(find.text('waiting'), findsOneWidget);
expect(tester.takeException(), isNull);
// Make sure the new transaction can complete and update correctly.
parser.completer.complete();
await parser.completer.future;
await delegate.setNewRouteFuture;
await tester.pump();
expect(find.text('update'), findsOneWidget);
});
});
testWidgets('Router.maybeOf can be null', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(buildBoilerPlate(
Text('dummy', key: key),
));
final BuildContext textContext = key.currentContext!;
// This should not throw error.
final Router<dynamic>? router = Router.maybeOf(textContext);
expect(router, isNull);
expect(
() => Router.of(textContext),
throwsA(isFlutterError.having((FlutterError e) => e.message, 'message', startsWith('Router')))
);
});
testWidgets('Simple router can handle pop route', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher dispatcher = RootBackButtonDispatcher();
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
return Text(Uri.decodeComponent(information!.uri.toString()));
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(delegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
backButtonDispatcher: dispatcher,
),
));
expect(find.text('initial'), findsOneWidget);
bool result = false;
// SynchronousFuture should complete immediately.
dispatcher.invokeCallback(SynchronousFuture<bool>(false))
.then((bool data) {
result = data;
});
expect(result, isTrue);
await tester.pump();
expect(find.text('popped'), findsOneWidget);
});
testWidgets('Router throw when passing routeInformationProvider without routeInformationParser', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
return Text(Uri.decodeComponent(information!.uri.toString()));
},
);
addTearDown(delegate.dispose);
expect(
() {
Router<RouteInformation>(
routeInformationProvider: provider,
routerDelegate: delegate,
);
},
throwsA(isAssertionError.having(
(AssertionError e) => e.message,
'message',
'A routeInformationParser must be provided when a routeInformationProvider is specified.',
)),
);
});
testWidgets('PopNavigatorRouterDelegateMixin works', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher dispatcher = RootBackButtonDispatcher();
final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
return Text(Uri.decodeComponent(information!.uri.toString()));
},
onPopPage: (Route<void> route, void result) {
provider.value = RouteInformation(
uri: Uri.parse('popped'),
);
return route.didPop(result);
},
);
addTearDown(delegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
backButtonDispatcher: dispatcher,
),
));
expect(find.text('initial'), findsOneWidget);
// Pushes a nameless route.
showDialog<void>(
useRootNavigator: false,
context: delegate.navigatorKey.currentContext!,
builder: (BuildContext context) => const Text('dialog'),
);
await tester.pumpAndSettle();
expect(find.text('dialog'), findsOneWidget);
// Pops the nameless route and makes sure the initial page is shown.
bool result = false;
result = await dispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pumpAndSettle();
expect(find.text('initial'), findsOneWidget);
expect(find.text('dialog'), findsNothing);
// Pops one more time.
result = false;
result = await dispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pumpAndSettle();
expect(find.text('popped'), findsOneWidget);
});
testWidgets('Nested routers back button dispatcher works', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
final SimpleRouterDelegate outerDelegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
final BackButtonDispatcher innerDispatcher = ChildBackButtonDispatcher(outerDispatcher);
innerDispatcher.takePriority();
final SimpleRouterDelegate innerDelegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? innerInformation) {
return Text(Uri.decodeComponent(information!.uri.toString()));
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped inner'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(innerDelegate.dispose);
// Creates the sub-router.
return Router<RouteInformation>(
backButtonDispatcher: innerDispatcher,
routerDelegate: innerDelegate,
);
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(outerDelegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: outerDelegate,
),
));
expect(find.text('initial'), findsOneWidget);
// The outer dispatcher should trigger the pop on the inner router.
bool result = false;
result = await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pump();
expect(find.text('popped inner'), findsOneWidget);
});
testWidgets('Nested router back button dispatcher works for multiple children', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
final BackButtonDispatcher innerDispatcher1 = ChildBackButtonDispatcher(outerDispatcher);
final BackButtonDispatcher innerDispatcher2 = ChildBackButtonDispatcher(outerDispatcher);
final SimpleRouterDelegate outerDelegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
late final SimpleRouterDelegate innerDelegate1;
addTearDown(() => innerDelegate1.dispose());
late final SimpleRouterDelegate innerDelegate2;
addTearDown(() => innerDelegate2.dispose());
// Creates the sub-router.
return Column(
children: <Widget>[
Text(Uri.decodeComponent(information!.uri.toString())),
Router<RouteInformation>(
backButtonDispatcher: innerDispatcher1,
routerDelegate: innerDelegate1 = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? innerInformation) {
return Container();
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped inner1'),
);
return SynchronousFuture<bool>(true);
},
),
),
Router<RouteInformation>(
backButtonDispatcher: innerDispatcher2,
routerDelegate: innerDelegate2 = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? innerInformation) {
return Container();
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped inner2'),
);
return SynchronousFuture<bool>(true);
},
),
),
],
);
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(outerDelegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: outerDelegate,
),
));
expect(find.text('initial'), findsOneWidget);
// If none of the children have taken the priority, the root router handles
// the pop.
bool result = false;
result = await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pump();
expect(find.text('popped outer'), findsOneWidget);
innerDispatcher1.takePriority();
result = false;
result = await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pump();
expect(find.text('popped inner1'), findsOneWidget);
// The last child dispatcher that took priority handles the pop.
innerDispatcher2.takePriority();
result = false;
result = await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pump();
expect(find.text('popped inner2'), findsOneWidget);
});
testWidgets('ChildBackButtonDispatcher can be replaced without calling the takePriority', (WidgetTester tester) async {
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
BackButtonDispatcher innerDispatcher = ChildBackButtonDispatcher(outerDispatcher);
final SimpleRouterDelegate outerDelegate1 = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
final SimpleRouterDelegate innerDelegate1 = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? innerInformation) {
return Container();
},
);
addTearDown(innerDelegate1.dispose);
// Creates the sub-router.
return Column(
children: <Widget>[
const Text('initial'),
Router<RouteInformation>(
backButtonDispatcher: innerDispatcher,
routerDelegate: innerDelegate1,
),
],
);
},
);
addTearDown(outerDelegate1.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routerDelegate: outerDelegate1,
),
));
// Creates a new child back button dispatcher and rebuild, this will cause
// the old one to be replaced and discarded.
innerDispatcher = ChildBackButtonDispatcher(outerDispatcher);
final SimpleRouterDelegate outerDelegate2 = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
final SimpleRouterDelegate innerDelegate2 = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? innerInformation) {
return Container();
},
);
addTearDown(innerDelegate2.dispose);
// Creates the sub-router.
return Column(
children: <Widget>[
const Text('initial'),
Router<RouteInformation>(
backButtonDispatcher: innerDispatcher,
routerDelegate: innerDelegate2,
),
],
);
},
);
addTearDown(outerDelegate2.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routerDelegate: outerDelegate2,
),
));
expect(tester.takeException(), isNull);
});
testWidgets('ChildBackButtonDispatcher take priority recursively', (WidgetTester tester) async {
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
final BackButtonDispatcher innerDispatcher1 = ChildBackButtonDispatcher(outerDispatcher);
final BackButtonDispatcher innerDispatcher2 = ChildBackButtonDispatcher(innerDispatcher1);
final BackButtonDispatcher innerDispatcher3 = ChildBackButtonDispatcher(innerDispatcher2);
late final SimpleRouterDelegate outerDelegate;
addTearDown(() => outerDelegate.dispose());
late final SimpleRouterDelegate innerDelegate1;
addTearDown(() => innerDelegate1.dispose());
late final SimpleRouterDelegate innerDelegate2;
addTearDown(() => innerDelegate2.dispose());
late final SimpleRouterDelegate innerDelegate3;
addTearDown(() => innerDelegate3.dispose());
bool isPopped = false;
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routerDelegate: outerDelegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
// Creates the sub-router.
return Router<RouteInformation>(
backButtonDispatcher: innerDispatcher1,
routerDelegate: innerDelegate1 = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? innerInformation) {
return Router<RouteInformation>(
backButtonDispatcher: innerDispatcher2,
routerDelegate: innerDelegate2 = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? innerInformation) {
return Router<RouteInformation>(
backButtonDispatcher: innerDispatcher3,
routerDelegate: innerDelegate3 = SimpleRouterDelegate(
onPopRoute: () {
isPopped = true;
return SynchronousFuture<bool>(true);
},
builder: (BuildContext context, RouteInformation? innerInformation) {
return Container();
},
),
);
},
),
);
},
),
);
},
),
),
));
// This should work without calling the takePriority on the innerDispatcher2
// and the innerDispatcher1.
innerDispatcher3.takePriority();
bool result = false;
result = await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
expect(isPopped, isTrue);
});
testWidgets('router does report URL change correctly', (WidgetTester tester) async {
RouteInformation? reportedRouteInformation;
RouteInformationReportingType? reportedType;
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(
onRouterReport: (RouteInformation information, RouteInformationReportingType type) {
// Makes sure we only report once after manually cleaning up.
expect(reportedRouteInformation, isNull);
expect(reportedType, isNull);
reportedRouteInformation = information;
reportedType = type;
},
);
addTearDown(provider.dispose);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
reportConfiguration: true,
builder: (BuildContext context, RouteInformation? information) {
return Text(Uri.decodeComponent(information!.uri.toString()));
},
);
delegate.onPopRoute = () {
delegate.routeInformation = RouteInformation(
uri: Uri.parse('popped'),
);
return SynchronousFuture<bool>(true);
};
addTearDown(delegate.dispose);
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
),
));
expect(find.text('initial'), findsOneWidget);
expect(reportedRouteInformation!.uri.toString(), 'initial');
expect(reportedType, RouteInformationReportingType.none);
reportedRouteInformation = null;
reportedType = null;
delegate.routeInformation = RouteInformation(
uri: Uri.parse('update'),
);
await tester.pump();
expect(find.text('initial'), findsNothing);
expect(find.text('update'), findsOneWidget);
expect(reportedRouteInformation!.uri.toString(), 'update');
expect(reportedType, RouteInformationReportingType.none);
// The router should report as non navigation event if only state changes.
reportedRouteInformation = null;
reportedType = null;
delegate.routeInformation = RouteInformation(
uri: Uri.parse('update'),
state: 'another state',
);
await tester.pump();
expect(find.text('update'), findsOneWidget);
expect(reportedRouteInformation!.uri.toString(), 'update');
expect(reportedRouteInformation!.state, 'another state');
expect(reportedType, RouteInformationReportingType.none);
reportedRouteInformation = null;
reportedType = null;
bool result = false;
result = await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pump();
expect(find.text('popped'), findsOneWidget);
expect(reportedRouteInformation!.uri.toString(), 'popped');
expect(reportedType, RouteInformationReportingType.none);
});
testWidgets('router can be forced to recognize or ignore navigating events', (WidgetTester tester) async {
RouteInformation? reportedRouteInformation;
RouteInformationReportingType? reportedType;
bool isNavigating = false;
late RouteInformation nextRouteInformation;
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(
onRouterReport: (RouteInformation information, RouteInformationReportingType type) {
// Makes sure we only report once after manually cleaning up.
expect(reportedRouteInformation, isNull);
expect(reportedType, isNull);
reportedRouteInformation = information;
reportedType = type;
},
);
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(reportConfiguration: true);
addTearDown(delegate.dispose);
delegate.builder = (BuildContext context, RouteInformation? information) {
return ElevatedButton(
child: Text(Uri.decodeComponent(information!.uri.toString())),
onPressed: () {
if (isNavigating) {
Router.navigate(context, () {
if (delegate.routeInformation != nextRouteInformation) {
delegate.routeInformation = nextRouteInformation;
}
});
} else {
Router.neglect(context, () {
if (delegate.routeInformation != nextRouteInformation) {
delegate.routeInformation = nextRouteInformation;
}
});
}
},
);
};
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
),
));
expect(find.text('initial'), findsOneWidget);
expect(reportedRouteInformation!.uri.toString(), 'initial');
expect(reportedType, RouteInformationReportingType.none);
reportedType = null;
reportedRouteInformation = null;
nextRouteInformation = RouteInformation(
uri: Uri.parse('update'),
);
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
expect(find.text('initial'), findsNothing);
expect(find.text('update'), findsOneWidget);
expect(reportedType, RouteInformationReportingType.neglect);
expect(reportedRouteInformation!.uri.toString(), 'update');
reportedType = null;
reportedRouteInformation = null;
isNavigating = true;
// This should not trigger any real navigating event because the
// nextRouteInformation does not change. However, the router should still
// report a route information because isNavigating = true.
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
expect(reportedType, RouteInformationReportingType.navigate);
expect(reportedRouteInformation!.uri.toString(), 'update');
reportedType = null;
reportedRouteInformation = null;
});
testWidgets('router ignore navigating events updates RouteInformationProvider', (WidgetTester tester) async {
RouteInformation? updatedRouteInformation;
late RouteInformation nextRouteInformation;
RouteInformationReportingType? reportingType;
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(
onRouterReport: (RouteInformation information, RouteInformationReportingType type) {
expect(reportingType, isNull);
expect(updatedRouteInformation, isNull);
updatedRouteInformation = information;
reportingType = type;
},
);
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(reportConfiguration: true);
addTearDown(delegate.dispose);
delegate.builder = (BuildContext context, RouteInformation? information) {
return ElevatedButton(
child: Text(Uri.decodeComponent(information!.uri.toString())),
onPressed: () {
Router.neglect(context, () {
if (delegate.routeInformation != nextRouteInformation) {
delegate.routeInformation = nextRouteInformation;
}
});
},
);
};
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
),
));
expect(find.text('initial'), findsOneWidget);
expect(updatedRouteInformation!.uri.toString(), 'initial');
expect(reportingType, RouteInformationReportingType.none);
updatedRouteInformation = null;
reportingType = null;
nextRouteInformation = RouteInformation(
uri: Uri.parse('update'),
);
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
expect(find.text('initial'), findsNothing);
expect(find.text('update'), findsOneWidget);
expect(updatedRouteInformation!.uri.toString(), 'update');
expect(reportingType, RouteInformationReportingType.neglect);
});
testWidgets('state change without location changes updates RouteInformationProvider', (WidgetTester tester) async {
RouteInformation? updatedRouteInformation;
late RouteInformation nextRouteInformation;
RouteInformationReportingType? reportingType;
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(
onRouterReport: (RouteInformation information, RouteInformationReportingType type) {
// This should never be a navigation event.
expect(reportingType, isNull);
expect(updatedRouteInformation, isNull);
updatedRouteInformation = information;
reportingType = type;
},
);
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
state: 'state1',
);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(reportConfiguration: true);
addTearDown(delegate.dispose);
delegate.builder = (BuildContext context, RouteInformation? information) {
return ElevatedButton(
child: Text(Uri.decodeComponent(information!.uri.toString())),
onPressed: () {
delegate.routeInformation = nextRouteInformation;
},
);
};
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
),
));
expect(find.text('initial'), findsOneWidget);
expect(updatedRouteInformation!.uri.toString(), 'initial');
expect(reportingType, RouteInformationReportingType.none);
updatedRouteInformation = null;
reportingType = null;
nextRouteInformation = RouteInformation(
uri: Uri.parse('initial'),
state: 'state2',
);
await tester.tap(find.byType(ElevatedButton));
await tester.pump();
expect(updatedRouteInformation!.uri.toString(), 'initial');
expect(updatedRouteInformation!.state, 'state2');
expect(reportingType, RouteInformationReportingType.none);
});
testWidgets('PlatformRouteInformationProvider works', (WidgetTester tester) async {
final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(
uri: Uri.parse('initial'),
),
);
addTearDown(provider.dispose);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
final List<Widget> children = <Widget>[];
if (information!.uri.toString().isNotEmpty) {
children.add(Text(information.uri.toString()));
}
if (information.state != null) {
children.add(Text(information.state.toString()));
}
return Column(
children: children,
);
},
);
addTearDown(delegate.dispose);
await tester.pumpWidget(MaterialApp.router(
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
));
expect(find.text('initial'), findsOneWidget);
// Pushes through the `pushRouteInformation` in the navigation method channel.
const Map<String, dynamic> testRouteInformation = <String, dynamic>{
'location': 'testRouteName',
'state': 'state',
};
final ByteData routerMessage = const JSONMethodCodec().encodeMethodCall(
const MethodCall('pushRouteInformation', testRouteInformation),
);
await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', routerMessage, (_) { });
await tester.pump();
expect(find.text('testRouteName'), findsOneWidget);
expect(find.text('state'), findsOneWidget);
// Pushes through the `pushRoute` in the navigation method channel.
const String testRouteName = 'newTestRouteName';
final ByteData message = const JSONMethodCodec().encodeMethodCall(
const MethodCall('pushRoute', testRouteName),
);
await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
await tester.pump();
expect(find.text('newTestRouteName'), findsOneWidget);
});
testWidgets('PlatformRouteInformationProvider updates route information', (WidgetTester tester) async {
final List<MethodCall> log = <MethodCall>[];
TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.navigation,
(MethodCall methodCall) async {
log.add(methodCall);
return null;
}
);
final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(
uri: Uri.parse('initial'),
),
);
addTearDown(provider.dispose);
log.clear();
provider.routerReportsNewRouteInformation(RouteInformation(uri: Uri.parse('a'), state: true));
// Implicit reporting pushes new history entry if the location changes.
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': true, 'replace': false }),
]);
log.clear();
provider.routerReportsNewRouteInformation(RouteInformation(uri: Uri.parse('a'), state: false));
// Since the location is the same, the provider sends replaces message.
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': false, 'replace': true }),
]);
log.clear();
provider.routerReportsNewRouteInformation(RouteInformation(uri: Uri.parse('b'), state: false), type: RouteInformationReportingType.neglect);
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'b', 'state': false, 'replace': true }),
]);
log.clear();
provider.routerReportsNewRouteInformation(RouteInformation(uri: Uri.parse('b'), state: false), type: RouteInformationReportingType.navigate);
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'b', 'state': false, 'replace': false }),
]);
});
testWidgets('PlatformRouteInformationProvider does not push new entry if query parameters are semantically the same', (WidgetTester tester) async {
final List<MethodCall> log = <MethodCall>[];
TestDefaultBinaryMessengerBinding
.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
SystemChannels.navigation,
(MethodCall methodCall) async {
log.add(methodCall);
return null;
}
);
final RouteInformation initial = RouteInformation(
uri: Uri.parse('initial?a=ws/abcd'),
);
final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
initialRouteInformation: initial
);
addTearDown(provider.dispose);
// Make sure engine is updated with initial route
provider.routerReportsNewRouteInformation(initial);
log.clear();
provider.routerReportsNewRouteInformation(
RouteInformation(
uri: Uri(
path: 'initial',
queryParameters: <String, String>{'a': 'ws/abcd'}, // This will be escaped.
),
),
);
expect(provider.value.uri.toString(), 'initial?a=ws%2Fabcd');
// should use `replace: true`
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'initial?a=ws%2Fabcd', 'state': null, 'replace': true }),
]);
log.clear();
provider.routerReportsNewRouteInformation(
RouteInformation(uri: Uri.parse('initial?a=1&b=2')),
);
log.clear();
// Change query parameters order
provider.routerReportsNewRouteInformation(
RouteInformation(uri: Uri.parse('initial?b=2&a=1')),
);
// should use `replace: true`
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'initial?b=2&a=1', 'state': null, 'replace': true }),
]);
log.clear();
provider.routerReportsNewRouteInformation(
RouteInformation(uri: Uri.parse('initial?a=1&a=2')),
);
log.clear();
// Change query parameters order for same key
provider.routerReportsNewRouteInformation(
RouteInformation(uri: Uri.parse('initial?a=2&a=1')),
);
// should use `replace: true`
expect(log, <Object>[
isMethodCall('selectMultiEntryHistory', arguments: null),
isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'initial?a=2&a=1', 'state': null, 'replace': true }),
]);
log.clear();
});
testWidgets('RootBackButtonDispatcher works', (WidgetTester tester) async {
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(
uri: Uri.parse('initial'),
),
);
addTearDown(provider.dispose);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
reportConfiguration: true,
builder: (BuildContext context, RouteInformation? information) {
return Text(Uri.decodeComponent(information!.uri.toString()));
},
);
addTearDown(delegate.dispose);
delegate.onPopRoute = () {
delegate.routeInformation = RouteInformation(
uri: Uri.parse('popped'),
);
return SynchronousFuture<bool>(true);
};
await tester.pumpWidget(MaterialApp.router(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
));
expect(find.text('initial'), findsOneWidget);
// Pop route through the message channel.
final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
await tester.pump();
expect(find.text('popped'), findsOneWidget);
});
testWidgets('BackButtonListener takes priority over root back dispatcher', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
// Creates the sub-router.
return Column(
children: <Widget>[
Text(Uri.decodeComponent(information!.uri.toString())),
BackButtonListener(
child: Container(),
onBackButtonPressed: () {
provider.value = RouteInformation(
uri: Uri.parse('popped inner1'),
);
return SynchronousFuture<bool>(true);
},
),
],
);
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(delegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
),
));
expect(find.text('initial'), findsOneWidget);
bool result = false;
result = await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pump();
expect(find.text('popped inner1'), findsOneWidget);
});
testWidgets('BackButtonListener updates callback if it has been changed', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
final SimpleRouterDelegate routerDelegate = SimpleRouterDelegate()
..builder = (BuildContext context, RouteInformation? information) {
// Creates the sub-router.
return Column(
children: <Widget>[
Text(Uri.decodeComponent(information!.uri.toString())),
BackButtonListener(
child: Container(),
onBackButtonPressed: () {
provider.value = RouteInformation(
uri: Uri.parse('first callback'),
);
return SynchronousFuture<bool>(true);
},
),
],
);
}
..onPopRoute = () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
};
addTearDown(routerDelegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: routerDelegate,
),
));
routerDelegate
..builder = (BuildContext context, RouteInformation? information) {
// Creates the sub-router.
return Column(
children: <Widget>[
Text(Uri.decodeComponent(information!.uri.toString())),
BackButtonListener(
child: Container(),
onBackButtonPressed: () {
provider.value = RouteInformation(
uri: Uri.parse('second callback'),
);
return SynchronousFuture<bool>(true);
},
),
],
);
}
..onPopRoute = () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
};
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: routerDelegate,
),
));
await tester.pump();
await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
await tester.pump();
expect(find.text('second callback'), findsOneWidget);
});
testWidgets('BackButtonListener clears callback if it is disposed', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
final SimpleRouterDelegate routerDelegate = SimpleRouterDelegate()
..builder = (BuildContext context, RouteInformation? information) {
// Creates the sub-router.
return Column(
children: <Widget>[
Text(Uri.decodeComponent(information!.uri.toString())),
BackButtonListener(
child: Container(),
onBackButtonPressed: () {
provider.value = RouteInformation(
uri: Uri.parse('first callback'),
);
return SynchronousFuture<bool>(true);
},
),
],
);
}
..onPopRoute = () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
};
addTearDown(routerDelegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: routerDelegate,
),
));
routerDelegate
..builder = (BuildContext context, RouteInformation? information) {
// Creates the sub-router.
return Column(
children: <Widget>[
Text(Uri.decodeComponent(information!.uri.toString())),
],
);
}
..onPopRoute = () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
};
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: routerDelegate,
),
));
await tester.pump();
await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
await tester.pump();
expect(find.text('popped outer'), findsOneWidget);
});
testWidgets('Nested backButtonListener should take priority', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
// Creates the sub-router.
return Column(
children: <Widget>[
Text(Uri.decodeComponent(information!.uri.toString())),
BackButtonListener(
child: BackButtonListener(
child: Container(),
onBackButtonPressed: () {
provider.value = RouteInformation(
uri: Uri.parse('popped inner2'),
);
return SynchronousFuture<bool>(true);
},
),
onBackButtonPressed: () {
provider.value = RouteInformation(
uri: Uri.parse('popped inner1'),
);
return SynchronousFuture<bool>(true);
},
),
],
);
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(delegate.dispose);
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
),
));
expect(find.text('initial'), findsOneWidget);
bool result = false;
result = await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pump();
expect(find.text('popped inner2'), findsOneWidget);
});
testWidgets('Nested backButtonListener that returns false should call next on the line', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
// Creates the sub-router.
return Column(
children: <Widget>[
Text(Uri.decodeComponent(information!.uri.toString())),
BackButtonListener(
child: BackButtonListener(
child: Container(),
onBackButtonPressed: () {
provider.value = RouteInformation(
uri: Uri.parse('popped inner2'),
);
return SynchronousFuture<bool>(false);
},
),
onBackButtonPressed: () {
provider.value = RouteInformation(
uri: Uri.parse('popped inner1'),
);
return SynchronousFuture<bool>(true);
},
),
],
);
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(delegate.dispose);
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
),
));
expect(find.text('initial'), findsOneWidget);
bool result = false;
result = await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
expect(result, isTrue);
await tester.pump();
expect(find.text('popped inner1'), findsOneWidget);
});
testWidgets('`didUpdateWidget` test', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher outerDispatcher = RootBackButtonDispatcher();
late StateSetter setState;
String location = 'first callback';
final SimpleRouterDelegate routerDelegate = SimpleRouterDelegate()
..builder = (BuildContext context, RouteInformation? information) {
// Creates the sub-router.
return Column(
children: <Widget>[
Text(Uri.decodeComponent(information!.uri.toString())),
StatefulBuilder(
builder: (BuildContext context, StateSetter setter) {
setState = setter;
return BackButtonListener(
child: Container(),
onBackButtonPressed: () {
provider.value = RouteInformation(
uri: Uri.parse(location),
);
return SynchronousFuture<bool>(true);
},
);
},
),
],
);
}
..onPopRoute = () {
provider.value = RouteInformation(
uri: Uri.parse('popped outer'),
);
return SynchronousFuture<bool>(true);
};
addTearDown(routerDelegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
backButtonDispatcher: outerDispatcher,
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: routerDelegate,
),
));
// Only update BackButtonListener widget.
setState(() {
location = 'second callback';
});
await tester.pump();
await outerDispatcher.invokeCallback(SynchronousFuture<bool>(false));
await tester.pump();
expect(find.text('second callback'), findsOneWidget);
});
testWidgets('Router reports location if it is different from location given by OS', (WidgetTester tester) async {
final List<RouteInformation> reportedRouteInformation = <RouteInformation>[];
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider(
onRouterReport: (RouteInformation info, RouteInformationReportingType type) => reportedRouteInformation.add(info),
)..value = RouteInformation(uri: Uri.parse('/home'));
addTearDown(provider.dispose);
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext _, RouteInformation? info) => Text('Current route: ${info?.uri}'),
reportConfiguration: true,
);
addTearDown(delegate.dispose);
await tester.pumpWidget(buildBoilerPlate(
Router<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: RedirectingInformationParser(<String, RouteInformation>{
'/doesNotExist' : RouteInformation(uri: Uri.parse('/404')),
}),
routerDelegate: delegate,
),
));
expect(find.text('Current route: /home'), findsOneWidget);
expect(reportedRouteInformation.single.uri.toString(), '/home');
provider.value = RouteInformation(uri: Uri.parse('/doesNotExist'));
await tester.pump();
expect(find.text('Current route: /404'), findsOneWidget);
expect(reportedRouteInformation[1].uri.toString(), '/404');
});
testWidgets('RouterInformationParser can look up dependencies and reparse', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher dispatcher = RootBackButtonDispatcher();
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
return Text(Uri.decodeComponent(information!.uri.toString()));
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(delegate.dispose);
int expectedMaxLines = 1;
bool parserCalled = false;
final Widget router = Router<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: CustomRouteInformationParser((RouteInformation information, BuildContext context) {
parserCalled = true;
final DefaultTextStyle style = DefaultTextStyle.of(context);
return RouteInformation(uri: Uri.parse('${style.maxLines}'));
}),
routerDelegate: delegate,
backButtonDispatcher: dispatcher,
);
await tester.pumpWidget(buildBoilerPlate(
DefaultTextStyle(
style: const TextStyle(),
maxLines: expectedMaxLines,
child: router,
),
));
expect(find.text('$expectedMaxLines'), findsOneWidget);
expect(parserCalled, isTrue);
parserCalled = false;
expectedMaxLines = 2;
await tester.pumpWidget(buildBoilerPlate(
DefaultTextStyle(
style: const TextStyle(),
maxLines: expectedMaxLines,
child: router,
),
));
await tester.pump();
expect(find.text('$expectedMaxLines'), findsOneWidget);
expect(parserCalled, isTrue);
});
testWidgets('RouterInformationParser can look up dependencies without reparsing', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher dispatcher = RootBackButtonDispatcher();
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
return Text(Uri.decodeComponent(information!.uri.toString()));
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(delegate.dispose);
const int expectedMaxLines = 1;
bool parserCalled = false;
final Widget router = Router<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: CustomRouteInformationParser((RouteInformation information, BuildContext context) {
parserCalled = true;
final DefaultTextStyle style = context.getInheritedWidgetOfExactType<DefaultTextStyle>()!;
return RouteInformation(uri: Uri.parse('${style.maxLines}'));
}),
routerDelegate: delegate,
backButtonDispatcher: dispatcher,
);
await tester.pumpWidget(buildBoilerPlate(
DefaultTextStyle(
style: const TextStyle(),
maxLines: expectedMaxLines,
child: router,
),
));
expect(find.text('$expectedMaxLines'), findsOneWidget);
expect(parserCalled, isTrue);
parserCalled = false;
const int newMaxLines = 2;
// This rebuild should not trigger re-parsing.
await tester.pumpWidget(buildBoilerPlate(
DefaultTextStyle(
style: const TextStyle(),
maxLines: newMaxLines,
child: router,
),
));
await tester.pump();
expect(find.text('$newMaxLines'), findsNothing);
expect(find.text('$expectedMaxLines'), findsOneWidget);
expect(parserCalled, isFalse);
});
testWidgets('Looks up dependencies in RouterDelegate does not trigger re-parsing', (WidgetTester tester) async {
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(
uri: Uri.parse('initial'),
);
final BackButtonDispatcher dispatcher = RootBackButtonDispatcher();
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (BuildContext context, RouteInformation? information) {
final DefaultTextStyle style = DefaultTextStyle.of(context);
return Text('${style.maxLines}');
},
onPopRoute: () {
provider.value = RouteInformation(
uri: Uri.parse('popped'),
);
return SynchronousFuture<bool>(true);
},
);
addTearDown(delegate.dispose);
int expectedMaxLines = 1;
bool parserCalled = false;
final Widget router = Router<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: CustomRouteInformationParser((RouteInformation information, BuildContext context) {
parserCalled = true;
return information;
}),
routerDelegate: delegate,
backButtonDispatcher: dispatcher,
);
await tester.pumpWidget(buildBoilerPlate(
DefaultTextStyle(
style: const TextStyle(),
maxLines: expectedMaxLines,
child: router,
),
));
expect(find.text('$expectedMaxLines'), findsOneWidget);
// Initial route will be parsed regardless.
expect(parserCalled, isTrue);
parserCalled = false;
expectedMaxLines = 2;
await tester.pumpWidget(buildBoilerPlate(
DefaultTextStyle(
style: const TextStyle(),
maxLines: expectedMaxLines,
child: router,
),
));
await tester.pump();
expect(find.text('$expectedMaxLines'), findsOneWidget);
expect(parserCalled, isFalse);
});
testWidgets('Router can initialize with RouterConfig', (WidgetTester tester) async {
const String expected = 'text';
final SimpleRouteInformationProvider provider = SimpleRouteInformationProvider();
addTearDown(provider.dispose);
provider.value = RouteInformation(uri: Uri.parse('/'));
final SimpleRouterDelegate delegate = SimpleRouterDelegate(
builder: (_, __) => const Text(expected),
);
addTearDown(delegate.dispose);
final RouterConfig<RouteInformation> config = RouterConfig<RouteInformation>(
routeInformationProvider: provider,
routeInformationParser: SimpleRouteInformationParser(),
routerDelegate: delegate,
backButtonDispatcher: RootBackButtonDispatcher(),
);
final Router<RouteInformation> router = Router<RouteInformation>.withConfig(config: config);
expect(router.routerDelegate, config.routerDelegate);
expect(router.routeInformationParser, config.routeInformationParser);
expect(router.routeInformationProvider, config.routeInformationProvider);
expect(router.backButtonDispatcher, config.backButtonDispatcher);
await tester.pumpWidget(buildBoilerPlate(router));
expect(find.text(expected), findsOneWidget);
});
group('RouteInformation uri api', () {
test('can produce correct uri from location', () async {
final RouteInformation info1 = RouteInformation(uri: Uri.parse('/a?abc=def&abc=jkl#mno'));
expect(info1.location, '/a?abc=def&abc=jkl#mno');
final Uri uri1 = info1.uri;
expect(uri1.scheme, '');
expect(uri1.host, '');
expect(uri1.path, '/a');
expect(uri1.fragment, 'mno');
expect(uri1.queryParametersAll.length, 1);
expect(uri1.queryParametersAll['abc']!.length, 2);
expect(uri1.queryParametersAll['abc']![0], 'def');
expect(uri1.queryParametersAll['abc']![1], 'jkl');
final RouteInformation info2 = RouteInformation(uri: Uri.parse('1'));
expect(info2.location, '1');
final Uri uri2 = info2.uri;
expect(uri2.scheme, '');
expect(uri2.host, '');
expect(uri2.path, '1');
expect(uri2.fragment, '');
expect(uri2.queryParametersAll.length, 0);
});
test('can produce correct location from uri', () async {
final RouteInformation info1 = RouteInformation(uri: Uri.parse('http://mydomain.com'));
expect(info1.uri.toString(), 'http://mydomain.com');
expect(info1.location, '/');
final RouteInformation info2 = RouteInformation(uri: Uri.parse('http://mydomain.com/abc?def=ghi&def=jkl#mno'));
expect(info2.uri.toString(), 'http://mydomain.com/abc?def=ghi&def=jkl#mno');
expect(info2.location, '/abc?def=ghi&def=jkl#mno');
});
});
test('$PlatformRouteInformationProvider dispatches object creation in constructor', () async {
Future<void> createAndDispose() async {
PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('http://google.com')),
).dispose();
}
await expectLater(
await memoryEvents(createAndDispose, PlatformRouteInformationProvider),
areCreateAndDispose,
);
});
}
Widget buildBoilerPlate(Widget child) {
return MaterialApp(
home: Scaffold(
body: child,
),
);
}
typedef SimpleRouterDelegateBuilder = Widget Function(BuildContext context, RouteInformation? information);
typedef SimpleRouterDelegatePopRoute = Future<bool> Function();
typedef SimpleNavigatorRouterDelegatePopPage<T> = bool Function(Route<T> route, T result);
typedef RouterReportRouterInformation = void Function(RouteInformation information, RouteInformationReportingType type);
typedef CustomRouteInformationParserCallback = RouteInformation Function(RouteInformation information, BuildContext context);
class SimpleRouteInformationParser extends RouteInformationParser<RouteInformation> {
SimpleRouteInformationParser();
@override
Future<RouteInformation> parseRouteInformation(RouteInformation information) {
return SynchronousFuture<RouteInformation>(information);
}
@override
RouteInformation restoreRouteInformation(RouteInformation configuration) {
return configuration;
}
}
class CustomRouteInformationParser extends RouteInformationParser<RouteInformation> {
const CustomRouteInformationParser(this.callback);
final CustomRouteInformationParserCallback callback;
@override
Future<RouteInformation> parseRouteInformationWithDependencies(RouteInformation information, BuildContext context) {
return SynchronousFuture<RouteInformation>(callback(information, context));
}
@override
RouteInformation restoreRouteInformation(RouteInformation configuration) {
return configuration;
}
}
class SimpleRouterDelegate extends RouterDelegate<RouteInformation> with ChangeNotifier {
SimpleRouterDelegate({
this.builder,
this.onPopRoute,
this.reportConfiguration = false,
}) {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
RouteInformation? get routeInformation => _routeInformation;
RouteInformation? _routeInformation;
set routeInformation(RouteInformation? newValue) {
_routeInformation = newValue;
notifyListeners();
}
SimpleRouterDelegateBuilder? builder;
SimpleRouterDelegatePopRoute? onPopRoute;
final bool reportConfiguration;
@override
RouteInformation? get currentConfiguration {
if (reportConfiguration) {
return routeInformation;
}
return null;
}
@override
Future<void> setNewRoutePath(RouteInformation configuration) {
_routeInformation = configuration;
return SynchronousFuture<void>(null);
}
@override
Future<bool> popRoute() {
return onPopRoute?.call() ?? SynchronousFuture<bool>(true);
}
@override
Widget build(BuildContext context) => builder!(context, routeInformation);
}
class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> with PopNavigatorRouterDelegateMixin<RouteInformation>, ChangeNotifier {
SimpleNavigatorRouterDelegate({
required this.builder,
required this.onPopPage,
});
@override
GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
RouteInformation get routeInformation => _routeInformation;
late RouteInformation _routeInformation;
SimpleRouterDelegateBuilder builder;
SimpleNavigatorRouterDelegatePopPage<void> onPopPage;
@override
Future<void> setNewRoutePath(RouteInformation configuration) {
_routeInformation = configuration;
return SynchronousFuture<void>(null);
}
bool _handlePopPage(Route<void> route, void data) {
return onPopPage(route, data);
}
@override
Widget build(BuildContext context) {
return Navigator(
key: navigatorKey,
onPopPage: _handlePopPage,
pages: <Page<void>>[
// We need at least two pages for the pop to propagate through.
// Otherwise, the navigator will bubble the pop to the system navigator.
const MaterialPage<void>(
child: Text('base'),
),
MaterialPage<void>(
key: ValueKey<String>(routeInformation.uri.toString()),
child: builder(context, routeInformation),
),
],
);
}
}
class SimpleRouteInformationProvider extends RouteInformationProvider with ChangeNotifier {
SimpleRouteInformationProvider({
this.onRouterReport,
}) {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
RouterReportRouterInformation? onRouterReport;
@override
RouteInformation get value => _value;
late RouteInformation _value;
set value(RouteInformation newValue) {
_value = newValue;
notifyListeners();
}
@override
void routerReportsNewRouteInformation(RouteInformation routeInformation, {RouteInformationReportingType type = RouteInformationReportingType.none}) {
_value = routeInformation;
onRouterReport?.call(routeInformation, type);
}
}
class SimpleAsyncRouteInformationParser extends RouteInformationParser<RouteInformation> {
SimpleAsyncRouteInformationParser();
late Future<RouteInformation> parsingFuture;
@override
Future<RouteInformation> parseRouteInformation(RouteInformation information) {
return parsingFuture = Future<RouteInformation>.value(information);
}
@override
RouteInformation restoreRouteInformation(RouteInformation configuration) {
return configuration;
}
}
class CompleterRouteInformationParser extends RouteInformationParser<RouteInformation> {
CompleterRouteInformationParser();
late Completer<void> completer;
@override
Future<RouteInformation> parseRouteInformation(RouteInformation information) async {
completer = Completer<void>();
await completer.future;
return SynchronousFuture<RouteInformation>(information);
}
@override
RouteInformation restoreRouteInformation(RouteInformation configuration) {
return configuration;
}
}
class SimpleAsyncRouterDelegate extends RouterDelegate<RouteInformation> with ChangeNotifier {
SimpleAsyncRouterDelegate({
required this.builder,
}) {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
RouteInformation? get routeInformation => _routeInformation;
RouteInformation? _routeInformation;
SimpleRouterDelegateBuilder builder;
late Future<void> setNewRouteFuture;
@override
Future<void> setNewRoutePath(RouteInformation configuration) {
_routeInformation = configuration;
return setNewRouteFuture = Future<void>.value();
}
@override
Future<bool> popRoute() {
return Future<bool>.value(true);
}
@override
Widget build(BuildContext context) => builder(context, routeInformation);
}
class RedirectingInformationParser extends RouteInformationParser<RouteInformation> {
RedirectingInformationParser(this.redirects);
final Map<String, RouteInformation> redirects;
@override
Future<RouteInformation> parseRouteInformation(RouteInformation information) {
return SynchronousFuture<RouteInformation>(redirects[information.uri.toString()] ?? information);
}
@override
RouteInformation restoreRouteInformation(RouteInformation configuration) {
return configuration;
}
}
| flutter/packages/flutter/test/widgets/router_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/router_test.dart",
"repo_id": "flutter",
"token_count": 26210
} | 698 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('ClampingScrollSimulation has a stable initial conditions', () {
void checkInitialConditions(double position, double velocity) {
final ClampingScrollSimulation simulation = ClampingScrollSimulation(position: position, velocity: velocity);
expect(simulation.x(0.0), moreOrLessEquals(position));
expect(simulation.dx(0.0), moreOrLessEquals(velocity));
}
checkInitialConditions(51.0, 2866.91537);
checkInitialConditions(584.0, 2617.294734);
checkInitialConditions(345.0, 1982.785934);
checkInitialConditions(0.0, 1831.366634);
checkInitialConditions(-156.2, 1541.57665);
checkInitialConditions(4.0, 1139.250439);
checkInitialConditions(4534.0, 1073.553798);
checkInitialConditions(75.0, 614.2093);
checkInitialConditions(5469.0, 182.114534);
});
test('ClampingScrollSimulation only decelerates, never speeds up', () {
// Regression test for https://github.com/flutter/flutter/issues/113424
final ClampingScrollSimulation simulation =
ClampingScrollSimulation(position: 0, velocity: 8000.0);
double time = 0.0;
double velocity = simulation.dx(time);
while (!simulation.isDone(time)) {
expect(time, lessThan(3.0));
time += 1 / 60;
final double nextVelocity = simulation.dx(time);
expect(nextVelocity, lessThanOrEqualTo(velocity));
velocity = nextVelocity;
}
});
test('ClampingScrollSimulation reaches a smooth stop: velocity is continuous and goes to zero', () {
// Regression test for https://github.com/flutter/flutter/issues/113424
const double initialVelocity = 8000.0;
const double maxDeceleration = 5130.0; // -acceleration(initialVelocity), from formula below
final ClampingScrollSimulation simulation =
ClampingScrollSimulation(position: 0, velocity: initialVelocity);
double time = 0.0;
double velocity = simulation.dx(time);
const double delta = 1 / 60;
do {
expect(time, lessThan(3.0));
time += delta;
final double nextVelocity = simulation.dx(time);
expect((nextVelocity - velocity).abs(), lessThan(delta * maxDeceleration));
velocity = nextVelocity;
} while (!simulation.isDone(time));
expect(velocity, moreOrLessEquals(0.0));
});
test('ClampingScrollSimulation is ballistic', () {
// Regression test for https://github.com/flutter/flutter/issues/120338
const double delta = 1 / 90;
final ClampingScrollSimulation undisturbed =
ClampingScrollSimulation(position: 0, velocity: 8000.0);
double time = 0.0;
ClampingScrollSimulation restarted = undisturbed;
final List<double> xsRestarted = <double>[];
final List<double> xsUndisturbed = <double>[];
final List<double> dxsRestarted = <double>[];
final List<double> dxsUndisturbed = <double>[];
do {
expect(time, lessThan(4.0));
time += delta;
restarted = ClampingScrollSimulation(
position: restarted.x(delta), velocity: restarted.dx(delta));
xsRestarted.add(restarted.x(0));
xsUndisturbed.add(undisturbed.x(time));
dxsRestarted.add(restarted.dx(0));
dxsUndisturbed.add(undisturbed.dx(time));
} while (!restarted.isDone(0) || !undisturbed.isDone(time));
// Compare the headline number first: the total distances traveled.
// This way, if the test fails, it shows the big final difference
// instead of the tiny difference that's in the very first frame.
expect(xsRestarted.last, moreOrLessEquals(xsUndisturbed.last));
// The whole trajectories along the way should match too.
for (int i = 0; i < xsRestarted.length; i++) {
expect(xsRestarted[i], moreOrLessEquals(xsUndisturbed[i]));
expect(dxsRestarted[i], moreOrLessEquals(dxsUndisturbed[i]));
}
});
test('ClampingScrollSimulation satisfies a physical acceleration formula', () {
// Different regression test for https://github.com/flutter/flutter/issues/120338
//
// This one provides a formula for the particle's acceleration as a function
// of its velocity, and checks that it behaves according to that formula.
// The point isn't that it's this specific formula, but just that there's
// some formula which depends only on velocity, not time, so that the
// physical metaphor makes sense.
// Copied from the implementation.
final double kDecelerationRate = math.log(0.78) / math.log(0.9);
// Same as the referenceVelocity in _flingDuration.
const double referenceVelocity = .015 * 9.80665 * 39.37 * 160.0 * 0.84 / 0.35;
// The value of _duration when velocity == referenceVelocity.
final double referenceDuration = kDecelerationRate * 0.35;
// The rate of deceleration when dx(time) == referenceVelocity.
final double referenceDeceleration = (kDecelerationRate - 1) * referenceVelocity / referenceDuration;
double acceleration(double velocity) {
return - velocity.sign
* referenceDeceleration *
math.pow(velocity.abs() / referenceVelocity,
(kDecelerationRate - 2) / (kDecelerationRate - 1));
}
double jerk(double velocity) {
return referenceVelocity / referenceDuration / referenceDuration
* (kDecelerationRate - 1) * (kDecelerationRate - 2)
* math.pow(velocity.abs() / referenceVelocity,
(kDecelerationRate - 3) / (kDecelerationRate - 1));
}
void checkAcceleration(double position, double velocity) {
final ClampingScrollSimulation simulation =
ClampingScrollSimulation(position: position, velocity: velocity);
double time = 0.0;
const double delta = 1/60;
for (; time < 2.0; time += delta) {
final double difference = simulation.dx(time + delta) - simulation.dx(time);
final double predictedDifference = delta * acceleration(simulation.dx(time + delta/2));
final double maxThirdDerivative = jerk(simulation.dx(time + delta));
expect((difference - predictedDifference).abs(),
lessThan(maxThirdDerivative * math.pow(delta, 2)/2));
}
}
checkAcceleration(51.0, 2866.91537);
checkAcceleration(584.0, 2617.294734);
checkAcceleration(345.0, 1982.785934);
checkAcceleration(0.0, 1831.366634);
checkAcceleration(-156.2, 1541.57665);
checkAcceleration(4.0, 1139.250439);
checkAcceleration(4534.0, 1073.553798);
checkAcceleration(75.0, 614.2093);
checkAcceleration(5469.0, 182.114534);
});
}
| flutter/packages/flutter/test/widgets/scroll_simulation_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scroll_simulation_test.dart",
"repo_id": "flutter",
"token_count": 2469
} | 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.
@TestOn('browser') // This file contains web-only library.
library;
import 'dart:js_interop';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:web/web.dart' as web;
extension on web.HTMLCollection {
Iterable<web.Element> get iterable => _genIterable(this);
}
extension on web.CSSRuleList {
Iterable<web.CSSRule> get iterable => _genIterable(this);
}
Iterable<T> _genIterable<T>(dynamic jsCollection) {
// ignore: avoid_dynamic_calls
return Iterable<T>.generate(jsCollection.length as int, (int index) => jsCollection.item(index) as T,);
}
void main() {
web.HTMLElement? element;
PlatformSelectableRegionContextMenu.debugOverrideRegisterViewFactory = (String viewType, Object Function(int viewId) fn, {bool isVisible = true}) {
element = fn(0) as web.HTMLElement;
// The element needs to be attached to the document body to receive mouse
// events.
web.document.body!.append(element! as JSAny);
};
// This force register the dom element.
PlatformSelectableRegionContextMenu(child: const Placeholder());
PlatformSelectableRegionContextMenu.debugOverrideRegisterViewFactory = null;
test('DOM element is set up correctly', () async {
expect(element, isNotNull);
expect(element!.style.width, '100%');
expect(element!.style.height, '100%');
expect(element!.classList.length, 1);
final String className = element!.className;
expect(web.document.head!.children.iterable, isNotEmpty);
bool foundStyle = false;
for (final web.Element element in web.document.head!.children.iterable) {
if (element.tagName != 'STYLE') {
continue;
}
final web.CSSRuleList? rules = (element as web.HTMLStyleElement).sheet?.rules;
if (rules != null) {
foundStyle = rules.iterable.any((web.CSSRule rule) => rule.cssText.contains(className));
}
if (foundStyle) {
break;
}
}
expect(foundStyle, isTrue);
});
testWidgets('right click can trigger select word', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
final UniqueKey spy = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: SelectableRegion(
focusNode: focusNode,
selectionControls: materialTextSelectionControls,
child: SelectionSpy(key: spy),
),
)
);
expect(element, isNotNull);
focusNode.requestFocus();
await tester.pump();
// Dispatch right click.
element!.dispatchEvent(
web.MouseEvent(
'mousedown',
web.MouseEventInit(
button: 2,
clientX: 200,
clientY: 300,
),
),
);
final RenderSelectionSpy renderSelectionSpy = tester.renderObject<RenderSelectionSpy>(find.byKey(spy));
expect(renderSelectionSpy.events, isNotEmpty);
SelectWordSelectionEvent? selectWordEvent;
for (final SelectionEvent event in renderSelectionSpy.events) {
if (event is SelectWordSelectionEvent) {
selectWordEvent = event;
break;
}
}
expect(selectWordEvent, isNotNull);
expect((selectWordEvent!.globalPosition.dx - 200).abs() < precisionErrorTolerance, isTrue);
expect((selectWordEvent.globalPosition.dy - 300).abs() < precisionErrorTolerance, isTrue);
});
}
class SelectionSpy extends LeafRenderObjectWidget {
const SelectionSpy({
super.key,
});
@override
RenderObject createRenderObject(BuildContext context) {
return RenderSelectionSpy(
SelectionContainer.maybeOf(context),
);
}
@override
void updateRenderObject(BuildContext context, covariant RenderObject renderObject) { }
}
class RenderSelectionSpy extends RenderProxyBox
with Selectable, SelectionRegistrant {
RenderSelectionSpy(
SelectionRegistrar? registrar,
) {
this.registrar = registrar;
}
final Set<VoidCallback> listeners = <VoidCallback>{};
List<SelectionEvent> events = <SelectionEvent>[];
@override
Size get size => _size;
Size _size = Size.zero;
@override
List<Rect> get boundingBoxes => _boundingBoxes;
final List<Rect> _boundingBoxes = <Rect>[];
@override
Size computeDryLayout(BoxConstraints constraints) {
_size = Size(constraints.maxWidth, constraints.maxHeight);
_boundingBoxes.add(Rect.fromLTWH(0.0, 0.0, constraints.maxWidth, constraints.maxHeight));
return _size;
}
@override
void addListener(VoidCallback listener) => listeners.add(listener);
@override
void removeListener(VoidCallback listener) => listeners.remove(listener);
@override
SelectionResult dispatchSelectionEvent(SelectionEvent event) {
events.add(event);
return SelectionResult.end;
}
@override
SelectedContent? getSelectedContent() {
return const SelectedContent(plainText: 'content');
}
@override
final SelectionGeometry value = const SelectionGeometry(
hasContent: true,
status: SelectionStatus.uncollapsed,
startSelectionPoint: SelectionPoint(
localPosition: Offset.zero,
lineHeight: 0.0,
handleType: TextSelectionHandleType.left,
),
endSelectionPoint: SelectionPoint(
localPosition: Offset.zero,
lineHeight: 0.0,
handleType: TextSelectionHandleType.left,
),
);
@override
void pushHandleLayers(LayerLink? startHandle, LayerLink? endHandle) { }
}
| flutter/packages/flutter/test/widgets/selectable_region_context_menu_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/selectable_region_context_menu_test.dart",
"repo_id": "flutter",
"token_count": 1998
} | 700 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('SemanticNode.rect is clipped', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100.0,
child: Flex(
clipBehavior: Clip.hardEdge,
direction: Axis.horizontal,
children: <Widget>[
SizedBox(
width: 75.0,
child: Text('1'),
),
SizedBox(
width: 75.0,
child: Text('2'),
),
SizedBox(
width: 75.0,
child: Text('3'),
),
],
),
),
),
));
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('overflowed'));
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
label: '1',
rect: const Rect.fromLTRB(0.0, 0.0, 75.0, 14.0),
),
TestSemantics(
label: '2',
rect: const Rect.fromLTRB(0.0, 0.0, 25.0, 14.0), // clipped form original 75.0 to 25.0
),
// node with Text 3 not present.
],
),
ignoreTransform: true,
ignoreId: true,
));
semantics.dispose();
});
testWidgets('SemanticsNode is not removed if out of bounds and merged into something within bounds', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100.0,
child: Flex(
clipBehavior: Clip.hardEdge,
direction: Axis.horizontal,
children: <Widget>[
SizedBox(
width: 75.0,
child: Text('1'),
),
MergeSemantics(
child: Flex(
direction: Axis.horizontal,
children: <Widget>[
SizedBox(
width: 75.0,
child: Text('2'),
),
SizedBox(
width: 75.0,
child: Text('3'),
),
],
),
),
],
),
),
),
));
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('overflowed'));
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
label: '1',
rect: const Rect.fromLTRB(0.0, 0.0, 75.0, 14.0),
),
TestSemantics(
label: '2\n3',
rect: const Rect.fromLTRB(0.0, 0.0, 25.0, 14.0), // clipped form original 75.0 to 25.0
),
],
),
ignoreTransform: true,
ignoreId: true,
));
semantics.dispose();
});
}
| flutter/packages/flutter/test/widgets/semantics_clipping_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_clipping_test.dart",
"repo_id": "flutter",
"token_count": 1985
} | 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.
// 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import '../impeller_test_helpers.dart';
Shader createShader(Rect bounds) {
return const LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: <Color>[Color(0x00FFFFFF), Color(0xFFFFFFFF)],
stops: <double>[0.1, 0.35],
).createShader(bounds);
}
void main() {
testWidgets('Can be constructed', (WidgetTester tester) async {
const Widget child = SizedBox(width: 100.0, height: 100.0);
await tester.pumpWidget(const ShaderMask(shaderCallback: createShader, child: child));
});
testWidgets('Bounds rect includes offset', (WidgetTester tester) async {
late Rect shaderBounds;
Shader recordShaderBounds(Rect bounds) {
shaderBounds = bounds;
return createShader(bounds);
}
final Widget widget = Align(
child: SizedBox(
width: 400.0,
height: 400.0,
child: ShaderMask(
shaderCallback: recordShaderBounds,
child: const SizedBox(width: 100.0, height: 100.0),
),
),
);
await tester.pumpWidget(widget);
// The shader bounds rectangle should reflect the position of the centered SizedBox.
expect(shaderBounds, equals(const Rect.fromLTWH(0.0, 0.0, 400.0, 400.0)));
});
testWidgets('Bounds rect includes offset visual inspection', (WidgetTester tester) async {
final Widget widgetBottomRight = Container(
width: 400,
height: 400,
color: const Color(0xFFFFFFFF),
child: RepaintBoundary(
child: Align(
alignment: Alignment.bottomRight,
child: ShaderMask(
shaderCallback: (Rect bounds) => const RadialGradient(
radius: 0.05,
colors: <Color>[Color(0xFFFF0000), Color(0xFF00FF00)],
tileMode: TileMode.mirror,
).createShader(bounds),
child: Container(
width: 100,
height: 100,
color: const Color(0xFFFFFFFF),
),
),
),
),
);
await tester.pumpWidget(widgetBottomRight);
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('shader_mask.bounds.matches_bottom_right.png'),
);
final Widget widgetTopLeft = Container(
width: 400,
height: 400,
color: const Color(0xFFFFFFFF),
child: RepaintBoundary(
child: Align(
alignment: Alignment.topLeft,
child: ShaderMask(
shaderCallback: (Rect bounds) => const RadialGradient(
radius: 0.05,
colors: <Color>[Color(0xFFFF0000), Color(0xFF00FF00)],
tileMode: TileMode.mirror,
).createShader(bounds),
child: Container(
width: 100,
height: 100,
color: const Color(0xFFFFFFFF),
),
),
),
),
);
await tester.pumpWidget(widgetTopLeft);
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('shader_mask.bounds.matches_top_left.png'),
);
}, skip: impellerEnabled); // https://github.com/flutter/flutter/issues/144555
}
| flutter/packages/flutter/test/widgets/shader_mask_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/shader_mask_test.dart",
"repo_id": "flutter",
"token_count": 1515
} | 702 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('SliverList reverse children (with keys)', (WidgetTester tester) async {
final List<int> items = List<int>.generate(20, (int i) => i);
const double itemHeight = 300.0;
const double viewportHeight = 500.0;
const double scrollPosition = 18 * itemHeight;
final ScrollController controller = ScrollController(initialScrollOffset: scrollPosition);
addTearDown(controller.dispose);
await tester.pumpWidget(_buildSliverList(
items: items,
controller: controller,
itemHeight: itemHeight,
viewportHeight: viewportHeight,
));
await tester.pumpAndSettle();
expect(controller.offset, scrollPosition);
expect(find.text('Tile 0'), findsNothing);
expect(find.text('Tile 1'), findsNothing);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 19'), findsOneWidget);
await tester.pumpWidget(_buildSliverList(
items: items.reversed.toList(),
controller: controller,
itemHeight: itemHeight,
viewportHeight: viewportHeight,
));
final int frames = await tester.pumpAndSettle();
expect(frames, 1); // ensures that there is no (animated) bouncing of the scrollable
expect(controller.offset, scrollPosition);
expect(find.text('Tile 19'), findsNothing);
expect(find.text('Tile 18'), findsNothing);
expect(find.text('Tile 1'), findsOneWidget);
expect(find.text('Tile 0'), findsOneWidget);
controller.jumpTo(0.0);
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(find.text('Tile 19'), findsOneWidget);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 1'), findsNothing);
expect(find.text('Tile 0'), findsNothing);
});
testWidgets('SliverList replace children (with keys)', (WidgetTester tester) async {
final List<int> items = List<int>.generate(20, (int i) => i);
const double itemHeight = 300.0;
const double viewportHeight = 500.0;
const double scrollPosition = 18 * itemHeight;
final ScrollController controller = ScrollController(initialScrollOffset: scrollPosition);
addTearDown(controller.dispose);
await tester.pumpWidget(_buildSliverList(
items: items,
controller: controller,
itemHeight: itemHeight,
viewportHeight: viewportHeight,
));
await tester.pumpAndSettle();
expect(controller.offset, scrollPosition);
expect(find.text('Tile 0'), findsNothing);
expect(find.text('Tile 1'), findsNothing);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 19'), findsOneWidget);
await tester.pumpWidget(_buildSliverList(
items: items.map<int>((int i) => i + 100).toList(),
controller: controller,
itemHeight: itemHeight,
viewportHeight: viewportHeight,
));
final int frames = await tester.pumpAndSettle();
expect(frames, 1); // ensures that there is no (animated) bouncing of the scrollable
expect(controller.offset, scrollPosition);
expect(find.text('Tile 0'), findsNothing);
expect(find.text('Tile 1'), findsNothing);
expect(find.text('Tile 18'), findsNothing);
expect(find.text('Tile 19'), findsNothing);
expect(find.text('Tile 100'), findsNothing);
expect(find.text('Tile 101'), findsNothing);
expect(find.text('Tile 118'), findsOneWidget);
expect(find.text('Tile 119'), findsOneWidget);
controller.jumpTo(0.0);
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(find.text('Tile 100'), findsOneWidget);
expect(find.text('Tile 101'), findsOneWidget);
expect(find.text('Tile 118'), findsNothing);
expect(find.text('Tile 119'), findsNothing);
});
testWidgets('SliverList replace with shorter children list (with keys)', (WidgetTester tester) async {
final List<int> items = List<int>.generate(20, (int i) => i);
const double itemHeight = 300.0;
const double viewportHeight = 500.0;
final double scrollPosition = items.length * itemHeight - viewportHeight;
final ScrollController controller = ScrollController(initialScrollOffset: scrollPosition);
addTearDown(controller.dispose);
await tester.pumpWidget(_buildSliverList(
items: items,
controller: controller,
itemHeight: itemHeight,
viewportHeight: viewportHeight,
));
await tester.pumpAndSettle();
expect(controller.offset, scrollPosition);
expect(find.text('Tile 0'), findsNothing);
expect(find.text('Tile 1'), findsNothing);
expect(find.text('Tile 17'), findsNothing);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 19'), findsOneWidget);
await tester.pumpWidget(_buildSliverList(
items: items.sublist(0, items.length - 1),
controller: controller,
itemHeight: itemHeight,
viewportHeight: viewportHeight,
));
final int frames = await tester.pumpAndSettle();
expect(frames, 1); // No animation when content shrinks suddenly.
expect(controller.offset, scrollPosition - itemHeight);
expect(find.text('Tile 0'), findsNothing);
expect(find.text('Tile 1'), findsNothing);
expect(find.text('Tile 17'), findsOneWidget);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 19'), findsNothing);
});
testWidgets('SliverList should layout first child in case of child reordering', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/35904.
List<String> items = <String>['1', '2'];
final ScrollController controller1 = ScrollController();
addTearDown(controller1.dispose);
await tester.pumpWidget(_buildSliverListRenderWidgetChild(items, controller1));
await tester.pumpAndSettle();
expect(find.text('Tile 1'), findsOneWidget);
expect(find.text('Tile 2'), findsOneWidget);
items = items.reversed.toList();
final ScrollController controller2 = ScrollController();
addTearDown(controller2.dispose);
await tester.pumpWidget(_buildSliverListRenderWidgetChild(items, controller2));
await tester.pumpAndSettle();
expect(find.text('Tile 1'), findsOneWidget);
expect(find.text('Tile 2'), findsOneWidget);
});
testWidgets('SliverList should recalculate inaccurate layout offset case 1', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/42142.
final List<int> items = List<int>.generate(20, (int i) => i);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
_buildSliverList(
items: List<int>.from(items),
controller: controller,
itemHeight: 50,
viewportHeight: 200,
),
);
await tester.pumpAndSettle();
await tester.drag(find.text('Tile 2'), const Offset(0.0, -1000.0));
await tester.pumpAndSettle();
// Viewport should be scrolled to the end of list.
expect(controller.offset, 800.0);
expect(find.text('Tile 15'), findsNothing);
expect(find.text('Tile 16'), findsOneWidget);
expect(find.text('Tile 17'), findsOneWidget);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 19'), findsOneWidget);
// Prepends item to the list.
items.insert(0, -1);
await tester.pumpWidget(
_buildSliverList(
items: List<int>.from(items),
controller: controller,
itemHeight: 50,
viewportHeight: 200,
),
);
await tester.pump();
// We need second pump to ensure the scheduled animation gets run.
await tester.pumpAndSettle();
// Scroll offset should stay the same, and the items in viewport should be
// shifted by one.
expect(controller.offset, 800.0);
expect(find.text('Tile 14'), findsNothing);
expect(find.text('Tile 15'), findsOneWidget);
expect(find.text('Tile 16'), findsOneWidget);
expect(find.text('Tile 17'), findsOneWidget);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 19'), findsNothing);
// Drags back to beginning and newly added item is visible.
await tester.drag(find.text('Tile 16'), const Offset(0.0, 1000.0));
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(find.text('Tile -1'), findsOneWidget);
expect(find.text('Tile 0'), findsOneWidget);
expect(find.text('Tile 1'), findsOneWidget);
expect(find.text('Tile 2'), findsOneWidget);
expect(find.text('Tile 3'), findsNothing);
});
testWidgets('SliverList should recalculate inaccurate layout offset case 2', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/42142.
final List<int> items = List<int>.generate(20, (int i) => i);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
_buildSliverList(
items: List<int>.from(items),
controller: controller,
itemHeight: 50,
viewportHeight: 200,
),
);
await tester.pumpAndSettle();
await tester.drag(find.text('Tile 2'), const Offset(0.0, -1000.0));
await tester.pumpAndSettle();
// Viewport should be scrolled to the end of list.
expect(controller.offset, 800.0);
expect(find.text('Tile 15'), findsNothing);
expect(find.text('Tile 16'), findsOneWidget);
expect(find.text('Tile 17'), findsOneWidget);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 19'), findsOneWidget);
// Reorders item to the front. This should make item 19 to be first child
// with layout offset = null.
final int swap = items[19];
items[19] = items[3];
items[3] = swap;
await tester.pumpWidget(
_buildSliverList(
items: List<int>.from(items),
controller: controller,
itemHeight: 50,
viewportHeight: 200,
),
);
await tester.pump();
// We need second pump to ensure the scheduled animation gets run.
await tester.pumpAndSettle();
// Scroll offset should stay the same
expect(controller.offset, 800.0);
expect(find.text('Tile 14'), findsNothing);
expect(find.text('Tile 15'), findsNothing);
expect(find.text('Tile 16'), findsOneWidget);
expect(find.text('Tile 17'), findsOneWidget);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 3'), findsOneWidget);
});
testWidgets('SliverList should start to perform layout from the initial child when there is no valid offset', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/66198.
bool isShow = true;
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
Widget buildSliverList(ScrollController controller) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200,
child: ListView(
controller: controller,
children: <Widget>[
if (isShow)
for (int i = 0; i < 20; i++)
SizedBox(
height: 50,
child: Text('Tile $i'),
),
const SizedBox(), // Use this widget to occupy the position where the offset is 0 when rebuild
const SizedBox(key: Key('key0'), height: 50.0),
const SizedBox(key: Key('key1'), height: 50.0),
],
),
),
),
);
}
await tester.pumpWidget(buildSliverList(controller));
await tester.pumpAndSettle();
// Scrolling to the bottom.
await tester.drag(find.text('Tile 2'), const Offset(0.0, -1000.0));
await tester.pumpAndSettle();
// Viewport should be scrolled to the end of list.
expect(controller.offset, 900.0);
expect(find.text('Tile 17'), findsNothing);
expect(find.text('Tile 18'), findsOneWidget);
expect(find.text('Tile 19'), findsOneWidget);
expect(find.byKey(const Key('key0')), findsOneWidget);
expect(find.byKey(const Key('key1')), findsOneWidget);
// Trigger rebuild.
isShow = false;
await tester.pumpWidget(buildSliverList(controller));
// After rebuild, [ContainerRenderObjectMixin] has two children, and
// neither of them has a valid layout offset.
// SliverList can layout normally without any assert or dead loop.
// Only the 'SizeBox' show in the viewport.
expect(controller.offset, 0.0);
expect(find.text('Tile 0'), findsNothing);
expect(find.text('Tile 19'), findsNothing);
expect(find.byKey(const Key('key0')), findsOneWidget);
expect(find.byKey(const Key('key1')), findsOneWidget);
});
}
Widget _buildSliverListRenderWidgetChild(List<String> items, ScrollController controller) {
return MaterialApp(
home: Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: SizedBox(
height: 500,
child: CustomScrollView(
controller: controller,
slivers: <Widget>[
SliverList(
delegate: SliverChildListDelegate(
items.map<Widget>((String item) {
return Chip(
key: Key(item),
label: Text('Tile $item'),
);
}).toList(),
),
),
],
),
),
),
),
);
}
Widget _buildSliverList({
List<int> items = const <int>[],
ScrollController? controller,
double itemHeight = 500.0,
double viewportHeight = 300.0,
}) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: viewportHeight,
child: CustomScrollView(
controller: controller,
slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int i) {
return SizedBox(
key: ValueKey<int>(items[i]),
height: itemHeight,
child: Text('Tile ${items[i]}'),
);
},
findChildIndexCallback: (Key key) {
final ValueKey<int> valueKey = key as ValueKey<int>;
final int index = items.indexOf(valueKey.value);
return index == -1 ? null : index;
},
childCount: items.length,
),
),
],
),
),
),
);
}
| flutter/packages/flutter/test/widgets/sliver_list_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/sliver_list_test.dart",
"repo_id": "flutter",
"token_count": 5696
} | 703 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void verifyPaintPosition(GlobalKey key, Offset ideal) {
final RenderObject target = key.currentContext!.findRenderObject()!;
expect(target.parent, isA<RenderViewport>());
final SliverPhysicalParentData parentData = target.parentData! as SliverPhysicalParentData;
final Offset actual = parentData.paintOffset;
expect(actual, ideal);
}
void main() {
testWidgets('Sliver protocol', (WidgetTester tester) async {
GlobalKey key1, key2, key3, key4, key5;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
BigSliver(key: key1 = GlobalKey()),
OverlappingSliver(key: key2 = GlobalKey()),
OverlappingSliver(key: key3 = GlobalKey()),
BigSliver(key: key4 = GlobalKey()),
BigSliver(key: key5 = GlobalKey()),
],
),
),
);
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
const double max = RenderBigSliver.height * 3.0 + (RenderOverlappingSliver.totalHeight) * 2.0 - 600.0; // 600 is the height of the test viewport
assert(max < 10000.0);
expect(max, 1450.0);
expect(position.pixels, 0.0);
expect(position.minScrollExtent, 0.0);
expect(position.maxScrollExtent, max);
position.animateTo(10000.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 10));
expect(position.pixels, max);
expect(position.minScrollExtent, 0.0);
expect(position.maxScrollExtent, max);
verifyPaintPosition(key1, Offset.zero);
verifyPaintPosition(key2, Offset.zero);
verifyPaintPosition(key3, Offset.zero);
verifyPaintPosition(key4, Offset.zero);
verifyPaintPosition(key5, const Offset(0.0, 50.0));
});
}
class RenderBigSliver extends RenderSliver {
static const double height = 550.0;
double get paintExtent => (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent);
@override
void performLayout() {
geometry = SliverGeometry(
scrollExtent: height,
paintExtent: paintExtent,
maxPaintExtent: height,
);
}
}
class BigSliver extends LeafRenderObjectWidget {
const BigSliver({ super.key });
@override
RenderBigSliver createRenderObject(BuildContext context) {
return RenderBigSliver();
}
}
class RenderOverlappingSliver extends RenderSliver {
static const double totalHeight = 200.0;
static const double fixedHeight = 100.0;
double get paintExtent {
return math.min(
math.max(
fixedHeight,
totalHeight - constraints.scrollOffset,
),
constraints.remainingPaintExtent,
);
}
double get layoutExtent {
return (totalHeight - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent);
}
@override
void performLayout() {
geometry = SliverGeometry(
scrollExtent: totalHeight,
paintExtent: paintExtent,
layoutExtent: layoutExtent,
maxPaintExtent: totalHeight,
);
}
}
class OverlappingSliver extends LeafRenderObjectWidget {
const OverlappingSliver({ super.key });
@override
RenderOverlappingSliver createRenderObject(BuildContext context) {
return RenderOverlappingSliver();
}
}
| flutter/packages/flutter/test/widgets/slivers_protocol_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/slivers_protocol_test.dart",
"repo_id": "flutter",
"token_count": 1366
} | 704 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
const BoxDecoration kBoxDecorationA = BoxDecoration(
color: Color(0xFFFF0000),
);
const BoxDecoration kBoxDecorationB = BoxDecoration(
color: Color(0xFF00FF00),
);
const BoxDecoration kBoxDecorationC = BoxDecoration(
color: Color(0xFF0000FF),
);
class TestBuildCounter extends StatelessWidget {
const TestBuildCounter({ super.key });
static int buildCount = 0;
@override
Widget build(BuildContext context) {
buildCount += 1;
return const DecoratedBox(decoration: kBoxDecorationA);
}
}
class FlipWidget extends StatefulWidget {
const FlipWidget({ super.key, required this.left, required this.right });
final Widget left;
final Widget right;
@override
FlipWidgetState createState() => FlipWidgetState();
}
class FlipWidgetState extends State<FlipWidget> {
bool _showLeft = true;
void flip() {
setState(() {
_showLeft = !_showLeft;
});
}
@override
Widget build(BuildContext context) {
return _showLeft ? widget.left : widget.right;
}
}
void flipStatefulWidget(WidgetTester tester, { bool skipOffstage = true }) {
tester.state<FlipWidgetState>(find.byType(FlipWidget, skipOffstage: skipOffstage)).flip();
}
| flutter/packages/flutter/test/widgets/test_widgets.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/test_widgets.dart",
"repo_id": "flutter",
"token_count": 465
} | 705 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'multi_view_testing.dart';
void main() {
testWidgets('Providing a RenderObjectWidget directly to the RootWidget fails', (WidgetTester tester) async {
// No render tree exists to attach the RenderObjectWidget to.
await tester.pumpWidget(
wrapWithView: false,
const ColoredBox(color: Colors.red),
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
startsWith('The render object for ColoredBox cannot find ancestor render object to attach to.'),
));
});
testWidgets('Moving a RenderObjectWidget to the RootWidget via GlobalKey fails', (WidgetTester tester) async {
final Widget globalKeyedWidget = ColoredBox(
key: GlobalKey(),
color: Colors.red,
);
await tester.pumpWidget(
wrapWithView: false,
View(
view: tester.view,
child: globalKeyedWidget,
),
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(
wrapWithView: false,
globalKeyedWidget,
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
contains('cannot find ancestor render object to attach to.'),
));
});
testWidgets('A View cannot be a child of a render object widget', (WidgetTester tester) async {
await tester.pumpWidget(Center(
child: View(
view: FakeView(tester.view),
child: Container(),
),
));
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
contains('cannot maintain an independent render tree at its current location.'),
));
});
testWidgets('The child of a ViewAnchor cannot be a View', (WidgetTester tester) async {
await tester.pumpWidget(
ViewAnchor(
child: View(
view: FakeView(tester.view),
child: Container(),
),
),
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
contains('cannot maintain an independent render tree at its current location.'),
));
});
testWidgets('A View can not be moved via GlobalKey to be a child of a RenderObject', (WidgetTester tester) async {
final Widget globalKeyedView = View(
key: GlobalKey(),
view: FakeView(tester.view),
child: const ColoredBox(color: Colors.red),
);
await tester.pumpWidget(
wrapWithView: false,
globalKeyedView,
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(
wrapWithView: false,
View(
view: tester.view,
child: globalKeyedView,
),
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
contains('cannot maintain an independent render tree at its current location.'),
));
});
testWidgets('The view property of a ViewAnchor cannot be a render object widget', (WidgetTester tester) async {
await tester.pumpWidget(
ViewAnchor(
view: const ColoredBox(color: Colors.red),
child: Container(),
),
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
startsWith('The render object for ColoredBox cannot find ancestor render object to attach to.'),
));
});
testWidgets('A RenderObject cannot be moved into the view property of a ViewAnchor via GlobalKey', (WidgetTester tester) async {
final Widget globalKeyedWidget = ColoredBox(
key: GlobalKey(),
color: Colors.red,
);
await tester.pumpWidget(
ViewAnchor(
child: globalKeyedWidget,
),
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(
ViewAnchor(
view: globalKeyedWidget,
child: const SizedBox(),
),
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
contains('cannot find ancestor render object to attach to.'),
));
});
testWidgets('ViewAnchor cannot be used at the top of the widget tree (outside of View)', (WidgetTester tester) async {
await tester.pumpWidget(
wrapWithView: false,
const ViewAnchor(
child: SizedBox(),
),
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
startsWith('The render object for SizedBox cannot find ancestor render object to attach to.'),
));
});
testWidgets('ViewAnchor cannot be moved to the top of the widget tree (outside of View) via GlobalKey', (WidgetTester tester) async {
final Widget globalKeyedViewAnchor = ViewAnchor(
key: GlobalKey(),
child: const SizedBox(),
);
await tester.pumpWidget(
wrapWithView: false,
View(
view: tester.view,
child: globalKeyedViewAnchor,
),
);
expect(tester.takeException(), isNull);
await tester.pumpWidget(
wrapWithView: false,
globalKeyedViewAnchor,
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
contains('cannot find ancestor render object to attach to.'),
));
});
testWidgets('View can be used at the top of the widget tree', (WidgetTester tester) async {
await tester.pumpWidget(
wrapWithView: false,
View(
view: tester.view,
child: Container(),
),
);
expect(tester.takeException(), isNull);
});
testWidgets('View can be moved to the top of the widget tree view GlobalKey', (WidgetTester tester) async {
final Widget globalKeyView = View(
view: FakeView(tester.view),
child: const ColoredBox(color: Colors.red),
);
await tester.pumpWidget(
wrapWithView: false,
View(
view: tester.view,
child: ViewAnchor(
view: globalKeyView, // This one has trouble when deactivating
child: const SizedBox(),
),
),
);
expect(tester.takeException(), isNull);
expect(find.byType(SizedBox), findsOneWidget);
expect(find.byType(ColoredBox), findsOneWidget);
await tester.pumpWidget(
wrapWithView: false,
globalKeyView,
);
expect(tester.takeException(), isNull);
expect(find.byType(SizedBox), findsNothing);
expect(find.byType(ColoredBox), findsOneWidget);
});
testWidgets('ViewCollection can be used at the top of the widget tree', (WidgetTester tester) async {
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: tester.view,
child: Container(),
),
],
),
);
expect(tester.takeException(), isNull);
});
testWidgets('ViewCollection cannot be used inside a View', (WidgetTester tester) async {
await tester.pumpWidget(
ViewCollection(
views: <Widget>[
View(
view: FakeView(tester.view),
child: Container(),
),
],
),
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
startsWith('The Element for ViewCollection cannot be inserted into slot "null" of its ancestor.'),
));
});
testWidgets('ViewCollection can be used as ViewAnchor.view', (WidgetTester tester) async {
await tester.pumpWidget(
ViewAnchor(
view: ViewCollection(
views: <Widget>[
View(
view: FakeView(tester.view),
child: Container(),
)
],
),
child: Container(),
),
);
expect(tester.takeException(), isNull);
});
testWidgets('ViewCollection cannot have render object widgets as children', (WidgetTester tester) async {
await tester.pumpWidget(
wrapWithView: false,
const ViewCollection(
views: <Widget>[
ColoredBox(color: Colors.red),
],
),
);
expect(tester.takeException(), isFlutterError.having(
(FlutterError error) => error.message,
'message',
startsWith('The render object for ColoredBox cannot find ancestor render object to attach to.'),
));
});
testWidgets('Views can be moved in and out of ViewCollections via GlobalKey', (WidgetTester tester) async {
final Widget greenView = View(
key: GlobalKey(debugLabel: 'green'),
view: tester.view,
child: const ColoredBox(color: Colors.green),
);
final Widget redView = View(
key: GlobalKey(debugLabel: 'red'),
view: FakeView(tester.view),
child: const ColoredBox(color: Colors.red),
);
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
greenView,
ViewCollection(
views: <Widget>[
redView,
],
),
]
),
);
expect(tester.takeException(), isNull);
expect(find.byType(ColoredBox), findsNWidgets(2));
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
redView,
ViewCollection(
views: <Widget>[
greenView,
],
),
]
),
);
expect(tester.takeException(), isNull);
expect(find.byType(ColoredBox), findsNWidgets(2));
});
testWidgets('Can move stuff between views via global key: viewA -> viewB', (WidgetTester tester) async {
final FlutterView greenView = tester.view;
final FlutterView redView = FakeView(tester.view);
final Widget globalKeyChild = SizedBox(
key: GlobalKey(),
);
Map<int, RenderObject> collectLeafRenderObjects() {
final Map<int, RenderObject> result = <int, RenderObject>{};
for (final RenderView renderView in RendererBinding.instance.renderViews) {
void visit(RenderObject object) {
result[renderView.flutterView.viewId] = object;
object.visitChildren(visit);
}
visit(renderView);
}
return result;
}
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: greenView,
child: ColoredBox(
color: Colors.green,
child: globalKeyChild,
),
),
View(
view: redView,
child: const ColoredBox(
color: Colors.red,
),
),
],
),
);
expect(
find.descendant(
of: findsColoredBox(Colors.green),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(
find.descendant(
of: findsColoredBox(Colors.red),
matching: find.byType(SizedBox),
),
findsNothing,
);
final RenderObject boxWithGlobalKey = tester.renderObject(find.byKey(globalKeyChild.key!));
Map<int, RenderObject> leafRenderObject = collectLeafRenderObjects();
expect(leafRenderObject[greenView.viewId], isA<RenderConstrainedBox>());
expect(leafRenderObject[redView.viewId], isNot(isA<RenderConstrainedBox>()));
// Move the child.
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: greenView,
child: const ColoredBox(
color: Colors.green,
),
),
View(
view: redView,
child: ColoredBox(
color: Colors.red,
child: globalKeyChild,
),
),
],
),
);
expect(
find.descendant(
of: findsColoredBox(Colors.green),
matching: find.byType(SizedBox),
),
findsNothing,
);
expect(
find.descendant(
of: findsColoredBox(Colors.red),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(
tester.renderObject(find.byKey(globalKeyChild.key!)),
equals(boxWithGlobalKey),
);
leafRenderObject = collectLeafRenderObjects();
expect(leafRenderObject[greenView.viewId], isNot(isA<RenderConstrainedBox>()));
expect(leafRenderObject[redView.viewId], isA<RenderConstrainedBox>());
});
testWidgets('Can move stuff between views via global key: viewB -> viewA', (WidgetTester tester) async {
final FlutterView greenView = tester.view;
final FlutterView redView = FakeView(tester.view);
final Widget globalKeyChild = SizedBox(
key: GlobalKey(),
);
Map<int, RenderObject> collectLeafRenderObjects() {
final Map<int, RenderObject> result = <int, RenderObject>{};
for (final RenderView renderView in RendererBinding.instance.renderViews) {
void visit(RenderObject object) {
result[renderView.flutterView.viewId] = object;
object.visitChildren(visit);
}
visit(renderView);
}
return result;
}
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: greenView,
child: const ColoredBox(
color: Colors.green,
),
),
View(
view: redView,
child: ColoredBox(
color: Colors.red,
child: globalKeyChild,
),
),
],
),
);
expect(
find.descendant(
of: findsColoredBox(Colors.red),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(
find.descendant(
of: findsColoredBox(Colors.green),
matching: find.byType(SizedBox),
),
findsNothing,
);
final RenderObject boxWithGlobalKey = tester.renderObject(find.byKey(globalKeyChild.key!));
Map<int, RenderObject> leafRenderObject = collectLeafRenderObjects();
expect(leafRenderObject[redView.viewId], isA<RenderConstrainedBox>());
expect(leafRenderObject[greenView.viewId], isNot(isA<RenderConstrainedBox>()));
// Move the child.
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: greenView,
child: ColoredBox(
color: Colors.green,
child: globalKeyChild,
),
),
View(
view: redView,
child: const ColoredBox(
color: Colors.red,
),
),
],
),
);
expect(
find.descendant(
of: findsColoredBox(Colors.red),
matching: find.byType(SizedBox),
),
findsNothing,
);
expect(
find.descendant(
of: findsColoredBox(Colors.green),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(
tester.renderObject(find.byKey(globalKeyChild.key!)),
equals(boxWithGlobalKey),
);
leafRenderObject = collectLeafRenderObjects();
expect(leafRenderObject[redView.viewId], isNot(isA<RenderConstrainedBox>()));
expect(leafRenderObject[greenView.viewId], isA<RenderConstrainedBox>());
});
testWidgets('Can move stuff out of a view that is going away, viewA -> ViewB', (WidgetTester tester) async {
final FlutterView greenView = tester.view;
final Key greenKey = UniqueKey();
final FlutterView redView = FakeView(tester.view);
final Key redKey = UniqueKey();
final Widget globalKeyChild = SizedBox(
key: GlobalKey(),
);
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
key: greenKey,
view: greenView,
child: const ColoredBox(
color: Colors.green,
),
),
View(
key: redKey,
view: redView,
child: ColoredBox(
color: Colors.red,
child: globalKeyChild,
),
),
],
),
);
expect(
find.descendant(
of: findsColoredBox(Colors.red),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(
find.descendant(
of: findsColoredBox(Colors.green),
matching: find.byType(SizedBox),
),
findsNothing,
);
final RenderObject boxWithGlobalKey = tester.renderObject(find.byKey(globalKeyChild.key!));
// Move the child and remove its view.
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
key: greenKey,
view: greenView,
child: ColoredBox(
color: Colors.green,
child: globalKeyChild,
),
),
],
),
);
expect(
findsColoredBox(Colors.red),
findsNothing,
);
expect(
find.descendant(
of: findsColoredBox(Colors.green),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(
tester.renderObject(find.byKey(globalKeyChild.key!)),
equals(boxWithGlobalKey),
);
});
testWidgets('Can move stuff out of a view that is going away, viewB -> ViewA', (WidgetTester tester) async {
final FlutterView greenView = tester.view;
final Key greenKey = UniqueKey();
final FlutterView redView = FakeView(tester.view);
final Key redKey = UniqueKey();
final Widget globalKeyChild = SizedBox(
key: GlobalKey(),
);
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
key: greenKey,
view: greenView,
child: ColoredBox(
color: Colors.green,
child: globalKeyChild,
),
),
View(
key: redKey,
view: redView,
child: const ColoredBox(
color: Colors.red,
),
),
],
),
);
expect(
find.descendant(
of: findsColoredBox(Colors.green),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(
find.descendant(
of: findsColoredBox(Colors.red),
matching: find.byType(SizedBox),
),
findsNothing,
);
final RenderObject boxWithGlobalKey = tester.renderObject(find.byKey(globalKeyChild.key!));
// Move the child and remove its view.
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
key: redKey,
view: redView,
child: ColoredBox(
color: Colors.red,
child: globalKeyChild,
),
),
],
),
);
expect(
findsColoredBox(Colors.green),
findsNothing,
);
expect(
find.descendant(
of: findsColoredBox(Colors.red),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(
tester.renderObject(find.byKey(globalKeyChild.key!)),
equals(boxWithGlobalKey),
);
});
testWidgets('Can move stuff out of a view that is moving itself, stuff ends up before view', (WidgetTester tester) async {
final Key key1 = UniqueKey();
final Key key2 = UniqueKey();
final Key key3 = UniqueKey();
final Key key4 = UniqueKey();
final GlobalKey viewKey = GlobalKey();
final GlobalKey childKey = GlobalKey();
await tester.pumpWidget(Column(
children: <Widget>[
SizedBox(key: key1),
ViewAnchor(
key: key2,
view: View(
key: viewKey,
view: FakeView(tester.view),
child: SizedBox(
child: ColoredBox(
key: childKey,
color: Colors.green,
),
),
),
child: const SizedBox(),
),
ViewAnchor(
key: key3,
child: const SizedBox(),
),
SizedBox(key: key4),
],
));
await tester.pumpWidget(Column(
children: <Widget>[
SizedBox(
key: key1,
child: ColoredBox(
key: childKey,
color: Colors.green,
),
),
ViewAnchor(
key: key2,
child: const SizedBox(),
),
ViewAnchor(
key: key3,
view: View(
key: viewKey,
view: FakeView(tester.view),
child: const SizedBox(),
),
child: const SizedBox(),
),
SizedBox(key: key4),
],
));
await tester.pumpWidget(Column(
children: <Widget>[
SizedBox(key: key1),
ViewAnchor(
key: key2,
view: View(
key: viewKey,
view: FakeView(tester.view),
child: SizedBox(
child: ColoredBox(
key: childKey,
color: Colors.green,
),
),
),
child: const SizedBox(),
),
ViewAnchor(
key: key3,
child: const SizedBox(),
),
SizedBox(key: key4),
],
));
});
testWidgets('Can move stuff out of a view that is moving itself, stuff ends up after view', (WidgetTester tester) async {
final Key key1 = UniqueKey();
final Key key2 = UniqueKey();
final Key key3 = UniqueKey();
final Key key4 = UniqueKey();
final GlobalKey viewKey = GlobalKey();
final GlobalKey childKey = GlobalKey();
await tester.pumpWidget(Column(
children: <Widget>[
SizedBox(key: key1),
ViewAnchor(
key: key2,
view: View(
key: viewKey,
view: FakeView(tester.view),
child: SizedBox(
child: ColoredBox(
key: childKey,
color: Colors.green,
),
),
),
child: const SizedBox(),
),
ViewAnchor(
key: key3,
child: const SizedBox(),
),
SizedBox(key: key4),
],
));
await tester.pumpWidget(Column(
children: <Widget>[
SizedBox(
key: key1,
),
ViewAnchor(
key: key2,
child: const SizedBox(),
),
ViewAnchor(
key: key3,
view: View(
key: viewKey,
view: FakeView(tester.view),
child: const SizedBox(),
),
child: const SizedBox(),
),
SizedBox(
key: key4,
child: ColoredBox(
key: childKey,
color: Colors.green,
),
),
],
));
await tester.pumpWidget(Column(
children: <Widget>[
SizedBox(key: key1),
ViewAnchor(
key: key2,
view: View(
key: viewKey,
view: FakeView(tester.view),
child: SizedBox(
child: ColoredBox(
key: childKey,
color: Colors.green,
),
),
),
child: const SizedBox(),
),
ViewAnchor(
key: key3,
child: const SizedBox(),
),
SizedBox(key: key4),
],
));
});
testWidgets('Can globalkey move down the tree from a view that is going away', (WidgetTester tester) async {
final FlutterView anchorView = FakeView(tester.view);
final Widget globalKeyChild = SizedBox(
key: GlobalKey(),
);
await tester.pumpWidget(
ColoredBox(
color: Colors.green,
child: ViewAnchor(
view: View(
view: anchorView,
child: ColoredBox(
color: Colors.yellow,
child: globalKeyChild,
),
),
child: const ColoredBox(color: Colors.red),
),
),
);
expect(findsColoredBox(Colors.green), findsOneWidget);
expect(findsColoredBox(Colors.yellow), findsOneWidget);
expect(
find.descendant(
of: findsColoredBox(Colors.yellow),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(findsColoredBox(Colors.red), findsOneWidget);
expect(
find.descendant(
of: findsColoredBox(Colors.red),
matching: find.byType(SizedBox),
),
findsNothing,
);
expect(find.byType(SizedBox), findsOneWidget);
final RenderObject boxWithGlobalKey = tester.renderObject(find.byKey(globalKeyChild.key!));
await tester.pumpWidget(
ColoredBox(
color: Colors.green,
child: ViewAnchor(
child: ColoredBox(
color: Colors.red,
child: globalKeyChild,
),
),
),
);
expect(findsColoredBox(Colors.green), findsOneWidget);
expect(findsColoredBox(Colors.yellow), findsNothing);
expect(
find.descendant(
of: findsColoredBox(Colors.yellow),
matching: find.byType(SizedBox),
),
findsNothing,
);
expect(findsColoredBox(Colors.red), findsOneWidget);
expect(
find.descendant(
of: findsColoredBox(Colors.red),
matching: find.byType(SizedBox),
),
findsOneWidget,
);
expect(find.byType(SizedBox), findsOneWidget);
expect(
tester.renderObject(find.byKey(globalKeyChild.key!)),
boxWithGlobalKey,
);
});
testWidgets('RenderObjects are disposed when a view goes away from a ViewAnchor', (WidgetTester tester) async {
final FlutterView anchorView = FakeView(tester.view);
await tester.pumpWidget(
ColoredBox(
color: Colors.green,
child: ViewAnchor(
view: View(
view: anchorView,
child: const ColoredBox(color: Colors.yellow),
),
child: const ColoredBox(color: Colors.red),
),
),
);
final RenderObject box = tester.renderObject(findsColoredBox(Colors.yellow));
await tester.pumpWidget(
const ColoredBox(
color: Colors.green,
child: ViewAnchor(
child: ColoredBox(color: Colors.red),
),
),
);
expect(box.debugDisposed, isTrue);
});
testWidgets('RenderObjects are disposed when a view goes away from a ViewCollection', (WidgetTester tester) async {
final FlutterView redView = tester.view;
final FlutterView greenView = FakeView(tester.view);
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: redView,
child: const ColoredBox(color: Colors.red),
),
View(
view: greenView,
child: const ColoredBox(color: Colors.green),
),
],
),
);
expect(findsColoredBox(Colors.green), findsOneWidget);
expect(findsColoredBox(Colors.red), findsOneWidget);
final RenderObject box = tester.renderObject(findsColoredBox(Colors.green));
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: redView,
child: const ColoredBox(color: Colors.red),
),
],
),
);
expect(findsColoredBox(Colors.green), findsNothing);
expect(findsColoredBox(Colors.red), findsOneWidget);
expect(box.debugDisposed, isTrue);
});
testWidgets('View can be wrapped and unwrapped', (WidgetTester tester) async {
final Widget view = View(
view: tester.view,
child: const SizedBox(),
);
await tester.pumpWidget(
wrapWithView: false,
view,
);
final RenderObject renderView = tester.renderObject(find.byType(View));
final RenderObject renderSizedBox = tester.renderObject(find.byType(SizedBox));
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[view],
),
);
expect(tester.renderObject(find.byType(View)), same(renderView));
expect(tester.renderObject(find.byType(SizedBox)), same(renderSizedBox));
await tester.pumpWidget(
wrapWithView: false,
view,
);
expect(tester.renderObject(find.byType(View)), same(renderView));
expect(tester.renderObject(find.byType(SizedBox)), same(renderSizedBox));
});
testWidgets('ViewAnchor with View can be wrapped and unwrapped', (WidgetTester tester) async {
final Widget viewAnchor = ViewAnchor(
view: View(
view: FakeView(tester.view),
child: const SizedBox(),
),
child: const ColoredBox(color: Colors.green),
);
await tester.pumpWidget(viewAnchor);
final List<RenderObject> renderViews = tester.renderObjectList(find.byType(View)).toList();
final RenderObject renderSizedBox = tester.renderObject(find.byType(SizedBox));
await tester.pumpWidget(ColoredBox(color: Colors.yellow, child: viewAnchor));
expect(tester.renderObjectList(find.byType(View)), renderViews);
expect(tester.renderObject(find.byType(SizedBox)), same(renderSizedBox));
await tester.pumpWidget(viewAnchor);
expect(tester.renderObjectList(find.byType(View)), renderViews);
expect(tester.renderObject(find.byType(SizedBox)), same(renderSizedBox));
});
testWidgets('Moving a View keeps its semantics tree stable', (WidgetTester tester) async {
final Widget view = View(
// No explicit key, we rely on the implicit key of the underlying RawView.
view: tester.view,
child: Semantics(
textDirection: TextDirection.ltr,
label: 'Hello',
child: const SizedBox(),
)
);
await tester.pumpWidget(
wrapWithView: false,
view,
);
final RenderObject renderSemantics = tester.renderObject(find.bySemanticsLabel('Hello'));
final SemanticsNode semantics = tester.getSemantics(find.bySemanticsLabel('Hello'));
expect(semantics.id, 1);
expect(renderSemantics.debugSemantics, same(semantics));
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
view,
],
),
);
final RenderObject renderSemanticsAfterMove = tester.renderObject(find.bySemanticsLabel('Hello'));
final SemanticsNode semanticsAfterMove = tester.getSemantics(find.bySemanticsLabel('Hello'));
expect(renderSemanticsAfterMove, same(renderSemantics));
expect(semanticsAfterMove.id, 1);
expect(semanticsAfterMove, same(semantics));
});
}
Finder findsColoredBox(Color color) {
return find.byWidgetPredicate((Widget widget) => widget is ColoredBox && widget.color == color);
}
| flutter/packages/flutter/test/widgets/tree_shape_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/tree_shape_test.dart",
"repo_id": "flutter",
"token_count": 14067
} | 706 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void verify(WidgetTester tester, List<Offset> answerKey) {
final List<Offset> testAnswers = tester.renderObjectList<RenderBox>(find.byType(SizedBox)).map<Offset>(
(RenderBox target) => target.localToGlobal(Offset.zero),
).toList();
expect(testAnswers, equals(answerKey));
}
void main() {
testWidgets('Basic Wrap test (LTR)', (WidgetTester tester) async {
await tester.pumpWidget(
const Wrap(
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
],
),
);
verify(tester, <Offset>[
Offset.zero,
const Offset(300.0, 0.0),
const Offset(0.0, 100.0),
const Offset(300.0, 100.0),
]);
await tester.pumpWidget(
const Wrap(
alignment: WrapAlignment.center,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
],
),
);
verify(tester, <Offset>[
const Offset(100.0, 0.0),
const Offset(400.0, 0.0),
const Offset(100.0, 100.0),
const Offset(400.0, 100.0),
]);
await tester.pumpWidget(
const Wrap(
alignment: WrapAlignment.end,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
],
),
);
verify(tester, <Offset>[
const Offset(200.0, 0.0),
const Offset(500.0, 0.0),
const Offset(200.0, 100.0),
const Offset(500.0, 100.0),
]);
await tester.pumpWidget(
const Wrap(
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 300.0, height: 50.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 50.0),
],
),
);
verify(tester, <Offset>[
Offset.zero,
const Offset(300.0, 0.0),
const Offset(0.0, 100.0),
const Offset(300.0, 100.0),
]);
await tester.pumpWidget(
const Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 300.0, height: 50.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 50.0),
],
),
);
verify(tester, <Offset>[
const Offset(0.0, 25.0),
const Offset(300.0, 0.0),
const Offset(0.0, 100.0),
const Offset(300.0, 125.0),
]);
await tester.pumpWidget(
const Wrap(
crossAxisAlignment: WrapCrossAlignment.end,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 300.0, height: 50.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 50.0),
],
),
);
verify(tester, <Offset>[
const Offset(0.0, 50.0),
const Offset(300.0, 0.0),
const Offset(0.0, 100.0),
const Offset(300.0, 150.0),
]);
});
testWidgets('Basic Wrap test (RTL)', (WidgetTester tester) async {
await tester.pumpWidget(
const Wrap(
textDirection: TextDirection.rtl,
children: <Widget>[
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
],
),
);
verify(tester, <Offset>[
const Offset(500.0, 0.0),
const Offset(200.0, 0.0),
const Offset(500.0, 100.0),
const Offset(200.0, 100.0),
]);
await tester.pumpWidget(
const Wrap(
alignment: WrapAlignment.center,
textDirection: TextDirection.rtl,
children: <Widget>[
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
],
),
);
verify(tester, <Offset>[
const Offset(400.0, 0.0),
const Offset(100.0, 0.0),
const Offset(400.0, 100.0),
const Offset(100.0, 100.0),
]);
await tester.pumpWidget(
const Wrap(
alignment: WrapAlignment.end,
textDirection: TextDirection.rtl,
children: <Widget>[
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
],
),
);
verify(tester, <Offset>[
const Offset(300.0, 0.0),
Offset.zero,
const Offset(300.0, 100.0),
const Offset(0.0, 100.0),
]);
await tester.pumpWidget(
const Wrap(
textDirection: TextDirection.ltr,
verticalDirection: VerticalDirection.up,
children: <Widget>[
SizedBox(width: 300.0, height: 50.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 50.0),
],
),
);
verify(tester, <Offset>[
const Offset(0.0, 550.0),
const Offset(300.0, 500.0),
const Offset(0.0, 400.0),
const Offset(300.0, 450.0),
]);
await tester.pumpWidget(
const Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
textDirection: TextDirection.ltr,
verticalDirection: VerticalDirection.up,
children: <Widget>[
SizedBox(width: 300.0, height: 50.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 50.0),
],
),
);
verify(tester, <Offset>[
const Offset(0.0, 525.0),
const Offset(300.0, 500.0),
const Offset(0.0, 400.0),
const Offset(300.0, 425.0),
]);
await tester.pumpWidget(
const Wrap(
crossAxisAlignment: WrapCrossAlignment.end,
textDirection: TextDirection.ltr,
verticalDirection: VerticalDirection.up,
children: <Widget>[
SizedBox(width: 300.0, height: 50.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 100.0),
SizedBox(width: 300.0, height: 50.0),
],
),
);
verify(tester, <Offset>[
const Offset(0.0, 500.0),
const Offset(300.0, 500.0),
const Offset(0.0, 400.0),
const Offset(300.0, 400.0),
]);
});
testWidgets('Empty wrap', (WidgetTester tester) async {
await tester.pumpWidget(const Center(child: Wrap(alignment: WrapAlignment.center)));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(Size.zero));
});
testWidgets('Wrap alignment (LTR)', (WidgetTester tester) async {
await tester.pumpWidget(const Wrap(
alignment: WrapAlignment.center,
spacing: 5.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(95.0, 0.0),
const Offset(200.0, 0.0),
const Offset(405.0, 0.0),
]);
await tester.pumpWidget(const Wrap(
alignment: WrapAlignment.spaceBetween,
spacing: 5.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
Offset.zero,
const Offset(200.0, 0.0),
const Offset(500.0, 0.0),
]);
await tester.pumpWidget(const Wrap(
alignment: WrapAlignment.spaceAround,
spacing: 5.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 310.0, height: 30.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(30.0, 0.0),
const Offset(195.0, 0.0),
const Offset(460.0, 0.0),
]);
await tester.pumpWidget(const Wrap(
alignment: WrapAlignment.spaceEvenly,
spacing: 5.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 310.0, height: 30.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(45.0, 0.0),
const Offset(195.0, 0.0),
const Offset(445.0, 0.0),
]);
});
testWidgets('Wrap alignment (RTL)', (WidgetTester tester) async {
await tester.pumpWidget(const Wrap(
alignment: WrapAlignment.center,
spacing: 5.0,
textDirection: TextDirection.rtl,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(605.0, 0.0),
const Offset(400.0, 0.0),
const Offset(95.0, 0.0),
]);
await tester.pumpWidget(const Wrap(
alignment: WrapAlignment.spaceBetween,
spacing: 5.0,
textDirection: TextDirection.rtl,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(700.0, 0.0),
const Offset(400.0, 0.0),
Offset.zero,
]);
await tester.pumpWidget(const Wrap(
alignment: WrapAlignment.spaceAround,
spacing: 5.0,
textDirection: TextDirection.rtl,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 310.0, height: 30.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(670.0, 0.0),
const Offset(405.0, 0.0),
const Offset(30.0, 0.0),
]);
await tester.pumpWidget(const Wrap(
alignment: WrapAlignment.spaceEvenly,
spacing: 5.0,
textDirection: TextDirection.rtl,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 310.0, height: 30.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(655.0, 0.0),
const Offset(405.0, 0.0),
const Offset(45.0, 0.0),
]);
});
testWidgets('Wrap runAlignment (DOWN)', (WidgetTester tester) async {
await tester.pumpWidget(const Wrap(
runAlignment: WrapAlignment.center,
runSpacing: 5.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 400.0, height: 40.0),
SizedBox(width: 500.0, height: 60.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(0.0, 230.0),
const Offset(100.0, 230.0),
const Offset(300.0, 230.0),
const Offset(0.0, 265.0),
const Offset(0.0, 310.0),
]);
await tester.pumpWidget(const Wrap(
runAlignment: WrapAlignment.spaceBetween,
runSpacing: 5.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 400.0, height: 40.0),
SizedBox(width: 500.0, height: 60.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
Offset.zero,
const Offset(100.0, 0.0),
const Offset(300.0, 0.0),
const Offset(0.0, 265.0),
const Offset(0.0, 540.0),
]);
await tester.pumpWidget(const Wrap(
runAlignment: WrapAlignment.spaceAround,
runSpacing: 5.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 400.0, height: 40.0),
SizedBox(width: 500.0, height: 70.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(0.0, 75.0),
const Offset(100.0, 75.0),
const Offset(300.0, 75.0),
const Offset(0.0, 260.0),
const Offset(0.0, 455.0),
]);
await tester.pumpWidget(const Wrap(
runAlignment: WrapAlignment.spaceEvenly,
runSpacing: 5.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 400.0, height: 40.0),
SizedBox(width: 500.0, height: 60.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(0.0, 115.0),
const Offset(100.0, 115.0),
const Offset(300.0, 115.0),
const Offset(0.0, 265.0),
const Offset(0.0, 425.0),
]);
});
testWidgets('Wrap runAlignment (UP)', (WidgetTester tester) async {
await tester.pumpWidget(const Wrap(
runAlignment: WrapAlignment.center,
runSpacing: 5.0,
textDirection: TextDirection.ltr,
verticalDirection: VerticalDirection.up,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 400.0, height: 40.0),
SizedBox(width: 500.0, height: 60.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(0.0, 360.0),
const Offset(100.0, 350.0),
const Offset(300.0, 340.0),
const Offset(0.0, 295.0),
const Offset(0.0, 230.0),
]);
await tester.pumpWidget(const Wrap(
runAlignment: WrapAlignment.spaceBetween,
runSpacing: 5.0,
textDirection: TextDirection.ltr,
verticalDirection: VerticalDirection.up,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 400.0, height: 40.0),
SizedBox(width: 500.0, height: 60.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(0.0, 590.0),
const Offset(100.0, 580.0),
const Offset(300.0, 570.0),
const Offset(0.0, 295.0),
Offset.zero,
]);
await tester.pumpWidget(const Wrap(
runAlignment: WrapAlignment.spaceAround,
runSpacing: 5.0,
textDirection: TextDirection.ltr,
verticalDirection: VerticalDirection.up,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 400.0, height: 40.0),
SizedBox(width: 500.0, height: 70.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(0.0, 515.0),
const Offset(100.0, 505.0),
const Offset(300.0, 495.0),
const Offset(0.0, 300.0),
const Offset(0.0, 75.0),
]);
await tester.pumpWidget(const Wrap(
runAlignment: WrapAlignment.spaceEvenly,
runSpacing: 5.0,
textDirection: TextDirection.ltr,
verticalDirection: VerticalDirection.up,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 400.0, height: 40.0),
SizedBox(width: 500.0, height: 60.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
const Offset(0.0, 475.0),
const Offset(100.0, 465.0),
const Offset(300.0, 455.0),
const Offset(0.0, 295.0),
const Offset(0.0, 115.0),
]);
});
testWidgets('Shrink-wrapping Wrap test', (WidgetTester tester) async {
await tester.pumpWidget(
const Align(
alignment: Alignment.topLeft,
child: Wrap(
alignment: WrapAlignment.end,
crossAxisAlignment: WrapCrossAlignment.end,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 100.0, height: 10.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 400.0, height: 40.0),
],
),
),
);
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(600.0, 70.0)));
verify(tester, <Offset>[
const Offset(0.0, 20.0),
const Offset(100.0, 10.0),
const Offset(300.0, 0.0),
const Offset(200.0, 30.0),
]);
await tester.pumpWidget(
const Align(
alignment: Alignment.topLeft,
child: Wrap(
alignment: WrapAlignment.end,
crossAxisAlignment: WrapCrossAlignment.end,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 400.0, height: 40.0),
SizedBox(width: 300.0, height: 30.0),
SizedBox(width: 200.0, height: 20.0),
SizedBox(width: 100.0, height: 10.0),
],
),
),
);
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(700.0, 60.0)));
verify(tester, <Offset>[
Offset.zero,
const Offset(400.0, 10.0),
const Offset(400.0, 40.0),
const Offset(600.0, 50.0),
]);
});
testWidgets('Wrap spacing test', (WidgetTester tester) async {
await tester.pumpWidget(
const Align(
alignment: Alignment.topLeft,
child: Wrap(
runSpacing: 10.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 500.0, height: 10.0),
SizedBox(width: 500.0, height: 20.0),
SizedBox(width: 500.0, height: 30.0),
SizedBox(width: 500.0, height: 40.0),
],
),
),
);
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(500.0, 130.0)));
verify(tester, <Offset>[
Offset.zero,
const Offset(0.0, 20.0),
const Offset(0.0, 50.0),
const Offset(0.0, 90.0),
]);
});
testWidgets('Vertical Wrap test with spacing', (WidgetTester tester) async {
await tester.pumpWidget(
const Align(
alignment: Alignment.topLeft,
child: Wrap(
direction: Axis.vertical,
spacing: 10.0,
runSpacing: 15.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 10.0, height: 250.0),
SizedBox(width: 20.0, height: 250.0),
SizedBox(width: 30.0, height: 250.0),
SizedBox(width: 40.0, height: 250.0),
SizedBox(width: 50.0, height: 250.0),
SizedBox(width: 60.0, height: 250.0),
],
),
),
);
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(150.0, 510.0)));
verify(tester, <Offset>[
Offset.zero,
const Offset(0.0, 260.0),
const Offset(35.0, 0.0),
const Offset(35.0, 260.0),
const Offset(90.0, 0.0),
const Offset(90.0, 260.0),
]);
await tester.pumpWidget(
const Align(
alignment: Alignment.topLeft,
child: Wrap(
spacing: 12.0,
runSpacing: 8.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 10.0, height: 250.0),
SizedBox(width: 20.0, height: 250.0),
SizedBox(width: 30.0, height: 250.0),
SizedBox(width: 40.0, height: 250.0),
SizedBox(width: 50.0, height: 250.0),
SizedBox(width: 60.0, height: 250.0),
],
),
),
);
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(270.0, 250.0)));
verify(tester, <Offset>[
Offset.zero,
const Offset(22.0, 0.0),
const Offset(54.0, 0.0),
const Offset(96.0, 0.0),
const Offset(148.0, 0.0),
const Offset(210.0, 0.0),
]);
});
testWidgets('Visual overflow generates a clip', (WidgetTester tester) async {
await tester.pumpWidget(const Wrap(
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 500.0, height: 500.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)), isNot(paints..clipRect()));
await tester.pumpWidget(const Wrap(
textDirection: TextDirection.ltr,
clipBehavior: Clip.hardEdge,
children: <Widget>[
SizedBox(width: 500.0, height: 500.0),
SizedBox(width: 500.0, height: 500.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)), paints..clipRect());
});
testWidgets('Hit test children in wrap', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(Wrap(
spacing: 10.0,
runSpacing: 15.0,
textDirection: TextDirection.ltr,
children: <Widget>[
const SizedBox(width: 200.0, height: 300.0),
const SizedBox(width: 200.0, height: 300.0),
const SizedBox(width: 200.0, height: 300.0),
const SizedBox(width: 200.0, height: 300.0),
SizedBox(
width: 200.0,
height: 300.0,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () { log.add('hit'); },
),
),
],
));
await tester.tapAt(const Offset(209.0, 314.0));
expect(log, isEmpty);
await tester.tapAt(const Offset(211.0, 314.0));
expect(log, isEmpty);
await tester.tapAt(const Offset(209.0, 316.0));
expect(log, isEmpty);
await tester.tapAt(const Offset(211.0, 316.0));
expect(log, equals(<String>['hit']));
});
testWidgets('RenderWrap toStringShallow control test', (WidgetTester tester) async {
await tester.pumpWidget(const Wrap(alignment: WrapAlignment.center));
final RenderBox wrap = tester.renderObject(find.byType(Wrap));
expect(wrap.toStringShallow(), hasOneLineDescription);
});
testWidgets('RenderWrap toString control test', (WidgetTester tester) async {
await tester.pumpWidget(const Wrap(
direction: Axis.vertical,
runSpacing: 7.0,
textDirection: TextDirection.ltr,
children: <Widget>[
SizedBox(width: 500.0, height: 400.0),
SizedBox(width: 500.0, height: 400.0),
SizedBox(width: 500.0, height: 400.0),
SizedBox(width: 500.0, height: 400.0),
],
));
final RenderBox wrap = tester.renderObject(find.byType(Wrap));
final double width = wrap.getMinIntrinsicWidth(600.0);
expect(width, equals(2021));
});
testWidgets('Wrap baseline control test', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: Baseline(
baseline: 175.0,
baselineType: TextBaseline.alphabetic,
child: DefaultTextStyle(
style: TextStyle(
fontFamily: 'FlutterTest',
fontSize: 100.0,
),
child: Wrap(
textDirection: TextDirection.ltr,
children: <Widget>[
Text('X', textDirection: TextDirection.ltr),
],
),
),
),
),
);
expect(tester.renderObject<RenderBox>(find.text('X')).size, const Size(100.0, 100.0));
expect(
tester.renderObject<RenderBox>(find.byType(Baseline)).size,
const Size(100.0, 200.0),
);
});
testWidgets('Spacing with slight overflow', (WidgetTester tester) async {
await tester.pumpWidget(const Wrap(
textDirection: TextDirection.ltr,
spacing: 10.0,
runSpacing: 10.0,
children: <Widget>[
SizedBox(width: 200.0, height: 10.0),
SizedBox(width: 200.0, height: 10.0),
SizedBox(width: 200.0, height: 10.0),
SizedBox(width: 171.0, height: 10.0),
],
));
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 600.0)));
verify(tester, <Offset>[
Offset.zero,
const Offset(210.0, 0.0),
const Offset(420.0, 0.0),
const Offset(0.0, 20.0),
]);
});
testWidgets('Object exactly matches container width', (WidgetTester tester) async {
await tester.pumpWidget(
const Column(
children: <Widget>[
Wrap(
textDirection: TextDirection.ltr,
spacing: 10.0,
runSpacing: 10.0,
children: <Widget>[
SizedBox(width: 800.0, height: 10.0),
],
),
],
),
);
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 10.0)));
verify(tester, <Offset>[Offset.zero]);
await tester.pumpWidget(
const Column(
children: <Widget>[
Wrap(
textDirection: TextDirection.ltr,
spacing: 10.0,
runSpacing: 10.0,
children: <Widget>[
SizedBox(width: 800.0, height: 10.0),
SizedBox(width: 800.0, height: 10.0),
],
),
],
),
);
expect(tester.renderObject<RenderBox>(find.byType(Wrap)).size, equals(const Size(800.0, 30.0)));
verify(tester, <Offset>[
Offset.zero,
const Offset(0.0, 20.0),
]);
});
testWidgets('Wrap can set and update clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(const Wrap(textDirection: TextDirection.ltr));
final RenderWrap renderObject = tester.allRenderObjects.whereType<RenderWrap>().first;
expect(renderObject.clipBehavior, equals(Clip.none));
await tester.pumpWidget(const Wrap(textDirection: TextDirection.ltr, clipBehavior: Clip.antiAlias));
expect(renderObject.clipBehavior, equals(Clip.antiAlias));
});
testWidgets('Horizontal wrap - IntrinsicsHeight', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/48679.
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IntrinsicHeight(
child: ColoredBox(
color: Colors.green,
child: Wrap(
children: <Widget>[
Text('Start', style: TextStyle(height: 1.0, fontSize: 16)),
Row(
children: <Widget>[
SizedBox(height: 40, width: 60),
],
),
Text('End', style: TextStyle(height: 1.0, fontSize: 16)),
],
),
),
),
),
),
);
// The row takes up the full width, therefore the "Start" and "End" text
// are placed before and after it and the total height is the sum of the
// individual heights.
expect(tester.getSize(find.byType(IntrinsicHeight)).height, 2 * 16 + 40);
});
testWidgets('Vertical wrap - IntrinsicsWidth', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/48679.
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: IntrinsicWidth(
child: ColoredBox(
color: Colors.green,
child: Wrap(
direction: Axis.vertical,
children: <Widget>[
Text('Start', style: TextStyle(height: 1.0, fontSize: 16)),
Column(
children: <Widget>[
SizedBox(height: 40, width: 60),
],
),
Text('End', style: TextStyle(height: 1.0, fontSize: 16)),
],
),
),
),
),
),
);
// The column takes up the full height, therefore the "Start" and "End" text
// are placed to the left and right of it and the total width is the sum of
// the individual widths.
expect(tester.getSize(find.byType(IntrinsicWidth)).width, 5 * 16 + 60 + 3 * 16);
});
}
| flutter/packages/flutter/test/widgets/wrap_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/wrap_test.dart",
"repo_id": "flutter",
"token_count": 14806
} | 707 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
void main() {
// Changes made in https://github.com/flutter/flutter/pull/122446
final clipboardData1 = ClipboardData();
final clipboardData2 = ClipboardData(text: null);
// Changes made in https://github.com/flutter/flutter/pull/60320
final SurfaceAndroidViewController surfaceController = SurfaceAndroidViewController(
viewId: 10,
viewType: 'FixTester',
layoutDirection: TextDirection.ltr,
);
int viewId = surfaceController.id;
final SurfaceAndroidViewController surfaceController = SurfaceAndroidViewController(
error: '',
);
final TextureAndroidViewController textureController = TextureAndroidViewController(
error: '',
);
final TextureAndroidViewController textureController = TextureAndroidViewController(
viewId: 10,
viewType: 'FixTester',
layoutDirection: TextDirection.ltr,
);
viewId = textureController.id;
// Changes made in https://github.com/flutter/flutter/pull/81303
await SystemChrome.setEnabledSystemUIOverlays(<SystemUiOverlay>[SystemUiOverlay.top]);
await SystemChrome.setEnabledSystemUIOverlays(<SystemUiOverlay>[SystemUiOverlay.bottom]);
await SystemChrome.setEnabledSystemUIOverlays(<SystemUiOverlay>[SystemUiOverlay.top, SystemUiOverlay.bottom]);
await SystemChrome.setEnabledSystemUIOverlays(<SystemUiOverlay>[]);
await SystemChrome.setEnabledSystemUIOverlays(error: '');
}
| flutter/packages/flutter/test_fixes/services/services.dart/0 | {
"file_path": "flutter/packages/flutter/test_fixes/services/services.dart",
"repo_id": "flutter",
"token_count": 484
} | 708 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:fuchsia_remote_debug_protocol/fuchsia_remote_debug_protocol.dart';
import 'error.dart';
class _DummyPortForwarder implements PortForwarder {
_DummyPortForwarder(this._port, this._remotePort);
final int _port;
final int _remotePort;
@override
int get port => _port;
@override
int get remotePort => _remotePort;
@override
String get openPortAddress => InternetAddress.loopbackIPv4.address;
@override
Future<void> stop() async { }
}
class _DummySshCommandRunner implements SshCommandRunner {
_DummySshCommandRunner();
void _log(String message) {
driverLog('_DummySshCommandRunner', message);
}
@override
String get sshConfigPath => '';
@override
String get address => InternetAddress.loopbackIPv4.address;
@override
String get interface => '';
@override
Future<List<String>> run(String command) async {
try {
final List<String> splitCommand = command.split(' ');
final String exe = splitCommand[0];
final List<String> args = splitCommand.skip(1).toList();
// This needs to remain async in the event that this command attempts to
// access something (like the hub) that requires interaction with this
// process's event loop. A specific example is attempting to run `find`, a
// synchronous command, on this own process's `out` directory. As `find`
// will wait indefinitely for the `out` directory to be serviced, causing
// a deadlock.
final ProcessResult r = await Process.run(exe, args);
return (r.stdout as String).split('\n');
} on ProcessException catch (e) {
_log("Error running '$command': $e");
}
return <String>[];
}
}
Future<PortForwarder> _dummyPortForwardingFunction(
String address,
int remotePort, [
String? interface,
String? configFile,
]) async {
return _DummyPortForwarder(remotePort, remotePort);
}
/// Utility class for creating connections to the Fuchsia Device.
///
/// If executed on a host (non-Fuchsia device), behaves the same as running
/// [FuchsiaRemoteConnection.connect] whereby the `FUCHSIA_REMOTE_URL` and
/// `FUCHSIA_SSH_CONFIG` variables must be set. If run on a Fuchsia device, will
/// connect locally without need for environment variables.
abstract final class FuchsiaCompat {
static void _init() {
fuchsiaPortForwardingFunction = _dummyPortForwardingFunction;
}
/// Restores state to normal if running on a Fuchsia device.
///
/// Noop if running on the host machine.
static void cleanup() {
restoreFuchsiaPortForwardingFunction();
}
/// Creates a connection to the Fuchsia device's Dart VM's.
///
/// See [FuchsiaRemoteConnection.connect] for more details.
/// [FuchsiaCompat.cleanup] must be called when the connection is no longer in
/// use. It is the caller's responsibility to call
/// [FuchsiaRemoteConnection.stop].
static Future<FuchsiaRemoteConnection> connect() async {
FuchsiaCompat._init();
return FuchsiaRemoteConnection.connectWithSshCommandRunner(
_DummySshCommandRunner());
}
}
| flutter/packages/flutter_driver/lib/src/common/fuchsia_compat.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/common/fuchsia_compat.dart",
"repo_id": "flutter",
"token_count": 1020
} | 709 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'timeline.dart';
/// GC related timeline events.
///
/// All these events occur only on the UI thread and are non overlapping.
const Set<String> kGCRootEvents = <String>{
'CollectNewGeneration',
'CollectOldGeneration',
'EvacuateNewGeneration',
'StartConcurrentMark',
};
/// Summarizes [TimelineEvents]s corresponding to [kGCRootEvents] category.
///
/// A sample event (some fields have been omitted for brevity):
/// ```json
/// {
/// "name": "StartConcurrentMarking",
/// "cat": "GC",
/// "ts": 3240710599608,
/// }
/// ```
/// This class provides methods to compute the total time spend in GC on
/// the UI thread.
class GCSummarizer {
GCSummarizer._(this.totalGCTimeMillis);
/// Creates a [GCSummarizer] given the timeline events.
static GCSummarizer fromEvents(List<TimelineEvent> gcEvents) {
double totalGCTimeMillis = 0;
TimelineEvent? lastGCBeginEvent;
for (final TimelineEvent event in gcEvents) {
if (!kGCRootEvents.contains(event.name)) {
continue;
}
if (event.phase == 'B') {
lastGCBeginEvent = event;
} else if (lastGCBeginEvent != null) {
// These events must not overlap.
assert(event.name == lastGCBeginEvent.name,
'Expected "${lastGCBeginEvent.name}" got "${event.name}"');
final double st = lastGCBeginEvent.timestampMicros!.toDouble();
final double end = event.timestampMicros!.toDouble();
lastGCBeginEvent = null;
totalGCTimeMillis += (end - st) / 1000;
}
}
return GCSummarizer._(totalGCTimeMillis);
}
/// Total time spent doing GC on the UI thread.
final double totalGCTimeMillis;
}
| flutter/packages/flutter_driver/lib/src/driver/gc_summarizer.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/driver/gc_summarizer.dart",
"repo_id": "flutter",
"token_count": 651
} | 710 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import '../common/wait.dart';
/// Base class for a condition that can be waited upon.
///
/// This class defines the wait logic and runs on device, while
/// [SerializableWaitCondition] takes care of the serialization between the
/// driver script running on the host and the extension running on device.
///
/// If you subclass this, you might also want to implement a [SerializableWaitCondition]
/// that takes care of serialization.
abstract class WaitCondition {
/// Gets the current status of the [condition], executed in the context of the
/// Flutter app:
///
/// * True, if the condition is satisfied.
/// * False otherwise.
///
/// The future returned by [wait] will complete when this [condition] is
/// fulfilled.
bool get condition;
/// Returns a future that completes when [condition] turns true.
Future<void> wait();
}
/// A condition that waits until no transient callbacks are scheduled.
class _InternalNoTransientCallbacksCondition implements WaitCondition {
/// Creates an [_InternalNoTransientCallbacksCondition] instance.
const _InternalNoTransientCallbacksCondition();
/// Factory constructor to parse an [InternalNoTransientCallbacksCondition]
/// instance from the given [SerializableWaitCondition] instance.
factory _InternalNoTransientCallbacksCondition.deserialize(SerializableWaitCondition condition) {
if (condition.conditionName != 'NoTransientCallbacksCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
return const _InternalNoTransientCallbacksCondition();
}
@override
bool get condition => SchedulerBinding.instance.transientCallbackCount == 0;
@override
Future<void> wait() async {
while (!condition) {
await SchedulerBinding.instance.endOfFrame;
}
assert(condition);
}
}
/// A condition that waits until no pending frame is scheduled.
class _InternalNoPendingFrameCondition implements WaitCondition {
/// Creates an [_InternalNoPendingFrameCondition] instance.
const _InternalNoPendingFrameCondition();
/// Factory constructor to parse an [InternalNoPendingFrameCondition] instance
/// from the given [SerializableWaitCondition] instance.
factory _InternalNoPendingFrameCondition.deserialize(SerializableWaitCondition condition) {
if (condition.conditionName != 'NoPendingFrameCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
return const _InternalNoPendingFrameCondition();
}
@override
bool get condition => !SchedulerBinding.instance.hasScheduledFrame;
@override
Future<void> wait() async {
while (!condition) {
await SchedulerBinding.instance.endOfFrame;
}
assert(condition);
}
}
/// A condition that waits until the Flutter engine has rasterized the first frame.
class _InternalFirstFrameRasterizedCondition implements WaitCondition {
/// Creates an [_InternalFirstFrameRasterizedCondition] instance.
const _InternalFirstFrameRasterizedCondition();
/// Factory constructor to parse an [InternalNoPendingFrameCondition] instance
/// from the given [SerializableWaitCondition] instance.
factory _InternalFirstFrameRasterizedCondition.deserialize(SerializableWaitCondition condition) {
if (condition.conditionName != 'FirstFrameRasterizedCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
return const _InternalFirstFrameRasterizedCondition();
}
@override
bool get condition => WidgetsBinding.instance.firstFrameRasterized;
@override
Future<void> wait() async {
await WidgetsBinding.instance.waitUntilFirstFrameRasterized;
assert(condition);
}
}
/// A condition that waits until no pending platform messages.
class _InternalNoPendingPlatformMessagesCondition implements WaitCondition {
/// Creates an [_InternalNoPendingPlatformMessagesCondition] instance.
const _InternalNoPendingPlatformMessagesCondition();
/// Factory constructor to parse an [_InternalNoPendingPlatformMessagesCondition] instance
/// from the given [SerializableWaitCondition] instance.
factory _InternalNoPendingPlatformMessagesCondition.deserialize(SerializableWaitCondition condition) {
if (condition.conditionName != 'NoPendingPlatformMessagesCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
return const _InternalNoPendingPlatformMessagesCondition();
}
@override
bool get condition {
final TestDefaultBinaryMessenger binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger as TestDefaultBinaryMessenger;
return binaryMessenger.pendingMessageCount == 0;
}
@override
Future<void> wait() async {
final TestDefaultBinaryMessenger binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger as TestDefaultBinaryMessenger;
while (!condition) {
await binaryMessenger.platformMessagesFinished;
}
assert(condition);
}
}
/// A combined condition that waits until all the given [conditions] are met.
class _InternalCombinedCondition implements WaitCondition {
/// Creates an [_InternalCombinedCondition] instance with the given list of
/// [conditions].
const _InternalCombinedCondition(this.conditions);
/// Factory constructor to parse an [_InternalCombinedCondition] instance from
/// the given [SerializableWaitCondition] instance.
factory _InternalCombinedCondition.deserialize(SerializableWaitCondition condition) {
if (condition.conditionName != 'CombinedCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
final CombinedCondition combinedCondition = condition as CombinedCondition;
final List<WaitCondition> conditions = combinedCondition.conditions.map(deserializeCondition).toList();
return _InternalCombinedCondition(conditions);
}
/// A list of conditions it waits for.
final List<WaitCondition> conditions;
@override
bool get condition {
return conditions.every((WaitCondition condition) => condition.condition);
}
@override
Future<void> wait() async {
while (!condition) {
for (final WaitCondition condition in conditions) {
await condition.wait();
}
}
assert(condition);
}
}
/// Parses a [WaitCondition] or its subclass from the given serializable [waitCondition].
WaitCondition deserializeCondition(SerializableWaitCondition waitCondition) {
final String conditionName = waitCondition.conditionName;
switch (conditionName) {
case 'NoTransientCallbacksCondition':
return _InternalNoTransientCallbacksCondition.deserialize(waitCondition);
case 'NoPendingFrameCondition':
return _InternalNoPendingFrameCondition.deserialize(waitCondition);
case 'FirstFrameRasterizedCondition':
return _InternalFirstFrameRasterizedCondition.deserialize(waitCondition);
case 'NoPendingPlatformMessagesCondition':
return _InternalNoPendingPlatformMessagesCondition.deserialize(waitCondition);
case 'CombinedCondition':
return _InternalCombinedCondition.deserialize(waitCondition);
}
throw SerializationException(
'Unsupported wait condition $conditionName in ${waitCondition.serialize()}');
}
| flutter/packages/flutter_driver/lib/src/extension/wait_conditions.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/extension/wait_conditions.dart",
"repo_id": "flutter",
"token_count": 2099
} | 711 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_driver/src/driver/timeline.dart';
import '../../common.dart';
void main() {
group('Timeline', () {
test('parses JSON', () {
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
'traceEvents': <Map<String, dynamic>>[
<String, dynamic>{
'name': 'test event',
'cat': 'test category',
'ph': 'B',
'pid': 123,
'tid': 234,
'dur': 345,
'tdur': 245,
'ts': 456,
'tts': 567,
'args': <String, dynamic>{
'arg1': true,
},
},
// Tests that we don't choke on missing data
<String, dynamic>{},
],
});
expect(timeline.events, hasLength(2));
final TimelineEvent e1 = timeline.events![1];
expect(e1.name, 'test event');
expect(e1.category, 'test category');
expect(e1.phase, 'B');
expect(e1.processId, 123);
expect(e1.threadId, 234);
expect(e1.duration, const Duration(microseconds: 345));
expect(e1.threadDuration, const Duration(microseconds: 245));
expect(e1.timestampMicros, 456);
expect(e1.threadTimestampMicros, 567);
expect(e1.arguments, <String, dynamic>{'arg1': true});
final TimelineEvent e2 = timeline.events![0];
expect(e2.name, isNull);
expect(e2.category, isNull);
expect(e2.phase, isNull);
expect(e2.processId, isNull);
expect(e2.threadId, isNull);
expect(e2.duration, isNull);
expect(e2.threadDuration, isNull);
expect(e2.timestampMicros, isNull);
expect(e2.threadTimestampMicros, isNull);
expect(e2.arguments, isNull);
});
test('sorts JSON', () {
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
'traceEvents': <Map<String, dynamic>>[
<String, dynamic>{
'name': 'test event 1',
'ts': 457,
},
<String, dynamic>{
'name': 'test event 2',
'ts': 456,
},
],
});
expect(timeline.events, hasLength(2));
expect(timeline.events![0].timestampMicros, equals(456));
expect(timeline.events![1].timestampMicros, equals(457));
expect(timeline.events![0].name, equals('test event 2'));
expect(timeline.events![1].name, equals('test event 1'));
});
test('sorts JSON nulls first', () {
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
'traceEvents': <Map<String, dynamic>>[
<String, dynamic>{
'name': 'test event 0',
'ts': null,
},
<String, dynamic>{
'name': 'test event 1',
'ts': 457,
},
<String, dynamic>{
'name': 'test event 2',
'ts': 456,
},
<String, dynamic>{
'name': 'test event 3',
'ts': null,
},
],
});
expect(timeline.events, hasLength(4));
expect(timeline.events![0].timestampMicros, isNull);
expect(timeline.events![1].timestampMicros, isNull);
expect(timeline.events![2].timestampMicros, equals(456));
expect(timeline.events![3].timestampMicros, equals(457));
expect(timeline.events![0].name, equals('test event 0'));
expect(timeline.events![1].name, equals('test event 3'));
expect(timeline.events![2].name, equals('test event 2'));
expect(timeline.events![3].name, equals('test event 1'));
});
});
}
| flutter/packages/flutter_driver/test/src/real_tests/timeline_test.dart/0 | {
"file_path": "flutter/packages/flutter_driver/test/src/real_tests/timeline_test.dart",
"repo_id": "flutter",
"token_count": 1741
} | 712 |
name: flutter_goldens
environment:
sdk: '>=3.2.0-0 <4.0.0'
dependencies:
# To update these, use "flutter update-packages --force-upgrade".
#
# For detailed instructions, refer to:
# https://github.com/flutter/flutter/wiki/Updating-dependencies-in-Flutter
flutter:
sdk: flutter
flutter_test:
sdk: flutter
crypto: 3.0.3
file: 7.0.0
meta: 1.12.0
platform: 3.1.4
process: 5.0.2
async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
boolean_selector: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
characters: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
clock: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
fake_async: 1.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker: 10.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_flutter_testing: 3.0.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
matcher: 0.12.16+1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
material_color_utilities: 0.8.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
path: 1.9.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_span: 1.10.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stack_trace: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stream_channel: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
string_scanner: 1.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
term_glyph: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_api: 0.7.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
typed_data: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vm_service: 14.2.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
# PUBSPEC CHECKSUM: 0688
| flutter/packages/flutter_goldens/pubspec.yaml/0 | {
"file_path": "flutter/packages/flutter_goldens/pubspec.yaml",
"repo_id": "flutter",
"token_count": 951
} | 713 |
{
"datePickerHourSemanticsLabelFew": "$hour sata",
"datePickerMinuteSemanticsLabelFew": "$minute minute",
"timerPickerHourLabelFew": "sata",
"timerPickerMinuteLabelFew": "min",
"timerPickerSecondLabelFew": "sec.",
"datePickerHourSemanticsLabelOne": "$hour sat",
"datePickerHourSemanticsLabelOther": "$hour sati",
"datePickerMinuteSemanticsLabelOne": "1 minuta",
"datePickerMinuteSemanticsLabelOther": "$minute minuta",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "prijepodne",
"postMeridiemAbbreviation": "poslijepodne",
"todayLabel": "Danas",
"alertDialogLabel": "Upozorenje",
"timerPickerHourLabelOne": "sat",
"timerPickerHourLabelOther": "sati",
"timerPickerMinuteLabelOne": "min",
"timerPickerMinuteLabelOther": "min",
"timerPickerSecondLabelOne": "sec.",
"timerPickerSecondLabelOther": "sec.",
"cutButtonLabel": "Izreži",
"copyButtonLabel": "Kopiraj",
"pasteButtonLabel": "Zalijepi",
"clearButtonLabel": "Clear",
"selectAllButtonLabel": "Odaberi sve",
"tabSemanticsLabel": "Kartica $tabIndex od $tabCount",
"modalBarrierDismissLabel": "Odbaci",
"searchTextFieldPlaceholderLabel": "Pretraživanje",
"noSpellCheckReplacementsLabel": "Nije pronađena nijedna zamjena",
"menuDismissLabel": "Odbacivanje menija",
"lookUpButtonLabel": "Pogled nagore",
"searchWebButtonLabel": "Pretraži Web",
"shareButtonLabel": "Dijeli..."
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_bs.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_bs.arb",
"repo_id": "flutter",
"token_count": 536
} | 714 |
{
"datePickerHourSemanticsLabelTwo": "$hour בדיוק",
"datePickerHourSemanticsLabelMany": "$hour בדיוק",
"datePickerMinuteSemanticsLabelTwo": "$minute דקות",
"datePickerMinuteSemanticsLabelMany": "$minute דקות",
"timerPickerHourLabelTwo": "שעות",
"timerPickerHourLabelMany": "שעות",
"timerPickerMinuteLabelTwo": "דק’",
"timerPickerMinuteLabelMany": "דק’",
"timerPickerSecondLabelTwo": "שנ’",
"timerPickerSecondLabelMany": "שנ’",
"datePickerHourSemanticsLabelOne": "$hour בדיוק",
"datePickerHourSemanticsLabelOther": "$hour בדיוק",
"datePickerMinuteSemanticsLabelOne": "דקה אחת",
"datePickerMinuteSemanticsLabelOther": "$minute דקות",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "היום",
"alertDialogLabel": "התראה",
"timerPickerHourLabelOne": "שעה",
"timerPickerHourLabelOther": "שעות",
"timerPickerMinuteLabelOne": "דק’",
"timerPickerMinuteLabelOther": "דק’",
"timerPickerSecondLabelOne": "שנ’",
"timerPickerSecondLabelOther": "שנ’",
"cutButtonLabel": "גזירה",
"copyButtonLabel": "העתקה",
"pasteButtonLabel": "הדבקה",
"selectAllButtonLabel": "בחירת הכול",
"tabSemanticsLabel": "כרטיסייה $tabIndex מתוך $tabCount",
"modalBarrierDismissLabel": "סגירה",
"searchTextFieldPlaceholderLabel": "חיפוש",
"noSpellCheckReplacementsLabel": "לא נמצאו חלופות",
"menuDismissLabel": "סגירת התפריט",
"lookUpButtonLabel": "חיפוש",
"searchWebButtonLabel": "חיפוש באינטרנט",
"shareButtonLabel": "שיתוף…",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_he.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_he.arb",
"repo_id": "flutter",
"token_count": 751
} | 715 |
{
"datePickerHourSemanticsLabelFew": "$hour val.",
"datePickerHourSemanticsLabelMany": "$hour val.",
"datePickerMinuteSemanticsLabelFew": "$minute min.",
"datePickerMinuteSemanticsLabelMany": "$minute min.",
"timerPickerHourLabelFew": "val.",
"timerPickerHourLabelMany": "val.",
"timerPickerMinuteLabelFew": "min.",
"timerPickerMinuteLabelMany": "min.",
"timerPickerSecondLabelFew": "sek.",
"timerPickerSecondLabelMany": "sek.",
"datePickerHourSemanticsLabelOne": "$hour val.",
"datePickerHourSemanticsLabelOther": "$hour val.",
"datePickerMinuteSemanticsLabelOne": "1 min.",
"datePickerMinuteSemanticsLabelOther": "$minute min.",
"datePickerDateOrder": "ymd",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "priešpiet",
"postMeridiemAbbreviation": "popiet",
"todayLabel": "Šiandien",
"alertDialogLabel": "Įspėjimas",
"timerPickerHourLabelOne": "val.",
"timerPickerHourLabelOther": "val.",
"timerPickerMinuteLabelOne": "min.",
"timerPickerMinuteLabelOther": "min.",
"timerPickerSecondLabelOne": "sek.",
"timerPickerSecondLabelOther": "sek.",
"cutButtonLabel": "Iškirpti",
"copyButtonLabel": "Kopijuoti",
"pasteButtonLabel": "Įklijuoti",
"selectAllButtonLabel": "Pasirinkti viską",
"tabSemanticsLabel": "$tabIndex skirtukas iš $tabCount",
"modalBarrierDismissLabel": "Atsisakyti",
"searchTextFieldPlaceholderLabel": "Paieška",
"noSpellCheckReplacementsLabel": "Nerasta jokių pakeitimų",
"menuDismissLabel": "Atsisakyti meniu",
"lookUpButtonLabel": "Ieškoti",
"searchWebButtonLabel": "Ieškoti žiniatinklyje",
"shareButtonLabel": "Bendrinti...",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_lt.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_lt.arb",
"repo_id": "flutter",
"token_count": 617
} | 716 |
{
"searchWebButtonLabel": "Pesquisar na Web",
"shareButtonLabel": "Partilhar…",
"lookUpButtonLabel": "Procurar",
"noSpellCheckReplacementsLabel": "Não foram encontradas substituições",
"menuDismissLabel": "Ignorar menu",
"searchTextFieldPlaceholderLabel": "Pesquise",
"tabSemanticsLabel": "Separador $tabIndex de $tabCount",
"datePickerHourSemanticsLabelOne": "$hour hora",
"datePickerHourSemanticsLabelOther": "$hour hora",
"datePickerMinuteSemanticsLabelOne": "1 minuto",
"datePickerMinuteSemanticsLabelOther": "$minute minutos",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "Hoje",
"alertDialogLabel": "Alerta",
"timerPickerHourLabelOne": "hora",
"timerPickerHourLabelOther": "horas",
"timerPickerMinuteLabelOne": "min",
"timerPickerMinuteLabelOther": "min",
"timerPickerSecondLabelOne": "seg",
"timerPickerSecondLabelOther": "seg",
"cutButtonLabel": "Cortar",
"copyButtonLabel": "Copiar",
"pasteButtonLabel": "Colar",
"selectAllButtonLabel": "Selecionar tudo",
"modalBarrierDismissLabel": "Ignorar"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_pt_PT.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_pt_PT.arb",
"repo_id": "flutter",
"token_count": 429
} | 717 |
{
"datePickerHourSemanticsLabelFew": "$hour години",
"datePickerHourSemanticsLabelMany": "$hour годин",
"datePickerMinuteSemanticsLabelFew": "$minute хвилини",
"datePickerMinuteSemanticsLabelMany": "$minute хвилин",
"timerPickerHourLabelFew": "години",
"timerPickerHourLabelMany": "годин",
"timerPickerMinuteLabelFew": "хв",
"timerPickerMinuteLabelMany": "хв",
"timerPickerSecondLabelFew": "с",
"timerPickerSecondLabelMany": "с",
"datePickerHourSemanticsLabelOne": "$hour година",
"datePickerHourSemanticsLabelOther": "$hour години",
"datePickerMinuteSemanticsLabelOne": "1 хвилина",
"datePickerMinuteSemanticsLabelOther": "$minute хвилини",
"datePickerDateOrder": "mdy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "дп",
"postMeridiemAbbreviation": "пп",
"todayLabel": "Сьогодні",
"alertDialogLabel": "Сповіщення",
"timerPickerHourLabelOne": "година",
"timerPickerHourLabelOther": "години",
"timerPickerMinuteLabelOne": "хв",
"timerPickerMinuteLabelOther": "хв",
"timerPickerSecondLabelOne": "с",
"timerPickerSecondLabelOther": "с",
"cutButtonLabel": "Вирізати",
"copyButtonLabel": "Копіювати",
"pasteButtonLabel": "Вставити",
"selectAllButtonLabel": "Вибрати все",
"tabSemanticsLabel": "Вкладка $tabIndex з $tabCount",
"modalBarrierDismissLabel": "Закрити",
"searchTextFieldPlaceholderLabel": "Шукайте",
"noSpellCheckReplacementsLabel": "Замін не знайдено",
"menuDismissLabel": "Закрити меню",
"lookUpButtonLabel": "Шукати",
"searchWebButtonLabel": "Пошук в Інтернеті",
"shareButtonLabel": "Поділитися…",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_uk.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_uk.arb",
"repo_id": "flutter",
"token_count": 774
} | 718 |
{
"scriptCategory": "English-like",
"timeOfDayFormat": "H:mm",
"openAppDrawerTooltip": "Naviqasiya menyusunu açın",
"backButtonTooltip": "Geri",
"closeButtonTooltip": "Bağlayın",
"deleteButtonTooltip": "Silin",
"nextMonthTooltip": "Növbəti ay",
"previousMonthTooltip": "Keçən ay",
"nextPageTooltip": "Növbəti səhifə",
"firstPageTooltip": "Birinci səhifə",
"lastPageTooltip": "Son səhifə",
"previousPageTooltip": "Əvvəlki səhifə",
"showMenuTooltip": "Menyunu göstərin",
"aboutListTileTitle": "$applicationName haqqında",
"licensesPageTitle": "Lisenziyalar",
"pageRowsInfoTitle": "$firstRow–$lastRow/$rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow/ təxminən $rowCount",
"rowsPerPageTitle": "Hər səhifə üzrə sıra:",
"tabLabel": "$tabIndex/$tabCount tab",
"selectedRowCountTitleOne": "1 element seçildi",
"selectedRowCountTitleOther": "$selectedRowCount element seçildi",
"cancelButtonLabel": "Ləğv edin",
"closeButtonLabel": "Bağlayın",
"continueButtonLabel": "Davam edin",
"copyButtonLabel": "Kopyalayın",
"cutButtonLabel": "Kəsin",
"scanTextButtonLabel": "Mətni skan edin",
"okButtonLabel": "OK",
"pasteButtonLabel": "Yerləşdirin",
"selectAllButtonLabel": "Hamısını seçin",
"viewLicensesButtonLabel": "Lisenziyalara baxın",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "Saat seçin",
"timePickerMinuteModeAnnouncement": "Dəqiqə seçin",
"modalBarrierDismissLabel": "İmtina edin",
"signedInLabel": "Daxil olundu",
"hideAccountsLabel": "Hesabları gizlədin",
"showAccountsLabel": "Hesabları göstərin",
"drawerLabel": "Naviqasiya menyusu",
"popupMenuLabel": "Popap menyusu",
"dialogLabel": "Dialoq",
"alertDialogLabel": "Bildiriş",
"searchFieldLabel": "Axtarın",
"reorderItemToStart": "Əvvələ köçürün",
"reorderItemToEnd": "Sona köçürün",
"reorderItemUp": "Yuxarı köçürün",
"reorderItemDown": "Aşağı köçürün",
"reorderItemLeft": "Sola köçürün",
"reorderItemRight": "Sağa köçürün",
"expandedIconTapHint": "Yığcamlaşdırın",
"collapsedIconTapHint": "Genişləndirin",
"remainingTextFieldCharacterCountOne": "1 simvol qalır",
"remainingTextFieldCharacterCountOther": "$remainingCount simvol qalır",
"refreshIndicatorSemanticLabel": "Yeniləyin",
"moreButtonTooltip": "Daha çox",
"dateSeparator": ".",
"dateHelpText": "aa.gg.iiii",
"selectYearSemanticsLabel": "İl seçin",
"unspecifiedDate": "Tarix",
"unspecifiedDateRange": "Tarix aralığı",
"dateInputLabel": "Tarix daxil edin",
"dateRangeStartLabel": "Başlama tarixi",
"dateRangeEndLabel": "Bitmə tarixi",
"dateRangeStartDateSemanticLabel": "Başlama tarixi: $fullDate",
"dateRangeEndDateSemanticLabel": "Bitmə tarixi: $fullDate",
"invalidDateFormatLabel": "Yanlış format.",
"invalidDateRangeLabel": "Yanlış aralıq.",
"dateOutOfRangeLabel": "Aralıqdan kənar.",
"saveButtonLabel": "Yadda saxlayın",
"datePickerHelpText": "Tarix seçin",
"dateRangePickerHelpText": "Aralıq seçin",
"calendarModeButtonLabel": "Təqvimə keçin",
"inputDateModeButtonLabel": "Daxiletməyə keçin",
"timePickerDialHelpText": "Vaxt seçin",
"timePickerInputHelpText": "Vaxt daxil edin",
"timePickerHourLabel": "Saat",
"timePickerMinuteLabel": "Dəqiqə",
"invalidTimeLabel": "Düzgün vaxt daxil edin",
"dialModeButtonLabel": "Yığım seçici rejiminə keçin",
"inputTimeModeButtonLabel": "Mətn daxiletmə rejiminə keçin",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 lisenziya",
"licensesPackageDetailTextOther": "$licenseCount lisenziya",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Böyük Hərf",
"keyboardKeyChannelDown": "Aşağıdakı kanala keçin",
"keyboardKeyChannelUp": "Yuxarıdakı kanala keçin",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Çıxarın",
"keyboardKeyEnd": "Son",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Əsas səhifə",
"keyboardKeyInsert": "Daxil edin",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Rəqəm",
"keyboardKeyNumpad1": "Rəq 1",
"keyboardKeyNumpad2": "Rəq 2",
"keyboardKeyNumpad3": "Rəq 3",
"keyboardKeyNumpad4": "Rəq 4",
"keyboardKeyNumpad5": "Rəq 5",
"keyboardKeyNumpad6": "Rəq 6",
"keyboardKeyNumpad7": "Rəq 7",
"keyboardKeyNumpad8": "Rəq 8",
"keyboardKeyNumpad9": "Rəq 9",
"keyboardKeyNumpad0": "Rəq 0",
"keyboardKeyNumpadAdd": "Rəq +",
"keyboardKeyNumpadComma": "Rəq ,",
"keyboardKeyNumpadDecimal": "Rəq .",
"keyboardKeyNumpadDivide": "Rəq /",
"keyboardKeyNumpadEnter": "Rəqəm Daxiletmə",
"keyboardKeyNumpadEqual": "Rəq =",
"keyboardKeyNumpadMultiply": "Rəq *",
"keyboardKeyNumpadParenLeft": "Rəq (",
"keyboardKeyNumpadParenRight": "Rəq )",
"keyboardKeyNumpadSubtract": "Rəq -",
"keyboardKeyPageDown": "Aşağı Səhifə",
"keyboardKeyPageUp": "Yuxarı Səhifə",
"keyboardKeyPower": "Qidalanma",
"keyboardKeyPowerOff": "Söndürmə",
"keyboardKeyPrintScreen": "Ekran Çapı",
"keyboardKeyScrollLock": "Sürüşdürmə",
"keyboardKeySelect": "Seçin",
"keyboardKeySpace": "Boşluq",
"keyboardKeyMetaMacOs": "Əmr",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Menyu paneli menyusu",
"currentDateLabel": "Bugün",
"scrimLabel": "Kətan",
"bottomSheetLabel": "Aşağıdakı Vərəq",
"scrimOnTapHint": "Bağlayın: $modalRouteContentName",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "yığcamlaşdırmaq üçün iki dəfə toxunun",
"expansionTileCollapsedHint": "genişləndirmək üçün iki dəfə toxunun",
"expansionTileExpandedTapHint": "Yığcamlaşdırın",
"expansionTileCollapsedTapHint": "Daha çox detallar üçün genişləndirin",
"expandedHint": "Yığcamlaşdırıldı",
"collapsedHint": "Genişləndirildi",
"menuDismissLabel": "Menyunu qapadın",
"lookUpButtonLabel": "Axtarın",
"searchWebButtonLabel": "Vebdə axtarın",
"shareButtonLabel": "Paylaşın...",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_az.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_az.arb",
"repo_id": "flutter",
"token_count": 2714
} | 719 |
{
"lookUpButtonLabel": "Regarder en haut",
"searchWebButtonLabel": "Rechercher sur le Web",
"shareButtonLabel": "Partager…",
"scanTextButtonLabel": "Balayer un texte",
"menuDismissLabel": "Ignorer le menu",
"expansionTileExpandedHint": "toucher deux fois pour réduire",
"expansionTileCollapsedHint": "toucher deux fois pour développer",
"expansionTileExpandedTapHint": "Réduire",
"expansionTileCollapsedTapHint": "Développer le panneau pour plus de détails",
"expandedHint": "Réduit",
"collapsedHint": "Développé",
"scrimLabel": "Grille",
"bottomSheetLabel": "Zone de contenu dans le bas de l'écran",
"scrimOnTapHint": "Fermer $modalRouteContentName",
"currentDateLabel": "Aujourd'hui",
"keyboardKeyShift": "Maj",
"menuBarMenuLabel": "Menu de la barre de menu",
"keyboardKeyNumpad8": "Num 8",
"keyboardKeyChannelDown": "Chaîne préc.",
"keyboardKeyCapsLock": "Verr. maj.",
"keyboardKeyMetaMacOs": "Commande",
"keyboardKeyMetaWindows": "Win",
"keyboardKeyNumLock": "Verr. num.",
"keyboardKeyNumpad1": "Num 1",
"keyboardKeyNumpad2": "Num 2",
"keyboardKeyNumpad3": "Num 3",
"keyboardKeyNumpad4": "Num 4",
"keyboardKeyNumpad5": "Num 5",
"keyboardKeyNumpad6": "Num 6",
"keyboardKeyNumpad7": "Num 7",
"keyboardKeyNumpad9": "Num 9",
"keyboardKeyNumpadAdd": "Num +",
"keyboardKeyNumpadComma": "Num ,",
"keyboardKeyPrintScreen": "Impression de l'écran",
"keyboardKeyNumpadDecimal": "Num .",
"keyboardKeyNumpadDivide": "Num /",
"keyboardKeyNumpadEnter": "Num Entrée",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyEnd": "Fin",
"keyboardKeyInsert": "Insér.",
"keyboardKeyHome": "Accueil",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyFn": "Fn",
"keyboardKeyEscape": "Échapp.",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyEject": "Éject.",
"keyboardKeyDelete": "Suppr",
"keyboardKeyControl": "Ctrl",
"keyboardKeyChannelUp": "Chaîne suiv.",
"keyboardKeyPower": "Alimentation",
"keyboardKeyBackspace": "Retour arrière",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyAlt": "Alt",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeySpace": "Espace",
"keyboardKeySelect": "Sélect.",
"keyboardKeyScrollLock": "Arrêt défilement",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyPowerOff": "Éteindre",
"keyboardKeyMeta": "Méta",
"keyboardKeyPageUp": "Bas page",
"keyboardKeyPageDown": "Haut page",
"keyboardKeyNumpad0": "Num 0",
"invalidTimeLabel": "Entrez une heure valide",
"licensesPackageDetailTextOne": "1 licence",
"timePickerDialHelpText": "Sélectionner l'heure",
"timePickerInputHelpText": "Entrer l'heure",
"timePickerHourLabel": "Heure",
"timePickerMinuteLabel": "Minutes",
"licensesPackageDetailTextOther": "$licenseCount licences",
"dialModeButtonLabel": "Passer au mode de sélection du cadran",
"inputTimeModeButtonLabel": "Passer au mode d'entrée Texte",
"dateSeparator": "/",
"dateRangeStartLabel": "Date de début",
"calendarModeButtonLabel": "Passer à l'agenda",
"dateRangePickerHelpText": "Sélectionner la plage",
"datePickerHelpText": "Sélectionner la date",
"saveButtonLabel": "Enregistrer",
"dateOutOfRangeLabel": "Hors de portée.",
"invalidDateRangeLabel": "Plage incorrecte.",
"invalidDateFormatLabel": "Format incorrect",
"dateRangeEndDateSemanticLabel": "Date de fin : $fullDate",
"dateRangeStartDateSemanticLabel": "Date de début : $fullDate",
"dateRangeEndLabel": "Date de fin",
"inputDateModeButtonLabel": "Passer à l'entrée",
"dateInputLabel": "Entrer une date",
"unspecifiedDateRange": "Période",
"unspecifiedDate": "Date",
"selectYearSemanticsLabel": "Sélectionner une année",
"dateHelpText": "jj-mm-aaaa",
"moreButtonTooltip": "Plus",
"selectedRowCountTitleOne": "1 élément sélectionné",
"remainingTextFieldCharacterCountOther": "$remainingCount caractères restants",
"openAppDrawerTooltip": "Ouvrir le menu de navigation",
"backButtonTooltip": "Retour",
"closeButtonTooltip": "Fermer",
"deleteButtonTooltip": "Supprimer",
"nextMonthTooltip": "Mois suivant",
"previousMonthTooltip": "Mois précédent",
"nextPageTooltip": "Page suivante",
"previousPageTooltip": "Page précédente",
"firstPageTooltip": "Première page",
"lastPageTooltip": "Dernière page",
"showMenuTooltip": "Afficher le menu",
"aboutListTileTitle": "À propos de $applicationName",
"licensesPageTitle": "Licences",
"pageRowsInfoTitle": "$firstRow à $lastRow sur $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow à $lastRow sur environ $rowCount",
"rowsPerPageTitle": "Lignes par page :",
"tabLabel": "Onglet $tabIndex sur $tabCount",
"remainingTextFieldCharacterCountOne": "1 caractère restant",
"selectedRowCountTitleOther": "$selectedRowCount éléments sélectionnés",
"cancelButtonLabel": "Annuler",
"closeButtonLabel": "Fermer",
"continueButtonLabel": "Continuer",
"copyButtonLabel": "Copier",
"cutButtonLabel": "Couper",
"okButtonLabel": "OK",
"pasteButtonLabel": "Coller",
"selectAllButtonLabel": "Tout sélectionner",
"viewLicensesButtonLabel": "Afficher les licences",
"anteMeridiemAbbreviation": "am",
"postMeridiemAbbreviation": "pm",
"timePickerHourModeAnnouncement": "Sélectionnez les heures",
"timePickerMinuteModeAnnouncement": "Sélectionnez les minutes",
"modalBarrierDismissLabel": "Ignorer",
"refreshIndicatorSemanticLabel": "Actualiser",
"hideAccountsLabel": "Masquer les comptes",
"showAccountsLabel": "Afficher les comptes",
"drawerLabel": "Menu de navigation",
"popupMenuLabel": "Menu contextuel",
"dialogLabel": "Boîte de dialogue",
"alertDialogLabel": "Alerte",
"searchFieldLabel": "Rechercher",
"reorderItemToStart": "Déplacer au début",
"reorderItemToEnd": "Déplacer à la fin",
"reorderItemUp": "Déplacer vers le haut",
"reorderItemDown": "Déplacer vers le bas",
"reorderItemLeft": "Déplacer vers la gauche",
"reorderItemRight": "Déplacer vers la droite",
"expandedIconTapHint": "Réduire",
"collapsedIconTapHint": "Développer",
"signedInLabel": "Connecté",
"scriptCategory": "English-like",
"timeOfDayFormat": "HH 'h' mm"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_fr_CA.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_fr_CA.arb",
"repo_id": "flutter",
"token_count": 2296
} | 720 |
{
"scriptCategory": "\u0074\u0061\u006c\u006c",
"timeOfDayFormat": "\u0048\u003a\u006d\u006d",
"openAppDrawerTooltip": "\u0ca8\u0ccd\u0caf\u0cbe\u0cb5\u0cbf\u0c97\u0cc7\u0cb6\u0ca8\u0ccd\u200c\u0020\u0cae\u0cc6\u0ca8\u0cc1\u0020\u0ca4\u0cc6\u0cb0\u0cc6\u0caf\u0cbf\u0cb0\u0cbf",
"backButtonTooltip": "\u0cb9\u0cbf\u0c82\u0ca4\u0cbf\u0cb0\u0cc1\u0c97\u0cbf",
"closeButtonTooltip": "\u0cae\u0cc1\u0c9a\u0ccd\u0c9a\u0cbf\u0cb0\u0cbf",
"deleteButtonTooltip": "\u0c85\u0cb3\u0cbf\u0cb8\u0cbf",
"nextMonthTooltip": "\u0cae\u0cc1\u0c82\u0ca6\u0cbf\u0ca8\u0020\u0ca4\u0cbf\u0c82\u0c97\u0cb3\u0cc1",
"previousMonthTooltip": "\u0cb9\u0cbf\u0c82\u0ca6\u0cbf\u0ca8\u0020\u0ca4\u0cbf\u0c82\u0c97\u0cb3\u0cc1",
"nextPageTooltip": "\u0cae\u0cc1\u0c82\u0ca6\u0cbf\u0ca8\u0020\u0caa\u0cc1\u0c9f",
"previousPageTooltip": "\u0cb9\u0cbf\u0c82\u0ca6\u0cbf\u0ca8\u0020\u0caa\u0cc1\u0c9f",
"firstPageTooltip": "\u0cae\u0cca\u0ca6\u0cb2\u0020\u0caa\u0cc1\u0c9f",
"lastPageTooltip": "\u0c95\u0cca\u0ca8\u0cc6\u0caf\u0020\u0caa\u0cc1\u0c9f",
"showMenuTooltip": "\u0cae\u0cc6\u0ca8\u0cc1\u0020\u0ca4\u0ccb\u0cb0\u0cbf\u0cb8\u0cbf",
"aboutListTileTitle": "\u0024\u0061\u0070\u0070\u006c\u0069\u0063\u0061\u0074\u0069\u006f\u006e\u004e\u0061\u006d\u0065\u0020\u0cac\u0c97\u0ccd\u0c97\u0cc6",
"licensesPageTitle": "\u0caa\u0cb0\u0cb5\u0cbe\u0ca8\u0c97\u0cbf\u0c97\u0cb3\u0cc1",
"pageRowsInfoTitle": "\u0024\u0072\u006f\u0077\u0043\u006f\u0075\u006e\u0074\u0020\u0cb0\u0cb2\u0ccd\u0cb2\u0cbf\u0020\u0024\u0066\u0069\u0072\u0073\u0074\u0052\u006f\u0077\u2013\u0024\u006c\u0061\u0073\u0074\u0052\u006f\u0077",
"pageRowsInfoTitleApproximate": "\u0024\u0072\u006f\u0077\u0043\u006f\u0075\u006e\u0074\u0020\u0cb0\u0cb2\u0ccd\u0cb2\u0cbf\u0020\u0024\u0066\u0069\u0072\u0073\u0074\u0052\u006f\u0077\u2013\u0024\u006c\u0061\u0073\u0074\u0052\u006f\u0077",
"rowsPerPageTitle": "\u0caa\u0ccd\u0cb0\u0ca4\u0cbf\u0020\u0caa\u0cc1\u0c9f\u0c95\u0ccd\u0c95\u0cc6\u0020\u0cb8\u0cbe\u0cb2\u0cc1\u0c97\u0cb3\u0cc1\u003a",
"tabLabel": "\u0024\u0074\u0061\u0062\u0043\u006f\u0075\u006e\u0074\u0020\u0cb0\u0cb2\u0ccd\u0cb2\u0cbf\u0ca8\u0020\u0024\u0074\u0061\u0062\u0049\u006e\u0064\u0065\u0078\u0020\u0c9f\u0ccd\u0caf\u0cbe\u0cac\u0ccd",
"selectedRowCountTitleOne": "\u0031\u0020\u0c90\u0c9f\u0c82\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0020\u0cae\u0cbe\u0ca1\u0cb2\u0cbe\u0c97\u0cbf\u0ca6\u0cc6",
"selectedRowCountTitleOther": "\u0024\u0073\u0065\u006c\u0065\u0063\u0074\u0065\u0064\u0052\u006f\u0077\u0043\u006f\u0075\u006e\u0074\u0020\u0c90\u0c9f\u0c82\u0c97\u0cb3\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0020\u0cae\u0cbe\u0ca1\u0cb2\u0cbe\u0c97\u0cbf\u0ca6\u0cc6",
"cancelButtonLabel": "\u0cb0\u0ca6\u0ccd\u0ca6\u0cc1\u0cae\u0cbe\u0ca1\u0cbf",
"closeButtonLabel": "\u0cae\u0cc1\u0c9a\u0ccd\u0c9a\u0cbf\u0cb0\u0cbf",
"continueButtonLabel": "\u0cae\u0cc1\u0c82\u0ca6\u0cc1\u0cb5\u0cb0\u0cbf\u0cb8\u0cbf",
"copyButtonLabel": "\u0ca8\u0c95\u0cb2\u0cbf\u0cb8\u0cbf",
"cutButtonLabel": "\u0c95\u0ca4\u0ccd\u0ca4\u0cb0\u0cbf\u0cb8\u0cbf",
"scanTextButtonLabel": "\u0caa\u0ca0\u0ccd\u0caf\u0cb5\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0cb8\u0ccd\u0c95\u0ccd\u0caf\u0cbe\u0ca8\u0ccd\u0020\u0cae\u0cbe\u0ca1\u0cbf",
"okButtonLabel": "\u0cb8\u0cb0\u0cbf",
"pasteButtonLabel": "\u0c85\u0c82\u0c9f\u0cbf\u0cb8\u0cbf",
"selectAllButtonLabel": "\u0c8e\u0cb2\u0ccd\u0cb2\u0cb5\u0ca8\u0ccd\u0ca8\u0cc2\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0020\u0cae\u0cbe\u0ca1\u0cbf",
"viewLicensesButtonLabel": "\u0caa\u0cb0\u0cb5\u0cbe\u0ca8\u0c97\u0cbf\u0c97\u0cb3\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0cb5\u0cbf\u0cd5\u0c95\u0ccd\u0cb7\u0cbf\u0cb8\u0cbf",
"anteMeridiemAbbreviation": "\u0cac\u0cc6\u0cb3\u0cbf\u0c97\u0ccd\u0c97\u0cc6",
"postMeridiemAbbreviation": "\u0cb8\u0c82\u0c9c\u0cc6",
"timePickerHourModeAnnouncement": "\u0c97\u0c82\u0c9f\u0cc6\u0c97\u0cb3\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0cae\u0cbe\u0ca1\u0cbf",
"timePickerMinuteModeAnnouncement": "\u0ca8\u0cbf\u0cae\u0cbf\u0cb7\u0c97\u0cb3\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0cae\u0cbe\u0ca1\u0cbf",
"modalBarrierDismissLabel": "\u0cb5\u0c9c\u0cbe\u0c97\u0cca\u0cb3\u0cbf\u0cb8\u0cbf",
"signedInLabel": "\u0cb8\u0cc8\u0ca8\u0ccd\u0020\u0c87\u0ca8\u0ccd\u0020\u0cae\u0cbe\u0ca1\u0cb2\u0cbe\u0c97\u0cbf\u0ca6\u0cc6",
"hideAccountsLabel": "\u0c96\u0cbe\u0ca4\u0cc6\u0c97\u0cb3\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0cae\u0cb0\u0cc6\u0cae\u0cbe\u0ca1\u0cbf",
"showAccountsLabel": "\u0c96\u0cbe\u0ca4\u0cc6\u0c97\u0cb3\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0ca4\u0ccb\u0cb0\u0cbf\u0cb8\u0cbf",
"drawerLabel": "\u0ca8\u0ccd\u0caf\u0cbe\u0cb5\u0cbf\u0c97\u0cc7\u0cb6\u0ca8\u0ccd\u200c\u0020\u0cae\u0cc6\u0ca8\u0cc1",
"popupMenuLabel": "\u0caa\u0cbe\u0caa\u0ccd\u0c85\u0caa\u0ccd\u0020\u0cae\u0cc6\u0ca8\u0cc1",
"dialogLabel": "\u0ca1\u0cc8\u0cb2\u0cbe\u0c97\u0ccd",
"alertDialogLabel": "\u0c8e\u0c9a\u0ccd\u0c9a\u0cb0\u0cbf\u0c95\u0cc6",
"searchFieldLabel": "\u0cb9\u0cc1\u0ca1\u0cc1\u0c95\u0cbf",
"reorderItemToStart": "\u0caa\u0ccd\u0cb0\u0cbe\u0cb0\u0c82\u0cad\u0c95\u0ccd\u0c95\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf",
"reorderItemToEnd": "\u0c95\u0cca\u0ca8\u0cc6\u0c97\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf",
"reorderItemUp": "\u0cae\u0cc7\u0cb2\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf",
"reorderItemDown": "\u0c95\u0cc6\u0cb3\u0c97\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf",
"reorderItemLeft": "\u0c8e\u0ca1\u0c95\u0ccd\u0c95\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf",
"reorderItemRight": "\u0cac\u0cb2\u0c95\u0ccd\u0c95\u0cc6\u0020\u0cb8\u0cb0\u0cbf\u0cb8\u0cbf",
"expandedIconTapHint": "\u0c95\u0cc1\u0c97\u0ccd\u0c97\u0cbf\u0cb8\u0cbf",
"collapsedIconTapHint": "\u0cb5\u0cbf\u0cb8\u0ccd\u0ca4\u0cb0\u0cbf\u0cb8\u0cbf",
"remainingTextFieldCharacterCountOne": "\u0031\u0020\u0c85\u0c95\u0ccd\u0cb7\u0cb0\u0020\u0c89\u0cb3\u0cbf\u0ca6\u0cbf\u0ca6\u0cc6",
"remainingTextFieldCharacterCountOther": "\u0024\u0072\u0065\u006d\u0061\u0069\u006e\u0069\u006e\u0067\u0043\u006f\u0075\u006e\u0074\u0020\u0c85\u0c95\u0ccd\u0cb7\u0cb0\u0c97\u0cb3\u0cc1\u0020\u0c89\u0cb3\u0cbf\u0ca6\u0cbf\u0cb5\u0cc6",
"refreshIndicatorSemanticLabel": "\u0cb0\u0cbf\u0cab\u0ccd\u0cb0\u0cc6\u0cb6\u0ccd\u0020\u0cae\u0cbe\u0ca1\u0cbf",
"moreButtonTooltip": "\u0c87\u0ca8\u0ccd\u0ca8\u0cb7\u0ccd\u0c9f\u0cc1",
"dateSeparator": "\u002f",
"dateHelpText": "\u006d\u006d\u002f\u0064\u0064\u002f\u0079\u0079\u0079\u0079",
"selectYearSemanticsLabel": "\u0cb5\u0cb0\u0ccd\u0cb7\u0cb5\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0cae\u0cbe\u0ca1\u0cbf",
"unspecifiedDate": "\u0ca6\u0cbf\u0ca8\u0cbe\u0c82\u0c95",
"unspecifiedDateRange": "\u0ca6\u0cbf\u0ca8\u0cbe\u0c82\u0c95\u0020\u0cb5\u0ccd\u0caf\u0cbe\u0caa\u0ccd\u0ca4\u0cbf",
"dateInputLabel": "\u0ca6\u0cbf\u0ca8\u0cbe\u0c82\u0c95\u0020\u0ca8\u0cae\u0cc2\u0ca6\u0cbf\u0cb8\u0cbf",
"dateRangeStartLabel": "\u0caa\u0ccd\u0cb0\u0cbe\u0cb0\u0c82\u0cad\u0020\u0ca6\u0cbf\u0ca8\u0cbe\u0c82\u0c95",
"dateRangeEndLabel": "\u0c85\u0c82\u0ca4\u0cbf\u0cae\u0020\u0ca6\u0cbf\u0ca8\u0cbe\u0c82\u0c95",
"dateRangeStartDateSemanticLabel": "\u0caa\u0ccd\u0cb0\u0cbe\u0cb0\u0c82\u0cad\u0020\u0ca6\u0cbf\u0ca8\u0cbe\u0c82\u0c95\u0020\u0024\u0066\u0075\u006c\u006c\u0044\u0061\u0074\u0065",
"dateRangeEndDateSemanticLabel": "\u0cae\u0cc1\u0c95\u0ccd\u0ca4\u0cbe\u0caf\u0020\u0ca6\u0cbf\u0ca8\u0cbe\u0c82\u0c95\u0020\u0024\u0066\u0075\u006c\u006c\u0044\u0061\u0074\u0065",
"invalidDateFormatLabel": "\u0c85\u0cae\u0cbe\u0ca8\u0ccd\u0caf\u0cb5\u0cbe\u0ca6\u0020\u0cab\u0cbe\u0cb0\u0ccd\u0cae\u0ccd\u0caf\u0cbe\u0c9f\u0ccd\u002e",
"invalidDateRangeLabel": "\u0c85\u0cae\u0cbe\u0ca8\u0ccd\u0caf\u0020\u0cb6\u0ccd\u0cb0\u0cc7\u0ca3\u0cbf\u002e",
"dateOutOfRangeLabel": "\u0cb5\u0ccd\u0caf\u0cbe\u0caa\u0ccd\u0ca4\u0cbf\u0caf\u0020\u0cb9\u0cca\u0cb0\u0c97\u0cbf\u0ca6\u0cc6",
"saveButtonLabel": "\u0cb8\u0cc7\u0cb5\u0ccd\u0020\u0cae\u0cbe\u0ca1\u0cbf",
"datePickerHelpText": "\u0ca6\u0cbf\u0ca8\u0cbe\u0c82\u0c95\u0cb5\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0cae\u0cbe\u0ca1\u0cbf",
"dateRangePickerHelpText": "\u0ca6\u0cbf\u0ca8\u0cbe\u0c82\u0c95\u0ca6\u0020\u0cb5\u0ccd\u0caf\u0cbe\u0caa\u0ccd\u0ca4\u0cbf\u0caf\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0cae\u0cbe\u0ca1\u0cbf",
"calendarModeButtonLabel": "\u0c95\u0ccd\u0caf\u0cbe\u0cb2\u0cc6\u0c82\u0ca1\u0cb0\u0ccd\u200c\u0c97\u0cc6\u0020\u0cac\u0ca6\u0cb2\u0cbf\u0cb8\u0cbf",
"inputDateModeButtonLabel": "\u0c87\u0ca8\u0ccd\u200c\u0caa\u0cc1\u0c9f\u0ccd\u200c\u0c97\u0cc6\u0020\u0cac\u0ca6\u0cb2\u0cbf\u0cb8\u0cbf",
"timePickerDialHelpText": "\u0cb8\u0cae\u0caf\u0cb5\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0cae\u0cbe\u0ca1\u0cbf",
"timePickerInputHelpText": "\u0cb8\u0cae\u0caf\u0cb5\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0ca8\u0cae\u0cc2\u0ca6\u0cbf\u0cb8\u0cbf",
"timePickerHourLabel": "\u0c97\u0c82\u0c9f\u0cc6",
"timePickerMinuteLabel": "\u0ca8\u0cbf\u0cae\u0cbf\u0cb7",
"invalidTimeLabel": "\u0cae\u0cbe\u0ca8\u0ccd\u0caf\u0cb5\u0cbe\u0ca6\u0020\u0cb8\u0cae\u0caf\u0cb5\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0ca8\u0cae\u0cc2\u0ca6\u0cbf\u0cb8\u0cbf",
"dialModeButtonLabel": "\u0ca1\u0caf\u0cb2\u0ccd\u0020\u0caa\u0cbf\u0c95\u0cb0\u0ccd\u200c\u0020\u0cae\u0ccb\u0ca1\u0ccd\u200c\u0c97\u0cc6\u0020\u0cac\u0ca6\u0cb2\u0cbe\u0caf\u0cbf\u0cb8\u0cbf",
"inputTimeModeButtonLabel": "\u0caa\u0ca0\u0ccd\u0caf\u0020\u0c87\u0ca8\u0ccd\u200c\u0caa\u0cc1\u0c9f\u0ccd\u0020\u0cae\u0ccb\u0ca1\u0ccd\u200c\u0c97\u0cc6\u0020\u0cac\u0ca6\u0cb2\u0cbe\u0caf\u0cbf\u0cb8\u0cbf",
"licensesPackageDetailTextZero": "\u004e\u006f\u0020\u006c\u0069\u0063\u0065\u006e\u0073\u0065\u0073",
"licensesPackageDetailTextOne": "\u0031\u0020\u0caa\u0cb0\u0cb5\u0cbe\u0ca8\u0c97\u0cbf",
"licensesPackageDetailTextOther": "\u0024\u006c\u0069\u0063\u0065\u006e\u0073\u0065\u0043\u006f\u0075\u006e\u0074\u0020\u0caa\u0cb0\u0cb5\u0cbe\u0ca8\u0c97\u0cbf\u0c97\u0cb3\u0cc1",
"keyboardKeyAlt": "\u0041\u006c\u0074",
"keyboardKeyAltGraph": "\u0041\u006c\u0074\u0047\u0072",
"keyboardKeyBackspace": "\u0042\u0061\u0063\u006b\u0073\u0070\u0061\u0063\u0065",
"keyboardKeyCapsLock": "\u0043\u0061\u0070\u0073\u0020\u004c\u006f\u0063\u006b",
"keyboardKeyChannelDown": "\u0043\u0068\u0061\u006e\u006e\u0065\u006c\u0020\u0044\u006f\u0077\u006e",
"keyboardKeyChannelUp": "\u0043\u0068\u0061\u006e\u006e\u0065\u006c\u0020\u0055\u0070",
"keyboardKeyControl": "\u0043\u0074\u0072\u006c",
"keyboardKeyDelete": "\u0044\u0065\u006c",
"keyboardKeyEject": "\u0045\u006a\u0065\u0063\u0074",
"keyboardKeyEnd": "\u0045\u006e\u0064",
"keyboardKeyEscape": "\u0045\u0073\u0063",
"keyboardKeyFn": "\u0046\u006e",
"keyboardKeyHome": "\u0048\u006f\u006d\u0065",
"keyboardKeyInsert": "\u0049\u006e\u0073\u0065\u0072\u0074",
"keyboardKeyMeta": "\u004d\u0065\u0074\u0061",
"keyboardKeyNumLock": "\u004e\u0075\u006d\u0020\u004c\u006f\u0063\u006b",
"keyboardKeyNumpad1": "\u004e\u0075\u006d\u0020\u0031",
"keyboardKeyNumpad2": "\u004e\u0075\u006d\u0020\u0032",
"keyboardKeyNumpad3": "\u004e\u0075\u006d\u0020\u0033",
"keyboardKeyNumpad4": "\u004e\u0075\u006d\u0020\u0034",
"keyboardKeyNumpad5": "\u004e\u0075\u006d\u0020\u0035",
"keyboardKeyNumpad6": "\u004e\u0075\u006d\u0020\u0036",
"keyboardKeyNumpad7": "\u004e\u0075\u006d\u0020\u0037",
"keyboardKeyNumpad8": "\u004e\u0075\u006d\u0020\u0038",
"keyboardKeyNumpad9": "\u004e\u0075\u006d\u0020\u0039",
"keyboardKeyNumpad0": "\u004e\u0075\u006d\u0020\u0030",
"keyboardKeyNumpadAdd": "\u004e\u0075\u006d\u0020\u002b",
"keyboardKeyNumpadComma": "\u004e\u0075\u006d\u0020\u002c",
"keyboardKeyNumpadDecimal": "\u004e\u0075\u006d\u0020\u002e",
"keyboardKeyNumpadDivide": "\u004e\u0075\u006d\u0020\u002f",
"keyboardKeyNumpadEnter": "\u004e\u0075\u006d\u0020\u0045\u006e\u0074\u0065\u0072",
"keyboardKeyNumpadEqual": "\u004e\u0075\u006d\u0020\u003d",
"keyboardKeyNumpadMultiply": "\u004e\u0075\u006d\u0020\u002a",
"keyboardKeyNumpadParenLeft": "\u004e\u0075\u006d\u0020\u0028",
"keyboardKeyNumpadParenRight": "\u004e\u0075\u006d\u0020\u0029",
"keyboardKeyNumpadSubtract": "\u004e\u0075\u006d\u0020\u002d",
"keyboardKeyPageDown": "\u0050\u0067\u0044\u006f\u0077\u006e",
"keyboardKeyPageUp": "\u0050\u0067\u0055\u0070",
"keyboardKeyPower": "\u0050\u006f\u0077\u0065\u0072",
"keyboardKeyPowerOff": "\u0050\u006f\u0077\u0065\u0072\u0020\u004f\u0066\u0066",
"keyboardKeyPrintScreen": "\u0050\u0072\u0069\u006e\u0074\u0020\u0053\u0063\u0072\u0065\u0065\u006e",
"keyboardKeyScrollLock": "\u0053\u0063\u0072\u006f\u006c\u006c\u0020\u004c\u006f\u0063\u006b",
"keyboardKeySelect": "\u0053\u0065\u006c\u0065\u0063\u0074",
"keyboardKeySpace": "\u0053\u0070\u0061\u0063\u0065",
"keyboardKeyMetaMacOs": "\u0043\u006f\u006d\u006d\u0061\u006e\u0064",
"keyboardKeyMetaWindows": "\u0057\u0069\u006e",
"menuBarMenuLabel": "\u0cae\u0cc6\u0ca8\u0cc1\u0020\u0cac\u0cbe\u0cb0\u0ccd\u200c\u0020\u0cae\u0cc6\u0ca8\u0cc1",
"currentDateLabel": "\u0c87\u0c82\u0ca6\u0cc1",
"scrimLabel": "\u0cb8\u0ccd\u0c95\u0ccd\u0cb0\u0cbf\u0cae\u0ccd",
"bottomSheetLabel": "\u0c95\u0cc6\u0cb3\u0cad\u0cbe\u0c97\u0ca6\u0020\u0cb6\u0cc0\u0c9f\u0ccd",
"scrimOnTapHint": "\u0024\u006d\u006f\u0064\u0061\u006c\u0052\u006f\u0075\u0074\u0065\u0043\u006f\u006e\u0074\u0065\u006e\u0074\u004e\u0061\u006d\u0065\u0020\u0c85\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0cae\u0cc1\u0c9a\u0ccd\u0c9a\u0cbf\u0cb0\u0cbf",
"keyboardKeyShift": "\u0053\u0068\u0069\u0066\u0074",
"expansionTileExpandedHint": "\u0c95\u0cc1\u0c97\u0ccd\u0c97\u0cbf\u0cb8\u0cb2\u0cc1\u0020\u0ca1\u0cac\u0cb2\u0ccd\u0020\u0c9f\u0ccd\u0caf\u0cbe\u0caa\u0ccd\u0020\u0cae\u0cbe\u0ca1\u0cbf",
"expansionTileCollapsedHint": "\u0cb5\u0cbf\u0cb8\u0ccd\u0ca4\u0cb0\u0cbf\u0cb8\u0cb2\u0cc1\u0020\u0ca1\u0cac\u0cb2\u0ccd\u0020\u0c9f\u0ccd\u0caf\u0cbe\u0caa\u0ccd\u0020\u0cae\u0cbe\u0ca1\u0cbf",
"expansionTileExpandedTapHint": "\u0c95\u0cc1\u0c97\u0ccd\u0c97\u0cbf\u0cb8\u0cbf",
"expansionTileCollapsedTapHint": "\u0c87\u0ca8\u0ccd\u0ca8\u0cb7\u0ccd\u0c9f\u0cc1\u0020\u0cb5\u0cbf\u0cb5\u0cb0\u0c97\u0cb3\u0cbf\u0c97\u0cbe\u0c97\u0cbf\u0020\u0cb5\u0cbf\u0cb8\u0ccd\u0ca4\u0cb0\u0cbf\u0cb8\u0cbf",
"expandedHint": "\u0c95\u0cc1\u0c97\u0ccd\u0c97\u0cbf\u0cb8\u0cb2\u0cbe\u0c97\u0cbf\u0ca6\u0cc6",
"collapsedHint": "\u0cb5\u0cbf\u0cb8\u0ccd\u0ca4\u0cb0\u0cbf\u0cb8\u0cb2\u0cbe\u0c97\u0cbf\u0ca6\u0cc6",
"menuDismissLabel": "\u0cae\u0cc6\u0ca8\u0cc1\u0cb5\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0cb5\u0c9c\u0cbe\u0c97\u0cc6\u0cc2\u0cb3\u0cbf\u0cb8\u0cbf",
"lookUpButtonLabel": "\u0cae\u0cc7\u0cb2\u0cc6\u0020\u0ca8\u0ccb\u0ca1\u0cbf",
"searchWebButtonLabel": "\u0cb5\u0cc6\u0cac\u0ccd\u200c\u0ca8\u0cb2\u0ccd\u0cb2\u0cbf\u0020\u0cb9\u0cc1\u0ca1\u0cc1\u0c95\u0cbf",
"shareButtonLabel": "\u0cb9\u0c82\u0c9a\u0cbf\u0c95\u0cca\u0cb3\u0ccd\u0cb3\u0cbf\u002e\u002e\u002e",
"clearButtonTooltip": "\u0043\u006c\u0065\u0061\u0072\u0020\u0074\u0065\u0078\u0074",
"selectedDateLabel": "\u0053\u0065\u006c\u0065\u0063\u0074\u0065\u0064"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_kn.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_kn.arb",
"repo_id": "flutter",
"token_count": 9851
} | 721 |
{
"scriptCategory": "tall",
"timeOfDayFormat": "H:mm",
"openAppDrawerTooltip": "ନାଭିଗେସନ୍ ମେନୁ ଖୋଲନ୍ତୁ",
"backButtonTooltip": "ପଛକୁ ଫେରନ୍ତୁ",
"closeButtonTooltip": "ବନ୍ଦ କରନ୍ତୁ",
"deleteButtonTooltip": "ଡିଲିଟ୍ କରନ୍ତୁ",
"nextMonthTooltip": "ପରବର୍ତ୍ତୀ ମାସ",
"previousMonthTooltip": "ପୂର୍ବ ମାସ",
"nextPageTooltip": "ପରବର୍ତ୍ତୀ ପେଜ୍",
"previousPageTooltip": "ପୂର୍ବବର୍ତ୍ତୀ ପେଜ୍",
"firstPageTooltip": "ପ୍ରଥମ ପୃଷ୍ଠା",
"lastPageTooltip": "ଶେଷ ପୃଷ୍ଠା",
"showMenuTooltip": "ମେନୁ ଦେଖାନ୍ତୁ",
"aboutListTileTitle": "$applicationName ବିଷୟରେ",
"licensesPageTitle": "ଲାଇସେନ୍ସଗୁଡ଼କ",
"pageRowsInfoTitle": "$rowCountର $firstRow–$lastRow",
"pageRowsInfoTitleApproximate": "ପାଖାପାଖି $rowCountର $firstRow–$lastRow",
"rowsPerPageTitle": "ପୃଷ୍ଠା ପିଛା ଧାଡ଼ି:",
"tabLabel": "$tabCountର $tabIndex ଟାବ୍",
"selectedRowCountTitleOne": "1ଟି ଆଇଟମ୍ ଚୟନ କରାଯାଇଛି",
"selectedRowCountTitleOther": "$selectedRowCountଟି ଆଇଟମ୍ ଚୟନ କରାଯାଇଛି",
"cancelButtonLabel": "ବାତିଲ କରନ୍ତୁ",
"closeButtonLabel": "ବନ୍ଦ କରନ୍ତୁ",
"continueButtonLabel": "ଜାରି ରଖନ୍ତୁ",
"copyButtonLabel": "କପି କରନ୍ତୁ",
"cutButtonLabel": "କଟ୍ କରନ୍ତୁ",
"scanTextButtonLabel": "ଟେକ୍ସଟ୍ ସ୍କାନ୍ କରନ୍ତୁ",
"okButtonLabel": "ଠିକ୍ ଅଛି",
"pasteButtonLabel": "ପେଷ୍ଟ କରନ୍ତୁ",
"selectAllButtonLabel": "ସବୁ ଚୟନ କରନ୍ତୁ",
"viewLicensesButtonLabel": "ଲାଇସେନ୍ସ ଦେଖନ୍ତୁ",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "ଘଣ୍ଟା ଚୟନ କରନ୍ତୁ",
"timePickerMinuteModeAnnouncement": "ମିନିଟ୍ ଚୟନ କରନ୍ତୁ",
"modalBarrierDismissLabel": "ଖାରଜ କରନ୍ତୁ",
"signedInLabel": "ସାଇନ୍ ଇନ୍ କରାଯାଇଛି",
"hideAccountsLabel": "ଆକାଉଣ୍ଟଗୁଡ଼ିକୁ ଲୁଚାନ୍ତୁ",
"showAccountsLabel": "ଆକାଉଣ୍ଟ ଦେଖାନ୍ତୁ",
"drawerLabel": "ନେଭିଗେସନ୍ ମେନୁ",
"popupMenuLabel": "ପପ୍-ଅପ୍ ମେନୁ",
"dialogLabel": "ଡାୟଲଗ୍",
"alertDialogLabel": "ଆଲର୍ଟ",
"searchFieldLabel": "ସନ୍ଧାନ କରନ୍ତୁ",
"reorderItemToStart": "ଆରମ୍ଭକୁ ଯାଆନ୍ତୁ",
"reorderItemToEnd": "ଶେଷକୁ ଯାଆନ୍ତୁ",
"reorderItemUp": "ଉପରକୁ ନିଅନ୍ତୁ",
"reorderItemDown": "ତଳକୁ ଯାଆନ୍ତୁ",
"reorderItemLeft": "ବାମକୁ ଯାଆନ୍ତୁ",
"reorderItemRight": "ଡାହାଣକୁ ଯାଆନ୍ତୁ",
"expandedIconTapHint": "ସଙ୍କୁଚିତ କରନ୍ତୁ",
"collapsedIconTapHint": "ପ୍ରସାରିତ କରନ୍ତୁ",
"remainingTextFieldCharacterCountOne": "1ଟି ଅକ୍ଷର ବାକି ଅଛି",
"remainingTextFieldCharacterCountOther": "$remainingCountଟି ଅକ୍ଷର ବାକି ଅଛି",
"refreshIndicatorSemanticLabel": "ରିଫ୍ରେସ୍ କରନ୍ତୁ",
"moreButtonTooltip": "ଅଧିକ",
"dateSeparator": "/",
"dateHelpText": "mm/dd/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_or.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_or.arb",
"repo_id": "flutter",
"token_count": 5381
} | 722 |
{
"scriptCategory": "dense",
"timeOfDayFormat": "h:mm a",
"showAccountsLabel": "கணக்குகளைக் காட்டும்",
"hideAccountsLabel": "கணக்குகளை மறைக்கும்",
"okButtonLabel": "சரி",
"continueButtonLabel": "தொடர்",
"nextPageTooltip": "அடுத்த பக்கம்",
"previousPageTooltip": "முந்தைய பக்கம்",
"firstPageTooltip": "முதல் பக்கத்திற்குச் செல்லும்",
"lastPageTooltip": "கடைசிப் பக்கத்திற்குச் செல்லும்",
"searchFieldLabel": "தேடல்",
"reorderItemToStart": "தொடக்கத்திற்கு நகர்த்தவும்",
"reorderItemToEnd": "இறுதிக்கு நகர்த்தவும்",
"reorderItemUp": "மேலே நகர்த்தவும்",
"reorderItemDown": "கீழே நகர்த்தவும்",
"reorderItemLeft": "இடப்புறம் நகர்த்தவும்",
"reorderItemRight": "வலப்புறம் நகர்த்தவும்",
"cutButtonLabel": "வெட்டு",
"scanTextButtonLabel": "வார்த்தைகளை ஸ்கேன் செய்",
"pasteButtonLabel": "ஒட்டு",
"previousMonthTooltip": "முந்தைய மாதம்",
"nextMonthTooltip": "அடுத்த மாதம்",
"closeButtonLabel": "மூடுக",
"copyButtonLabel": "நகலெடு",
"closeButtonTooltip": "மூடுக",
"deleteButtonTooltip": "நீக்கு",
"selectAllButtonLabel": "அனைத்தையும் தேர்ந்தெடு",
"openAppDrawerTooltip": "வழிசெலுத்தல் மெனுவைத் திற",
"backButtonTooltip": "முந்தைய பக்கம்",
"showMenuTooltip": "மெனுவைக் காட்டு",
"aboutListTileTitle": "$applicationName பற்றி",
"licensesPageTitle": "உரிமங்கள்",
"pageRowsInfoTitle": "$firstRow–$lastRow / $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow / $rowCount",
"rowsPerPageTitle": "ஒரு பக்கத்திற்கான வரிசைகள்:",
"tabLabel": "தாவல் $tabIndex / $tabCount",
"selectedRowCountTitleZero": "எந்த வரிசையும் தேர்ந்தெடுக்கவில்லை",
"selectedRowCountTitleOne": "1 வரிசை தேர்ந்தெடுக்கப்பட்டது",
"selectedRowCountTitleOther": "$selectedRowCount வரிசைகள் தேர்ந்தெடுக்கப்பட்டன",
"cancelButtonLabel": "ரத்துசெய்",
"viewLicensesButtonLabel": "உரிமங்களைக் காட்டு",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "மணிநேரத்தைத் தேர்ந்தெடுக்கவும்",
"timePickerMinuteModeAnnouncement": "நிமிடங்களைத் தேர்ந்தெடுக்கவும்",
"modalBarrierDismissLabel": "நிராகரிக்கும்",
"signedInLabel": "உள்நுழைந்துள்ளீர்கள்",
"drawerLabel": "வழிசெலுத்தல் மெனு",
"popupMenuLabel": "பாப்-அப் மெனு",
"dialogLabel": "உரையாடல்",
"alertDialogLabel": "விழிப்பூட்டல்",
"expandedIconTapHint": "சுருக்கும்",
"collapsedIconTapHint": "விரிக்கும்",
"remainingTextFieldCharacterCountZero": "எழுத்துக்கள் எதுவும் இல்லை",
"remainingTextFieldCharacterCountOne": "1 எழுத்து மீதமுள்ளது",
"remainingTextFieldCharacterCountOther": "$remainingCount எழுத்துகள் மீதமுள்ளன",
"refreshIndicatorSemanticLabel": "ரெஃப்ரெஷ் செய்யும்",
"moreButtonTooltip": "மேலும்",
"dateSeparator": "/",
"dateHelpText": "mm/dd/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_ta.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ta.arb",
"repo_id": "flutter",
"token_count": 6068
} | 723 |
{
"reorderItemToStart": "আৰম্ভণিলৈ স্থানান্তৰ কৰক",
"reorderItemToEnd": "শেষলৈ স্থানান্তৰ কৰক",
"reorderItemUp": "ওপৰলৈ নিয়ক",
"reorderItemDown": "তললৈ স্থানান্তৰ কৰক",
"reorderItemLeft": "বাওঁফাললৈ স্থানান্তৰ কৰক",
"reorderItemRight": "সোঁফাললৈ স্থানান্তৰ কৰক"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_as.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_as.arb",
"repo_id": "flutter",
"token_count": 327
} | 724 |
{
"reorderItemToStart": "Déplacer vers le début",
"reorderItemToEnd": "Déplacer vers la fin",
"reorderItemUp": "Déplacer vers le haut",
"reorderItemDown": "Déplacer vers le bas",
"reorderItemLeft": "Déplacer vers la gauche",
"reorderItemRight": "Déplacer vers la droite"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_fr.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_fr.arb",
"repo_id": "flutter",
"token_count": 112
} | 725 |
{
"reorderItemToStart": "ផ្លាស់ទីទៅចំណុចចាប់ផ្ដើម",
"reorderItemToEnd": "ផ្លាស់ទីទៅចំណុចបញ្ចប់",
"reorderItemUp": "ផ្លាស់ទីឡើងលើ",
"reorderItemDown": "ផ្លាស់ទីចុះក្រោម",
"reorderItemLeft": "ផ្លាស់ទីទៅឆ្វេង",
"reorderItemRight": "ផ្លាស់ទីទៅស្តាំ"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_km.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_km.arb",
"repo_id": "flutter",
"token_count": 388
} | 726 |
{
"reorderItemToStart": "Sogeza hadi mwanzo",
"reorderItemToEnd": "Sogeza hadi mwisho",
"reorderItemUp": "Sogeza juu",
"reorderItemDown": "Sogeza chini",
"reorderItemLeft": "Sogeza kushoto",
"reorderItemRight": "Sogeza kulia"
}
| flutter/packages/flutter_localizations/lib/src/l10n/widgets_sw.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_sw.arb",
"repo_id": "flutter",
"token_count": 104
} | 727 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'l10n/generated_widgets_localizations.dart';
/// Localized values for widgets.
///
/// ## Supported languages
///
/// This class supports locales with the following [Locale.languageCode]s:
///
/// {@macro flutter.localizations.widgets.languages}
///
/// This list is available programmatically via [kWidgetsSupportedLanguages].
///
/// Besides localized strings, this class also maps [locale] to [textDirection].
/// All locales are [TextDirection.ltr] except for locales with the following
/// [Locale.languageCode] values, which are [TextDirection.rtl]:
///
/// * ar - Arabic
/// * fa - Farsi
/// * he - Hebrew
/// * ps - Pashto
/// * sd - Sindhi
/// * ur - Urdu
///
abstract class GlobalWidgetsLocalizations implements WidgetsLocalizations {
/// Construct an object that defines the localized values for the widgets
/// library for the given [textDirection].
const GlobalWidgetsLocalizations(this.textDirection);
@override
final TextDirection textDirection;
/// A [LocalizationsDelegate] for [WidgetsLocalizations].
///
/// Most internationalized apps will use [GlobalMaterialLocalizations.delegates]
/// as the value of [MaterialApp.localizationsDelegates] to include
/// the localizations for both the material and widget libraries.
static const LocalizationsDelegate<WidgetsLocalizations> delegate = _WidgetsLocalizationsDelegate();
}
class _WidgetsLocalizationsDelegate extends LocalizationsDelegate<WidgetsLocalizations> {
const _WidgetsLocalizationsDelegate();
@override
bool isSupported(Locale locale) => kWidgetsSupportedLanguages.contains(locale.languageCode);
static final Map<Locale, Future<WidgetsLocalizations>> _loadedTranslations = <Locale, Future<WidgetsLocalizations>>{};
@override
Future<WidgetsLocalizations> load(Locale locale) {
assert(isSupported(locale));
return _loadedTranslations.putIfAbsent(locale, () {
return SynchronousFuture<WidgetsLocalizations>(getWidgetsTranslation(
locale,
)!);
});
}
@override
bool shouldReload(_WidgetsLocalizationsDelegate old) => false;
@override
String toString() => 'GlobalWidgetsLocalizations.delegate(${kWidgetsSupportedLanguages.length} locales)';
}
| flutter/packages/flutter_localizations/lib/src/widgets_localizations.dart/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/widgets_localizations.dart",
"repo_id": "flutter",
"token_count": 732
} | 728 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui' as ui;
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'finders.dart';
import 'widget_tester.dart';
/// The result of evaluating a semantics node by a [AccessibilityGuideline].
class Evaluation {
/// Create a passing evaluation.
const Evaluation.pass()
: passed = true,
reason = null;
/// Create a failing evaluation, with an optional [reason] explaining the
/// result.
const Evaluation.fail([this.reason]) : passed = false;
// private constructor for adding cases together.
const Evaluation._(this.passed, this.reason);
/// Whether the given tree or node passed the policy evaluation.
final bool passed;
/// If [passed] is false, contains the reason for failure.
final String? reason;
/// Combines two evaluation results.
///
/// The [reason] will be concatenated with a newline, and [passed] will be
/// combined with an `&&` operator.
Evaluation operator +(Evaluation? other) {
if (other == null) {
return this;
}
final StringBuffer buffer = StringBuffer();
if (reason != null && reason!.isNotEmpty) {
buffer.write(reason);
buffer.writeln();
}
if (other.reason != null && other.reason!.isNotEmpty) {
buffer.write(other.reason);
}
return Evaluation._(
passed && other.passed,
buffer.isEmpty ? null : buffer.toString(),
);
}
}
// Examples can assume:
// typedef HomePage = Placeholder;
/// An accessibility guideline describes a recommendation an application should
/// meet to be considered accessible.
///
/// Use [meetsGuideline] matcher to test whether a screen meets the
/// accessibility guideline.
///
/// {@tool snippet}
///
/// This sample demonstrates how to run an accessibility guideline in a unit
/// test against a single screen.
///
/// ```dart
/// testWidgets('HomePage meets androidTapTargetGuideline', (WidgetTester tester) async {
/// final SemanticsHandle handle = tester.ensureSemantics();
/// await tester.pumpWidget(const MaterialApp(home: HomePage()));
/// await expectLater(tester, meetsGuideline(androidTapTargetGuideline));
/// handle.dispose();
/// });
/// ```
/// {@end-tool}
///
/// See also:
/// * [androidTapTargetGuideline], which checks that tappable nodes have a
/// minimum size of 48 by 48 pixels.
/// * [iOSTapTargetGuideline], which checks that tappable nodes have a minimum
/// size of 44 by 44 pixels.
/// * [textContrastGuideline], which provides guidance for text contrast
/// requirements specified by [WCAG](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html#contrast-ratiodef).
/// * [labeledTapTargetGuideline], which enforces that all nodes with a tap or
/// long press action also have a label.
abstract class AccessibilityGuideline {
/// A const constructor allows subclasses to be const.
const AccessibilityGuideline();
/// Evaluate whether the current state of the `tester` conforms to the rule.
FutureOr<Evaluation> evaluate(WidgetTester tester);
/// A description of the policy restrictions and criteria.
String get description;
}
/// A guideline which enforces that all tappable semantics nodes have a minimum
/// size.
///
/// Each platform defines its own guidelines for minimum tap areas.
///
/// See also:
/// * [AccessibilityGuideline], which provides a general overview of
/// accessibility guidelines and how to use them.
/// * [androidTapTargetGuideline], which checks that tappable nodes have a
/// minimum size of 48 by 48 pixels.
/// * [iOSTapTargetGuideline], which checks that tappable nodes have a minimum
/// size of 44 by 44 pixels.
@visibleForTesting
class MinimumTapTargetGuideline extends AccessibilityGuideline {
/// Create a new [MinimumTapTargetGuideline].
const MinimumTapTargetGuideline({required this.size, required this.link});
/// The minimum allowed size of a tappable node.
final Size size;
/// A link describing the tap target guidelines for a platform.
final String link;
/// The gap between targets to their parent scrollables to be consider as valid
/// tap targets.
///
/// This avoid cases where a tap target is partially scrolled off-screen that
/// result in a smaller tap area.
static const double _kMinimumGapToBoundary = 0.001;
@override
FutureOr<Evaluation> evaluate(WidgetTester tester) {
Evaluation result = const Evaluation.pass();
for (final RenderView view in tester.binding.renderViews) {
result += _traverse(
view.flutterView,
view.owner!.semanticsOwner!.rootSemanticsNode!,
);
}
return result;
}
Evaluation _traverse(FlutterView view, SemanticsNode node) {
Evaluation result = const Evaluation.pass();
node.visitChildren((SemanticsNode child) {
result += _traverse(view, child);
return true;
});
if (node.isMergedIntoParent) {
return result;
}
if (shouldSkipNode(node)) {
return result;
}
Rect paintBounds = node.rect;
SemanticsNode? current = node;
while (current != null) {
final Matrix4? transform = current.transform;
if (transform != null) {
paintBounds = MatrixUtils.transformRect(transform, paintBounds);
}
// skip node if it is touching the edge scrollable, since it might
// be partially scrolled offscreen.
if (current.hasFlag(SemanticsFlag.hasImplicitScrolling) &&
_isAtBoundary(paintBounds, current.rect)) {
return result;
}
current = current.parent;
}
final Rect viewRect = Offset.zero & view.physicalSize;
if (_isAtBoundary(paintBounds, viewRect)) {
return result;
}
// shrink by device pixel ratio.
final Size candidateSize = paintBounds.size / view.devicePixelRatio;
if (candidateSize.width < size.width - precisionErrorTolerance ||
candidateSize.height < size.height - precisionErrorTolerance) {
result += Evaluation.fail(
'$node: expected tap target size of at least $size, '
'but found $candidateSize\n'
'See also: $link',
);
}
return result;
}
static bool _isAtBoundary(Rect child, Rect parent) {
if (child.left - parent.left > _kMinimumGapToBoundary &&
parent.right - child.right > _kMinimumGapToBoundary &&
child.top - parent.top > _kMinimumGapToBoundary &&
parent.bottom - child.bottom > _kMinimumGapToBoundary) {
return false;
}
return true;
}
/// Returns whether [SemanticsNode] should be skipped for minimum tap target
/// guideline.
///
/// Skips nodes which are link, hidden, or do not have actions.
bool shouldSkipNode(SemanticsNode node) {
final SemanticsData data = node.getSemanticsData();
// Skip node if it has no actions, or is marked as hidden.
if ((!data.hasAction(ui.SemanticsAction.longPress) &&
!data.hasAction(ui.SemanticsAction.tap)) ||
data.hasFlag(ui.SemanticsFlag.isHidden)) {
return true;
}
// Skip links https://www.w3.org/WAI/WCAG21/Understanding/target-size.html
if (data.hasFlag(ui.SemanticsFlag.isLink)) {
return true;
}
return false;
}
@override
String get description => 'Tappable objects should be at least $size';
}
/// A guideline which enforces that all nodes with a tap or long press action
/// also have a label.
///
/// See also:
/// * [AccessibilityGuideline], which provides a general overview of
/// accessibility guidelines and how to use them.
@visibleForTesting
class LabeledTapTargetGuideline extends AccessibilityGuideline {
const LabeledTapTargetGuideline._();
@override
String get description => 'Tappable widgets should have a semantic label';
@override
FutureOr<Evaluation> evaluate(WidgetTester tester) {
Evaluation result = const Evaluation.pass();
for (final RenderView view in tester.binding.renderViews) {
result += _traverse(view.owner!.semanticsOwner!.rootSemanticsNode!);
}
return result;
}
Evaluation _traverse(SemanticsNode node) {
Evaluation result = const Evaluation.pass();
node.visitChildren((SemanticsNode child) {
result += _traverse(child);
return true;
});
if (node.isMergedIntoParent ||
node.isInvisible ||
node.hasFlag(ui.SemanticsFlag.isHidden) ||
node.hasFlag(ui.SemanticsFlag.isTextField)) {
return result;
}
final SemanticsData data = node.getSemanticsData();
// Skip node if it has no actions, or is marked as hidden.
if (!data.hasAction(ui.SemanticsAction.longPress) &&
!data.hasAction(ui.SemanticsAction.tap)) {
return result;
}
if ((data.label.isEmpty) && (data.tooltip.isEmpty)) {
result += Evaluation.fail(
'$node: expected tappable node to have semantic label, '
'but none was found.',
);
}
return result;
}
}
/// A guideline which verifies that all nodes that contribute semantics via text
/// meet minimum contrast levels.
///
/// The guidelines are defined by the Web Content Accessibility Guidelines,
/// http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html.
///
/// See also:
/// * [AccessibilityGuideline], which provides a general overview of
/// accessibility guidelines and how to use them.
@visibleForTesting
class MinimumTextContrastGuideline extends AccessibilityGuideline {
/// Create a new [MinimumTextContrastGuideline].
const MinimumTextContrastGuideline();
/// The minimum text size considered large for contrast checking.
///
/// Defined by http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html
static const int kLargeTextMinimumSize = 18;
/// The minimum text size for bold text to be considered large for contrast
/// checking.
///
/// Defined by http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html
static const int kBoldTextMinimumSize = 14;
/// The minimum contrast ratio for normal text.
///
/// Defined by http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html
static const double kMinimumRatioNormalText = 4.5;
/// The minimum contrast ratio for large text.
///
/// Defined by http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html
static const double kMinimumRatioLargeText = 3.0;
static const double _kDefaultFontSize = 12.0;
static const double _tolerance = -0.01;
@override
Future<Evaluation> evaluate(WidgetTester tester) async {
Evaluation result = const Evaluation.pass();
for (final RenderView renderView in tester.binding.renderViews) {
final OffsetLayer layer = renderView.debugLayer! as OffsetLayer;
final SemanticsNode root = renderView.owner!.semanticsOwner!.rootSemanticsNode!;
late ui.Image image;
final ByteData? byteData = await tester.binding.runAsync<ByteData?>(
() async {
// Needs to be the same pixel ratio otherwise our dimensions won't match
// the last transform layer.
final double ratio = 1 / renderView.flutterView.devicePixelRatio;
image = await layer.toImage(renderView.paintBounds, pixelRatio: ratio);
final ByteData? data = await image.toByteData();
image.dispose();
return data;
},
);
result += await _evaluateNode(root, tester, image, byteData!, renderView);
}
return result;
}
Future<Evaluation> _evaluateNode(
SemanticsNode node,
WidgetTester tester,
ui.Image image,
ByteData byteData,
RenderView renderView,
) async {
Evaluation result = const Evaluation.pass();
// Skip disabled nodes, as they not required to pass contrast check.
final bool isDisabled = node.hasFlag(ui.SemanticsFlag.hasEnabledState) &&
!node.hasFlag(ui.SemanticsFlag.isEnabled);
if (node.isInvisible ||
node.isMergedIntoParent ||
node.hasFlag(ui.SemanticsFlag.isHidden) ||
isDisabled) {
return result;
}
final SemanticsData data = node.getSemanticsData();
final List<SemanticsNode> children = <SemanticsNode>[];
node.visitChildren((SemanticsNode child) {
children.add(child);
return true;
});
for (final SemanticsNode child in children) {
result += await _evaluateNode(child, tester, image, byteData, renderView);
}
if (shouldSkipNode(data)) {
return result;
}
final String text = data.label.isEmpty ? data.value : data.label;
final Iterable<Element> elements = find.text(text).hitTestable().evaluate();
for (final Element element in elements) {
result += await _evaluateElement(node, element, tester, image, byteData, renderView);
}
return result;
}
Future<Evaluation> _evaluateElement(
SemanticsNode node,
Element element,
WidgetTester tester,
ui.Image image,
ByteData byteData,
RenderView renderView,
) async {
// Look up inherited text properties to determine text size and weight.
late bool isBold;
double? fontSize;
late final Rect screenBounds;
late final Rect paintBoundsWithOffset;
final RenderObject? renderBox = element.renderObject;
if (renderBox is! RenderBox) {
throw StateError('Unexpected renderObject type: $renderBox');
}
final Matrix4 globalTransform = renderBox.getTransformTo(null);
paintBoundsWithOffset = MatrixUtils.transformRect(globalTransform, renderBox.paintBounds.inflate(4.0));
// The semantics node transform will include root view transform, which is
// not included in renderBox.getTransformTo(null). Manually multiply the
// root transform to the global transform.
final Matrix4 rootTransform = Matrix4.identity();
renderView.applyPaintTransform(renderView.child!, rootTransform);
rootTransform.multiply(globalTransform);
screenBounds = MatrixUtils.transformRect(rootTransform, renderBox.paintBounds);
Rect nodeBounds = node.rect;
SemanticsNode? current = node;
while (current != null) {
final Matrix4? transform = current.transform;
if (transform != null) {
nodeBounds = MatrixUtils.transformRect(transform, nodeBounds);
}
current = current.parent;
}
final Rect intersection = nodeBounds.intersect(screenBounds);
if (intersection.width <= 0 || intersection.height <= 0) {
// Skip this element since it doesn't correspond to the given semantic
// node.
return const Evaluation.pass();
}
final Widget widget = element.widget;
final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(element);
if (widget is Text) {
final TextStyle? style = widget.style;
final TextStyle effectiveTextStyle = style == null || style.inherit
? defaultTextStyle.style.merge(widget.style)
: style;
isBold = effectiveTextStyle.fontWeight == FontWeight.bold;
fontSize = effectiveTextStyle.fontSize;
} else if (widget is EditableText) {
isBold = widget.style.fontWeight == FontWeight.bold;
fontSize = widget.style.fontSize;
} else {
throw StateError('Unexpected widget type: ${widget.runtimeType}');
}
if (isNodeOffScreen(paintBoundsWithOffset, renderView.flutterView)) {
return const Evaluation.pass();
}
final Map<Color, int> colorHistogram = _colorsWithinRect(byteData, paintBoundsWithOffset, image.width, image.height);
// Node was too far off screen.
if (colorHistogram.isEmpty) {
return const Evaluation.pass();
}
final _ContrastReport report = _ContrastReport(colorHistogram);
final double contrastRatio = report.contrastRatio();
final double targetContrastRatio = this.targetContrastRatio(fontSize, bold: isBold);
if (contrastRatio - targetContrastRatio >= _tolerance) {
return const Evaluation.pass();
}
return Evaluation.fail(
'$node:\n'
'Expected contrast ratio of at least $targetContrastRatio '
'but found ${contrastRatio.toStringAsFixed(2)} '
'for a font size of $fontSize.\n'
'The computed colors was:\n'
'light - ${report.lightColor}, dark - ${report.darkColor}\n'
'See also: '
'https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html',
);
}
/// Returns whether node should be skipped.
///
/// Skip routes which might have labels, and nodes without any text.
bool shouldSkipNode(SemanticsData data) =>
data.hasFlag(ui.SemanticsFlag.scopesRoute) ||
(data.label.trim().isEmpty && data.value.trim().isEmpty);
/// Returns if a rectangle of node is off the screen.
///
/// Allows node to be of screen partially before culling the node.
bool isNodeOffScreen(Rect paintBounds, ui.FlutterView window) {
final Size windowPhysicalSize = window.physicalSize * window.devicePixelRatio;
return paintBounds.top < -50.0 ||
paintBounds.left < -50.0 ||
paintBounds.bottom > windowPhysicalSize.height + 50.0 ||
paintBounds.right > windowPhysicalSize.width + 50.0;
}
/// Returns the required contrast ratio for the [fontSize] and [bold] setting.
///
/// Defined by http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html
double targetContrastRatio(double? fontSize, {required bool bold}) {
final double fontSizeOrDefault = fontSize ?? _kDefaultFontSize;
if ((bold && fontSizeOrDefault >= kBoldTextMinimumSize) ||
fontSizeOrDefault >= kLargeTextMinimumSize) {
return kMinimumRatioLargeText;
}
return kMinimumRatioNormalText;
}
@override
String get description => 'Text contrast should follow WCAG guidelines';
}
/// A guideline which verifies that all elements specified by [finder]
/// meet minimum contrast levels.
///
/// See also:
/// * [AccessibilityGuideline], which provides a general overview of
/// accessibility guidelines and how to use them.
class CustomMinimumContrastGuideline extends AccessibilityGuideline {
/// Creates a custom guideline which verifies that all elements specified
/// by [finder] meet minimum contrast levels.
///
/// An optional description string can be given using the [description] parameter.
const CustomMinimumContrastGuideline({
required this.finder,
this.minimumRatio = 4.5,
this.tolerance = 0.01,
String description = 'Contrast should follow custom guidelines',
}) : _description = description;
/// The minimum contrast ratio allowed.
///
/// Defaults to 4.5, the minimum contrast
/// ratio for normal text, defined by WCAG.
/// See http://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html.
final double minimumRatio;
/// Tolerance for minimum contrast ratio.
///
/// Any contrast ratio greater than [minimumRatio] or within a distance of [tolerance]
/// from [minimumRatio] passes the test.
/// Defaults to 0.01.
final double tolerance;
/// The [Finder] used to find a subset of elements.
///
/// [finder] determines which subset of elements will be tested for
/// contrast ratio.
final Finder finder;
final String _description;
@override
String get description => _description;
@override
Future<Evaluation> evaluate(WidgetTester tester) async {
// Compute elements to be evaluated.
final List<Element> elements = finder.evaluate().toList();
final Map<FlutterView, ui.Image> images = <FlutterView, ui.Image>{};
final Map<FlutterView, ByteData> byteDatas = <FlutterView, ByteData>{};
// Collate all evaluations into a final evaluation, then return.
Evaluation result = const Evaluation.pass();
for (final Element element in elements) {
final FlutterView view = tester.viewOf(find.byElementPredicate((Element e) => e == element));
final RenderView renderView = tester.binding.renderViews.firstWhere((RenderView r) => r.flutterView == view);
final OffsetLayer layer = renderView.debugLayer! as OffsetLayer;
late final ui.Image image;
late final ByteData byteData;
// Obtain a previously rendered image or render one for a new view.
await tester.binding.runAsync(() async {
image = images[view] ??= await layer.toImage(
renderView.paintBounds,
// Needs to be the same pixel ratio otherwise our dimensions
// won't match the last transform layer.
pixelRatio: 1 / view.devicePixelRatio,
);
byteData = byteDatas[view] ??= (await image.toByteData())!;
});
result = result + _evaluateElement(element, byteData, image);
}
return result;
}
// How to evaluate a single element.
Evaluation _evaluateElement(Element element, ByteData byteData, ui.Image image) {
final RenderBox renderObject = element.renderObject! as RenderBox;
final Rect originalPaintBounds = renderObject.paintBounds;
final Rect inflatedPaintBounds = originalPaintBounds.inflate(4.0);
final Rect paintBounds = Rect.fromPoints(
renderObject.localToGlobal(inflatedPaintBounds.topLeft),
renderObject.localToGlobal(inflatedPaintBounds.bottomRight),
);
final Map<Color, int> colorHistogram = _colorsWithinRect(byteData, paintBounds, image.width, image.height);
if (colorHistogram.isEmpty) {
return const Evaluation.pass();
}
final _ContrastReport report = _ContrastReport(colorHistogram);
final double contrastRatio = report.contrastRatio();
if (contrastRatio >= minimumRatio - tolerance) {
return const Evaluation.pass();
} else {
return Evaluation.fail(
'$element:\nExpected contrast ratio of at least '
'$minimumRatio but found ${contrastRatio.toStringAsFixed(2)} \n'
'The computed light color was: ${report.lightColor}, '
'The computed dark color was: ${report.darkColor}\n'
'$description',
);
}
}
}
/// A class that reports the contrast ratio of a part of the screen.
///
/// Commonly used in accessibility testing to obtain the contrast ratio of
/// text widgets and other types of widgets.
class _ContrastReport {
/// Generates a contrast report given a color histogram.
///
/// The contrast ratio of the most frequent light color and the most
/// frequent dark color is calculated. Colors are divided into light and
/// dark colors based on their lightness as an [HSLColor].
factory _ContrastReport(Map<Color, int> colorHistogram) {
// To determine the lighter and darker color, partition the colors
// by HSL lightness and then choose the mode from each group.
double totalLightness = 0.0;
int count = 0;
for (final MapEntry<Color, int> entry in colorHistogram.entries) {
totalLightness += HSLColor.fromColor(entry.key).lightness * entry.value;
count += entry.value;
}
final double averageLightness = totalLightness / count;
assert(!averageLightness.isNaN);
MapEntry<Color, int>? lightColor;
MapEntry<Color, int>? darkColor;
// Find the most frequently occurring light and dark color.
for (final MapEntry<Color, int> entry in colorHistogram.entries) {
final double lightness = HSLColor.fromColor(entry.key).lightness;
final int count = entry.value;
if (lightness <= averageLightness) {
if (count > (darkColor?.value ?? 0)) {
darkColor = entry;
}
} else if (count > (lightColor?.value ?? 0)) {
lightColor = entry;
}
}
// If there is only single color, it is reported as both dark and light.
return _ContrastReport._(
lightColor?.key ?? darkColor!.key,
darkColor?.key ?? lightColor!.key,
);
}
const _ContrastReport._(this.lightColor, this.darkColor);
/// The most frequently occurring light color. Uses [Colors.transparent] if
/// the rectangle is empty.
final Color lightColor;
/// The most frequently occurring dark color. Uses [Colors.transparent] if
/// the rectangle is empty.
final Color darkColor;
/// Computes the contrast ratio as defined by the WCAG.
///
/// Source: https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html
double contrastRatio() => (lightColor.computeLuminance() + 0.05) / (darkColor.computeLuminance() + 0.05);
}
/// Gives the color histogram of all pixels inside a given rectangle on the
/// screen.
///
/// Given a [ByteData] object [data], which stores the color of each pixel
/// in row-first order, where each pixel is given in 4 bytes in RGBA order,
/// and [paintBounds], the rectangle, and [width] and [height],
// the dimensions of the [ByteData] returns color histogram.
Map<Color, int> _colorsWithinRect(
ByteData data,
Rect paintBounds,
int width,
int height,
) {
final Rect truePaintBounds = paintBounds.intersect(Rect.fromLTWH(0.0, 0.0, width.toDouble(), height.toDouble()));
final int leftX = truePaintBounds.left.floor();
final int rightX = truePaintBounds.right.ceil();
final int topY = truePaintBounds.top.floor();
final int bottomY = truePaintBounds.bottom.ceil();
final Map<int, int> rgbaToCount = <int, int>{};
int getPixel(ByteData data, int x, int y) {
final int offset = (y * width + x) * 4;
return data.getUint32(offset);
}
for (int x = leftX; x < rightX; x++) {
for (int y = topY; y < bottomY; y++) {
rgbaToCount.update(
getPixel(data, x, y),
(int count) => count + 1,
ifAbsent: () => 1,
);
}
}
return rgbaToCount.map<Color, int>((int rgba, int count) {
final int argb = (rgba << 24) | (rgba >> 8) & 0xFFFFFFFF;
return MapEntry<Color, int>(Color(argb), count);
});
}
/// A guideline which requires tappable semantic nodes a minimum size of
/// 48 by 48.
///
/// See also:
///
/// * [Android tap target guidelines](https://support.google.com/accessibility/android/answer/7101858?hl=en).
/// * [AccessibilityGuideline], which provides a general overview of
/// accessibility guidelines and how to use them.
/// * [iOSTapTargetGuideline], which checks that tappable nodes have a minimum
/// size of 44 by 44 pixels.
const AccessibilityGuideline androidTapTargetGuideline = MinimumTapTargetGuideline(
size: Size(48.0, 48.0),
link: 'https://support.google.com/accessibility/android/answer/7101858?hl=en',
);
/// A guideline which requires tappable semantic nodes a minimum size of
/// 44 by 44.
///
/// See also:
///
/// * [iOS human interface guidelines](https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/).
/// * [AccessibilityGuideline], which provides a general overview of
/// accessibility guidelines and how to use them.
/// * [androidTapTargetGuideline], which checks that tappable nodes have a
/// minimum size of 48 by 48 pixels.
const AccessibilityGuideline iOSTapTargetGuideline = MinimumTapTargetGuideline(
size: Size(44.0, 44.0),
link: 'https://developer.apple.com/design/human-interface-guidelines/ios/visual-design/adaptivity-and-layout/',
);
/// A guideline which requires text contrast to meet minimum values.
///
/// This guideline traverses the semantics tree looking for nodes with values or
/// labels that corresponds to a Text or Editable text widget. Given the
/// background pixels for the area around this widget, it performs a very naive
/// partitioning of the colors into "light" and "dark" and then chooses the most
/// frequently occurring color in each partition as a representative of the
/// foreground and background colors. The contrast ratio is calculated from
/// these colors according to the [WCAG](https://www.w3.org/TR/UNDERSTANDING-WCAG20/visual-audio-contrast-contrast.html#contrast-ratiodef)
///
/// * [AccessibilityGuideline], which provides a general overview of
/// accessibility guidelines and how to use them.
const AccessibilityGuideline textContrastGuideline = MinimumTextContrastGuideline();
/// A guideline which enforces that all nodes with a tap or long press action
/// also have a label.
///
/// * [AccessibilityGuideline], which provides a general overview of
/// accessibility guidelines and how to use them.
const AccessibilityGuideline labeledTapTargetGuideline = LabeledTapTargetGuideline._();
| flutter/packages/flutter_test/lib/src/accessibility.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/accessibility.dart",
"repo_id": "flutter",
"token_count": 9334
} | 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 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
/// The [RestorationManager] used for tests.
///
/// Unlike the real [RestorationManager], this one just keeps the restoration
/// data in memory and does not make it available to the engine.
class TestRestorationManager extends RestorationManager {
/// Creates a [TestRestorationManager].
TestRestorationManager() {
// Ensures that [rootBucket] always returns a synchronous future to avoid
// extra pumps in tests.
restoreFrom(TestRestorationData.empty);
}
@override
Future<RestorationBucket?> get rootBucket {
_debugRootBucketAccessed = true;
return super.rootBucket;
}
/// The current restoration data from which the current state can be restored.
///
/// To restore the state to the one described by this data, pass the
/// [TestRestorationData] obtained from this getter back to [restoreFrom].
///
/// See also:
///
/// * [WidgetTester.getRestorationData], which makes this data available
/// in a widget test.
TestRestorationData get restorationData => _restorationData;
late TestRestorationData _restorationData;
/// Whether the [rootBucket] has been obtained.
bool get debugRootBucketAccessed => _debugRootBucketAccessed;
bool _debugRootBucketAccessed = false;
/// Restores the state from the provided [TestRestorationData].
///
/// The restoration data obtained form [restorationData] can be passed into
/// this method to restore the state to what it was when the restoration data
/// was originally retrieved.
///
/// See also:
///
/// * [WidgetTester.restoreFrom], which exposes this method to a widget test.
void restoreFrom(TestRestorationData data) {
_restorationData = data;
handleRestorationUpdateFromEngine(enabled: true, data: data.binary);
}
/// Disabled state restoration.
///
/// To turn restoration back on call [restoreFrom].
void disableRestoration() {
_restorationData = TestRestorationData.empty;
handleRestorationUpdateFromEngine(enabled: false, data: null);
}
@override
Future<void> sendToEngine(Uint8List encodedData) async {
_restorationData = TestRestorationData._(encodedData);
}
}
/// Restoration data that can be used to restore the state to the one described
/// by this data.
///
/// See also:
///
/// * [WidgetTester.getRestorationData], which retrieves the restoration data
/// from the widget under test.
/// * [WidgetTester.restoreFrom], which takes a [TestRestorationData] to
/// restore the state of the widget under test from the provided data.
class TestRestorationData {
const TestRestorationData._(this.binary);
/// Empty restoration data indicating that no data is available to restore
/// state from.
static const TestRestorationData empty = TestRestorationData._(null);
/// The serialized representation of the restoration data.
///
/// Should only be accessed by the test framework.
@protected
final Uint8List? binary;
}
| flutter/packages/flutter_test/lib/src/restoration.dart/0 | {
"file_path": "flutter/packages/flutter_test/lib/src/restoration.dart",
"repo_id": "flutter",
"token_count": 879
} | 730 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('collectAllElements goes in LTR DFS', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
await tester.pumpWidget(Directionality(
key: key,
textDirection: TextDirection.ltr,
child: Row(
children: <Widget>[
RichText(text: const TextSpan(text: 'a')),
RichText(text: const TextSpan(text: 'b')),
],
),
));
final List<Element> elements = collectAllElementsFrom(
key.currentContext! as Element,
skipOffstage: false,
).toList();
expect(elements.length, 3);
expect(elements[0].widget, isA<Row>());
expect(elements[1].widget, isA<RichText>());
expect(((elements[1].widget as RichText).text as TextSpan).text, 'a');
expect(elements[2].widget, isA<RichText>());
expect(((elements[2].widget as RichText).text as TextSpan).text, 'b');
});
}
| flutter/packages/flutter_test/test/all_elements_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/all_elements_test.dart",
"repo_id": "flutter",
"token_count": 441
} | 731 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'utils/fake_and_mock_utils.dart';
void main() {
group('TestDisplay', () {
Display trueDisplay() => PlatformDispatcher.instance.displays.single;
TestDisplay boundDisplay() => WidgetsBinding.instance.platformDispatcher.displays.single as TestDisplay;
tearDown(() {
boundDisplay().reset();
});
testWidgets('can handle new methods without breaking', (WidgetTester tester) async {
final dynamic testDisplay = tester.view.display;
//ignore: avoid_dynamic_calls
expect(testDisplay.someNewProperty, null);
});
testWidgets('can fake devicePixelRatio', (WidgetTester tester) async {
verifyPropertyFaked<double>(
tester: tester,
realValue: trueDisplay().devicePixelRatio,
fakeValue: trueDisplay().devicePixelRatio + 1,
propertyRetriever: () => boundDisplay().devicePixelRatio,
propertyFaker: (_, double fake) {
boundDisplay().devicePixelRatio = fake;
},
);
});
testWidgets('can reset devicePixelRatio', (WidgetTester tester) async {
verifyPropertyReset<double>(
tester: tester,
fakeValue: trueDisplay().devicePixelRatio + 1,
propertyRetriever: () => boundDisplay().devicePixelRatio,
propertyResetter: () => boundDisplay().resetDevicePixelRatio(),
propertyFaker: (double fake) {
boundDisplay().devicePixelRatio = fake;
},
);
});
testWidgets('resetting devicePixelRatio also resets view.devicePixelRatio', (WidgetTester tester) async {
verifyPropertyReset(
tester: tester,
fakeValue: trueDisplay().devicePixelRatio + 1,
propertyRetriever: () => tester.view.devicePixelRatio,
propertyResetter: () => boundDisplay().resetDevicePixelRatio(),
propertyFaker: (double dpr) => boundDisplay().devicePixelRatio = dpr,
);
});
testWidgets('updating devicePixelRatio also updates view.devicePixelRatio', (WidgetTester tester) async {
tester.view.display.devicePixelRatio = tester.view.devicePixelRatio + 1;
expect(tester.view.devicePixelRatio, tester.view.display.devicePixelRatio);
});
testWidgets('can fake refreshRate', (WidgetTester tester) async {
verifyPropertyFaked<double>(
tester: tester,
realValue: trueDisplay().refreshRate,
fakeValue: trueDisplay().refreshRate + 1,
propertyRetriever: () => boundDisplay().refreshRate,
propertyFaker: (_, double fake) {
boundDisplay().refreshRate = fake;
},
);
});
testWidgets('can reset refreshRate', (WidgetTester tester) async {
verifyPropertyReset<double>(
tester: tester,
fakeValue: trueDisplay().refreshRate + 1,
propertyRetriever: () => boundDisplay().refreshRate,
propertyResetter: () => boundDisplay().resetRefreshRate(),
propertyFaker: (double fake) {
boundDisplay().refreshRate = fake;
},
);
});
testWidgets('can fake size', (WidgetTester tester) async {
verifyPropertyFaked<Size>(
tester: tester,
realValue: trueDisplay().size,
fakeValue: const Size(354, 856),
propertyRetriever: () => boundDisplay().size,
propertyFaker: (_, Size fake) {
boundDisplay().size = fake;
},
);
});
testWidgets('can reset size', (WidgetTester tester) async {
verifyPropertyReset<Size>(
tester: tester,
fakeValue: const Size(465, 980),
propertyRetriever: () => boundDisplay().size,
propertyResetter: () => boundDisplay().resetSize(),
propertyFaker: (Size fake) {
boundDisplay().size = fake;
},
);
});
testWidgets('can reset all values', (WidgetTester tester) async {
final DisplaySnapshot initial = DisplaySnapshot(tester.view.display);
tester.view.display.devicePixelRatio = 7;
tester.view.display.refreshRate = 40;
tester.view.display.size = const Size(476, 823);
final DisplaySnapshot faked = DisplaySnapshot(tester.view.display);
tester.view.display.reset();
final DisplaySnapshot reset = DisplaySnapshot(tester.view.display);
expect(initial, isNot(matchesSnapshot(faked)));
expect(initial, matchesSnapshot(reset));
});
});
}
class DisplaySnapshot {
DisplaySnapshot(Display display) :
devicePixelRatio = display.devicePixelRatio,
refreshRate = display.refreshRate,
id = display.id,
size = display.size;
final double devicePixelRatio;
final double refreshRate;
final int id;
final Size size;
}
Matcher matchesSnapshot(DisplaySnapshot expected) => _DisplaySnapshotMatcher(expected);
class _DisplaySnapshotMatcher extends Matcher {
_DisplaySnapshotMatcher(this.expected);
final DisplaySnapshot expected;
@override
Description describe(Description description) {
description.add('snapshot of a Display matches');
return description;
}
@override
Description describeMismatch(dynamic item, Description mismatchDescription, Map<dynamic, dynamic> matchState, bool verbose) {
assert(item is DisplaySnapshot, 'Can only match against snapshots of Display.');
final DisplaySnapshot actual = item as DisplaySnapshot;
if (actual.devicePixelRatio != expected.devicePixelRatio) {
mismatchDescription.add('actual.devicePixelRatio (${actual.devicePixelRatio}) did not match expected.devicePixelRatio (${expected.devicePixelRatio})');
}
if (actual.refreshRate != expected.refreshRate) {
mismatchDescription.add('actual.refreshRate (${actual.refreshRate}) did not match expected.refreshRate (${expected.refreshRate})');
}
if (actual.size != expected.size) {
mismatchDescription.add('actual.size (${actual.size}) did not match expected.size (${expected.size})');
}
if (actual.id != expected.id) {
mismatchDescription.add('actual.id (${actual.id}) did not match expected.id (${expected.id})');
}
return mismatchDescription;
}
@override
bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
assert(item is DisplaySnapshot, 'Can only match against snapshots of Display.');
final DisplaySnapshot actual = item as DisplaySnapshot;
return actual.devicePixelRatio == expected.devicePixelRatio &&
actual.refreshRate == expected.refreshRate &&
actual.size == expected.size &&
actual.id == expected.id;
}
}
| flutter/packages/flutter_test/test/display_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/display_test.dart",
"repo_id": "flutter",
"token_count": 2434
} | 732 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[];
Future<void> testExecutable(FutureOr<void> Function() testMain) async {
reportTestException = (FlutterErrorDetails details, String testDescription) {
errors.add(details);
};
// The error that the test throws in their run methods below will be forwarded
// to our exception handler above and do not cause the test to fail. The
// tearDown method then checks that the test threw the expected exception.
await testMain();
}
void pipelineOwnerTestRun() {
testWidgets('open SemanticsHandle from PipelineOwner fails test', (WidgetTester tester) async {
final int outstandingHandles = tester.binding.debugOutstandingSemanticsHandles;
tester.binding.ensureSemantics();
expect(tester.binding.debugOutstandingSemanticsHandles, outstandingHandles + 1);
// SemanticsHandle is not disposed on purpose to verify in tearDown that
// the test failed due to an active SemanticsHandle.
});
tearDown(() {
expect(errors, hasLength(1));
expect(errors.single.toString(), contains('SemanticsHandle was active at the end of the test'));
});
}
void semanticsBindingTestRun() {
testWidgets('open SemanticsHandle from SemanticsBinding fails test', (WidgetTester tester) async {
final int outstandingHandles = tester.binding.debugOutstandingSemanticsHandles;
tester.binding.ensureSemantics();
expect(tester.binding.debugOutstandingSemanticsHandles, outstandingHandles + 1);
// SemanticsHandle is not disposed on purpose to verify in tearDown that
// the test failed due to an active SemanticsHandle.
});
tearDown(() {
expect(errors, hasLength(1));
expect(errors.single.toString(), contains('SemanticsHandle was active at the end of the test'));
});
}
void failingTestTestRun() {
testWidgets('open SemanticsHandle from SemanticsBinding fails test', (WidgetTester tester) async {
final int outstandingHandles = tester.binding.debugOutstandingSemanticsHandles;
tester.binding.ensureSemantics();
expect(tester.binding.debugOutstandingSemanticsHandles, outstandingHandles + 1);
// Failing expectation to verify that an open semantics handle doesn't
// cause any cascading failures and only the failing expectation is
// reported.
expect(1, equals(2));
fail('The test should never have gotten this far.');
});
tearDown(() {
expect(errors, hasLength(1));
expect(errors.single.toString(), contains('Expected: <2>'));
expect(errors.single.toString(), contains('Actual: <1>'));
});
}
| flutter/packages/flutter_test/test/semantics_checker/flutter_test_config.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/semantics_checker/flutter_test_config.dart",
"repo_id": "flutter",
"token_count": 834
} | 733 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
class RecognizableTestException implements Exception {
const RecognizableTestException();
}
class TestDelegate extends BinaryMessenger {
@override
Future<ByteData?>? send(String channel, ByteData? message) async {
expect(channel, '');
expect(message, isNull);
throw const RecognizableTestException();
}
// Rest of the API isn't needed for this test.
@override
Future<void> handlePlatformMessage(String channel, ByteData? data, ui.PlatformMessageResponseCallback? callback) => throw UnimplementedError();
@override
void setMessageHandler(String channel, MessageHandler? handler) => throw UnimplementedError();
}
class WorkingTestDelegate extends BinaryMessenger {
@override
Future<ByteData?>? send(String channel, ByteData? message) async {
return ByteData.sublistView(Uint8List.fromList(<int>[1, 2, 3]));
}
// Rest of the API isn't needed for this test.
@override
Future<void> handlePlatformMessage(String channel, ByteData? data, ui.PlatformMessageResponseCallback? callback) => throw UnimplementedError();
@override
void setMessageHandler(String channel, MessageHandler? handler) => throw UnimplementedError();
}
void main() {
testWidgets('Caught exceptions are caught by the test framework', (WidgetTester tester) async {
final BinaryMessenger delegate = TestDelegate();
final Future<ByteData?>? future = delegate.send('', null);
expect(future, isNotNull);
// TODO(srawlins): Fix this static issue,
// https://github.com/flutter/flutter/issues/105750.
// ignore: body_might_complete_normally_catch_error
await future!.catchError((Object error) { });
try {
await TestDefaultBinaryMessenger(delegate).send('', null);
expect(true, isFalse); // should not reach here
} catch (error) {
expect(error, const RecognizableTestException());
}
});
testWidgets('Mock MessageHandler is set correctly',
(WidgetTester tester) async {
final TestDefaultBinaryMessenger binaryMessenger =
TestDefaultBinaryMessenger(WorkingTestDelegate());
binaryMessenger.setMockMessageHandler(
'',
(ByteData? message) async =>
ByteData.sublistView(Uint8List.fromList(<int>[2, 3, 4])));
final ByteData? result = await binaryMessenger.send('', null);
expect(result?.buffer.asUint8List(), Uint8List.fromList(<int>[2, 3, 4]));
});
test('Mock StreamHandler is set correctly', () async {
const EventChannel channel = EventChannel('');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockStreamHandler(
channel,
MockStreamHandler.inline(onListen: (Object? arguments, MockStreamHandlerEventSink events) {
events.success(arguments);
events.error(code: 'code', message: 'message', details: 'details');
events.endOfStream();
})
);
expect(
channel.receiveBroadcastStream('argument'),
emitsInOrder(<Object?>[
'argument',
emitsError(
isA<PlatformException>()
.having((PlatformException e) => e.code, 'code', 'code')
.having((PlatformException e) => e.message, 'message', 'message')
.having((PlatformException e) => e.details, 'details', 'details'),
),
emitsDone,
]),
);
});
testWidgets('Mock AllMessagesHandler is set correctly',
(WidgetTester tester) async {
final TestDefaultBinaryMessenger binaryMessenger =
TestDefaultBinaryMessenger(WorkingTestDelegate());
binaryMessenger.allMessagesHandler =
(String channel, MessageHandler? handler, ByteData? message) async =>
ByteData.sublistView(Uint8List.fromList(<int>[2, 3, 4]));
final ByteData? result = await binaryMessenger.send('', null);
expect(result?.buffer.asUint8List(), Uint8List.fromList(<int>[2, 3, 4]));
});
}
| flutter/packages/flutter_test/test/test_default_binary_messenger_test.dart/0 | {
"file_path": "flutter/packages/flutter_test/test/test_default_binary_messenger_test.dart",
"repo_id": "flutter",
"token_count": 1416
} | 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.
// Do not add package imports to this file.
import 'dart:convert'; // flutter_ignore: dart_convert_import.
import 'dart:io'; // flutter_ignore: dart_io_import.
/// Executes the required Flutter tasks for a desktop build.
Future<void> main(List<String> arguments) async {
final String targetPlatform = arguments[0];
final String buildMode = arguments[1].toLowerCase();
final String? dartDefines = Platform.environment['DART_DEFINES'];
final bool dartObfuscation = Platform.environment['DART_OBFUSCATION'] == 'true';
final String? frontendServerStarterPath = Platform.environment['FRONTEND_SERVER_STARTER_PATH'];
final String? extraFrontEndOptions = Platform.environment['EXTRA_FRONT_END_OPTIONS'];
final String? extraGenSnapshotOptions = Platform.environment['EXTRA_GEN_SNAPSHOT_OPTIONS'];
final String? flutterEngine = Platform.environment['FLUTTER_ENGINE'];
final String? flutterRoot = Platform.environment['FLUTTER_ROOT'];
final String flutterTarget = Platform.environment['FLUTTER_TARGET']
?? pathJoin(<String>['lib', 'main.dart']);
final String? codeSizeDirectory = Platform.environment['CODE_SIZE_DIRECTORY'];
final String? localEngine = Platform.environment['LOCAL_ENGINE'];
final String? localEngineHost = Platform.environment['LOCAL_ENGINE_HOST'];
final String? projectDirectory = Platform.environment['PROJECT_DIR'];
final String? splitDebugInfo = Platform.environment['SPLIT_DEBUG_INFO'];
final String? bundleSkSLPath = Platform.environment['BUNDLE_SKSL_PATH'];
final bool trackWidgetCreation = Platform.environment['TRACK_WIDGET_CREATION'] == 'true';
final bool treeShakeIcons = Platform.environment['TREE_SHAKE_ICONS'] == 'true';
final bool verbose = Platform.environment['VERBOSE_SCRIPT_LOGGING'] == 'true';
final bool prefixedErrors = Platform.environment['PREFIXED_ERROR_LOGGING'] == 'true';
if (projectDirectory == null) {
stderr.write('PROJECT_DIR environment variable must be set to the location of Flutter project to be built.');
exit(1);
}
if (flutterRoot == null || flutterRoot.isEmpty) {
stderr.write('FLUTTER_ROOT environment variable must be set to the location of the Flutter SDK.');
exit(1);
}
Directory.current = projectDirectory;
if (localEngine != null && !localEngine.contains(buildMode)) {
stderr.write('''
ERROR: Requested build with Flutter local engine at '$localEngine'
This engine is not compatible with FLUTTER_BUILD_MODE: '$buildMode'.
You can fix this by updating the LOCAL_ENGINE environment variable, or
by running:
flutter build <platform> --local-engine=<platform>_$buildMode --local-engine-host=host_$buildMode
or
flutter build <platform> --local-engine=<platform>_${buildMode}_unopt --local-engine-host=host_${buildMode}_unopt
========================================================================
''');
exit(1);
}
if (localEngineHost != null && !localEngineHost.contains(buildMode)) {
stderr.write('''
ERROR: Requested build with Flutter local engine host at '$localEngineHost'
This engine is not compatible with FLUTTER_BUILD_MODE: '$buildMode'.
You can fix this by updating the LOCAL_ENGINE_HOST environment variable, or
by running:
flutter build <platform> --local-engine=<platform>_$buildMode --local-engine-host=host_$buildMode
or
flutter build <platform> --local-engine=<platform>_$buildMode --local-engine-host=host_${buildMode}_unopt
========================================================================
''');
exit(1);
}
final String flutterExecutable = pathJoin(<String>[
flutterRoot,
'bin',
if (Platform.isWindows)
'flutter.bat'
else
'flutter',
]);
final String bundlePlatform = targetPlatform;
final String target = '${buildMode}_bundle_${bundlePlatform}_assets';
final Process assembleProcess = await Process.start(
flutterExecutable,
<String>[
if (verbose)
'--verbose',
if (prefixedErrors)
'--prefixed-errors',
if (flutterEngine != null) '--local-engine-src-path=$flutterEngine',
if (localEngine != null) '--local-engine=$localEngine',
if (localEngineHost != null) '--local-engine-host=$localEngineHost',
'assemble',
'--no-version-check',
'--output=build',
'-dTargetPlatform=$targetPlatform',
'-dTrackWidgetCreation=$trackWidgetCreation',
'-dBuildMode=$buildMode',
'-dTargetFile=$flutterTarget',
'-dTreeShakeIcons="$treeShakeIcons"',
'-dDartObfuscation=$dartObfuscation',
if (bundleSkSLPath != null)
'-dBundleSkSLPath=$bundleSkSLPath',
if (codeSizeDirectory != null)
'-dCodeSizeDirectory=$codeSizeDirectory',
if (splitDebugInfo != null)
'-dSplitDebugInfo=$splitDebugInfo',
if (dartDefines != null)
'--DartDefines=$dartDefines',
if (extraGenSnapshotOptions != null)
'--ExtraGenSnapshotOptions=$extraGenSnapshotOptions',
if (frontendServerStarterPath != null)
'-dFrontendServerStarterPath=$frontendServerStarterPath',
if (extraFrontEndOptions != null)
'--ExtraFrontEndOptions=$extraFrontEndOptions',
target,
],
);
assembleProcess.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen(stdout.writeln);
assembleProcess.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen(stderr.writeln);
if (await assembleProcess.exitCode != 0) {
exit(1);
}
}
/// Perform a simple path join on the segments based on the current platform.
///
/// Does not normalize paths that have repeated separators.
String pathJoin(List<String> segments) {
final String separator = Platform.isWindows ? r'\' : '/';
return segments.join(separator);
}
| flutter/packages/flutter_tools/bin/tool_backend.dart/0 | {
"file_path": "flutter/packages/flutter_tools/bin/tool_backend.dart",
"repo_id": "flutter",
"token_count": 1964
} | 735 |
// This script is used to warm the Gradle cache by downloading the Flutter dependencies
// used during the build. This script is invoked when `flutter precache` is run.
//
// Command:
// gradle -b <flutter-sdk>packages/flutter_tools/gradle/resolve_dependencies.gradle
// resolveDependencies
//
// This way, Gradle can run with the `--offline` flag later on to eliminate any
// network request during the build process.
//
// This includes:
// 1. The embedding
// 2. libflutter.so
import java.nio.file.Paths
String storageUrl = System.getenv('FLUTTER_STORAGE_BASE_URL') ?: "https://storage.googleapis.com"
String engineRealm = Paths.get(flutterRoot.absolutePath, "bin", "internal", "engine.realm")
.toFile().text.trim()
if (engineRealm) {
engineRealm = engineRealm + "/"
}
repositories {
google()
mavenCentral()
maven {
url "$storageUrl/${engineRealm}download.flutter.io"
}
}
File flutterRoot = projectDir.parentFile.parentFile.parentFile
assert flutterRoot.isDirectory()
String engineVersion = Paths.get(flutterRoot.absolutePath, "bin", "internal", "engine.version")
.toFile().text.trim()
configurations {
flutterRelease.extendsFrom releaseImplementation
flutterDebug.extendsFrom debugImplementation
flutterProfile.extendsFrom debugImplementation
}
dependencies {
flutterRelease "io.flutter:flutter_embedding_release:1.0.0-$engineVersion"
flutterRelease "io.flutter:armeabi_v7a_release:1.0.0-$engineVersion"
flutterRelease "io.flutter:arm64_v8a_release:1.0.0-$engineVersion"
flutterProfile "io.flutter:flutter_embedding_profile:1.0.0-$engineVersion"
flutterProfile "io.flutter:armeabi_v7a_profile:1.0.0-$engineVersion"
flutterProfile "io.flutter:arm64_v8a_profile:1.0.0-$engineVersion"
flutterDebug "io.flutter:flutter_embedding_debug:1.0.0-$engineVersion"
flutterDebug "io.flutter:armeabi_v7a_debug:1.0.0-$engineVersion"
flutterDebug "io.flutter:arm64_v8a_debug:1.0.0-$engineVersion"
flutterDebug "io.flutter:x86_debug:1.0.0-$engineVersion"
flutterDebug "io.flutter:x86_64_debug:1.0.0-$engineVersion"
}
task resolveDependencies {
configurations.each { configuration ->
if (configuration.name.startsWith("flutter")) {
configuration.resolve()
}
}
}
| flutter/packages/flutter_tools/gradle/resolve_dependencies.gradle/0 | {
"file_path": "flutter/packages/flutter_tools/gradle/resolve_dependencies.gradle",
"repo_id": "flutter",
"token_count": 867
} | 736 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="catalog - custom_semantics" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/examples/catalog/lib/custom_semantics.dart" />
<method />
</configuration>
</component> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___custom_semantics.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___custom_semantics.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 96
} | 737 |
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="manual_tests - card_collection" type="FlutterRunConfigurationType" factoryName="Flutter">
<option name="filePath" value="$PROJECT_DIR$/dev/manual_tests/lib/card_collection.dart" />
<method />
</configuration>
</component> | flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___card_collection.xml.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/manual_tests___card_collection.xml.copy.tmpl",
"repo_id": "flutter",
"token_count": 97
} | 738 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import '../application_package.dart';
import '../base/common.dart' show throwToolExit;
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../build_info.dart';
import '../convert.dart';
import '../device.dart';
import '../device_port_forwarder.dart';
import '../project.dart';
import '../protocol_discovery.dart';
import 'android.dart';
import 'android_builder.dart';
import 'android_console.dart';
import 'android_sdk.dart';
import 'application_package.dart';
/// Whether the [AndroidDevice] is believed to be a physical device or an emulator.
enum HardwareType { emulator, physical }
/// Map to help our `isLocalEmulator` detection.
///
/// See [AndroidDevice] for more explanation of why this is needed.
const Map<String, HardwareType> kKnownHardware = <String, HardwareType>{
'goldfish': HardwareType.emulator,
'qcom': HardwareType.physical,
'ranchu': HardwareType.emulator,
'samsungexynos7420': HardwareType.physical,
'samsungexynos7580': HardwareType.physical,
'samsungexynos7870': HardwareType.physical,
'samsungexynos7880': HardwareType.physical,
'samsungexynos8890': HardwareType.physical,
'samsungexynos8895': HardwareType.physical,
'samsungexynos9810': HardwareType.physical,
'samsungexynos7570': HardwareType.physical,
};
/// A physical Android device or emulator.
///
/// While [isEmulator] attempts to distinguish between the device categories,
/// this is a best effort process and not a guarantee; certain physical devices
/// identify as emulators. These device identifiers may be added to the [kKnownHardware]
/// map to specify that they are actually physical devices.
class AndroidDevice extends Device {
AndroidDevice(
super.id, {
this.productID,
required this.modelID,
this.deviceCodeName,
required Logger logger,
required ProcessManager processManager,
required Platform platform,
required AndroidSdk androidSdk,
required FileSystem fileSystem,
AndroidConsoleSocketFactory androidConsoleSocketFactory = kAndroidConsoleSocketFactory,
}) : _logger = logger,
_processManager = processManager,
_androidSdk = androidSdk,
_platform = platform,
_fileSystem = fileSystem,
_androidConsoleSocketFactory = androidConsoleSocketFactory,
_processUtils = ProcessUtils(logger: logger, processManager: processManager),
super(
category: Category.mobile,
platformType: PlatformType.android,
ephemeral: true,
);
final Logger _logger;
final ProcessManager _processManager;
final AndroidSdk _androidSdk;
final Platform _platform;
final FileSystem _fileSystem;
final ProcessUtils _processUtils;
final AndroidConsoleSocketFactory _androidConsoleSocketFactory;
final String? productID;
final String modelID;
final String? deviceCodeName;
@override
// Wirelessly paired Android devices should have `adb-tls-connect` in the id.
// Source: https://android.googlesource.com/platform/packages/modules/adb/+/f4ba8d73079b99532069dbe888a58167b8723d6c/adb_mdns.h#30
DeviceConnectionInterface get connectionInterface =>
id.contains('adb-tls-connect')
? DeviceConnectionInterface.wireless
: DeviceConnectionInterface.attached;
late final Future<Map<String, String>> _properties = () async {
Map<String, String> properties = <String, String>{};
final List<String> propCommand = adbCommandForDevice(<String>['shell', 'getprop']);
_logger.printTrace(propCommand.join(' '));
try {
// We pass an encoding of latin1 so that we don't try and interpret the
// `adb shell getprop` result as UTF8.
final ProcessResult result = await _processManager.run(
propCommand,
stdoutEncoding: latin1,
stderrEncoding: latin1,
);
if (result.exitCode == 0 || _allowHeapCorruptionOnWindows(result.exitCode, _platform)) {
properties = parseAdbDeviceProperties(result.stdout as String);
} else {
_logger.printError('Error ${result.exitCode} retrieving device properties for $name:');
_logger.printError(result.stderr as String);
}
} on ProcessException catch (error) {
_logger.printError('Error retrieving device properties for $name: $error');
}
return properties;
}();
Future<String?> _getProperty(String name) async {
return (await _properties)[name];
}
@override
late final Future<bool> isLocalEmulator = () async {
final String? hardware = await _getProperty('ro.hardware');
_logger.printTrace('ro.hardware = $hardware');
if (kKnownHardware.containsKey(hardware)) {
// Look for known hardware models.
return kKnownHardware[hardware] == HardwareType.emulator;
}
// Fall back to a best-effort heuristic-based approach.
final String? characteristics = await _getProperty('ro.build.characteristics');
_logger.printTrace('ro.build.characteristics = $characteristics');
return characteristics != null && characteristics.contains('emulator');
}();
/// The unique identifier for the emulator that corresponds to this device, or
/// null if it is not an emulator.
///
/// The ID returned matches that in the output of `flutter emulators`. Fetching
/// this name may require connecting to the device and if an error occurs null
/// will be returned.
@override
Future<String?> get emulatorId async {
if (!(await isLocalEmulator)) {
return null;
}
// Emulators always have IDs in the format emulator-(port) where port is the
// Android Console port number.
final RegExp emulatorPortRegex = RegExp(r'emulator-(\d+)');
final Match? portMatch = emulatorPortRegex.firstMatch(id);
if (portMatch == null || portMatch.groupCount < 1) {
return null;
}
const String host = 'localhost';
final int port = int.parse(portMatch.group(1)!);
_logger.printTrace('Fetching avd name for $name via Android console on $host:$port');
try {
final Socket socket = await _androidConsoleSocketFactory(host, port);
final AndroidConsole console = AndroidConsole(socket);
try {
await console
.connect()
.timeout(const Duration(seconds: 2),
onTimeout: () => throw TimeoutException('Connection timed out'));
return await console
.getAvdName()
.timeout(const Duration(seconds: 2),
onTimeout: () => throw TimeoutException('"avd name" timed out'));
} finally {
console.destroy();
}
} on Exception catch (e) {
_logger.printTrace('Failed to fetch avd name for emulator at $host:$port: $e');
// If we fail to connect to the device, we should not fail so just return
// an empty name. This data is best-effort.
return null;
}
}
@override
late final Future<TargetPlatform> targetPlatform = () async {
// http://developer.android.com/ndk/guides/abis.html (x86, armeabi-v7a, ...)
switch (await _getProperty('ro.product.cpu.abi')) {
case 'arm64-v8a':
// Perform additional verification for 64 bit ABI. Some devices,
// like the Kindle Fire 8, misreport the abilist. We might not
// be able to retrieve this property, in which case we fall back
// to assuming 64 bit.
final String? abilist = await _getProperty('ro.product.cpu.abilist');
if (abilist == null || abilist.contains('arm64-v8a')) {
return TargetPlatform.android_arm64;
} else {
return TargetPlatform.android_arm;
}
case 'x86_64':
return TargetPlatform.android_x64;
case 'x86':
return TargetPlatform.android_x86;
default:
return TargetPlatform.android_arm;
}
}();
@override
Future<bool> supportsRuntimeMode(BuildMode buildMode) async {
switch (await targetPlatform) {
case TargetPlatform.android_arm:
case TargetPlatform.android_arm64:
case TargetPlatform.android_x64:
return buildMode != BuildMode.jitRelease;
case TargetPlatform.android_x86:
return buildMode == BuildMode.debug;
case TargetPlatform.android:
case TargetPlatform.darwin:
case TargetPlatform.fuchsia_arm64:
case TargetPlatform.fuchsia_x64:
case TargetPlatform.ios:
case TargetPlatform.linux_arm64:
case TargetPlatform.linux_x64:
case TargetPlatform.tester:
case TargetPlatform.web_javascript:
case TargetPlatform.windows_x64:
case TargetPlatform.windows_arm64:
throw UnsupportedError('Invalid target platform for Android');
}
}
@override
Future<String> get sdkNameAndVersion async => 'Android ${await _sdkVersion} (API ${await apiVersion})';
Future<String?> get _sdkVersion => _getProperty('ro.build.version.release');
@visibleForTesting
Future<String?> get apiVersion => _getProperty('ro.build.version.sdk');
AdbLogReader? _logReader;
AdbLogReader? _pastLogReader;
List<String> adbCommandForDevice(List<String> args) {
return <String>[_androidSdk.adbPath!, '-s', id, ...args];
}
Future<RunResult> runAdbCheckedAsync(
List<String> params, {
String? workingDirectory,
bool allowReentrantFlutter = false,
}) async {
return _processUtils.run(
adbCommandForDevice(params),
throwOnError: true,
workingDirectory: workingDirectory,
allowReentrantFlutter: allowReentrantFlutter,
allowedFailures: (int value) => _allowHeapCorruptionOnWindows(value, _platform),
);
}
bool _isValidAdbVersion(String adbVersion) {
// Sample output: 'Android Debug Bridge version 1.0.31'
final Match? versionFields = RegExp(r'(\d+)\.(\d+)\.(\d+)').firstMatch(adbVersion);
if (versionFields != null) {
final int majorVersion = int.parse(versionFields[1]!);
final int minorVersion = int.parse(versionFields[2]!);
final int patchVersion = int.parse(versionFields[3]!);
if (majorVersion > 1) {
return true;
}
if (majorVersion == 1 && minorVersion > 0) {
return true;
}
if (majorVersion == 1 && minorVersion == 0 && patchVersion >= 39) {
return true;
}
return false;
}
_logger.printError(
'Unrecognized adb version string $adbVersion. Skipping version check.');
return true;
}
Future<bool> _checkForSupportedAdbVersion() async {
final String? adbPath = _androidSdk.adbPath;
if (adbPath == null) {
return false;
}
try {
final RunResult adbVersion = await _processUtils.run(
<String>[adbPath, 'version'],
throwOnError: true,
);
if (_isValidAdbVersion(adbVersion.stdout)) {
return true;
}
_logger.printError('The ADB at "$adbPath" is too old; please install version 1.0.39 or later.');
} on Exception catch (error, trace) {
_logger.printError('Error running ADB: $error', stackTrace: trace);
}
return false;
}
Future<bool> _checkForSupportedAndroidVersion() async {
final String? adbPath = _androidSdk.adbPath;
if (adbPath == null) {
return false;
}
try {
// If the server is automatically restarted, then we get irrelevant
// output lines like this, which we want to ignore:
// adb server is out of date. killing..
// * daemon started successfully *
await _processUtils.run(
<String>[adbPath, 'start-server'],
throwOnError: true,
);
// This has been reported to return null on some devices. In this case,
// assume the lowest supported API to still allow Flutter to run.
// Sample output: '22'
final String sdkVersion = await _getProperty('ro.build.version.sdk')
?? minApiLevel.toString();
final int? sdkVersionParsed = int.tryParse(sdkVersion);
if (sdkVersionParsed == null) {
_logger.printError('Unexpected response from getprop: "$sdkVersion"');
return false;
}
if (sdkVersionParsed < minApiLevel) {
_logger.printError(
'The Android version ($sdkVersion) on the target device is too old. Please '
'use a $minVersionName (version $minApiLevel / $minVersionText) device or later.');
return false;
}
return true;
} on Exception catch (e, stacktrace) {
_logger.printError('Unexpected failure from adb: $e');
_logger.printError('Stacktrace: $stacktrace');
return false;
}
}
String _getDeviceSha1Path(AndroidApk apk) {
return '/data/local/tmp/sky.${apk.id}.sha1';
}
Future<String> _getDeviceApkSha1(AndroidApk apk) async {
final RunResult result = await _processUtils.run(
adbCommandForDevice(<String>['shell', 'cat', _getDeviceSha1Path(apk)]));
return result.stdout;
}
String _getSourceSha1(AndroidApk apk) {
final File shaFile = _fileSystem.file('${apk.applicationPackage.path}.sha1');
return shaFile.existsSync() ? shaFile.readAsStringSync() : '';
}
@override
String get name => modelID;
@override
bool get supportsFlavors => true;
@override
Future<bool> isAppInstalled(
ApplicationPackage app, {
String? userIdentifier,
}) async {
// This call takes 400ms - 600ms.
try {
final RunResult listOut = await runAdbCheckedAsync(<String>[
'shell',
'pm',
'list',
'packages',
if (userIdentifier != null)
...<String>['--user', userIdentifier],
app.id,
]);
return LineSplitter.split(listOut.stdout).contains('package:${app.id}');
} on Exception catch (error) {
_logger.printTrace('$error');
return false;
}
}
@override
Future<bool> isLatestBuildInstalled(covariant AndroidApk app) async {
final String installedSha1 = await _getDeviceApkSha1(app);
return installedSha1.isNotEmpty && installedSha1 == _getSourceSha1(app);
}
@override
Future<bool> installApp(
covariant AndroidApk app, {
String? userIdentifier,
}) async {
if (!await _adbIsValid) {
return false;
}
final bool wasInstalled = await isAppInstalled(app, userIdentifier: userIdentifier);
if (wasInstalled && await isLatestBuildInstalled(app)) {
_logger.printTrace('Latest build already installed.');
return true;
}
_logger.printTrace('Installing APK.');
if (await _installApp(app, userIdentifier: userIdentifier)) {
return true;
}
_logger.printTrace('Warning: Failed to install APK.');
if (!wasInstalled) {
return false;
}
_logger.printStatus('Uninstalling old version...');
if (!await uninstallApp(app, userIdentifier: userIdentifier)) {
_logger.printError('Error: Uninstalling old version failed.');
return false;
}
if (!await _installApp(app, userIdentifier: userIdentifier)) {
_logger.printError('Error: Failed to install APK again.');
return false;
}
return true;
}
Future<bool> _installApp(
AndroidApk app, {
String? userIdentifier,
}) async {
if (!app.applicationPackage.existsSync()) {
_logger.printError('"${_fileSystem.path.relative(app.applicationPackage.path)}" does not exist.');
return false;
}
final Status status = _logger.startProgress(
'Installing ${_fileSystem.path.relative(app.applicationPackage.path)}...',
);
final RunResult installResult = await _processUtils.run(
adbCommandForDevice(<String>[
'install',
'-t',
'-r',
if (userIdentifier != null)
...<String>['--user', userIdentifier],
app.applicationPackage.path,
]));
status.stop();
// Some versions of adb exit with exit code 0 even on failure :(
// Parsing the output to check for failures.
final RegExp failureExp = RegExp(r'^Failure.*$', multiLine: true);
final String? failure = failureExp.stringMatch(installResult.stdout);
if (failure != null) {
_logger.printError('Package install error: $failure');
return false;
}
if (installResult.exitCode != 0) {
if (installResult.stderr.contains('Bad user number')) {
_logger.printError('Error: User "$userIdentifier" not found. Run "adb shell pm list users" to see list of available identifiers.');
} else {
_logger.printError('Error: ADB exited with exit code ${installResult.exitCode}');
_logger.printError('$installResult');
}
return false;
}
try {
await runAdbCheckedAsync(<String>[
'shell', 'echo', '-n', _getSourceSha1(app), '>', _getDeviceSha1Path(app),
]);
} on ProcessException catch (error) {
_logger.printError('adb shell failed to write the SHA hash: $error.');
return false;
}
return true;
}
@override
Future<bool> uninstallApp(
ApplicationPackage app, {
String? userIdentifier,
}) async {
if (!await _adbIsValid) {
return false;
}
String uninstallOut;
try {
final RunResult uninstallResult = await _processUtils.run(
adbCommandForDevice(<String>[
'uninstall',
if (userIdentifier != null)
...<String>['--user', userIdentifier],
app.id,
]),
throwOnError: true,
);
uninstallOut = uninstallResult.stdout;
} on Exception catch (error) {
_logger.printError('adb uninstall failed: $error');
return false;
}
final RegExp failureExp = RegExp(r'^Failure.*$', multiLine: true);
final String? failure = failureExp.stringMatch(uninstallOut);
if (failure != null) {
_logger.printError('Package uninstall error: $failure');
return false;
}
return true;
}
// Whether the adb and Android versions are aligned.
late final Future<bool> _adbIsValid = () async {
return await _checkForSupportedAdbVersion() && await _checkForSupportedAndroidVersion();
}();
AndroidApk? _package;
@override
Future<LaunchResult> startApp(
AndroidApk? package, {
String? mainPath,
String? route,
required DebuggingOptions debuggingOptions,
Map<String, Object?> platformArgs = const <String, Object>{},
bool prebuiltApplication = false,
bool ipv6 = false,
String? userIdentifier,
}) async {
if (!await _adbIsValid) {
return LaunchResult.failed();
}
final TargetPlatform devicePlatform = await targetPlatform;
if (devicePlatform == TargetPlatform.android_x86 &&
!debuggingOptions.buildInfo.isDebug) {
_logger.printError('Profile and release builds are only supported on ARM/x64 targets.');
return LaunchResult.failed();
}
AndroidApk? builtPackage = package;
AndroidArch androidArch;
switch (devicePlatform) {
case TargetPlatform.android_arm:
androidArch = AndroidArch.armeabi_v7a;
case TargetPlatform.android_arm64:
androidArch = AndroidArch.arm64_v8a;
case TargetPlatform.android_x64:
androidArch = AndroidArch.x86_64;
case TargetPlatform.android_x86:
androidArch = AndroidArch.x86;
case TargetPlatform.android:
case TargetPlatform.darwin:
case TargetPlatform.fuchsia_arm64:
case TargetPlatform.fuchsia_x64:
case TargetPlatform.ios:
case TargetPlatform.linux_arm64:
case TargetPlatform.linux_x64:
case TargetPlatform.tester:
case TargetPlatform.web_javascript:
case TargetPlatform.windows_arm64:
case TargetPlatform.windows_x64:
_logger.printError('Android platforms are only supported.');
return LaunchResult.failed();
}
if (!prebuiltApplication || _androidSdk.licensesAvailable && _androidSdk.latestVersion == null) {
_logger.printTrace('Building APK');
final FlutterProject project = FlutterProject.current();
await androidBuilder!.buildApk(
project: project,
target: mainPath ?? 'lib/main.dart',
androidBuildInfo: AndroidBuildInfo(
debuggingOptions.buildInfo,
targetArchs: <AndroidArch>[androidArch],
fastStart: debuggingOptions.fastStart,
),
);
// Package has been built, so we can get the updated application ID and
// activity name from the .apk.
builtPackage = await ApplicationPackageFactory.instance!
.getPackageForPlatform(devicePlatform, buildInfo: debuggingOptions.buildInfo) as AndroidApk?;
}
// There was a failure parsing the android project information.
if (builtPackage == null) {
throwToolExit('Problem building Android application: see above error(s).');
}
_logger.printTrace("Stopping app '${builtPackage.name}' on $name.");
await stopApp(builtPackage, userIdentifier: userIdentifier);
if (!await installApp(builtPackage, userIdentifier: userIdentifier)) {
return LaunchResult.failed();
}
final bool traceStartup = platformArgs['trace-startup'] as bool? ?? false;
ProtocolDiscovery? vmServiceDiscovery;
if (debuggingOptions.debuggingEnabled) {
vmServiceDiscovery = ProtocolDiscovery.vmService(
// Avoid using getLogReader, which returns a singleton instance, because the
// VM Service discovery will dispose at the end. creating a new logger here allows
// logs to be surfaced normally during `flutter drive`.
await AdbLogReader.createLogReader(
this,
_processManager,
),
portForwarder: portForwarder,
hostPort: debuggingOptions.hostVmServicePort,
devicePort: debuggingOptions.deviceVmServicePort,
ipv6: ipv6,
logger: _logger,
);
}
final String dartVmFlags = computeDartVmFlags(debuggingOptions);
final String? traceAllowlist = debuggingOptions.traceAllowlist;
final String? traceSkiaAllowlist = debuggingOptions.traceSkiaAllowlist;
final String? traceToFile = debuggingOptions.traceToFile;
final List<String> cmd = <String>[
'shell', 'am', 'start',
'-a', 'android.intent.action.MAIN',
'-c', 'android.intent.category.LAUNCHER',
'-f', '0x20000000', // FLAG_ACTIVITY_SINGLE_TOP
if (debuggingOptions.enableDartProfiling)
...<String>['--ez', 'enable-dart-profiling', 'true'],
if (traceStartup)
...<String>['--ez', 'trace-startup', 'true'],
if (route != null)
...<String>['--es', 'route', route],
if (debuggingOptions.enableSoftwareRendering)
...<String>['--ez', 'enable-software-rendering', 'true'],
if (debuggingOptions.skiaDeterministicRendering)
...<String>['--ez', 'skia-deterministic-rendering', 'true'],
if (debuggingOptions.traceSkia)
...<String>['--ez', 'trace-skia', 'true'],
if (traceAllowlist != null)
...<String>['--es', 'trace-allowlist', traceAllowlist],
if (traceSkiaAllowlist != null)
...<String>['--es', 'trace-skia-allowlist', traceSkiaAllowlist],
if (debuggingOptions.traceSystrace)
...<String>['--ez', 'trace-systrace', 'true'],
if (traceToFile != null)
...<String>['--es', 'trace-to-file', traceToFile],
if (debuggingOptions.endlessTraceBuffer)
...<String>['--ez', 'endless-trace-buffer', 'true'],
if (debuggingOptions.dumpSkpOnShaderCompilation)
...<String>['--ez', 'dump-skp-on-shader-compilation', 'true'],
if (debuggingOptions.cacheSkSL)
...<String>['--ez', 'cache-sksl', 'true'],
if (debuggingOptions.purgePersistentCache)
...<String>['--ez', 'purge-persistent-cache', 'true'],
if (debuggingOptions.enableImpeller == ImpellerStatus.enabled)
...<String>['--ez', 'enable-impeller', 'true'],
if (debuggingOptions.enableImpeller == ImpellerStatus.disabled)
...<String>['--ez', 'enable-impeller', 'false'],
if (debuggingOptions.enableVulkanValidation)
...<String>['--ez', 'enable-vulkan-validation', 'true'],
if (debuggingOptions.debuggingEnabled) ...<String>[
if (debuggingOptions.buildInfo.isDebug) ...<String>[
...<String>['--ez', 'enable-checked-mode', 'true'],
...<String>['--ez', 'verify-entry-points', 'true'],
],
if (debuggingOptions.startPaused)
...<String>['--ez', 'start-paused', 'true'],
if (debuggingOptions.disableServiceAuthCodes)
...<String>['--ez', 'disable-service-auth-codes', 'true'],
if (dartVmFlags.isNotEmpty)
...<String>['--es', 'dart-flags', dartVmFlags],
if (debuggingOptions.useTestFonts)
...<String>['--ez', 'use-test-fonts', 'true'],
if (debuggingOptions.verboseSystemLogs)
...<String>['--ez', 'verbose-logging', 'true'],
if (userIdentifier != null)
...<String>['--user', userIdentifier],
],
builtPackage.launchActivity,
];
final String result = (await runAdbCheckedAsync(cmd)).stdout;
// This invocation returns 0 even when it fails.
if (result.contains('Error: ')) {
_logger.printError(result.trim(), wrap: false);
return LaunchResult.failed();
}
_package = builtPackage;
if (!debuggingOptions.debuggingEnabled) {
return LaunchResult.succeeded();
}
// Wait for the service protocol port here. This will complete once the
// device has printed "VM Service is listening on...".
_logger.printTrace('Waiting for VM Service port to be available...');
try {
Uri? vmServiceUri;
if (debuggingOptions.buildInfo.isDebug || debuggingOptions.buildInfo.isProfile) {
vmServiceUri = await vmServiceDiscovery?.uri;
if (vmServiceUri == null) {
_logger.printError(
'Error waiting for a debug connection: '
'The log reader stopped unexpectedly',
);
return LaunchResult.failed();
}
}
return LaunchResult.succeeded(vmServiceUri: vmServiceUri);
} on Exception catch (error) {
_logger.printError('Error waiting for a debug connection: $error');
return LaunchResult.failed();
} finally {
await vmServiceDiscovery?.cancel();
}
}
@override
bool get supportsHotReload => true;
@override
bool get supportsHotRestart => true;
@override
bool get supportsFastStart => true;
@override
Future<bool> stopApp(
ApplicationPackage? app, {
String? userIdentifier,
}) async {
if (app == null) {
return false;
}
final List<String> command = adbCommandForDevice(<String>[
'shell',
'am',
'force-stop',
if (userIdentifier != null)
...<String>['--user', userIdentifier],
app.id,
]);
return _processUtils.stream(command).then<bool>(
(int exitCode) => exitCode == 0 || _allowHeapCorruptionOnWindows(exitCode, _platform));
}
@override
Future<MemoryInfo> queryMemoryInfo() async {
final AndroidApk? package = _package;
if (package == null) {
_logger.printError('Android package unknown, skipping dumpsys meminfo.');
return const MemoryInfo.empty();
}
final RunResult runResult = await _processUtils.run(adbCommandForDevice(<String>[
'shell',
'dumpsys',
'meminfo',
package.id,
'-d',
]));
if (runResult.exitCode != 0) {
return const MemoryInfo.empty();
}
return parseMeminfoDump(runResult.stdout);
}
@override
void clearLogs() {
_processUtils.runSync(adbCommandForDevice(<String>['logcat', '-c']));
}
@override
FutureOr<DeviceLogReader> getLogReader({
ApplicationPackage? app,
bool includePastLogs = false,
}) async {
// The Android log reader isn't app-specific. The `app` parameter isn't used.
if (includePastLogs) {
return _pastLogReader ??= await AdbLogReader.createLogReader(
this,
_processManager,
includePastLogs: true,
);
} else {
return _logReader ??= await AdbLogReader.createLogReader(
this,
_processManager,
);
}
}
@override
late final DevicePortForwarder? portForwarder = () {
final String? adbPath = _androidSdk.adbPath;
if (adbPath == null) {
return null;
}
return AndroidDevicePortForwarder(
processManager: _processManager,
logger: _logger,
deviceId: id,
adbPath: adbPath,
);
}();
static final RegExp _timeRegExp = RegExp(r'^\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}', multiLine: true);
/// Return the most recent timestamp in the Android log or [null] if there is
/// no available timestamp. The format can be passed to logcat's -T option.
@visibleForTesting
Future<String?> lastLogcatTimestamp() async {
RunResult output;
try {
output = await runAdbCheckedAsync(<String>[
'shell', '-x', 'logcat', '-v', 'time', '-t', '1',
]);
} on Exception catch (error) {
_logger.printError('Failed to extract the most recent timestamp from the Android log: $error.');
return null;
}
final Match? timeMatch = _timeRegExp.firstMatch(output.stdout);
return timeMatch?.group(0);
}
@override
bool isSupported() => true;
@override
bool get supportsScreenshot => true;
@override
Future<void> takeScreenshot(File outputFile) async {
const String remotePath = '/data/local/tmp/flutter_screenshot.png';
await runAdbCheckedAsync(<String>['shell', 'screencap', '-p', remotePath]);
await _processUtils.run(
adbCommandForDevice(<String>['pull', remotePath, outputFile.path]),
throwOnError: true,
);
await runAdbCheckedAsync(<String>['shell', 'rm', remotePath]);
}
@override
bool isSupportedForProject(FlutterProject flutterProject) {
return flutterProject.android.existsSync();
}
@override
Future<void> dispose() async {
_logReader?._stop();
_pastLogReader?._stop();
}
}
Map<String, String> parseAdbDeviceProperties(String str) {
final Map<String, String> properties = <String, String>{};
final RegExp propertyExp = RegExp(r'\[(.*?)\]: \[(.*?)\]');
for (final Match match in propertyExp.allMatches(str)) {
properties[match.group(1)!] = match.group(2)!;
}
return properties;
}
/// Process the dumpsys info formatted in a table-like structure.
///
/// Currently this only pulls information from the "App Summary" subsection.
///
/// Example output:
///
/// ```
/// Applications Memory Usage (in Kilobytes):
/// Uptime: 441088659 Realtime: 521464097
///
/// ** MEMINFO in pid 16141 [io.flutter.demo.gallery] **
/// Pss Private Private SwapPss Heap Heap Heap
/// Total Dirty Clean Dirty Size Alloc Free
/// ------ ------ ------ ------ ------ ------ ------
/// Native Heap 8648 8620 0 16 20480 12403 8076
/// Dalvik Heap 547 424 40 18 2628 1092 1536
/// Dalvik Other 464 464 0 0
/// Stack 496 496 0 0
/// Ashmem 2 0 0 0
/// Gfx dev 212 204 0 0
/// Other dev 48 0 48 0
/// .so mmap 10770 708 9372 25
/// .apk mmap 240 0 0 0
/// .ttf mmap 35 0 32 0
/// .dex mmap 2205 4 1172 0
/// .oat mmap 64 0 0 0
/// .art mmap 4228 3848 24 2
/// Other mmap 20713 4 20704 0
/// GL mtrack 2380 2380 0 0
/// Unknown 43971 43968 0 1
/// TOTAL 95085 61120 31392 62 23108 13495 9612
///
/// App Summary
/// Pss(KB)
/// ------
/// Java Heap: 4296
/// Native Heap: 8620
/// Code: 11288
/// Stack: 496
/// Graphics: 2584
/// Private Other: 65228
/// System: 2573
///
/// TOTAL: 95085 TOTAL SWAP PSS: 62
///
/// Objects
/// Views: 9 ViewRootImpl: 1
/// AppContexts: 3 Activities: 1
/// Assets: 4 AssetManagers: 3
/// Local Binders: 10 Proxy Binders: 18
/// Parcel memory: 6 Parcel count: 24
/// Death Recipients: 0 OpenSSL Sockets: 0
/// WebViews: 0
///
/// SQL
/// MEMORY_USED: 0
/// PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0
/// ...
/// ```
///
/// For more information, see https://developer.android.com/studio/command-line/dumpsys.
@visibleForTesting
AndroidMemoryInfo parseMeminfoDump(String input) {
final AndroidMemoryInfo androidMemoryInfo = AndroidMemoryInfo();
final List<String> lines = input.split('\n');
final String timelineData = lines.firstWhere((String line) =>
line.startsWith('${AndroidMemoryInfo._kUpTimeKey}: '));
final List<String> times = timelineData.trim().split('${AndroidMemoryInfo._kRealTimeKey}:');
androidMemoryInfo.realTime = int.tryParse(times.last.trim()) ?? 0;
lines
.skipWhile((String line) => !line.contains('App Summary'))
.takeWhile((String line) => !line.contains('TOTAL'))
.where((String line) => line.contains(':'))
.forEach((String line) {
final List<String> sections = line.trim().split(':');
final String key = sections.first.trim();
final int value = int.tryParse(sections.last.trim()) ?? 0;
switch (key) {
case AndroidMemoryInfo._kJavaHeapKey:
androidMemoryInfo.javaHeap = value;
case AndroidMemoryInfo._kNativeHeapKey:
androidMemoryInfo.nativeHeap = value;
case AndroidMemoryInfo._kCodeKey:
androidMemoryInfo.code = value;
case AndroidMemoryInfo._kStackKey:
androidMemoryInfo.stack = value;
case AndroidMemoryInfo._kGraphicsKey:
androidMemoryInfo.graphics = value;
case AndroidMemoryInfo._kPrivateOtherKey:
androidMemoryInfo.privateOther = value;
case AndroidMemoryInfo._kSystemKey:
androidMemoryInfo.system = value;
}
});
return androidMemoryInfo;
}
/// Android specific implementation of memory info.
class AndroidMemoryInfo extends MemoryInfo {
static const String _kUpTimeKey = 'Uptime';
static const String _kRealTimeKey = 'Realtime';
static const String _kJavaHeapKey = 'Java Heap';
static const String _kNativeHeapKey = 'Native Heap';
static const String _kCodeKey = 'Code';
static const String _kStackKey = 'Stack';
static const String _kGraphicsKey = 'Graphics';
static const String _kPrivateOtherKey = 'Private Other';
static const String _kSystemKey = 'System';
static const String _kTotalKey = 'Total';
// Realtime is time since the system was booted includes deep sleep. Clock
// is monotonic, and ticks even when the CPU is in power saving modes.
int realTime = 0;
// Each measurement has KB as a unit.
int javaHeap = 0;
int nativeHeap = 0;
int code = 0;
int stack = 0;
int graphics = 0;
int privateOther = 0;
int system = 0;
@override
Map<String, Object> toJson() {
return <String, Object>{
'platform': 'Android',
_kRealTimeKey: realTime,
_kJavaHeapKey: javaHeap,
_kNativeHeapKey: nativeHeap,
_kCodeKey: code,
_kStackKey: stack,
_kGraphicsKey: graphics,
_kPrivateOtherKey: privateOther,
_kSystemKey: system,
_kTotalKey: javaHeap + nativeHeap + code + stack + graphics + privateOther + system,
};
}
}
/// A log reader that logs from `adb logcat`.
class AdbLogReader extends DeviceLogReader {
AdbLogReader._(this._adbProcess, this.name);
@visibleForTesting
factory AdbLogReader.test(Process adbProcess, String name) = AdbLogReader._;
/// Create a new [AdbLogReader] from an [AndroidDevice] instance.
static Future<AdbLogReader> createLogReader(
AndroidDevice device,
ProcessManager processManager, {
bool includePastLogs = false,
}) async {
// logcat -T is not supported on Android releases before Lollipop.
const int kLollipopVersionCode = 21;
final int? apiVersion = (String? v) {
// If the API version string isn't found, conservatively assume that the
// version is less recent than the one we're looking for.
return v == null ? kLollipopVersionCode - 1 : int.tryParse(v);
}(await device.apiVersion);
// Start the adb logcat process and filter the most recent logs since `lastTimestamp`.
// Some devices (notably LG) will only output logcat via shell
// https://github.com/flutter/flutter/issues/51853
final List<String> args = <String>[
'shell',
'-x',
'logcat',
'-v',
'time',
];
// If past logs are included then filter for 'flutter' logs only.
if (includePastLogs) {
args.addAll(<String>['-s', 'flutter']);
} else if (apiVersion != null && apiVersion >= kLollipopVersionCode) {
// Otherwise, filter for logs appearing past the present.
// '-T 0` means the timestamp of the logcat command invocation.
final String? lastLogcatTimestamp = await device.lastLogcatTimestamp();
args.addAll(<String>[
'-T',
if (lastLogcatTimestamp != null) "'$lastLogcatTimestamp'" else '0',
]);
}
final Process process = await processManager.start(device.adbCommandForDevice(args));
return AdbLogReader._(process, device.name);
}
final Process _adbProcess;
@override
final String name;
late final StreamController<String> _linesController = StreamController<String>.broadcast(
onListen: _start,
onCancel: _stop,
);
@override
Stream<String> get logLines => _linesController.stream;
void _start() {
// We expect logcat streams to occasionally contain invalid utf-8,
// see: https://github.com/flutter/flutter/pull/8864.
const Utf8Decoder decoder = Utf8Decoder(reportErrors: false);
_adbProcess.stdout.transform<String>(decoder)
.transform<String>(const LineSplitter())
.listen(_onLine);
_adbProcess.stderr.transform<String>(decoder)
.transform<String>(const LineSplitter())
.listen(_onLine);
unawaited(_adbProcess.exitCode.whenComplete(() {
if (_linesController.hasListener) {
_linesController.close();
}
}));
}
// 'W/ActivityManager(pid): '
static final RegExp _logFormat = RegExp(r'^[VDIWEF]\/.*?\(\s*(\d+)\):\s');
static final List<RegExp> _allowedTags = <RegExp>[
RegExp(r'^[VDIWEF]\/flutter[^:]*:\s+', caseSensitive: false),
RegExp(r'^[IE]\/DartVM[^:]*:\s+'),
RegExp(r'^[WEF]\/AndroidRuntime:\s+'),
RegExp(r'^[WEF]\/AndroidRuntime\([0-9]+\):\s+'),
RegExp(r'^[WEF]\/ActivityManager:\s+.*(\bflutter\b|\bdomokit\b|\bsky\b)'),
RegExp(r'^[WEF]\/System\.err:\s+'),
RegExp(r'^[F]\/[\S^:]+:\s+'),
];
// E/SurfaceSyncer(22636): Failed to find sync for id=9
// Some versions of Android spew this out. It is inactionable to the end user
// and causes no problems for the application.
static final RegExp _surfaceSyncerSpam = RegExp(r'^E/SurfaceSyncer\(\s*\d+\): Failed to find sync for id=\d+');
// 'F/libc(pid): Fatal signal 11'
static final RegExp _fatalLog = RegExp(r'^F\/libc\s*\(\s*\d+\):\sFatal signal (\d+)');
// 'I/DEBUG(pid): ...'
static final RegExp _tombstoneLine = RegExp(r'^[IF]\/DEBUG\s*\(\s*\d+\):\s(.+)$');
// 'I/DEBUG(pid): Tombstone written to: '
static final RegExp _tombstoneTerminator = RegExp(r'^Tombstone written to:\s');
// we default to true in case none of the log lines match
bool _acceptedLastLine = true;
// Whether a fatal crash is happening or not.
// During a fatal crash only lines from the crash are accepted, the rest are
// dropped.
bool _fatalCrash = false;
// The format of the line is controlled by the '-v' parameter passed to
// adb logcat. We are currently passing 'time', which has the format:
// mm-dd hh:mm:ss.milliseconds Priority/Tag( PID): ....
void _onLine(String line) {
// This line might be processed after the subscription is closed but before
// adb stops streaming logs.
if (_linesController.isClosed) {
return;
}
final Match? timeMatch = AndroidDevice._timeRegExp.firstMatch(line);
if (timeMatch == null || line.length == timeMatch.end) {
_acceptedLastLine = false;
return;
}
// Chop off the time.
line = line.substring(timeMatch.end + 1);
final Match? logMatch = _logFormat.firstMatch(line);
if (logMatch != null) {
bool acceptLine = false;
if (_fatalCrash) {
// While a fatal crash is going on, only accept lines from the crash
// Otherwise the crash log in the console may get interrupted
final Match? fatalMatch = _tombstoneLine.firstMatch(line);
if (fatalMatch != null) {
acceptLine = true;
line = fatalMatch[1]!;
if (_tombstoneTerminator.hasMatch(line)) {
// Hit crash terminator, stop logging the crash info
_fatalCrash = false;
}
}
} else if (appPid != null && int.parse(logMatch.group(1)!) == appPid) {
acceptLine = !_surfaceSyncerSpam.hasMatch(line);
if (_fatalLog.hasMatch(line)) {
// Hit fatal signal, app is now crashing
_fatalCrash = true;
}
} else {
// Filter on approved names and levels.
acceptLine = _allowedTags.any((RegExp re) => re.hasMatch(line));
}
if (acceptLine) {
_acceptedLastLine = true;
_linesController.add(line);
return;
}
_acceptedLastLine = false;
} else if (line == '--------- beginning of system' ||
line == '--------- beginning of main') {
// hide the ugly adb logcat log boundaries at the start
_acceptedLastLine = false;
} else {
// If it doesn't match the log pattern at all, then pass it through if we
// passed the last matching line through. It might be a multiline message.
if (_acceptedLastLine) {
_linesController.add(line);
return;
}
}
}
void _stop() {
_linesController.close();
_adbProcess.kill();
}
@override
void dispose() {
_stop();
}
}
/// A [DevicePortForwarder] implemented for Android devices that uses adb.
class AndroidDevicePortForwarder extends DevicePortForwarder {
AndroidDevicePortForwarder({
required ProcessManager processManager,
required Logger logger,
required String deviceId,
required String adbPath,
}) : _deviceId = deviceId,
_adbPath = adbPath,
_logger = logger,
_processUtils = ProcessUtils(logger: logger, processManager: processManager);
final String _deviceId;
final String _adbPath;
final Logger _logger;
final ProcessUtils _processUtils;
static int? _extractPort(String portString) {
return int.tryParse(portString.trim());
}
@override
List<ForwardedPort> get forwardedPorts {
final List<ForwardedPort> ports = <ForwardedPort>[];
String stdout;
try {
stdout = _processUtils.runSync(
<String>[
_adbPath,
'-s',
_deviceId,
'forward',
'--list',
],
throwOnError: true,
).stdout.trim();
} on ProcessException catch (error) {
_logger.printError('Failed to list forwarded ports: $error.');
return ports;
}
final List<String> lines = LineSplitter.split(stdout).toList();
for (final String line in lines) {
if (!line.startsWith(_deviceId)) {
continue;
}
final List<String> splitLine = line.split('tcp:');
// Sanity check splitLine.
if (splitLine.length != 3) {
continue;
}
// Attempt to extract ports.
final int? hostPort = _extractPort(splitLine[1]);
final int? devicePort = _extractPort(splitLine[2]);
// Failed, skip.
if (hostPort == null || devicePort == null) {
continue;
}
ports.add(ForwardedPort(hostPort, devicePort));
}
return ports;
}
@override
Future<int> forward(int devicePort, { int? hostPort }) async {
hostPort ??= 0;
final RunResult process = await _processUtils.run(
<String>[
_adbPath,
'-s',
_deviceId,
'forward',
'tcp:$hostPort',
'tcp:$devicePort',
],
throwOnError: true,
);
if (process.stderr.isNotEmpty) {
process.throwException('adb returned error:\n${process.stderr}');
}
if (process.exitCode != 0) {
if (process.stdout.isNotEmpty) {
process.throwException('adb returned error:\n${process.stdout}');
}
process.throwException('adb failed without a message');
}
if (hostPort == 0) {
if (process.stdout.isEmpty) {
process.throwException('adb did not report forwarded port');
}
hostPort = int.tryParse(process.stdout);
if (hostPort == null) {
process.throwException('adb returned invalid port number:\n${process.stdout}');
}
} else {
// stdout may be empty or the port we asked it to forward, though it's
// not documented (or obvious) what triggers each case.
//
// Observations are:
// - On MacOS it's always empty when Flutter spawns the process, but
// - On MacOS it prints the port number when run from the terminal, unless
// the port is already forwarded, when it also prints nothing.
// - On ChromeOS, the port appears to be printed even when Flutter spawns
// the process
//
// To cover all cases, we accept the output being either empty or exactly
// the port number, but treat any other output as probably being an error
// message.
if (process.stdout.isNotEmpty && process.stdout.trim() != '$hostPort') {
process.throwException('adb returned error:\n${process.stdout}');
}
}
return hostPort!;
}
@override
Future<void> unforward(ForwardedPort forwardedPort) async {
final String tcpLine = 'tcp:${forwardedPort.hostPort}';
final RunResult runResult = await _processUtils.run(
<String>[
_adbPath,
'-s',
_deviceId,
'forward',
'--remove',
tcpLine,
],
);
if (runResult.exitCode == 0) {
return;
}
_logger.printError('Failed to unforward port: $runResult');
}
@override
Future<void> dispose() async {
for (final ForwardedPort port in forwardedPorts) {
await unforward(port);
}
}
}
// In platform tools 29.0.0 adb.exe seems to be ending with this heap
// corruption error code on seemingly successful termination. Ignore
// this error on windows.
bool _allowHeapCorruptionOnWindows(int exitCode, Platform platform) {
return exitCode == -1073740940 && platform.isWindows;
}
| flutter/packages/flutter_tools/lib/src/android/android_device.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/android/android_device.dart",
"repo_id": "flutter",
"token_count": 18459
} | 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:meta/meta.dart';
import '../../base/file_system.dart';
import '../../base/project_migrator.dart';
import '../../base/version.dart';
import '../../project.dart';
import '../android_studio.dart';
import '../gradle_utils.dart';
import '../java.dart';
// Android Studio 2022.2 "Flamingo" is the first to bundle a Java 17 JDK.
// Previous versions bundled a Java 11 JDK.
@visibleForTesting
final Version androidStudioFlamingo = Version(2022, 2, 0);
@visibleForTesting
const String gradleVersion7_6_1 = r'7.6.1';
// String that can be placed in the gradle-wrapper.properties to opt out of this
// migrator.
@visibleForTesting
const String optOutFlag = 'NoFlutterGradleWrapperUpgrade';
// Only the major version matters.
final Version flamingoBundledJava = Version(17, 0, 0);
// These gradle versions were chosen because they
// 1. Were output by 'flutter create' at some point in flutter's history and
// 2. Are less than 7.3, the lowest supported gradle version for JDK 17
const List<String> gradleVersionsToUpgradeFrom =
<String>['5.6.2', '6.7'];
// Define log messages as constants to re-use in testing.
@visibleForTesting
const String gradleWrapperNotFound =
'gradle-wrapper.properties not found, skipping Gradle-Java version compatibility check.';
@visibleForTesting
const String androidStudioNotFound =
'Android Studio version could not be detected, '
'skipping Gradle-Java version compatibility check.';
@visibleForTesting
const String androidStudioVersionBelowFlamingo =
'Version of Android Studio is less than Flamingo (the first impacted version),'
' no migration attempted.';
@visibleForTesting
const String javaVersionNot17 =
'Version of Java is different than impacted version, no migration attempted.';
@visibleForTesting
const String javaVersionNotFound =
'Version of Java not found, no migration attempted.';
@visibleForTesting
const String conflictDetected = 'Conflict detected between versions of Android Studio '
'and Gradle, upgrading Gradle version from current to 7.4';
@visibleForTesting
const String gradleVersionNotFound = 'Failed to parse Gradle version from distribution url, '
'skipping Gradle-Java version compatibility check.';
@visibleForTesting
const String optOutFlagEnabled = 'Skipping Android Studio Java-Gradle compatibility '
"because opt out flag: '$optOutFlag' is enabled in gradle-wrapper.properties file.";
@visibleForTesting
const String errorWhileMigrating = 'Encountered an error while attempting Gradle-Java '
'version compatibility check, skipping migration attempt. Error was: ';
/// Migrate to a newer version of Gradle when the existing one does not support
/// the version of Java provided by the detected Android Studio version.
///
/// For more info see the Gradle-Java compatibility matrix:
/// https://docs.gradle.org/current/userguide/compatibility.html
class AndroidStudioJavaGradleConflictMigration extends ProjectMigrator {
AndroidStudioJavaGradleConflictMigration(
super.logger,
{required AndroidProject project,
AndroidStudio? androidStudio,
required Java? java,
}) : _gradleWrapperPropertiesFile = getGradleWrapperFile(project.hostAppGradleRoot),
_androidStudio = androidStudio,
_java = java;
final File _gradleWrapperPropertiesFile;
final AndroidStudio? _androidStudio;
final Java? _java;
@override
void migrate() {
try {
if (!_gradleWrapperPropertiesFile.existsSync()) {
logger.printTrace(gradleWrapperNotFound);
return;
}
if (_androidStudio == null || _androidStudio.version == null) {
logger.printTrace(androidStudioNotFound);
return;
} else if (_androidStudio.version!.major < androidStudioFlamingo.major) {
logger.printTrace(androidStudioVersionBelowFlamingo);
return;
}
if (_java?.version == null) {
logger.printTrace(javaVersionNotFound);
return;
}
if (_java!.version!.major != flamingoBundledJava.major) {
logger.printTrace(javaVersionNot17);
return;
}
processFileLines(_gradleWrapperPropertiesFile);
} on Exception catch (e) {
logger.printTrace(errorWhileMigrating + e.toString());
} on Error catch (e) {
logger.printTrace(errorWhileMigrating + e.toString());
}
}
@override
String migrateFileContents(String fileContents) {
if (fileContents.contains(optOutFlag)) {
logger.printTrace(optOutFlagEnabled);
return fileContents;
}
final RegExpMatch? gradleDistributionUrl = gradleOrgVersionMatch.firstMatch(fileContents);
if (gradleDistributionUrl == null
|| gradleDistributionUrl.groupCount < 1
|| gradleDistributionUrl[1] == null) {
logger.printTrace(gradleVersionNotFound);
return fileContents;
}
final String existingVersionString = gradleDistributionUrl[1]!;
if (gradleVersionsToUpgradeFrom.contains(existingVersionString)) {
logger.printStatus('Conflict detected between Android Studio Java version and Gradle version, '
'upgrading Gradle version from $existingVersionString to $gradleVersion7_6_1.');
final String? gradleDistributionUrlString = gradleDistributionUrl.group(0);
if (gradleDistributionUrlString != null) {
final String upgradedDistributionUrl =
gradleDistributionUrlString.replaceAll(existingVersionString, gradleVersion7_6_1);
fileContents = fileContents.replaceFirst(gradleOrgVersionMatch, upgradedDistributionUrl);
} else {
logger.printTrace(gradleVersionNotFound);
}
}
return fileContents;
}
}
| flutter/packages/flutter_tools/lib/src/android/migrations/android_studio_java_gradle_conflict_migration.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/android/migrations/android_studio_java_gradle_conflict_migration.dart",
"repo_id": "flutter",
"token_count": 1848
} | 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:convert';
import 'dart:io' as io show Directory, File, Link, Process, ProcessException, ProcessResult, ProcessSignal, ProcessStartMode, systemEncoding;
import 'dart:typed_data';
import 'package:file/file.dart';
import 'package:meta/meta.dart';
import 'package:path/path.dart' as p; // flutter_ignore: package_path_import
import 'package:process/process.dart';
import 'common.dart' show throwToolExit;
import 'platform.dart';
// The Flutter tool hits file system and process errors that only the end-user can address.
// We would like these errors to not hit crash logging. In these cases, we
// should exit gracefully and provide potentially useful advice. For example, if
// a write fails because the target device is full, we can explain that with a
// ToolExit and a message that is more clear than the FileSystemException by
// itself.
/// On windows this is error code 2: ERROR_FILE_NOT_FOUND, and on
/// macOS/Linux it is error code 2/ENOENT: No such file or directory.
const int kSystemCannotFindFile = 2;
/// A [FileSystem] that throws a [ToolExit] on certain errors.
///
/// If a [FileSystem] error is not caused by the Flutter tool, and can only be
/// addressed by the user, it should be caught by this [FileSystem] and thrown
/// as a [ToolExit] using [throwToolExit].
///
/// Cf. If there is some hope that the tool can continue when an operation fails
/// with an error, then that error/operation should not be handled here. For
/// example, the tool should generally be able to continue executing even if it
/// fails to delete a file.
class ErrorHandlingFileSystem extends ForwardingFileSystem {
ErrorHandlingFileSystem({
required FileSystem delegate,
required Platform platform,
}) :
_platform = platform,
super(delegate);
@visibleForTesting
FileSystem get fileSystem => delegate;
final Platform _platform;
/// Allow any file system operations executed within the closure to fail with any
/// operating system error, rethrowing an [Exception] instead of a [ToolExit].
///
/// This should not be used with async file system operation.
///
/// This can be used to bypass the [ErrorHandlingFileSystem] permission exit
/// checks for situations where failure is acceptable, such as the flutter
/// persistent settings cache.
static void noExitOnFailure(void Function() operation) {
final bool previousValue = ErrorHandlingFileSystem._noExitOnFailure;
try {
ErrorHandlingFileSystem._noExitOnFailure = true;
operation();
} finally {
ErrorHandlingFileSystem._noExitOnFailure = previousValue;
}
}
/// Delete the file or directory and return true if it exists, take no
/// action and return false if it does not.
///
/// This method should be preferred to checking if it exists and
/// then deleting, because it handles the edge case where the file or directory
/// is deleted by a different program between the two calls.
static bool deleteIfExists(FileSystemEntity file, {bool recursive = false}) {
if (!file.existsSync()) {
return false;
}
try {
file.deleteSync(recursive: recursive);
} on FileSystemException catch (err) {
// Certain error codes indicate the file could not be found. It could have
// been deleted by a different program while the tool was running.
// if it still exists, the file likely exists on a read-only volume.
if (err.osError?.errorCode != kSystemCannotFindFile || _noExitOnFailure) {
rethrow;
}
if (file.existsSync()) {
throwToolExit(
'The Flutter tool tried to delete the file or directory ${file.path} but was '
"unable to. This may be due to the file and/or project's location on a read-only "
'volume. Consider relocating the project and trying again',
);
}
}
return true;
}
static bool _noExitOnFailure = false;
@override
Directory get currentDirectory {
try {
return _runSync(() => directory(delegate.currentDirectory), platform: _platform);
} on FileSystemException catch (err) {
// Special handling for OS error 2 for current directory only.
if (err.osError?.errorCode == kSystemCannotFindFile) {
throwToolExit(
'Unable to read current working directory. This can happen if the directory the '
'Flutter tool was run from was moved or deleted.'
);
}
rethrow;
}
}
@override
File file(dynamic path) => ErrorHandlingFile(
platform: _platform,
fileSystem: this,
delegate: delegate.file(path),
);
@override
Directory directory(dynamic path) => ErrorHandlingDirectory(
platform: _platform,
fileSystem: this,
delegate: delegate.directory(path),
);
@override
Link link(dynamic path) => ErrorHandlingLink(
platform: _platform,
fileSystem: this,
delegate: delegate.link(path),
);
// 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;
}
@override
String toString() => delegate.toString();
}
class ErrorHandlingFile
extends ForwardingFileSystemEntity<File, io.File>
with ForwardingFile {
ErrorHandlingFile({
required Platform platform,
required this.fileSystem,
required this.delegate,
}) :
_platform = platform;
@override
final io.File delegate;
@override
final ErrorHandlingFileSystem fileSystem;
final Platform _platform;
@override
File wrapFile(io.File delegate) => ErrorHandlingFile(
platform: _platform,
fileSystem: fileSystem,
delegate: delegate,
);
@override
Directory wrapDirectory(io.Directory delegate) => ErrorHandlingDirectory(
platform: _platform,
fileSystem: fileSystem,
delegate: delegate,
);
@override
Link wrapLink(io.Link delegate) => ErrorHandlingLink(
platform: _platform,
fileSystem: fileSystem,
delegate: delegate,
);
@override
Future<File> writeAsBytes(
List<int> bytes, {
FileMode mode = FileMode.write,
bool flush = false,
}) async {
return _run<File>(
() async => wrap(await delegate.writeAsBytes(
bytes,
mode: mode,
flush: flush,
)),
platform: _platform,
failureMessage: 'Flutter failed to write to a file at "${delegate.path}"',
posixPermissionSuggestion: _posixPermissionSuggestion(<String>[delegate.path]),
);
}
@override
String readAsStringSync({Encoding encoding = utf8}) {
return _runSync<String>(
() => delegate.readAsStringSync(),
platform: _platform,
failureMessage: 'Flutter failed to read a file at "${delegate.path}"',
posixPermissionSuggestion: _posixPermissionSuggestion(<String>[delegate.path]),
);
}
@override
void writeAsBytesSync(
List<int> bytes, {
FileMode mode = FileMode.write,
bool flush = false,
}) {
_runSync<void>(
() => delegate.writeAsBytesSync(bytes, mode: mode, flush: flush),
platform: _platform,
failureMessage: 'Flutter failed to write to a file at "${delegate.path}"',
posixPermissionSuggestion: _posixPermissionSuggestion(<String>[delegate.path]),
);
}
@override
Future<File> writeAsString(
String contents, {
FileMode mode = FileMode.write,
Encoding encoding = utf8,
bool flush = false,
}) async {
return _run<File>(
() async => wrap(await delegate.writeAsString(
contents,
mode: mode,
encoding: encoding,
flush: flush,
)),
platform: _platform,
failureMessage: 'Flutter failed to write to a file at "${delegate.path}"',
posixPermissionSuggestion: _posixPermissionSuggestion(<String>[delegate.path]),
);
}
@override
void writeAsStringSync(
String contents, {
FileMode mode = FileMode.write,
Encoding encoding = utf8,
bool flush = false,
}) {
_runSync<void>(
() => delegate.writeAsStringSync(
contents,
mode: mode,
encoding: encoding,
flush: flush,
),
platform: _platform,
failureMessage: 'Flutter failed to write to a file at "${delegate.path}"',
posixPermissionSuggestion: _posixPermissionSuggestion(<String>[delegate.path]),
);
}
// TODO(aam): Pass `exclusive` through after dartbug.com/49647 lands.
@override
void createSync({bool recursive = false, bool exclusive = false}) {
_runSync<void>(
() => delegate.createSync(
recursive: recursive,
),
platform: _platform,
failureMessage: 'Flutter failed to create file at "${delegate.path}"',
posixPermissionSuggestion: recursive ? null : _posixPermissionSuggestion(<String>[delegate.parent.path]),
);
}
@override
RandomAccessFile openSync({FileMode mode = FileMode.read}) {
return _runSync<RandomAccessFile>(
() => delegate.openSync(
mode: mode,
),
platform: _platform,
failureMessage: 'Flutter failed to open a file at "${delegate.path}"',
posixPermissionSuggestion: _posixPermissionSuggestion(<String>[delegate.path]),
);
}
/// This copy method attempts to handle file system errors from both reading
/// and writing the copied file.
@override
File copySync(String newPath) {
final File resultFile = fileSystem.file(newPath);
// First check if the source file can be read. If not, bail through error
// handling.
_runSync<void>(
() => delegate.openSync().closeSync(),
platform: _platform,
failureMessage: 'Flutter failed to copy $path to $newPath due to source location error',
posixPermissionSuggestion: _posixPermissionSuggestion(<String>[path]),
);
// Next check if the destination file can be written. If not, bail through
// error handling.
_runSync<void>(
() => resultFile.createSync(recursive: true),
platform: _platform,
failureMessage: 'Flutter failed to copy $path to $newPath due to destination location error'
);
// If both of the above checks passed, attempt to copy the file and catch
// any thrown errors.
try {
return wrapFile(delegate.copySync(newPath));
} on FileSystemException {
// Proceed below
}
// If the copy failed but both of the above checks passed, copy the bytes
// directly.
_runSync(() {
RandomAccessFile? source;
RandomAccessFile? sink;
try {
source = delegate.openSync();
sink = resultFile.openSync(mode: FileMode.writeOnly);
// 64k is the same sized buffer used by dart:io for `File.openRead`.
final Uint8List buffer = Uint8List(64 * 1024);
final int totalBytes = source.lengthSync();
int bytes = 0;
while (bytes < totalBytes) {
final int chunkLength = source.readIntoSync(buffer);
sink.writeFromSync(buffer, 0, chunkLength);
bytes += chunkLength;
}
} catch (err) { // ignore: avoid_catches_without_on_clauses, rethrows
ErrorHandlingFileSystem.deleteIfExists(resultFile, recursive: true);
rethrow;
} finally {
source?.closeSync();
sink?.closeSync();
}
}, platform: _platform,
failureMessage: 'Flutter failed to copy $path to $newPath due to unknown error',
posixPermissionSuggestion: _posixPermissionSuggestion(<String>[path, resultFile.parent.path]),
);
// The original copy failed, but the manual copy worked.
return wrapFile(resultFile);
}
String _posixPermissionSuggestion(List<String> paths) => 'Try running:\n'
' sudo chown -R \$(whoami) ${paths.map(fileSystem.path.absolute).join(' ')}';
@override
String toString() => delegate.toString();
}
class ErrorHandlingDirectory
extends ForwardingFileSystemEntity<Directory, io.Directory>
with ForwardingDirectory<Directory> {
ErrorHandlingDirectory({
required Platform platform,
required this.fileSystem,
required this.delegate,
}) :
_platform = platform;
@override
final io.Directory delegate;
@override
final ErrorHandlingFileSystem fileSystem;
final Platform _platform;
@override
File wrapFile(io.File delegate) => ErrorHandlingFile(
platform: _platform,
fileSystem: fileSystem,
delegate: delegate,
);
@override
Directory wrapDirectory(io.Directory delegate) => ErrorHandlingDirectory(
platform: _platform,
fileSystem: fileSystem,
delegate: delegate,
);
@override
Link wrapLink(io.Link delegate) => ErrorHandlingLink(
platform: _platform,
fileSystem: fileSystem,
delegate: delegate,
);
@override
Directory childDirectory(String basename) {
return fileSystem.directory(fileSystem.path.join(path, basename));
}
@override
File childFile(String basename) {
return fileSystem.file(fileSystem.path.join(path, basename));
}
@override
Link childLink(String basename) {
return fileSystem.link(fileSystem.path.join(path, basename));
}
@override
void createSync({bool recursive = false}) {
return _runSync<void>(
() => delegate.createSync(recursive: recursive),
platform: _platform,
failureMessage:
'Flutter failed to create a directory at "${delegate.path}"',
posixPermissionSuggestion: recursive ? null : _posixPermissionSuggestion(delegate.parent.path),
);
}
@override
Future<Directory> createTemp([String? prefix]) {
return _run<Directory>(
() async => wrap(await delegate.createTemp(prefix)),
platform: _platform,
failureMessage:
'Flutter failed to create a temporary directory with prefix "$prefix"',
);
}
@override
Directory createTempSync([String? prefix]) {
return _runSync<Directory>(
() => wrap(delegate.createTempSync(prefix)),
platform: _platform,
failureMessage:
'Flutter failed to create a temporary directory with prefix "$prefix"',
);
}
@override
Future<Directory> create({bool recursive = false}) {
return _run<Directory>(
() async => wrap(await delegate.create(recursive: recursive)),
platform: _platform,
failureMessage:
'Flutter failed to create a directory at "${delegate.path}"',
posixPermissionSuggestion: recursive ? null : _posixPermissionSuggestion(delegate.parent.path),
);
}
@override
Future<Directory> delete({bool recursive = false}) {
return _run<Directory>(
() async => wrap(fileSystem.directory((await delegate.delete(recursive: recursive)).path)),
platform: _platform,
failureMessage:
'Flutter failed to delete a directory at "${delegate.path}"',
posixPermissionSuggestion: recursive ? null : _posixPermissionSuggestion(delegate.path),
);
}
@override
void deleteSync({bool recursive = false}) {
return _runSync<void>(
() => delegate.deleteSync(recursive: recursive),
platform: _platform,
failureMessage:
'Flutter failed to delete a directory at "${delegate.path}"',
posixPermissionSuggestion: recursive ? null : _posixPermissionSuggestion(delegate.path),
);
}
@override
bool existsSync() {
return _runSync<bool>(
() => delegate.existsSync(),
platform: _platform,
failureMessage:
'Flutter failed to check for directory existence at "${delegate.path}"',
posixPermissionSuggestion: _posixPermissionSuggestion(delegate.parent.path),
);
}
String _posixPermissionSuggestion(String path) => 'Try running:\n'
' sudo chown -R \$(whoami) ${fileSystem.path.absolute(path)}';
@override
String toString() => delegate.toString();
}
class ErrorHandlingLink
extends ForwardingFileSystemEntity<Link, io.Link>
with ForwardingLink {
ErrorHandlingLink({
required Platform platform,
required this.fileSystem,
required this.delegate,
}) :
_platform = platform;
@override
final io.Link delegate;
@override
final ErrorHandlingFileSystem fileSystem;
final Platform _platform;
@override
File wrapFile(io.File delegate) => ErrorHandlingFile(
platform: _platform,
fileSystem: fileSystem,
delegate: delegate,
);
@override
Directory wrapDirectory(io.Directory delegate) => ErrorHandlingDirectory(
platform: _platform,
fileSystem: fileSystem,
delegate: delegate,
);
@override
Link wrapLink(io.Link delegate) => ErrorHandlingLink(
platform: _platform,
fileSystem: fileSystem,
delegate: delegate,
);
@override
String toString() => delegate.toString();
}
const String _kNoExecutableFound = 'The Flutter tool could not locate an executable with suitable permissions';
Future<T> _run<T>(Future<T> Function() op, {
required Platform platform,
String? failureMessage,
String? posixPermissionSuggestion,
}) async {
try {
return await op();
} on ProcessPackageExecutableNotFoundException catch (e) {
if (e.candidates.isNotEmpty) {
throwToolExit('$_kNoExecutableFound: $e');
}
rethrow;
} on FileSystemException catch (e) {
if (platform.isWindows) {
_handleWindowsException(e, failureMessage, e.osError?.errorCode ?? 0);
} else if (platform.isLinux || platform.isMacOS) {
_handlePosixException(e, failureMessage, e.osError?.errorCode ?? 0, posixPermissionSuggestion);
}
rethrow;
} on io.ProcessException catch (e) {
if (platform.isWindows) {
_handleWindowsException(e, failureMessage, e.errorCode);
} else if (platform.isLinux) {
_handlePosixException(e, failureMessage, e.errorCode, posixPermissionSuggestion);
} if (platform.isMacOS) {
_handleMacOSException(e, failureMessage, e.errorCode, posixPermissionSuggestion);
}
rethrow;
}
}
T _runSync<T>(T Function() op, {
required Platform platform,
String? failureMessage,
String? posixPermissionSuggestion,
}) {
try {
return op();
} on ProcessPackageExecutableNotFoundException catch (e) {
if (e.candidates.isNotEmpty) {
throwToolExit('$_kNoExecutableFound: $e');
}
rethrow;
} on FileSystemException catch (e) {
if (platform.isWindows) {
_handleWindowsException(e, failureMessage, e.osError?.errorCode ?? 0);
} else if (platform.isLinux || platform.isMacOS) {
_handlePosixException(e, failureMessage, e.osError?.errorCode ?? 0, posixPermissionSuggestion);
}
rethrow;
} on io.ProcessException catch (e) {
if (platform.isWindows) {
_handleWindowsException(e, failureMessage, e.errorCode);
} else if (platform.isLinux) {
_handlePosixException(e, failureMessage, e.errorCode, posixPermissionSuggestion);
} if (platform.isMacOS) {
_handleMacOSException(e, failureMessage, e.errorCode, posixPermissionSuggestion);
}
rethrow;
}
}
/// A [ProcessManager] that throws a [ToolExit] on certain errors.
///
/// If a [ProcessException] is not caused by the Flutter tool, and can only be
/// addressed by the user, it should be caught by this [ProcessManager] and thrown
/// as a [ToolExit] using [throwToolExit].
///
/// See also:
/// * [ErrorHandlingFileSystem], for a similar file system strategy.
class ErrorHandlingProcessManager extends ProcessManager {
ErrorHandlingProcessManager({
required ProcessManager delegate,
required Platform platform,
}) : _delegate = delegate,
_platform = platform;
final ProcessManager _delegate;
final Platform _platform;
@override
bool canRun(dynamic executable, {String? workingDirectory}) {
return _runSync(
() => _delegate.canRun(executable, workingDirectory: workingDirectory),
platform: _platform,
failureMessage: 'Flutter failed to run "$executable"',
posixPermissionSuggestion: 'Try running:\n'
' sudo chown -R \$(whoami) $executable && chmod u+rx $executable',
);
}
@override
bool killPid(int pid, [io.ProcessSignal signal = io.ProcessSignal.sigterm]) {
return _runSync(
() => _delegate.killPid(pid, signal),
platform: _platform,
);
}
@override
Future<io.ProcessResult> run(
List<Object> command, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
Encoding? stdoutEncoding = io.systemEncoding,
Encoding? stderrEncoding = io.systemEncoding,
}) {
return _run(() {
return _delegate.run(
command,
workingDirectory: workingDirectory,
environment: environment,
includeParentEnvironment: includeParentEnvironment,
runInShell: runInShell,
stdoutEncoding: stdoutEncoding,
stderrEncoding: stderrEncoding,
);
},
platform: _platform,
failureMessage: 'Flutter failed to run "${command.join(' ')}"',
);
}
@override
Future<io.Process> start(
List<Object> command, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
io.ProcessStartMode mode = io.ProcessStartMode.normal,
}) {
return _run(() {
return _delegate.start(
command,
workingDirectory: workingDirectory,
environment: environment,
includeParentEnvironment: includeParentEnvironment,
runInShell: runInShell,
mode: mode,
);
},
platform: _platform,
failureMessage: 'Flutter failed to run "${command.join(' ')}"',
);
}
@override
io.ProcessResult runSync(
List<Object> command, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
Encoding? stdoutEncoding = io.systemEncoding,
Encoding? stderrEncoding = io.systemEncoding,
}) {
return _runSync(() {
return _delegate.runSync(
command,
workingDirectory: workingDirectory,
environment: environment,
includeParentEnvironment: includeParentEnvironment,
runInShell: runInShell,
stdoutEncoding: stdoutEncoding,
stderrEncoding: stderrEncoding,
);
},
platform: _platform,
failureMessage: 'Flutter failed to run "${command.join(' ')}"',
);
}
}
void _handlePosixException(Exception e, String? message, int errorCode, String? posixPermissionSuggestion) {
// From:
// https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/errno.h
// https://github.com/torvalds/linux/blob/master/include/uapi/asm-generic/errno-base.h
// https://github.com/apple/darwin-xnu/blob/master/bsd/dev/dtrace/scripts/errno.d
const int eperm = 1;
const int enospc = 28;
const int eacces = 13;
// Catch errors and bail when:
String? errorMessage;
switch (errorCode) {
case enospc:
errorMessage =
'$message. The target device is full.'
'\n$e\n'
'Free up space and try again.';
case eperm:
case eacces:
final StringBuffer errorBuffer = StringBuffer();
if (message != null && message.isNotEmpty) {
errorBuffer.writeln('$message.');
} else {
errorBuffer.writeln('The flutter tool cannot access the file or directory.');
}
errorBuffer.writeln('Please ensure that the SDK and/or project is installed in a location '
'that has read/write permissions for the current user.');
if (posixPermissionSuggestion != null && posixPermissionSuggestion.isNotEmpty) {
errorBuffer.writeln(posixPermissionSuggestion);
}
errorMessage = errorBuffer.toString();
default:
// Caller must rethrow the exception.
break;
}
_throwFileSystemException(errorMessage);
}
void _handleMacOSException(Exception e, String? message, int errorCode, String? posixPermissionSuggestion) {
// https://github.com/apple/darwin-xnu/blob/master/bsd/dev/dtrace/scripts/errno.d
const int ebadarch = 86;
if (errorCode == ebadarch) {
final StringBuffer errorBuffer = StringBuffer();
if (message != null) {
errorBuffer.writeln('$message.');
}
errorBuffer.writeln('The binary was built with the incorrect architecture to run on this machine.');
errorBuffer.writeln('If you are on an ARM Apple Silicon Mac, Flutter requires the Rosetta translation environment. Try running:');
errorBuffer.writeln(' sudo softwareupdate --install-rosetta --agree-to-license');
_throwFileSystemException(errorBuffer.toString());
}
_handlePosixException(e, message, errorCode, posixPermissionSuggestion);
}
void _handleWindowsException(Exception e, String? message, int errorCode) {
// From:
// https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes
const int kDeviceFull = 112;
const int kUserMappedSectionOpened = 1224;
const int kAccessDenied = 5;
const int kFatalDeviceHardwareError = 483;
const int kDeviceDoesNotExist = 433;
// Catch errors and bail when:
String? errorMessage;
switch (errorCode) {
case kAccessDenied:
errorMessage =
'$message. The flutter tool cannot access the file or directory.\n'
'Please ensure that the SDK and/or project is installed in a location '
'that has read/write permissions for the current user.';
case kDeviceFull:
errorMessage =
'$message. The target device is full.'
'\n$e\n'
'Free up space and try again.';
case kUserMappedSectionOpened:
errorMessage =
'$message. The file is being used by another program.'
'\n$e\n'
'Do you have an antivirus program running? '
'Try disabling your antivirus program and try again.';
case kFatalDeviceHardwareError:
errorMessage =
'$message. There is a problem with the device driver '
'that this file or directory is stored on.';
case kDeviceDoesNotExist:
errorMessage =
'$message. The device was not found.'
'\n$e\n'
'Verify the device is mounted and try again.';
default:
// Caller must rethrow the exception.
break;
}
_throwFileSystemException(errorMessage);
}
void _throwFileSystemException(String? errorMessage) {
if (errorMessage == null) {
return;
}
if (ErrorHandlingFileSystem._noExitOnFailure) {
throw FileSystemException(errorMessage);
}
throwToolExit(errorMessage);
}
| flutter/packages/flutter_tools/lib/src/base/error_handling_io.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/base/error_handling_io.dart",
"repo_id": "flutter",
"token_count": 9267
} | 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 'platform.dart';
/// Class containing some message strings that can be produced by Flutter tools.
//
// This allows partial reimplementations of the flutter tool to override
// certain messages.
// TODO(andrewkolos): It is unclear if this is worth keeping. See
// https://github.com/flutter/flutter/issues/125155.
class UserMessages {
// Messages used in multiple components.
String get flutterToolBugInstructions =>
'Please report a bug at https://github.com/flutter/flutter/issues.';
// Messages used in FlutterValidator
String flutterStatusInfo(String? channel, String? version, String os, String locale) =>
'Channel ${channel ?? 'unknown'}, ${version ?? 'unknown version'}, on $os, locale $locale';
String flutterVersion(String version, String channel, String flutterRoot) =>
'Flutter version $version on channel $channel at $flutterRoot';
String get flutterUnknownChannel =>
'Currently on an unknown channel. Run `flutter channel` to switch to an official channel.\n'
"If that doesn't fix the issue, reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install.";
String get flutterUnknownVersion =>
'Cannot resolve current version, possibly due to local changes.\n'
'Reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install.';
String flutterRevision(String revision, String age, String date) =>
'Framework revision $revision ($age), $date';
String flutterUpstreamRepositoryUrl(String url) => 'Upstream repository $url';
String get flutterUpstreamRepositoryUnknown =>
'Unknown upstream repository.\n'
'Reinstall Flutter by following instructions at https://flutter.dev/docs/get-started/install.';
String flutterUpstreamRepositoryUrlEnvMismatch(String url) => 'Upstream repository $url is not the same as FLUTTER_GIT_URL';
String flutterUpstreamRepositoryUrlNonStandard(String url) =>
'Upstream repository $url is not a standard remote.\n'
'Set environment variable "FLUTTER_GIT_URL" to $url to dismiss this error.';
String flutterGitUrl(String url) => 'FLUTTER_GIT_URL = $url';
String engineRevision(String revision) => 'Engine revision $revision';
String dartRevision(String revision) => 'Dart version $revision';
String devToolsVersion(String version) => 'DevTools version $version';
String pubMirrorURL(String url) => 'Pub download mirror $url';
String flutterMirrorURL(String url) => 'Flutter download mirror $url';
String get flutterBinariesDoNotRun =>
'Downloaded executables cannot execute on host.\n'
'See https://github.com/flutter/flutter/issues/6207 for more information.';
String get flutterBinariesLinuxRepairCommands =>
'On Debian/Ubuntu/Mint: sudo apt-get install lib32stdc++6\n'
'On Fedora: dnf install libstdc++.i686\n'
'On Arch: pacman -S lib32-gcc-libs';
String get flutterValidatorErrorIntentional =>
'If those were intentional, you can disregard the above warnings; however it is '
'recommended to use "git" directly to perform update checks and upgrades.';
// Messages used in NoIdeValidator
String get noIdeStatusInfo => 'No supported IDEs installed';
List<String> get noIdeInstallationInfo => <String>[
'IntelliJ - https://www.jetbrains.com/idea/',
'Android Studio - https://developer.android.com/studio/',
'VS Code - https://code.visualstudio.com/',
];
// Messages used in IntellijValidator
String intellijStatusInfo(String version) => 'version $version';
String get intellijPluginInfo =>
'For information about installing plugins, see\n'
'https://flutter.dev/intellij-setup/#installing-the-plugins';
String intellijMinimumVersion(String minVersion) =>
'This install is older than the minimum recommended version of $minVersion.';
String intellijLocation(String installPath) => 'IntelliJ at $installPath';
// Message used in IntellijValidatorOnMac
String get intellijMacUnknownResult => 'Cannot determine if IntelliJ is installed';
// Messages used in DeviceValidator
String get devicesMissing => 'No devices available';
String devicesAvailable(int devices) => '$devices available';
// Messages used in AndroidValidator
String androidCantRunJavaBinary(String javaBinary) => 'Cannot execute $javaBinary to determine the version';
String get androidUnknownJavaVersion => 'Could not determine java version';
String androidJavaVersion(String javaVersion) => 'Java version $javaVersion';
String androidJavaMinimumVersion(String javaVersion) => 'Java version $javaVersion is older than the minimum recommended version of 1.8';
String androidSdkLicenseOnly(String envKey) =>
'Android SDK contains licenses only.\n'
'Your first build of an Android application will take longer than usual, '
'while gradle downloads the missing components. This functionality will '
'only work if the licenses in the licenses folder in $envKey are valid.\n'
'If the Android SDK has been installed to another location, set $envKey to that location.\n'
'You may also want to add it to your PATH environment variable.\n\n'
'Certain features, such as `flutter emulators` and `flutter devices`, will '
'not work without the currently missing SDK components.';
String androidBadSdkDir(String envKey, String homeDir) =>
'$envKey = $homeDir\n'
'but Android SDK not found at this location.';
String androidMissingSdkInstructions(Platform platform) =>
'Unable to locate Android SDK.\n'
'Install Android Studio from: https://developer.android.com/studio/index.html\n'
'On first launch it will assist you in installing the Android SDK components.\n'
'(or visit ${androidSdkInstallUrl(platform)} for detailed instructions).\n'
'If the Android SDK has been installed to a custom location, please use\n'
'`flutter config --android-sdk` to update to that location.\n';
String androidSdkLocation(String directory) => 'Android SDK at $directory';
String androidSdkPlatformToolsVersion(String platform, String tools) =>
'Platform $platform, build-tools $tools';
String androidSdkInstallHelp(Platform platform) =>
'Try re-installing or updating your Android SDK,\n'
'visit ${androidSdkInstallUrl(platform)} for detailed instructions.';
// Also occurs in AndroidLicenseValidator
String androidStatusInfo(String version) => 'Android SDK version $version';
// Messages used in AndroidLicenseValidator
String get androidMissingJdk =>
'No Java Development Kit (JDK) found; You must have the environment '
'variable JAVA_HOME set and the java binary in your PATH. '
'You can download the JDK from https://www.oracle.com/technetwork/java/javase/downloads/.';
String androidJdkLocation(String location) => 'Java binary at: $location';
String get androidLicensesAll => 'All Android licenses accepted.';
String get androidLicensesSome => 'Some Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses';
String get androidLicensesNone => 'Android licenses not accepted. To resolve this, run: flutter doctor --android-licenses';
String androidLicensesUnknown(Platform platform) =>
'Android license status unknown.\n'
'Run `flutter doctor --android-licenses` to accept the SDK licenses.\n'
'See ${androidSdkInstallUrl(platform)} for more details.';
String androidSdkManagerOutdated(String managerPath) =>
'A newer version of the Android SDK is required. To update, run:\n'
'$managerPath --update\n';
String androidLicensesTimeout(String managerPath) => 'Intentionally killing $managerPath';
String get androidSdkShort => 'Unable to locate Android SDK.';
String androidMissingSdkManager(String sdkManagerPath, Platform platform) =>
'Android sdkmanager tool not found ($sdkManagerPath).\n'
'Try re-installing or updating your Android SDK,\n'
'visit ${androidSdkInstallUrl(platform)} for detailed instructions.';
String androidCannotRunSdkManager(String sdkManagerPath, String error, Platform platform) =>
'Android sdkmanager tool was found, but failed to run ($sdkManagerPath): "$error".\n'
'Try re-installing or updating your Android SDK,\n'
'visit ${androidSdkInstallUrl(platform)} for detailed instructions.';
String androidSdkBuildToolsOutdated(int sdkMinVersion, String buildToolsMinVersion, Platform platform) =>
'Flutter requires Android SDK $sdkMinVersion and the Android BuildTools $buildToolsMinVersion\n'
'To update the Android SDK visit ${androidSdkInstallUrl(platform)} for detailed instructions.';
String get androidMissingCmdTools => 'cmdline-tools component is missing\n'
'Run `path/to/sdkmanager --install "cmdline-tools;latest"`\n'
'See https://developer.android.com/studio/command-line for more details.';
// Messages used in AndroidStudioValidator
String androidStudioVersion(String version) => 'version $version';
String androidStudioLocation(String location) => 'Android Studio at $location';
String get androidStudioNeedsUpdate => 'Try updating or re-installing Android Studio.';
String get androidStudioResetDir =>
'Consider removing your android-studio-dir setting by running:\n'
'flutter config --android-studio-dir=';
String get aaptNotFound =>
'Could not locate aapt. Please ensure you have the Android buildtools installed.';
// Messages used in NoAndroidStudioValidator
String androidStudioMissing(String location) =>
'android-studio-dir = $location\n'
'but Android Studio not found at this location.';
String androidStudioInstallation(Platform platform) =>
'Android Studio not found; download from https://developer.android.com/studio/index.html\n'
'(or visit ${androidSdkInstallUrl(platform)} for detailed instructions).';
// Messages used in XcodeValidator
String xcodeLocation(String location) => 'Xcode at $location';
String xcodeOutdated(String requiredVersion) =>
'Flutter requires Xcode $requiredVersion or higher.\n'
'Download the latest version or update via the Mac App Store.';
String xcodeRecommended(String recommendedVersion) =>
'Flutter recommends a minimum Xcode version of $recommendedVersion.\n'
'Download the latest version or update via the Mac App Store.';
String get xcodeEula => "Xcode end user license agreement not signed; open Xcode or run the command 'sudo xcodebuild -license'.";
String get xcodeMissingSimct =>
'Xcode requires additional components to be installed in order to run.\n'
'Launch Xcode and install additional required components when prompted or run:\n'
' sudo xcodebuild -runFirstLaunch';
String get xcodeMissing =>
'Xcode not installed; this is necessary for iOS and macOS development.\n'
'Download at https://developer.apple.com/xcode/.';
String get xcodeIncomplete =>
'Xcode installation is incomplete; a full installation is necessary for iOS and macOS development.\n'
'Download at: https://developer.apple.com/xcode/\n'
'Or install Xcode via the App Store.\n'
'Once installed, run:\n'
' sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer\n'
' sudo xcodebuild -runFirstLaunch';
// Messages used in CocoaPodsValidator
String cocoaPodsVersion(String version) => 'CocoaPods version $version';
String cocoaPodsMissing(String consequence, String installInstructions) =>
'CocoaPods not installed.\n'
'$consequence\n'
'To install $installInstructions';
String cocoaPodsUnknownVersion(String consequence, String upgradeInstructions) =>
'Unknown CocoaPods version installed.\n'
'$consequence\n'
'To upgrade $upgradeInstructions';
String cocoaPodsOutdated(String currentVersion, String recVersion, String consequence, String upgradeInstructions) =>
'CocoaPods $currentVersion out of date ($recVersion is recommended).\n'
'$consequence\n'
'To upgrade $upgradeInstructions';
String cocoaPodsBrokenInstall(String consequence, String reinstallInstructions) =>
'CocoaPods installed but not working.\n'
'$consequence\n'
'To re-install $reinstallInstructions';
// Messages used in VisualStudioValidator
String visualStudioVersion(String name, String version) => '$name version $version';
String visualStudioLocation(String location) => 'Visual Studio at $location';
String windows10SdkVersion(String version) => 'Windows 10 SDK version $version';
String visualStudioMissingComponents(String workload, List<String> components) =>
'Visual Studio is missing necessary components. Please re-run the '
'Visual Studio installer for the "$workload" workload, and include these components:\n'
' ${components.join('\n ')}\n'
' Windows 10 SDK';
String get windows10SdkNotFound =>
'Unable to locate a Windows 10 SDK. If building fails, install the Windows 10 SDK in Visual Studio.';
String visualStudioMissing(String workload) =>
'Visual Studio not installed; this is necessary to develop Windows apps.\n'
'Download at https://visualstudio.microsoft.com/downloads/.\n'
'Please install the "$workload" workload, including all of its default components';
String visualStudioTooOld(String minimumVersion, String workload) =>
'Visual Studio $minimumVersion or later is required.\n'
'Download at https://visualstudio.microsoft.com/downloads/.\n'
'Please install the "$workload" workload, including all of its default components';
String get visualStudioIsPrerelease => 'The current Visual Studio installation is a pre-release version. It may not be '
'supported by Flutter yet.';
String get visualStudioNotLaunchable =>
'The current Visual Studio installation is not launchable. Please reinstall Visual Studio.';
String get visualStudioIsIncomplete => 'The current Visual Studio installation is incomplete.\n'
'Please use Visual Studio Installer to complete the installation or reinstall Visual Studio.';
String get visualStudioRebootRequired => 'Visual Studio requires a reboot of your system to complete installation.';
// Messages used in LinuxDoctorValidator
String get clangMissing => 'clang++ is required for Linux development.\n'
'It is likely available from your distribution (e.g.: apt install clang), or '
'can be downloaded from https://releases.llvm.org/';
String clangTooOld(String minimumVersion) => 'clang++ $minimumVersion or later is required.';
String get cmakeMissing => 'CMake is required for Linux development.\n'
'It is likely available from your distribution (e.g.: apt install cmake), or '
'can be downloaded from https://cmake.org/download/';
String cmakeTooOld(String minimumVersion) => 'cmake $minimumVersion or later is required.';
String ninjaVersion(String version) => 'ninja version $version';
String get ninjaMissing => 'ninja is required for Linux development.\n'
'It is likely available from your distribution (e.g.: apt install ninja-build), or '
'can be downloaded from https://github.com/ninja-build/ninja/releases';
String ninjaTooOld(String minimumVersion) => 'ninja $minimumVersion or later is required.';
String pkgConfigVersion(String version) => 'pkg-config version $version';
String get pkgConfigMissing => 'pkg-config is required for Linux development.\n'
'It is likely available from your distribution (e.g.: apt install pkg-config), or '
'can be downloaded from https://www.freedesktop.org/wiki/Software/pkg-config/';
String pkgConfigTooOld(String minimumVersion) => 'pkg-config $minimumVersion or later is required.';
String get gtkLibrariesMissing => 'GTK 3.0 development libraries are required for Linux development.\n'
'They are likely available from your distribution (e.g.: apt install libgtk-3-dev)';
// Messages used in FlutterCommand
String flutterElapsedTime(String name, String elapsedTime) => '"flutter $name" took $elapsedTime.';
String get flutterNoDevelopmentDevice =>
"Unable to locate a development device; please run 'flutter doctor' "
'for information about installing additional components.';
String get flutterNoSupportedDevices => 'No supported devices connected.';
String flutterMissPlatformProjects(List<String> unsupportedDevicesType) =>
'If you would like your app to run on ${unsupportedDevicesType.join(' or ')}, consider running `flutter create .` to generate projects for these platforms.';
String get flutterSpecifyDeviceWithAllOption =>
'More than one device connected; please specify a device with '
"the '-d <deviceId>' flag, or use '-d all' to act on all devices.";
String get flutterSpecifyDevice =>
'More than one device connected; please specify a device with '
"the '-d <deviceId>' flag.";
String get flutterNoPubspec =>
'Error: No pubspec.yaml file found.\n'
'This command should be run from the root of your Flutter project.';
String flutterTargetFileMissing(String path) => 'Target file "$path" not found.';
String get flutterBasePatchFlagsExclusive => 'Error: Only one of --baseline, --patch is allowed.';
String get flutterBaselineRequiresTraceFile => 'Error: --baseline requires --compilation-trace-file to be specified.';
String get flutterPatchRequiresTraceFile => 'Error: --patch requires --compilation-trace-file to be specified.';
// Messages used in FlutterCommandRunner
String runnerNoRoot(String error) => 'Unable to locate flutter root: $error';
String runnerWrapColumnInvalid(dynamic value) =>
'Argument to --wrap-column must be a positive integer. You supplied $value.';
String runnerWrapColumnParseError(dynamic value) =>
'Unable to parse argument --wrap-column=$value. Must be a positive integer.';
String runnerBugReportFinished(String zipFileName) =>
'Bug report written to $zipFileName.\n'
'Warning: this bug report contains local paths, device identifiers, and log snippets.';
String get runnerNoRecordTo => 'record-to location not specified';
String get runnerNoReplayFrom => 'replay-from location not specified';
String runnerNoEngineSrcDir(String enginePackageName, String engineEnvVar) =>
'Unable to detect local Flutter engine src directory.\n'
'Either specify a dependency_override for the $enginePackageName package in your pubspec.yaml and '
'ensure --package-root is set if necessary, or set the \$$engineEnvVar environment variable, or '
'use --local-engine-src-path to specify the path to the root of your flutter/engine repository.';
String runnerNoEngineBuildDirInPath(String engineSourcePath) =>
'Unable to detect a Flutter engine build directory in $engineSourcePath.\n'
"Please ensure that $engineSourcePath is a Flutter engine 'src' directory and that "
"you have compiled the engine in that directory, which should produce an 'out' directory";
String get runnerLocalEngineOrWebSdkRequired =>
'You must specify --local-engine or --local-web-sdk if you are using a locally built engine or web sdk.';
String get runnerLocalEngineRequiresHostEngine =>
'You are using a locally built engine (--local-engine) but have not specified --local-engine-host.\n'
'You may be building with a different engine than the one you are running with. '
'See https://github.com/flutter/flutter/issues/132245 for details.';
String runnerNoEngineBuild(String engineBuildPath) =>
'No Flutter engine build found at $engineBuildPath.';
String runnerNoWebSdk(String webSdkPath) =>
'No Flutter web sdk found at $webSdkPath.';
String runnerWrongFlutterInstance(String flutterRoot, String currentDir) =>
"Warning: the 'flutter' tool you are currently running is not the one from the current directory:\n"
' running Flutter : $flutterRoot\n'
' current directory: $currentDir\n'
'This can happen when you have multiple copies of flutter installed. Please check your system path to verify '
"that you're running the expected version (run 'flutter --version' to see which flutter is on your path).\n";
String runnerRemovedFlutterRepo(String flutterRoot, String flutterPath) =>
'Warning! This package referenced a Flutter repository via the .packages file that is '
"no longer available. The repository from which the 'flutter' tool is currently "
'executing will be used instead.\n'
' running Flutter tool: $flutterRoot\n'
' previous reference : $flutterPath\n'
'This can happen if you deleted or moved your copy of the Flutter repository, or '
'if it was on a volume that is no longer mounted or has been mounted at a '
'different location. Please check your system path to verify that you are running '
"the expected version (run 'flutter --version' to see which flutter is on your path).\n";
String runnerChangedFlutterRepo(String flutterRoot, String flutterPath) =>
"Warning! The 'flutter' tool you are currently running is from a different Flutter "
'repository than the one last used by this package. The repository from which the '
"'flutter' tool is currently executing will be used instead.\n"
' running Flutter tool: $flutterRoot\n'
' previous reference : $flutterPath\n'
'This can happen when you have multiple copies of flutter installed. Please check '
'your system path to verify that you are running the expected version (run '
"'flutter --version' to see which flutter is on your path).\n";
String invalidVersionSettingHintMessage(String invalidVersion) =>
'Invalid version $invalidVersion found, default value will be used.\n'
'In pubspec.yaml, a valid version should look like: build-name+build-number.\n'
'In Android, build-name is used as versionName while build-number used as versionCode.\n'
'Read more about Android versioning at https://developer.android.com/studio/publish/versioning\n'
'In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.\n'
'Read more about iOS versioning at\n'
'https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html\n';
String androidSdkInstallUrl(Platform platform) {
const String baseUrl = 'https://flutter.dev/docs/get-started/install';
const String fragment = '#android-setup';
if (platform.isMacOS) {
return '$baseUrl/macos$fragment';
} else if (platform.isLinux) {
return '$baseUrl/linux$fragment';
} else if (platform.isWindows) {
return '$baseUrl/windows$fragment';
} else {
return baseUrl;
}
}
}
| flutter/packages/flutter_tools/lib/src/base/user_messages.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/base/user_messages.dart",
"repo_id": "flutter",
"token_count": 6788
} | 742 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:meta/meta.dart';
import '../../android/deferred_components_gen_snapshot_validator.dart';
import '../../base/deferred_component.dart';
import '../../build_info.dart';
import '../../project.dart';
import '../build_system.dart';
import '../depfile.dart';
import 'android.dart';
/// Creates a [DeferredComponentsGenSnapshotValidator], runs the checks, and displays the validator
/// output to the developer if changes are recommended.
class DeferredComponentsGenSnapshotValidatorTarget extends Target {
/// Create an [AndroidAotDeferredComponentsBundle] implementation for a given [targetPlatform] and [buildMode].
DeferredComponentsGenSnapshotValidatorTarget({
required this.deferredComponentsDependencies,
required this.nonDeferredComponentsDependencies,
this.title,
this.exitOnFail = true,
});
/// The [AndroidAotDeferredComponentsBundle] derived target instances this rule depends on.
final List<AndroidAotDeferredComponentsBundle> deferredComponentsDependencies;
final List<Target> nonDeferredComponentsDependencies;
/// The title of the [DeferredComponentsGenSnapshotValidator] that is
/// displayed to the developer when logging results.
final String? title;
/// Whether to exit the tool if a recommended change is found by the
/// [DeferredComponentsGenSnapshotValidator].
final bool exitOnFail;
/// The abis to validate.
List<String> get _abis {
final List<String> abis = <String>[];
for (final AndroidAotDeferredComponentsBundle target in deferredComponentsDependencies) {
if (deferredComponentsTargets.contains(target.name)) {
abis.add(
getAndroidArchForName(getNameForTargetPlatform(target.dependency.targetPlatform)).archName
);
}
}
return abis;
}
@override
String get name => 'deferred_components_gen_snapshot_validator';
@override
List<Source> get inputs => const <Source>[];
@override
List<Source> get outputs => const <Source>[];
@override
List<String> get depfiles => <String>[
'flutter_$name.d',
];
@override
List<Target> get dependencies {
final List<Target> deps = <Target>[CompositeTarget(deferredComponentsDependencies)];
deps.addAll(nonDeferredComponentsDependencies);
return deps;
}
@visibleForTesting
DeferredComponentsGenSnapshotValidator? validator;
@override
Future<void> build(Environment environment) async {
validator = DeferredComponentsGenSnapshotValidator(
environment,
title: title,
exitOnFail: exitOnFail,
);
final List<LoadingUnit> generatedLoadingUnits = LoadingUnit.parseGeneratedLoadingUnits(
environment.outputDir,
environment.logger,
abis: _abis
);
validator!
..checkAppAndroidManifestComponentLoadingUnitMapping(
FlutterProject.current().manifest.deferredComponents ?? <DeferredComponent>[],
generatedLoadingUnits,
)
..checkAgainstLoadingUnitsCache(generatedLoadingUnits)
..writeLoadingUnitsCache(generatedLoadingUnits);
validator!.handleResults();
environment.depFileService.writeToFile(
Depfile(validator!.inputs, validator!.outputs),
environment.buildDir.childFile('flutter_$name.d'),
);
}
}
| flutter/packages/flutter_tools/lib/src/build_system/targets/deferred_components.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/deferred_components.dart",
"repo_id": "flutter",
"token_count": 1116
} | 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:pub_semver/pub_semver.dart';
import 'base/logger.dart';
import 'build_info.dart';
import 'cmake_project.dart';
/// Extracts the `BINARY_NAME` from a project's CMake file.
///
/// Returns `null` if it cannot be found.
String? getCmakeExecutableName(CmakeBasedProject project) {
if (!project.cmakeFile.existsSync()) {
return null;
}
final RegExp nameSetPattern = RegExp(r'^\s*set\(BINARY_NAME\s*"(.*)"\s*\)\s*$');
for (final String line in project.cmakeFile.readAsLinesSync()) {
final RegExpMatch? match = nameSetPattern.firstMatch(line);
if (match != null) {
return match.group(1);
}
}
return null;
}
String _escapeBackslashes(String s) {
return s.replaceAll(r'\', r'\\');
}
String _determineVersionString(CmakeBasedProject project, BuildInfo buildInfo) {
// Prefer the build arguments for version information.
final String buildName = buildInfo.buildName ?? project.parent.manifest.buildName ?? '1.0.0';
final String? buildNumber = buildInfo.buildName != null
? buildInfo.buildNumber
: (buildInfo.buildNumber ?? project.parent.manifest.buildNumber);
return buildNumber != null
? '$buildName+$buildNumber'
: buildName;
}
Version _determineVersion(CmakeBasedProject project, BuildInfo buildInfo, Logger logger) {
final String version = _determineVersionString(project, buildInfo);
try {
return Version.parse(version);
} on FormatException {
logger.printWarning('Warning: could not parse version $version, defaulting to 1.0.0.');
return Version(1, 0, 0);
}
}
/// Attempts to map a Dart version's build identifier (the part after a +) into
/// a single integer. Returns null for complex build identifiers like `foo` or `1.2`.
int? _tryDetermineBuildVersion(Version version) {
if (version.build.isEmpty) {
return 0;
}
if (version.build.length != 1) {
return null;
}
final Object buildIdentifier = version.build.first;
return buildIdentifier is int ? buildIdentifier : null;
}
/// Writes a generated CMake configuration file for [project], including
/// variables expected by the build template and an environment variable list
/// for calling back into Flutter.
void writeGeneratedCmakeConfig(
String flutterRoot,
CmakeBasedProject project,
BuildInfo buildInfo,
Map<String, String> environment,
Logger logger,
) {
// Only a limited set of variables are needed by the CMake files themselves,
// the rest are put into a list to pass to the re-entrant build step.
final String escapedFlutterRoot = _escapeBackslashes(flutterRoot);
final String escapedProjectDir = _escapeBackslashes(project.parent.directory.path);
final Version version = _determineVersion(project, buildInfo, logger);
final int? buildVersion = _tryDetermineBuildVersion(version);
// Since complex Dart build identifiers cannot be converted into integers,
// different Dart versions may be converted into the same Windows numeric version.
// Warn the user as some Windows installers, like MSI, don't update files if their versions are equal.
if (buildVersion == null && project is WindowsProject) {
final String buildIdentifier = version.build.join('.');
logger.printWarning(
'Warning: build identifier $buildIdentifier in version $version is not numeric '
'and cannot be converted into a Windows build version number. Defaulting to 0.\n'
'This may cause issues with Windows installers.'
);
}
final StringBuffer buffer = StringBuffer('''
# Generated code do not commit.
file(TO_CMAKE_PATH "$escapedFlutterRoot" FLUTTER_ROOT)
file(TO_CMAKE_PATH "$escapedProjectDir" PROJECT_DIR)
set(FLUTTER_VERSION "$version" PARENT_SCOPE)
set(FLUTTER_VERSION_MAJOR ${version.major} PARENT_SCOPE)
set(FLUTTER_VERSION_MINOR ${version.minor} PARENT_SCOPE)
set(FLUTTER_VERSION_PATCH ${version.patch} PARENT_SCOPE)
set(FLUTTER_VERSION_BUILD ${buildVersion ?? 0} PARENT_SCOPE)
# Environment variables to pass to tool_backend.sh
list(APPEND FLUTTER_TOOL_ENVIRONMENT
"FLUTTER_ROOT=$escapedFlutterRoot"
"PROJECT_DIR=$escapedProjectDir"
''');
environment.forEach((String key, String value) {
final String configValue = _escapeBackslashes(value);
buffer.writeln(' "$key=$configValue"');
});
buffer.writeln(')');
project.generatedCmakeConfigFile
..createSync(recursive: true)
..writeAsStringSync(buffer.toString());
}
| flutter/packages/flutter_tools/lib/src/cmake.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/cmake.dart",
"repo_id": "flutter",
"token_count": 1425
} | 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 '../base/analyze_size.dart';
import '../base/common.dart';
import '../base/logger.dart';
import '../base/os.dart';
import '../build_info.dart';
import '../cache.dart';
import '../features.dart';
import '../globals.dart' as globals;
import '../linux/build_linux.dart';
import '../project.dart';
import '../runner/flutter_command.dart' show FlutterCommandResult;
import 'build.dart';
/// A command to build a linux desktop target through a build shell script.
class BuildLinuxCommand extends BuildSubCommand {
BuildLinuxCommand({
required super.logger,
required OperatingSystemUtils operatingSystemUtils,
bool verboseHelp = false,
}) : _operatingSystemUtils = operatingSystemUtils,
super(verboseHelp: verboseHelp) {
addCommonDesktopBuildOptions(verboseHelp: verboseHelp);
final String defaultTargetPlatform =
(_operatingSystemUtils.hostPlatform == HostPlatform.linux_arm64) ?
'linux-arm64' : 'linux-x64';
argParser.addOption('target-platform',
defaultsTo: defaultTargetPlatform,
allowed: <String>['linux-arm64', 'linux-x64'],
help: 'The target platform for which the app is compiled.',
);
argParser.addOption('target-sysroot',
defaultsTo: '/',
help: 'The root filesystem path of target platform for which '
'the app is compiled. This option is valid only '
'if the current host and target architectures are different.',
);
}
final OperatingSystemUtils _operatingSystemUtils;
@override
final String name = 'linux';
@override
bool get hidden => !featureFlags.isLinuxEnabled || !globals.platform.isLinux;
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{
DevelopmentArtifact.linux,
};
@override
String get description => 'Build a Linux desktop application.';
@override
Future<FlutterCommandResult> runCommand() async {
final BuildInfo buildInfo = await getBuildInfo();
final FlutterProject flutterProject = FlutterProject.current();
final TargetPlatform targetPlatform =
getTargetPlatformForName(stringArg('target-platform')!);
final bool needCrossBuild =
_operatingSystemUtils.hostPlatform.platformName
!= targetPlatform.simpleName;
if (!featureFlags.isLinuxEnabled) {
throwToolExit('"build linux" is not currently supported. To enable, run "flutter config --enable-linux-desktop".');
}
if (!globals.platform.isLinux) {
throwToolExit('"build linux" only supported on Linux hosts.');
}
// Cross-building for x64 targets on arm64 hosts is not supported.
if (_operatingSystemUtils.hostPlatform != HostPlatform.linux_x64 &&
targetPlatform != TargetPlatform.linux_arm64) {
throwToolExit('"cross-building" only supported on Linux x64 hosts.');
}
// TODO(fujino): https://github.com/flutter/flutter/issues/74929
if (_operatingSystemUtils.hostPlatform == HostPlatform.linux_x64 &&
targetPlatform == TargetPlatform.linux_arm64) {
throwToolExit(
'Cross-build from Linux x64 host to Linux arm64 target is not currently supported.');
}
displayNullSafetyMode(buildInfo);
final Logger logger = globals.logger;
await buildLinux(
flutterProject.linux,
buildInfo,
target: targetFile,
sizeAnalyzer: SizeAnalyzer(
fileSystem: globals.fs,
logger: logger,
flutterUsage: globals.flutterUsage,
analytics: analytics,
),
needCrossBuild: needCrossBuild,
targetPlatform: targetPlatform,
targetSysroot: stringArg('target-sysroot')!,
logger: logger,
);
return FlutterCommandResult.success();
}
}
| flutter/packages/flutter_tools/lib/src/commands/build_linux.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/build_linux.dart",
"repo_id": "flutter",
"token_count": 1322
} | 745 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:process/process.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/process.dart';
import '../base/terminal.dart';
import '../cache.dart';
import '../globals.dart' as globals;
import '../persistent_tool_state.dart';
import '../runner/flutter_command.dart';
import '../version.dart';
/// The flutter downgrade command returns the SDK to the last recorded version
/// for a particular branch.
///
/// For example, suppose a user on the beta channel upgrades from 1.2.3 to 1.4.6.
/// The tool will record that sha "abcdefg" was the last active beta channel in the
/// persistent tool state. If the user is still on the beta channel and runs
/// flutter downgrade, this will take the user back to "abcdefg". They will not be
/// able to downgrade again, since the tool only records one prior version.
/// Additionally, if they had switched channels to stable before trying to downgrade,
/// the command would fail since there was no previously recorded stable version.
class DowngradeCommand extends FlutterCommand {
DowngradeCommand({
bool verboseHelp = false,
PersistentToolState? persistentToolState,
required Logger logger,
ProcessManager? processManager,
FlutterVersion? flutterVersion,
Terminal? terminal,
Stdio? stdio,
FileSystem? fileSystem,
}) : _terminal = terminal,
_flutterVersion = flutterVersion,
_persistentToolState = persistentToolState,
_processManager = processManager,
_stdio = stdio,
_logger = logger,
_fileSystem = fileSystem {
argParser.addOption(
'working-directory',
hide: !verboseHelp,
help: 'Override the downgrade working directory. '
'This is only intended to enable integration testing of the tool itself. '
'It allows one to use the flutter tool from one checkout to downgrade a '
'different checkout.'
);
argParser.addFlag(
'prompt',
defaultsTo: true,
hide: !verboseHelp,
help: 'Show the downgrade prompt.'
);
}
Terminal? _terminal;
FlutterVersion? _flutterVersion;
PersistentToolState? _persistentToolState;
ProcessUtils? _processUtils;
ProcessManager? _processManager;
final Logger _logger;
Stdio? _stdio;
FileSystem? _fileSystem;
@override
String get description => 'Downgrade Flutter to the last active version for the current channel.';
@override
String get name => 'downgrade';
@override
final String category = FlutterCommandCategory.sdk;
@override
Future<FlutterCommandResult> runCommand() async {
// Commands do not necessarily have access to the correct zone injected
// values when being created. Fields must be lazily instantiated in runCommand,
// at least until the zone injection is refactored.
_terminal ??= globals.terminal;
_flutterVersion ??= globals.flutterVersion;
_persistentToolState ??= globals.persistentToolState;
_processManager ??= globals.processManager;
_processUtils ??= ProcessUtils(processManager: _processManager!, logger: _logger);
_stdio ??= globals.stdio;
_fileSystem ??= globals.fs;
String workingDirectory = Cache.flutterRoot!;
if (argResults!.wasParsed('working-directory')) {
workingDirectory = stringArg('working-directory')!;
_flutterVersion = FlutterVersion(
fs: _fileSystem!,
flutterRoot: workingDirectory,
);
}
final String currentChannel = _flutterVersion!.channel;
final Channel? channel = getChannelForName(currentChannel);
if (channel == null) {
throwToolExit(
'Flutter is not currently on a known channel. '
'Use "flutter channel" to switch to an official channel. '
);
}
final PersistentToolState persistentToolState = _persistentToolState!;
final String? lastFlutterVersion = persistentToolState.lastActiveVersion(channel);
final String? currentFlutterVersion = _flutterVersion?.frameworkRevision;
if (lastFlutterVersion == null || currentFlutterVersion == lastFlutterVersion) {
final String trailing = await _createErrorMessage(workingDirectory, channel);
throwToolExit(
'There is no previously recorded version for channel "$currentChannel".\n'
'$trailing'
);
}
// Detect unknown versions.
final ProcessUtils processUtils = _processUtils!;
final RunResult parseResult = await processUtils.run(<String>[
'git', 'describe', '--tags', lastFlutterVersion,
], workingDirectory: workingDirectory);
if (parseResult.exitCode != 0) {
throwToolExit('Failed to parse version for downgrade:\n${parseResult.stderr}');
}
final String humanReadableVersion = parseResult.stdout;
// If there is a terminal attached, prompt the user to confirm the downgrade.
final Stdio stdio = _stdio!;
final Terminal terminal = _terminal!;
if (stdio.hasTerminal && boolArg('prompt')) {
terminal.usesTerminalUi = true;
final String result = await terminal.promptForCharInput(
const <String>['y', 'n'],
prompt: 'Downgrade flutter to version $humanReadableVersion?',
logger: _logger,
);
if (result == 'n') {
return FlutterCommandResult.success();
}
} else {
_logger.printStatus('Downgrading Flutter to version $humanReadableVersion');
}
// To downgrade the tool, we perform a git checkout --hard, and then
// switch channels. The version recorded must have existed on that branch
// so this operation is safe.
try {
await processUtils.run(
<String>['git', 'reset', '--hard', lastFlutterVersion],
throwOnError: true,
workingDirectory: workingDirectory,
);
} on ProcessException catch (error) {
throwToolExit(
'Unable to downgrade Flutter: The tool could not update to the version '
'$humanReadableVersion.\n'
'Error: $error'
);
}
try {
await processUtils.run(
// The `--` bit (because it's followed by nothing) means that we don't actually change
// anything in the working tree, which avoids the need to first go into detached HEAD mode.
<String>['git', 'checkout', currentChannel, '--'],
throwOnError: true,
workingDirectory: workingDirectory,
);
} on ProcessException catch (error) {
throwToolExit(
'Unable to downgrade Flutter: The tool could not switch to the channel '
'$currentChannel.\n'
'Error: $error'
);
}
await FlutterVersion.resetFlutterVersionFreshnessCheck();
_logger.printStatus('Success');
return FlutterCommandResult.success();
}
// Formats an error message that lists the currently stored versions.
Future<String> _createErrorMessage(String workingDirectory, Channel currentChannel) async {
final StringBuffer buffer = StringBuffer();
for (final Channel channel in Channel.values) {
if (channel == currentChannel) {
continue;
}
final String? sha = _persistentToolState?.lastActiveVersion(channel);
if (sha == null) {
continue;
}
final RunResult parseResult = await _processUtils!.run(<String>[
'git', 'describe', '--tags', sha,
], workingDirectory: workingDirectory);
if (parseResult.exitCode == 0) {
buffer.writeln('Channel "${getNameForChannel(channel)}" was previously on: ${parseResult.stdout}.');
}
}
return buffer.toString();
}
}
| flutter/packages/flutter_tools/lib/src/commands/downgrade.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/downgrade.dart",
"repo_id": "flutter",
"token_count": 2623
} | 746 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:meta/meta.dart';
import 'package:package_config/package_config_types.dart';
import '../asset.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../build_info.dart';
import '../bundle_builder.dart';
import '../devfs.dart';
import '../device.dart';
import '../globals.dart' as globals;
import '../native_assets.dart';
import '../project.dart';
import '../runner/flutter_command.dart';
import '../test/coverage_collector.dart';
import '../test/event_printer.dart';
import '../test/runner.dart';
import '../test/test_time_recorder.dart';
import '../test/test_wrapper.dart';
import '../test/watcher.dart';
import '../web/compile.dart';
/// The name of the directory where Integration Tests are placed.
///
/// When there are test files specified for the test command that are part of
/// this directory, *relative to the package root*, the files will be executed
/// as Integration Tests.
const String _kIntegrationTestDirectory = 'integration_test';
/// A command to run tests.
///
/// This command has two modes of execution:
///
/// ## Unit / Widget Tests
///
/// These tests run in the Flutter Tester, which is a desktop-based Flutter
/// embedder. In this mode, tests are quick to compile and run.
///
/// By default, if no flags are passed to the `flutter test` command, the Tool
/// will recursively find all files within the `test/` directory that end with
/// the `*_test.dart` suffix, and run them in a single invocation.
///
/// See:
/// - https://flutter.dev/docs/cookbook/testing/unit/introduction
/// - https://flutter.dev/docs/cookbook/testing/widget/introduction
///
/// ## Integration Tests
///
/// These tests run in a connected Flutter Device, similar to `flutter run`. As
/// a result, iteration is slower because device-based artifacts have to be
/// built.
///
/// Integration tests should be placed in the `integration_test/` directory of
/// your package. To run these tests, use `flutter test integration_test`.
///
/// See:
/// - https://flutter.dev/docs/testing/integration-tests
class TestCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts {
TestCommand({
bool verboseHelp = false,
this.testWrapper = const TestWrapper(),
this.testRunner = const FlutterTestRunner(),
this.verbose = false,
this.nativeAssetsBuilder,
}) {
requiresPubspecYaml();
usesPubOption();
addNullSafetyModeOptions(hide: !verboseHelp);
usesFrontendServerStarterPathOption(verboseHelp: verboseHelp);
usesTrackWidgetCreation(verboseHelp: verboseHelp);
addEnableExperimentation(hide: !verboseHelp);
usesDartDefineOption();
usesWebRendererOption();
usesDeviceUserOption();
usesFlavorOption();
addEnableImpellerFlag(verboseHelp: verboseHelp);
argParser
..addFlag('experimental-faster-testing',
negatable: false,
hide: !verboseHelp,
help: 'Run each test in a separate lightweight Flutter Engine to speed up testing.'
)
..addMultiOption('name',
help: 'A regular expression matching substrings of the names of tests to run.',
valueHelp: 'regexp',
splitCommas: false,
)
..addMultiOption('plain-name',
help: 'A plain-text substring of the names of tests to run.',
valueHelp: 'substring',
splitCommas: false,
)
..addOption('tags',
abbr: 't',
help: 'Run only tests associated with the specified tags. See: https://pub.dev/packages/test#tagging-tests',
)
..addOption('exclude-tags',
abbr: 'x',
help: 'Run only tests that do not have the specified tags. See: https://pub.dev/packages/test#tagging-tests',
)
..addFlag('start-paused',
negatable: false,
help: 'Start in a paused mode and wait for a debugger to connect.\n'
'You must specify a single test file to run, explicitly.\n'
'Instructions for connecting with a debugger are printed to the '
'console once the test has started.',
)
..addFlag('run-skipped',
help: 'Run skipped tests instead of skipping them.',
)
..addFlag('disable-service-auth-codes',
negatable: false,
hide: !verboseHelp,
help: '(deprecated) Allow connections to the VM service without using authentication codes. '
'(Not recommended! This can open your device to remote code execution attacks!)'
)
..addFlag('coverage',
negatable: false,
help: 'Whether to collect coverage information.',
)
..addFlag('merge-coverage',
negatable: false,
help: 'Whether to merge coverage data with "coverage/lcov.base.info".\n'
'Implies collecting coverage data. (Requires lcov.)',
)
..addFlag('branch-coverage',
negatable: false,
help: 'Whether to collect branch coverage information. '
'Implies collecting coverage data.',
)
..addFlag('ipv6',
negatable: false,
hide: !verboseHelp,
help: 'Whether to use IPv6 for the test harness server socket.',
)
..addOption('coverage-path',
defaultsTo: 'coverage/lcov.info',
help: 'Where to store coverage information (if coverage is enabled).',
)
..addMultiOption('coverage-package',
help: 'A regular expression matching packages names '
'to include in the coverage report (if coverage is enabled). '
'If unset, matches the current package name.',
valueHelp: 'package-name-regexp',
splitCommas: false,
)
..addFlag('machine',
hide: !verboseHelp,
negatable: false,
help: 'Handle machine structured JSON command input '
'and provide output and progress in machine friendly format.',
)
..addFlag('update-goldens',
negatable: false,
help: 'Whether "matchesGoldenFile()" calls within your test methods should ' // flutter_ignore: golden_tag (see analyze.dart)
'update the golden files rather than test for an existing match.',
)
..addOption('concurrency',
abbr: 'j',
help: 'The number of concurrent test processes to run. This will be ignored '
'when running integration tests.',
valueHelp: 'jobs',
)
..addFlag('test-assets',
defaultsTo: true,
help: 'Whether to build the assets bundle for testing. '
'This takes additional time before running the tests. '
'Consider using "--no-test-assets" if assets are not required.',
)
// --platform is not supported to be used by Flutter developers. It only
// exists to test the Flutter framework itself and may be removed entirely
// in the future. Developers should either use plain `flutter test`, or
// `package:integration_test` instead.
..addOption('platform',
allowed: const <String>['tester', 'chrome'],
hide: !verboseHelp,
defaultsTo: 'tester',
help: 'Selects the test backend.',
allowedHelp: <String, String>{
'tester': 'Run tests using the VM-based test environment.',
'chrome': '(deprecated) Run tests using the Google Chrome web browser. '
'This value is intended for testing the Flutter framework '
'itself and may be removed at any time.',
},
)
..addOption('test-randomize-ordering-seed',
help: 'The seed to randomize the execution order of test cases within test files. '
'Must be a 32bit unsigned integer or the string "random", '
'which indicates that a seed should be selected randomly. '
'By default, tests run in the order they are declared.',
)
..addOption('total-shards',
help: 'Tests can be sharded with the "--total-shards" and "--shard-index" '
'arguments, allowing you to split up your test suites and run '
'them separately.'
)
..addOption('shard-index',
help: 'Tests can be sharded with the "--total-shards" and "--shard-index" '
'arguments, allowing you to split up your test suites and run '
'them separately.'
)
..addFlag('enable-vmservice',
hide: !verboseHelp,
help: 'Enables the VM service without "--start-paused". This flag is '
'intended for use with tests that will use "dart:developer" to '
'interact with the VM service at runtime.\n'
'This flag is ignored if "--start-paused" or coverage are requested, as '
'the VM service will be enabled in those cases regardless.'
)
..addOption('reporter',
abbr: 'r',
help: 'Set how to print test results. If unset, value will default to either compact or expanded.',
allowed: <String>['compact', 'expanded', 'github', 'json'],
allowedHelp: <String, String>{
'compact': 'A single line that updates dynamically (The default reporter).',
'expanded': 'A separate line for each update. May be preferred when logging to a file or in continuous integration.',
'github': 'A custom reporter for GitHub Actions (the default reporter when running on GitHub Actions).',
'json': 'A machine-readable format. See: https://dart.dev/go/test-docs/json_reporter.md',
},
)
..addOption('file-reporter',
help: 'Enable an additional reporter writing test results to a file.\n'
'Should be in the form <reporter>:<filepath>, '
'Example: "json:reports/tests.json".'
)
..addOption('timeout',
help: 'The default test timeout, specified either '
'in seconds (e.g. "60s"), '
'as a multiplier of the default timeout (e.g. "2x"), '
'or as the string "none" to disable the timeout entirely.',
);
addDdsOptions(verboseHelp: verboseHelp);
addServeObservatoryOptions(verboseHelp: verboseHelp);
usesFatalWarningsOption(verboseHelp: verboseHelp);
}
/// The interface for starting and configuring the tester.
final TestWrapper testWrapper;
/// Interface for running the tester process.
final FlutterTestRunner testRunner;
final TestCompilerNativeAssetsBuilder? nativeAssetsBuilder;
final bool verbose;
@visibleForTesting
bool get isIntegrationTest => _isIntegrationTest;
bool _isIntegrationTest = false;
final Set<Uri> _testFileUris = <Uri>{};
bool get isWeb => stringArg('platform') == 'chrome';
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async {
final Set<DevelopmentArtifact> results = _isIntegrationTest
// Use [DeviceBasedDevelopmentArtifacts].
? await super.requiredArtifacts
: <DevelopmentArtifact>{};
if (isWeb) {
results.add(DevelopmentArtifact.web);
}
return results;
}
@override
String get name => 'test';
@override
String get description => 'Run Flutter unit tests for the current project.';
@override
String get category => FlutterCommandCategory.project;
@override
Future<FlutterCommandResult> verifyThenRunCommand(String? commandPath) {
final List<Uri> testUris = argResults!.rest.map(_parseTestArgument).toList();
if (testUris.isEmpty) {
// We don't scan the entire package, only the test/ subdirectory, so that
// files with names like "hit_test.dart" don't get run.
final Directory testDir = globals.fs.directory('test');
if (!testDir.existsSync()) {
throwToolExit('Test directory "${testDir.path}" not found.');
}
_testFileUris.addAll(_findTests(testDir).map(Uri.file));
if (_testFileUris.isEmpty) {
throwToolExit(
'Test directory "${testDir.path}" does not appear to contain any test files.\n'
'Test files must be in that directory and end with the pattern "_test.dart".'
);
}
} else {
for (final Uri uri in testUris) {
// Test files may have query strings to support name/line/col:
// flutter test test/foo.dart?name=a&line=1
String testPath = uri.replace(query: '').toFilePath();
testPath = globals.fs.path.absolute(testPath);
testPath = globals.fs.path.normalize(testPath);
if (globals.fs.isDirectorySync(testPath)) {
_testFileUris.addAll(_findTests(globals.fs.directory(testPath)).map(Uri.file));
} else {
_testFileUris.add(Uri.file(testPath).replace(query: uri.query));
}
}
}
// This needs to be set before [super.verifyThenRunCommand] so that the
// correct [requiredArtifacts] can be identified before [run] takes place.
final List<String> testFilePaths = _testFileUris.map((Uri uri) => uri.replace(query: '').toFilePath()).toList();
_isIntegrationTest = _shouldRunAsIntegrationTests(globals.fs.currentDirectory.absolute.path, testFilePaths);
globals.printTrace(
'Found ${_testFileUris.length} files which will be executed as '
'${_isIntegrationTest ? 'Integration' : 'Widget'} Tests.',
);
return super.verifyThenRunCommand(commandPath);
}
@override
Future<FlutterCommandResult> runCommand() async {
if (!globals.fs.isFileSync('pubspec.yaml')) {
throwToolExit(
'Error: No pubspec.yaml file found in the current working directory.\n'
'Run this command from the root of your project. Test files must be '
"called *_test.dart and must reside in the package's 'test' "
'directory (or one of its subdirectories).');
}
final FlutterProject flutterProject = FlutterProject.current();
final bool buildTestAssets = boolArg('test-assets');
final List<String> names = stringsArg('name');
final List<String> plainNames = stringsArg('plain-name');
final String? tags = stringArg('tags');
final String? excludeTags = stringArg('exclude-tags');
final BuildInfo buildInfo = await getBuildInfo(forcedBuildMode: BuildMode.debug);
TestTimeRecorder? testTimeRecorder;
if (verbose) {
testTimeRecorder = TestTimeRecorder(globals.logger);
}
if (buildInfo.packageConfig['test_api'] == null) {
throwToolExit(
'Error: cannot run without a dependency on either "package:flutter_test" or "package:test". '
'Ensure the following lines are present in your pubspec.yaml:'
'\n\n'
'dev_dependencies:\n'
' flutter_test:\n'
' sdk: flutter\n',
);
}
bool experimentalFasterTesting = boolArg('experimental-faster-testing');
if (experimentalFasterTesting) {
if (_isIntegrationTest || isWeb) {
experimentalFasterTesting = false;
globals.printStatus(
'--experimental-faster-testing was parsed but will be ignored. This '
'option is not supported when running integration tests or web tests.',
);
} else if (_testFileUris.length == 1) {
experimentalFasterTesting = false;
globals.printStatus(
'--experimental-faster-testing was parsed but will be ignored. This '
'option should not be used when running a single test file.',
);
}
}
final bool startPaused = boolArg('start-paused');
if (startPaused && _testFileUris.length != 1) {
throwToolExit(
'When using --start-paused, you must specify a single test file to run.',
exitCode: 1,
);
}
final String? webRendererString = stringArg('web-renderer');
final WebRendererMode webRenderer = (webRendererString != null)
? WebRendererMode.values.byName(webRendererString)
: WebRendererMode.auto;
final DebuggingOptions debuggingOptions = DebuggingOptions.enabled(
buildInfo,
startPaused: startPaused,
disableServiceAuthCodes: boolArg('disable-service-auth-codes'),
serveObservatory: boolArg('serve-observatory'),
// On iOS >=14, keeping this enabled will leave a prompt on the screen.
disablePortPublication: true,
enableDds: enableDds,
nullAssertions: boolArg(FlutterOptions.kNullAssertions),
usingCISystem: usingCISystem,
enableImpeller: ImpellerStatus.fromBool(argResults!['enable-impeller'] as bool?),
debugLogsDirectoryPath: debugLogsDirectoryPath,
webRenderer: webRenderer,
);
String? testAssetDirectory;
if (buildTestAssets) {
await _buildTestAsset(flavor: buildInfo.flavor, impellerStatus: debuggingOptions.enableImpeller);
testAssetDirectory = globals.fs.path.
join(flutterProject.directory.path, 'build', 'unit_test_assets');
}
final String? concurrencyString = stringArg('concurrency');
int? jobs = concurrencyString == null ? null : int.tryParse(concurrencyString);
if (jobs != null && (jobs <= 0 || !jobs.isFinite)) {
throwToolExit(
'Could not parse -j/--concurrency argument. It must be an integer greater than zero.'
);
}
if (_isIntegrationTest || isWeb) {
if (argResults!.wasParsed('concurrency')) {
globals.printStatus(
'-j/--concurrency was parsed but will be ignored, this option is not '
'supported when running Integration Tests or web tests.',
);
}
// Running with concurrency will result in deploying multiple test apps
// on the connected device concurrently, which is not supported.
jobs = 1;
} else if (experimentalFasterTesting) {
if (argResults!.wasParsed('concurrency')) {
globals.printStatus(
'-j/--concurrency was parsed but will be ignored. This option is not '
'compatible with --experimental-faster-testing.',
);
}
}
final int? shardIndex = int.tryParse(stringArg('shard-index') ?? '');
if (shardIndex != null && (shardIndex < 0 || !shardIndex.isFinite)) {
throwToolExit(
'Could not parse --shard-index=$shardIndex argument. It must be an integer greater than -1.');
}
final int? totalShards = int.tryParse(stringArg('total-shards') ?? '');
if (totalShards != null && (totalShards <= 0 || !totalShards.isFinite)) {
throwToolExit(
'Could not parse --total-shards=$totalShards argument. It must be an integer greater than zero.');
}
if (totalShards != null && shardIndex == null) {
throwToolExit(
'If you set --total-shards you need to also set --shard-index.');
}
if (shardIndex != null && totalShards == null) {
throwToolExit(
'If you set --shard-index you need to also set --total-shards.');
}
final bool enableVmService = boolArg('enable-vmservice');
if (experimentalFasterTesting && enableVmService) {
globals.printStatus(
'--enable-vmservice was parsed but will be ignored. This option is not '
'compatible with --experimental-faster-testing.',
);
}
final bool ipv6 = boolArg('ipv6');
if (experimentalFasterTesting && ipv6) {
// [ipv6] is set when the user desires for the test harness server to use
// IPv6, but a test harness server will not be started at all when
// [experimentalFasterTesting] is set.
globals.printStatus(
'--ipv6 was parsed but will be ignored. This option is not compatible '
'with --experimental-faster-testing.',
);
}
final bool machine = boolArg('machine');
CoverageCollector? collector;
if (boolArg('coverage') || boolArg('merge-coverage') ||
boolArg('branch-coverage')) {
final Set<String> packagesToInclude = _getCoveragePackages(
stringsArg('coverage-package'),
flutterProject,
buildInfo.packageConfig,
);
collector = CoverageCollector(
verbose: !machine,
libraryNames: packagesToInclude,
packagesPath: buildInfo.packagesPath,
resolver: await CoverageCollector.getResolver(buildInfo.packagesPath),
testTimeRecorder: testTimeRecorder,
branchCoverage: boolArg('branch-coverage'),
);
}
TestWatcher? watcher;
if (machine) {
watcher = EventPrinter(parent: collector, out: globals.stdio.stdout);
} else if (collector != null) {
watcher = collector;
}
Device? integrationTestDevice;
if (_isIntegrationTest) {
integrationTestDevice = await findTargetDevice();
// Disable reporting of test results to native test frameworks. This isn't
// needed as the Flutter Tool will be responsible for reporting results.
buildInfo.dartDefines.add('INTEGRATION_TEST_SHOULD_REPORT_RESULTS_TO_NATIVE=false');
if (integrationTestDevice == null) {
throwToolExit(
'No devices are connected. '
'Ensure that `flutter doctor` shows at least one connected device',
);
}
if (integrationTestDevice.platformType == PlatformType.web) {
// TODO(jiahaog): Support web. https://github.com/flutter/flutter/issues/66264
throwToolExit('Web devices are not supported for integration tests yet.');
}
if (buildInfo.packageConfig['integration_test'] == null) {
throwToolExit(
'Error: cannot run without a dependency on "package:integration_test". '
'Ensure the following lines are present in your pubspec.yaml:'
'\n\n'
'dev_dependencies:\n'
' integration_test:\n'
' sdk: flutter\n',
);
}
if (stringArg('flavor') != null && !integrationTestDevice.supportsFlavors) {
throwToolExit('--flavor is only supported for Android, macOS, and iOS devices.');
}
}
final Stopwatch? testRunnerTimeRecorderStopwatch = testTimeRecorder?.start(TestTimePhases.TestRunner);
final int result;
if (experimentalFasterTesting) {
assert(!isWeb && !_isIntegrationTest && _testFileUris.length > 1);
result = await testRunner.runTestsBySpawningLightweightEngines(
_testFileUris.toList(),
debuggingOptions: debuggingOptions,
names: names,
plainNames: plainNames,
tags: tags,
excludeTags: excludeTags,
machine: machine,
updateGoldens: boolArg('update-goldens'),
concurrency: jobs,
testAssetDirectory: testAssetDirectory,
flutterProject: flutterProject,
randomSeed: stringArg('test-randomize-ordering-seed'),
reporter: stringArg('reporter'),
fileReporter: stringArg('file-reporter'),
timeout: stringArg('timeout'),
runSkipped: boolArg('run-skipped'),
shardIndex: shardIndex,
totalShards: totalShards,
testTimeRecorder: testTimeRecorder,
);
} else {
result = await testRunner.runTests(
testWrapper,
_testFileUris.toList(),
debuggingOptions: debuggingOptions,
names: names,
plainNames: plainNames,
tags: tags,
excludeTags: excludeTags,
watcher: watcher,
enableVmService: collector != null || startPaused || enableVmService,
ipv6: ipv6,
machine: machine,
updateGoldens: boolArg('update-goldens'),
concurrency: jobs,
testAssetDirectory: testAssetDirectory,
flutterProject: flutterProject,
web: isWeb,
randomSeed: stringArg('test-randomize-ordering-seed'),
reporter: stringArg('reporter'),
fileReporter: stringArg('file-reporter'),
timeout: stringArg('timeout'),
runSkipped: boolArg('run-skipped'),
shardIndex: shardIndex,
totalShards: totalShards,
integrationTestDevice: integrationTestDevice,
integrationTestUserIdentifier: stringArg(FlutterOptions.kDeviceUser),
testTimeRecorder: testTimeRecorder,
nativeAssetsBuilder: nativeAssetsBuilder,
);
}
testTimeRecorder?.stop(TestTimePhases.TestRunner, testRunnerTimeRecorderStopwatch!);
if (collector != null) {
final Stopwatch? collectTimeRecorderStopwatch = testTimeRecorder?.start(TestTimePhases.CoverageDataCollect);
final bool collectionResult = await collector.collectCoverageData(
stringArg('coverage-path'),
mergeCoverageData: boolArg('merge-coverage'),
);
testTimeRecorder?.stop(TestTimePhases.CoverageDataCollect, collectTimeRecorderStopwatch!);
if (!collectionResult) {
testTimeRecorder?.print();
throwToolExit(null);
}
}
testTimeRecorder?.print();
if (result != 0) {
throwToolExit(null);
}
return FlutterCommandResult.success();
}
Set<String> _getCoveragePackages(
List<String> packagesRegExps,
FlutterProject flutterProject,
PackageConfig packageConfig,
) {
final String projectName = flutterProject.manifest.appName;
final Set<String> packagesToInclude = <String>{
if (packagesRegExps.isEmpty) projectName,
};
try {
for (final String regExpStr in packagesRegExps) {
final RegExp regExp = RegExp(regExpStr);
packagesToInclude.addAll(
packageConfig.packages
.map((Package e) => e.name)
.where((String e) => regExp.hasMatch(e)),
);
}
} on FormatException catch (e) {
throwToolExit('Regular expression syntax is invalid. $e');
}
return packagesToInclude;
}
/// Parses a test file/directory target passed as an argument and returns it
/// as an absolute file:/// [URI] with optional querystring for name/line/col.
Uri _parseTestArgument(String arg) {
// We can't parse Windows paths as URIs if they have query strings, so
// parse the file and query parts separately.
final int queryStart = arg.indexOf('?');
String filePart = queryStart == -1 ? arg : arg.substring(0, queryStart);
final String queryPart = queryStart == -1 ? '' : arg.substring(queryStart + 1);
filePart = globals.fs.path.absolute(filePart);
filePart = globals.fs.path.normalize(filePart);
return Uri.file(filePart)
.replace(query: queryPart.isEmpty ? null : queryPart);
}
Future<void> _buildTestAsset({
required String? flavor,
required ImpellerStatus impellerStatus,
}) async {
final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle();
final int build = await assetBundle.build(
packagesPath: '.packages',
flavor: flavor,
);
if (build != 0) {
throwToolExit('Error: Failed to build asset bundle');
}
if (_needRebuild(assetBundle.entries)) {
await writeBundle(
globals.fs.directory(globals.fs.path.join('build', 'unit_test_assets')),
assetBundle.entries,
targetPlatform: TargetPlatform.tester,
impellerStatus: impellerStatus,
processManager: globals.processManager,
fileSystem: globals.fs,
artifacts: globals.artifacts!,
logger: globals.logger,
projectDir: globals.fs.currentDirectory,
);
}
}
bool _needRebuild(Map<String, AssetBundleEntry> entries) {
// TODO(andrewkolos): This logic might fail in the future if we change the
// schema of the contents of the asset manifest file and the user does not
// perform a `flutter clean` after upgrading.
// See https://github.com/flutter/flutter/issues/128563.
final File manifest = globals.fs.file(globals.fs.path.join('build', 'unit_test_assets', 'AssetManifest.bin'));
if (!manifest.existsSync()) {
return true;
}
final DateTime lastModified = manifest.lastModifiedSync();
final File pub = globals.fs.file('pubspec.yaml');
if (pub.lastModifiedSync().isAfter(lastModified)) {
return true;
}
final Iterable<DevFSFileContent> files = entries.values
.map((AssetBundleEntry asset) => asset.content)
.whereType<DevFSFileContent>();
for (final DevFSFileContent entry in files) {
// Calling isModified to access file stats first in order for isModifiedAfter
// to work.
if (entry.isModified && entry.isModifiedAfter(lastModified)) {
return true;
}
}
return false;
}
}
/// Searches [directory] and returns files that end with `_test.dart` as
/// absolute paths.
Iterable<String> _findTests(Directory directory) {
return directory.listSync(recursive: true, followLinks: false)
.where((FileSystemEntity entity) => entity.path.endsWith('_test.dart') &&
globals.fs.isFileSync(entity.path))
.map((FileSystemEntity entity) => globals.fs.path.absolute(entity.path));
}
/// Returns true if there are files that are Integration Tests.
///
/// The [currentDirectory] and [testFiles] parameters here must be provided as
/// absolute paths.
///
/// Throws an exception if there are both Integration Tests and Widget Tests
/// found in [testFiles].
bool _shouldRunAsIntegrationTests(String currentDirectory, List<String> testFiles) {
final String integrationTestDirectory = globals.fs.path.join(currentDirectory, _kIntegrationTestDirectory);
if (testFiles.every((String absolutePath) => !absolutePath.startsWith(integrationTestDirectory))) {
return false;
}
if (testFiles.every((String absolutePath) => absolutePath.startsWith(integrationTestDirectory))) {
return true;
}
throwToolExit(
'Integration tests and unit tests cannot be run in a single invocation.'
' Use separate invocations of `flutter test` to run integration tests'
' and unit tests.'
);
}
| flutter/packages/flutter_tools/lib/src/commands/test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/commands/test.dart",
"repo_id": "flutter",
"token_count": 11072
} | 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 'package:meta/meta.dart';
import 'package:package_config/package_config.dart';
import 'package:process/process.dart';
import '../base/bot_detector.dart';
import '../base/common.dart';
import '../base/context.dart';
import '../base/file_system.dart';
import '../base/io.dart' as io;
import '../base/io.dart';
import '../base/logger.dart';
import '../base/platform.dart';
import '../base/process.dart';
import '../cache.dart';
import '../convert.dart';
import '../dart/package_map.dart';
import '../project.dart';
import '../reporting/reporting.dart';
/// The [Pub] instance.
Pub get pub => context.get<Pub>()!;
/// The console environment key used by the pub tool.
const String _kPubEnvironmentKey = 'PUB_ENVIRONMENT';
/// The console environment key used by the pub tool to find the cache directory.
const String _kPubCacheEnvironmentKey = 'PUB_CACHE';
typedef MessageFilter = String? Function(String message);
bool _tryDeleteDirectory(Directory directory, Logger logger) {
try {
if (directory.existsSync()) {
directory.deleteSync(recursive: true);
}
} on FileSystemException {
logger.printWarning('Failed to delete directory at: ${directory.path}');
return false;
}
return true;
}
/// Represents Flutter-specific data that is added to the `PUB_ENVIRONMENT`
/// environment variable and allows understanding the type of requests made to
/// the package site on Flutter's behalf.
// DO NOT update without contacting kevmoo.
// We have server-side tooling that assumes the values are consistent.
class PubContext {
PubContext._(this._values) {
for (final String item in _values) {
if (!_validContext.hasMatch(item)) {
throw ArgumentError.value(
_values, 'value', 'Must match RegExp ${_validContext.pattern}');
}
}
}
static PubContext getVerifyContext(String commandName) =>
PubContext._(<String>['verify', commandName.replaceAll('-', '_')]);
static final PubContext create = PubContext._(<String>['create']);
static final PubContext createPackage = PubContext._(<String>['create_pkg']);
static final PubContext createPlugin = PubContext._(<String>['create_plugin']);
static final PubContext interactive = PubContext._(<String>['interactive']);
static final PubContext pubGet = PubContext._(<String>['get']);
static final PubContext pubUpgrade = PubContext._(<String>['upgrade']);
static final PubContext pubAdd = PubContext._(<String>['add']);
static final PubContext pubRemove = PubContext._(<String>['remove']);
static final PubContext pubForward = PubContext._(<String>['forward']);
static final PubContext pubPassThrough = PubContext._(<String>['passthrough']);
static final PubContext runTest = PubContext._(<String>['run_test']);
static final PubContext flutterTests = PubContext._(<String>['flutter_tests']);
static final PubContext updatePackages = PubContext._(<String>['update_packages']);
final List<String> _values;
static final RegExp _validContext = RegExp('[a-z][a-z_]*[a-z]');
@override
String toString() => 'PubContext: ${_values.join(':')}';
String toAnalyticsString() {
return _values.map((String s) => s.replaceAll('_', '-')).toList().join('-');
}
}
/// Describes the amount of output that should get printed from a `pub` command.
/// [PubOutputMode.all] indicates that the complete output is printed. This is
/// typically the default.
/// [PubOutputMode.none] indicates that no output should be printed.
/// [PubOutputMode.summaryOnly] indicates that only summary information should be printed.
enum PubOutputMode {
none,
all,
summaryOnly,
}
/// A handle for interacting with the pub tool.
abstract class Pub {
/// Create a default [Pub] instance.
factory Pub({
required FileSystem fileSystem,
required Logger logger,
required ProcessManager processManager,
required Platform platform,
required BotDetector botDetector,
required Usage usage,
}) = _DefaultPub;
/// Create a [Pub] instance with a mocked [stdio].
@visibleForTesting
factory Pub.test({
required FileSystem fileSystem,
required Logger logger,
required ProcessManager processManager,
required Platform platform,
required BotDetector botDetector,
required Usage usage,
required Stdio stdio,
}) = _DefaultPub.test;
/// Runs `pub get` for [project].
///
/// [context] provides extra information to package server requests to
/// understand usage.
///
/// If [shouldSkipThirdPartyGenerator] is true, the overall pub get will be
/// skipped if the package config file has a "generator" other than "pub".
/// Defaults to true.
///
/// [outputMode] determines how verbose the output from `pub get` will be.
/// If [PubOutputMode.all] is used, `pub get` will print its typical output
/// which includes information about all changed dependencies. If
/// [PubOutputMode.summaryOnly] is used, only summary information will be printed.
/// This is useful for cases where the user is typically not interested in
/// what dependencies were changed, such as when running `flutter create`.
///
/// Will also resolve dependencies in the example folder if present.
Future<void> get({
required PubContext context,
required FlutterProject project,
bool upgrade = false,
bool offline = false,
String? flutterRootOverride,
bool checkUpToDate = false,
bool shouldSkipThirdPartyGenerator = true,
PubOutputMode outputMode = PubOutputMode.all,
});
/// Runs pub in 'batch' mode.
///
/// forwarding complete lines written by pub to its stdout/stderr streams to
/// the corresponding stream of this process, optionally applying filtering.
/// The pub process will not receive anything on its stdin stream.
///
/// The `--trace` argument is passed to `pub` when `showTraceForErrors`
/// `isRunningOnBot` is true.
///
/// [context] provides extra information to package server requests to
/// understand usage.
Future<void> batch(
List<String> arguments, {
required PubContext context,
String? directory,
MessageFilter? filter,
String failureMessage = 'pub failed',
});
/// Runs pub in 'interactive' mode.
///
/// This will run the pub process with StdioInherited (unless [_stdio] is set
/// for testing).
///
/// The pub process will be run in current working directory, so `--directory`
/// should be passed appropriately in [arguments]. This ensures output from
/// pub will refer to relative paths correctly.
///
/// [touchesPackageConfig] should be true if this is a command expected to
/// create a new `.dart_tool/package_config.json` file.
Future<void> interactively(
List<String> arguments, {
FlutterProject? project,
required PubContext context,
required String command,
bool touchesPackageConfig = false,
bool generateSyntheticPackage = false,
PubOutputMode outputMode = PubOutputMode.all
});
}
class _DefaultPub implements Pub {
_DefaultPub({
required FileSystem fileSystem,
required Logger logger,
required ProcessManager processManager,
required Platform platform,
required BotDetector botDetector,
required Usage usage,
}) : _fileSystem = fileSystem,
_logger = logger,
_platform = platform,
_botDetector = botDetector,
_usage = usage,
_processUtils = ProcessUtils(
logger: logger,
processManager: processManager,
),
_processManager = processManager,
_stdio = null;
@visibleForTesting
_DefaultPub.test({
required FileSystem fileSystem,
required Logger logger,
required ProcessManager processManager,
required Platform platform,
required BotDetector botDetector,
required Usage usage,
required Stdio stdio,
}) : _fileSystem = fileSystem,
_logger = logger,
_platform = platform,
_botDetector = botDetector,
_usage = usage,
_processUtils = ProcessUtils(
logger: logger,
processManager: processManager,
),
_processManager = processManager,
_stdio = stdio;
final FileSystem _fileSystem;
final Logger _logger;
final ProcessUtils _processUtils;
final Platform _platform;
final BotDetector _botDetector;
final Usage _usage;
final ProcessManager _processManager;
final Stdio? _stdio;
@override
Future<void> get({
required PubContext context,
required FlutterProject project,
bool upgrade = false,
bool offline = false,
bool generateSyntheticPackage = false,
bool generateSyntheticPackageForExample = false,
String? flutterRootOverride,
bool checkUpToDate = false,
bool shouldSkipThirdPartyGenerator = true,
PubOutputMode outputMode = PubOutputMode.all,
}) async {
final String directory = project.directory.path;
final File packageConfigFile = project.packageConfigFile;
final File lastVersion = _fileSystem.file(
_fileSystem.path.join(directory, '.dart_tool', 'version'));
final File currentVersion = _fileSystem.file(
_fileSystem.path.join(Cache.flutterRoot!, 'version'));
final File pubspecYaml = project.pubspecFile;
final File pubLockFile = _fileSystem.file(
_fileSystem.path.join(directory, 'pubspec.lock')
);
if (shouldSkipThirdPartyGenerator && project.packageConfigFile.existsSync()) {
Map<String, Object?> packageConfigMap;
try {
packageConfigMap = jsonDecode(
project.packageConfigFile.readAsStringSync(),
) as Map<String, Object?>;
} on FormatException {
packageConfigMap = <String, Object?>{};
}
final bool isPackageConfigGeneratedByThirdParty =
packageConfigMap.containsKey('generator') &&
packageConfigMap['generator'] != 'pub';
if (isPackageConfigGeneratedByThirdParty) {
_logger.printTrace('Skipping pub get: generated by third-party.');
return;
}
}
// If the pubspec.yaml is older than the package config file and the last
// flutter version used is the same as the current version skip pub get.
// This will incorrectly skip pub on the master branch if dependencies
// are being added/removed from the flutter framework packages, but this
// can be worked around by manually running pub.
if (checkUpToDate &&
packageConfigFile.existsSync() &&
pubLockFile.existsSync() &&
pubspecYaml.lastModifiedSync().isBefore(pubLockFile.lastModifiedSync()) &&
pubspecYaml.lastModifiedSync().isBefore(packageConfigFile.lastModifiedSync()) &&
lastVersion.existsSync() &&
lastVersion.readAsStringSync() == currentVersion.readAsStringSync()) {
_logger.printTrace('Skipping pub get: version match.');
return;
}
final String command = upgrade ? 'upgrade' : 'get';
final bool verbose = _logger.isVerbose;
final List<String> args = <String>[
if (_logger.supportsColor)
'--color',
if (verbose)
'--verbose',
'--directory',
_fileSystem.path.relative(directory),
...<String>[
command,
],
if (offline)
'--offline',
'--example',
];
await _runWithStdioInherited(
args,
command: command,
context: context,
directory: directory,
failureMessage: 'pub $command failed',
flutterRootOverride: flutterRootOverride,
outputMode: outputMode,
);
await _updateVersionAndPackageConfig(project);
}
/// Runs pub with [arguments] and [ProcessStartMode.inheritStdio] mode.
///
/// Uses [ProcessStartMode.normal] and [Pub._stdio] if [Pub.test] constructor
/// was used.
///
/// Prints the stdout and stderr of the whole run, unless silenced using
/// [printProgress].
///
/// Sends an analytics event.
Future<void> _runWithStdioInherited(
List<String> arguments, {
required String command,
required PubOutputMode outputMode,
required PubContext context,
required String directory,
String failureMessage = 'pub failed',
String? flutterRootOverride,
}) async {
int exitCode;
final List<String> pubCommand = <String>[..._pubCommand, ...arguments];
final Map<String, String> pubEnvironment = await _createPubEnvironment(context: context, flutterRootOverride: flutterRootOverride, summaryOnly: outputMode == PubOutputMode.summaryOnly);
try {
if (outputMode != PubOutputMode.none) {
final io.Stdio? stdio = _stdio;
if (stdio == null) {
// Let pub inherit stdio and output directly to the tool's stdout and
// stderr handles.
final io.Process process = await _processUtils.start(
pubCommand,
workingDirectory: _fileSystem.path.current,
environment: pubEnvironment,
mode: ProcessStartMode.inheritStdio,
);
exitCode = await process.exitCode;
} else {
// Omit [mode] parameter to send output to [process.stdout] and
// [process.stderr].
final io.Process process = await _processUtils.start(
pubCommand,
workingDirectory: _fileSystem.path.current,
environment: pubEnvironment,
);
// Direct pub output to [Pub._stdio] for tests.
final StreamSubscription<List<int>> stdoutSubscription =
process.stdout.listen(stdio.stdout.add);
final StreamSubscription<List<int>> stderrSubscription =
process.stderr.listen(stdio.stderr.add);
await Future.wait<void>(<Future<void>>[
stdoutSubscription.asFuture<void>(),
stderrSubscription.asFuture<void>(),
]);
unawaited(stdoutSubscription.cancel());
unawaited(stderrSubscription.cancel());
exitCode = await process.exitCode;
}
} else {
// Do not try to use [ProcessUtils.start] here, because it requires you
// to read all data out of the stdout and stderr streams. If you don't
// read the streams, it may appear to work fine on your platform but
// will block the tool's process on Windows.
// See https://api.dart.dev/stable/dart-io/Process/start.html
//
// [ProcessUtils.run] will send the output to [result.stdout] and
// [result.stderr], which we will ignore.
final RunResult result = await _processUtils.run(
pubCommand,
workingDirectory: _fileSystem.path.current,
environment: pubEnvironment,
);
exitCode = result.exitCode;
}
// The exception is rethrown, so don't catch only Exceptions.
} catch (exception) { // ignore: avoid_catches_without_on_clauses
if (exception is io.ProcessException) {
final StringBuffer buffer = StringBuffer('${exception.message}\n');
final String directoryExistsMessage = _fileSystem.directory(directory).existsSync()
? 'exists'
: 'does not exist';
buffer.writeln('Working directory: "$directory" ($directoryExistsMessage)');
buffer.write(_stringifyPubEnv(pubEnvironment));
throw io.ProcessException(
exception.executable,
exception.arguments,
buffer.toString(),
exception.errorCode,
);
}
rethrow;
}
final int code = exitCode;
final String result = code == 0 ? 'success' : 'failure';
PubResultEvent(
context: context.toAnalyticsString(),
result: result,
usage: _usage,
).send();
if (code != 0) {
final StringBuffer buffer = StringBuffer('$failureMessage\n');
buffer.writeln('command: "${pubCommand.join(' ')}"');
buffer.write(_stringifyPubEnv(pubEnvironment));
buffer.writeln('exit code: $code');
_logger.printTrace(buffer.toString());
throwToolExit(null, exitCode: code);
}
}
// For surfacing pub env in crash reporting
String _stringifyPubEnv(Map<String, String> map, {String prefix = 'pub env'}) {
if (map.isEmpty) {
return '';
}
final StringBuffer buffer = StringBuffer();
buffer.writeln('$prefix: {');
for (final MapEntry<String, String> entry in map.entries) {
buffer.writeln(' "${entry.key}": "${entry.value}",');
}
buffer.writeln('}');
return buffer.toString();
}
@override
Future<void> batch(
List<String> arguments, {
required PubContext context,
String? directory,
MessageFilter? filter,
String failureMessage = 'pub failed',
String? flutterRootOverride,
}) async {
final bool showTraceForErrors = await _botDetector.isRunningOnBot;
String lastPubMessage = 'no message';
String? filterWrapper(String line) {
lastPubMessage = line;
if (filter == null) {
return line;
}
return filter(line);
}
if (showTraceForErrors) {
arguments.insert(0, '--trace');
}
final Map<String, String> pubEnvironment = await _createPubEnvironment(context: context, flutterRootOverride: flutterRootOverride);
final List<String> pubCommand = <String>[..._pubCommand, ...arguments];
final int code = await _processUtils.stream(
pubCommand,
workingDirectory: directory,
mapFunction: filterWrapper, // may set versionSolvingFailed, lastPubMessage
environment: pubEnvironment,
);
String result = 'success';
if (code != 0) {
result = 'failure';
}
PubResultEvent(
context: context.toAnalyticsString(),
result: result,
usage: _usage,
).send();
if (code != 0) {
final StringBuffer buffer = StringBuffer('$failureMessage\n');
buffer.writeln('command: "${pubCommand.join(' ')}"');
buffer.write(_stringifyPubEnv(pubEnvironment));
buffer.writeln('exit code: $code');
buffer.writeln('last line of pub output: "${lastPubMessage.trim()}"');
throwToolExit(
buffer.toString(),
exitCode: code,
);
}
}
@override
Future<void> interactively(
List<String> arguments, {
FlutterProject? project,
required PubContext context,
required String command,
bool touchesPackageConfig = false,
bool generateSyntheticPackage = false,
PubOutputMode outputMode = PubOutputMode.all
}) async {
await _runWithStdioInherited(
arguments,
command: command,
directory: _fileSystem.currentDirectory.path,
context: context,
outputMode: outputMode,
);
if (touchesPackageConfig && project != null) {
await _updateVersionAndPackageConfig(project);
}
}
/// The command used for running pub.
late final List<String> _pubCommand = _computePubCommand();
List<String> _computePubCommand() {
// TODO(zanderso): refactor to use artifacts.
final String sdkPath = _fileSystem.path.joinAll(<String>[
Cache.flutterRoot!,
'bin',
'cache',
'dart-sdk',
'bin',
'dart',
]);
if (!_processManager.canRun(sdkPath)) {
throwToolExit(
'Your Flutter SDK download may be corrupt or missing permissions to run. '
'Try re-downloading the Flutter SDK into a directory that has read/write '
'permissions for the current user.'
);
}
return <String>[sdkPath, 'pub', '--suppress-analytics'];
}
// Returns the environment value that should be used when running pub.
//
// Includes any existing environment variable, if one exists.
//
// [context] provides extra information to package server requests to
// understand usage.
Future<String> _getPubEnvironmentValue(PubContext pubContext) async {
// DO NOT update this function without contacting kevmoo.
// We have server-side tooling that assumes the values are consistent.
final String? existing = _platform.environment[_kPubEnvironmentKey];
final List<String> values = <String>[
if (existing != null && existing.isNotEmpty) existing,
if (await _botDetector.isRunningOnBot) 'flutter_bot',
'flutter_cli',
...pubContext._values,
];
return values.join(':');
}
/// There are 2 ways to get the pub cache location
///
/// 1) Provide the _kPubCacheEnvironmentKey.
/// 2) The pub default user-level pub cache.
///
/// If we are using 2, check if there are pre-packaged packages in
/// $FLUTTER_ROOT/.pub-preload-cache and install them in the user-level cache.
String? _getPubCacheIfAvailable() {
if (_platform.environment.containsKey(_kPubCacheEnvironmentKey)) {
return _platform.environment[_kPubCacheEnvironmentKey];
}
_preloadPubCache();
// Use pub's default location by returning null.
return null;
}
/// Load any package-files stored in FLUTTER_ROOT/.pub-preload-cache into the
/// pub cache if it exists.
///
/// Deletes the [preloadCacheDir].
void _preloadPubCache() {
final String flutterRootPath = Cache.flutterRoot!;
final Directory flutterRoot = _fileSystem.directory(flutterRootPath);
final Directory preloadCacheDir = flutterRoot.childDirectory('.pub-preload-cache');
if (preloadCacheDir.existsSync()) {
/// We only want to inform about existing caches on first run of a freshly
/// downloaded Flutter SDK. Therefore it is conditioned on the existence
/// of the .pub-preload-cache dir.
final Iterable<String> cacheFiles =
preloadCacheDir
.listSync()
.map((FileSystemEntity f) => f.path)
.where((String path) => path.endsWith('.tar.gz'));
_processManager.runSync(<String>[..._pubCommand, 'cache', 'preload', ...cacheFiles]);
_tryDeleteDirectory(preloadCacheDir, _logger);
}
}
/// The full environment used when running pub.
///
/// [context] provides extra information to package server requests to
/// understand usage.
Future<Map<String, String>> _createPubEnvironment({
required PubContext context,
String? flutterRootOverride,
bool? summaryOnly = false,
}) async {
final Map<String, String> environment = <String, String>{
'FLUTTER_ROOT': flutterRootOverride ?? Cache.flutterRoot!,
_kPubEnvironmentKey: await _getPubEnvironmentValue(context),
if (summaryOnly ?? false) 'PUB_SUMMARY_ONLY': '1',
};
final String? pubCache = _getPubCacheIfAvailable();
if (pubCache != null) {
environment[_kPubCacheEnvironmentKey] = pubCache;
}
return environment;
}
/// Updates the .dart_tool/version file to be equal to current Flutter
/// version.
///
/// Calls [_updatePackageConfig] for [project] and [project.example] (if it
/// exists).
///
/// This should be called after pub invocations that are expected to update
/// the packageConfig.
Future<void> _updateVersionAndPackageConfig(FlutterProject project) async {
if (!project.packageConfigFile.existsSync()) {
throwToolExit('${project.directory}: pub did not create .dart_tools/package_config.json file.');
}
final File lastVersion = _fileSystem.file(
_fileSystem.path.join(project.directory.path, '.dart_tool', 'version'),
);
final File currentVersion = _fileSystem.file(
_fileSystem.path.join(Cache.flutterRoot!, 'version'));
lastVersion.writeAsStringSync(currentVersion.readAsStringSync());
await _updatePackageConfig(project);
if (project.hasExampleApp && project.example.pubspecFile.existsSync()) {
await _updatePackageConfig(project.example);
}
}
/// Update the package configuration file in [project].
///
/// Creates a corresponding `package_config_subset` file that is used by the
/// build system to avoid rebuilds caused by an updated pub timestamp.
///
/// if `project.generateSyntheticPackage` is `true` then insert flutter_gen
/// synthetic package into the package configuration. This is used by the l10n
/// localization tooling to insert a new reference into the package_config
/// file, allowing the import of a package URI that is not specified in the
/// pubspec.yaml
///
/// For more information, see:
/// * [generateLocalizations], `in lib/src/localizations/gen_l10n.dart`
Future<void> _updatePackageConfig(FlutterProject project) async {
final File packageConfigFile = project.packageConfigFile;
final PackageConfig packageConfig = await loadPackageConfigWithLogging(packageConfigFile, logger: _logger);
packageConfigFile.parent
.childFile('package_config_subset')
.writeAsStringSync(_computePackageConfigSubset(
packageConfig,
_fileSystem,
));
if (!project.manifest.generateSyntheticPackage) {
return;
}
if (packageConfig.packages.any((Package package) => package.name == 'flutter_gen')) {
return;
}
// TODO(jonahwillams): Using raw json manipulation here because
// savePackageConfig always writes to local io, and it changes absolute
// paths to relative on round trip.
// See: https://github.com/dart-lang/package_config/issues/99,
// and: https://github.com/dart-lang/package_config/issues/100.
// Because [loadPackageConfigWithLogging] succeeded [packageConfigFile]
// we can rely on the file to exist and be correctly formatted.
final Map<String, dynamic> jsonContents =
json.decode(packageConfigFile.readAsStringSync()) as Map<String, dynamic>;
(jsonContents['packages'] as List<dynamic>).add(<String, dynamic>{
'name': 'flutter_gen',
'rootUri': 'flutter_gen',
'languageVersion': '2.12',
});
packageConfigFile.writeAsStringSync(json.encode(jsonContents));
}
// Subset the package config file to only the parts that are relevant for
// rerunning the dart compiler.
String _computePackageConfigSubset(PackageConfig packageConfig, FileSystem fileSystem) {
final StringBuffer buffer = StringBuffer();
for (final Package package in packageConfig.packages) {
buffer.writeln(package.name);
buffer.writeln(package.languageVersion);
buffer.writeln(package.root);
buffer.writeln(package.packageUriRoot);
}
buffer.writeln(packageConfig.version);
return buffer.toString();
}
}
| flutter/packages/flutter_tools/lib/src/dart/pub.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/dart/pub.dart",
"repo_id": "flutter",
"token_count": 9051
} | 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:meta/meta.dart';
import 'base/async_guard.dart';
import 'base/terminal.dart';
import 'globals.dart' as globals;
class ValidatorTask {
ValidatorTask(this.validator, this.result);
final DoctorValidator validator;
final Future<ValidationResult> result;
}
/// A series of tools and required install steps for a target platform (iOS or Android).
abstract class Workflow {
const Workflow();
/// Whether the workflow applies to this platform (as in, should we ever try and use it).
bool get appliesToHostPlatform;
/// Are we functional enough to list devices?
bool get canListDevices;
/// Could this thing launch *something*? It may still have minor issues.
bool get canLaunchDevices;
/// Are we functional enough to list emulators?
bool get canListEmulators;
}
enum ValidationType {
crash,
missing,
partial,
notAvailable,
success,
}
enum ValidationMessageType {
error,
hint,
information,
}
abstract class DoctorValidator {
const DoctorValidator(this.title);
/// This is displayed in the CLI.
final String title;
String get slowWarning => 'This is taking an unexpectedly long time...';
static const Duration _slowWarningDuration = Duration(seconds: 10);
/// Duration before the spinner should display [slowWarning].
Duration get slowWarningDuration => _slowWarningDuration;
Future<ValidationResult> validate();
}
/// A validator that runs other [DoctorValidator]s and combines their output
/// into a single [ValidationResult]. It uses the title of the first validator
/// passed to the constructor and reports the statusInfo of the first validator
/// that provides one. Other titles and statusInfo strings are discarded.
class GroupedValidator extends DoctorValidator {
GroupedValidator(this.subValidators) : super(subValidators[0].title);
final List<DoctorValidator> subValidators;
List<ValidationResult> _subResults = <ValidationResult>[];
/// Sub-validator results.
///
/// To avoid losing information when results are merged, the sub-results are
/// cached on this field when they are available. The results are in the same
/// order as the sub-validator list.
List<ValidationResult> get subResults => _subResults;
@override
String get slowWarning => _currentSlowWarning;
String _currentSlowWarning = 'Initializing...';
@override
Future<ValidationResult> validate() async {
final List<ValidatorTask> tasks = <ValidatorTask>[
for (final DoctorValidator validator in subValidators)
ValidatorTask(
validator,
asyncGuard<ValidationResult>(() => validator.validate()),
),
];
final List<ValidationResult> results = <ValidationResult>[];
for (final ValidatorTask subValidator in tasks) {
_currentSlowWarning = subValidator.validator.slowWarning;
try {
results.add(await subValidator.result);
} on Exception catch (exception, stackTrace) {
results.add(ValidationResult.crash(exception, stackTrace));
}
}
_currentSlowWarning = 'Merging results...';
return _mergeValidationResults(results);
}
ValidationResult _mergeValidationResults(List<ValidationResult> results) {
assert(results.isNotEmpty, 'Validation results should not be empty');
_subResults = results;
ValidationType mergedType = results[0].type;
final List<ValidationMessage> mergedMessages = <ValidationMessage>[];
String? statusInfo;
for (final ValidationResult result in results) {
statusInfo ??= result.statusInfo;
switch (result.type) {
case ValidationType.success:
if (mergedType == ValidationType.missing) {
mergedType = ValidationType.partial;
}
case ValidationType.notAvailable:
case ValidationType.partial:
mergedType = ValidationType.partial;
case ValidationType.crash:
case ValidationType.missing:
if (mergedType == ValidationType.success) {
mergedType = ValidationType.partial;
}
}
mergedMessages.addAll(result.messages);
}
return ValidationResult(mergedType, mergedMessages,
statusInfo: statusInfo);
}
}
@immutable
class ValidationResult {
/// [ValidationResult.type] should only equal [ValidationResult.success]
/// if no [messages] are hints or errors.
const ValidationResult(this.type, this.messages, { this.statusInfo });
factory ValidationResult.crash(Object error, [StackTrace? stackTrace]) {
return ValidationResult(ValidationType.crash, <ValidationMessage>[
const ValidationMessage.error(
'Due to an error, the doctor check did not complete. '
'If the error message below is not helpful, '
'please let us know about this issue at https://github.com/flutter/flutter/issues.'),
ValidationMessage.error('$error'),
if (stackTrace != null)
// Stacktrace is informational. Printed in verbose mode only.
ValidationMessage('$stackTrace'),
], statusInfo: 'the doctor check crashed');
}
final ValidationType type;
// A short message about the status.
final String? statusInfo;
final List<ValidationMessage> messages;
String get leadingBox {
switch (type) {
case ValidationType.crash:
return '[☠]';
case ValidationType.missing:
return '[✗]';
case ValidationType.success:
return '[✓]';
case ValidationType.notAvailable:
case ValidationType.partial:
return '[!]';
}
}
String get coloredLeadingBox {
switch (type) {
case ValidationType.crash:
return globals.terminal.color(leadingBox, TerminalColor.red);
case ValidationType.missing:
return globals.terminal.color(leadingBox, TerminalColor.red);
case ValidationType.success:
return globals.terminal.color(leadingBox, TerminalColor.green);
case ValidationType.notAvailable:
case ValidationType.partial:
return globals.terminal.color(leadingBox, TerminalColor.yellow);
}
}
/// The string representation of the type.
String get typeStr {
switch (type) {
case ValidationType.crash:
return 'crash';
case ValidationType.missing:
return 'missing';
case ValidationType.success:
return 'installed';
case ValidationType.notAvailable:
return 'notAvailable';
case ValidationType.partial:
return 'partial';
}
}
@override
String toString() {
return '$runtimeType($type, $messages, $statusInfo)';
}
}
/// A status line for the flutter doctor validation to display.
///
/// The [message] is required and represents either an informational statement
/// about the particular doctor validation that passed, or more context
/// on the cause and/or solution to the validation failure.
@immutable
class ValidationMessage {
/// Create a validation message with information for a passing validator.
///
/// By default this is not displayed unless the doctor is run in
/// verbose mode.
///
/// The [contextUrl] may be supplied to link to external resources. This
/// is displayed after the informative message in verbose modes.
const ValidationMessage(this.message, { this.contextUrl, String? piiStrippedMessage })
: type = ValidationMessageType.information, piiStrippedMessage = piiStrippedMessage ?? message;
/// Create a validation message with information for a failing validator.
const ValidationMessage.error(this.message, { String? piiStrippedMessage })
: type = ValidationMessageType.error,
piiStrippedMessage = piiStrippedMessage ?? message,
contextUrl = null;
/// Create a validation message with information for a partially failing
/// validator.
const ValidationMessage.hint(this.message, { String? piiStrippedMessage })
: type = ValidationMessageType.hint,
piiStrippedMessage = piiStrippedMessage ?? message,
contextUrl = null;
final ValidationMessageType type;
final String? contextUrl;
final String message;
/// Optional message with PII stripped, to show instead of [message].
final String piiStrippedMessage;
bool get isError => type == ValidationMessageType.error;
bool get isHint => type == ValidationMessageType.hint;
bool get isInformation => type == ValidationMessageType.information;
String get indicator {
switch (type) {
case ValidationMessageType.error:
return '✗';
case ValidationMessageType.hint:
return '!';
case ValidationMessageType.information:
return '•';
}
}
String get coloredIndicator {
switch (type) {
case ValidationMessageType.error:
return globals.terminal.color(indicator, TerminalColor.red);
case ValidationMessageType.hint:
return globals.terminal.color(indicator, TerminalColor.yellow);
case ValidationMessageType.information:
return globals.terminal.color(indicator, TerminalColor.green);
}
}
@override
String toString() => message;
@override
bool operator ==(Object other) {
return other is ValidationMessage
&& other.message == message
&& other.type == type
&& other.contextUrl == contextUrl;
}
@override
int get hashCode => Object.hash(type, message, contextUrl);
}
class NoIdeValidator extends DoctorValidator {
NoIdeValidator() : super('Flutter IDE Support');
@override
Future<ValidationResult> validate() async {
return ValidationResult(
// Info hint to user they do not have a supported IDE installed
ValidationType.notAvailable,
globals.userMessages.noIdeInstallationInfo.map((String ideInfo) => ValidationMessage(ideInfo)).toList(),
statusInfo: globals.userMessages.noIdeStatusInfo,
);
}
}
class ValidatorWithResult extends DoctorValidator {
ValidatorWithResult(super.title, this.result);
final ValidationResult result;
@override
Future<ValidationResult> validate() async => result;
}
| flutter/packages/flutter_tools/lib/src/doctor_validator.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/doctor_validator.dart",
"repo_id": "flutter",
"token_count": 3287
} | 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 'dart:async';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/net.dart';
import '../base/process.dart';
import '../convert.dart';
import '../globals.dart' as globals;
/// This is a basic wrapper class for the Fuchsia SDK's `pm` tool.
class FuchsiaPM {
/// Initializes the staging area at [buildPath] for creating the Fuchsia
/// package for the app named [appName].
///
/// When successful, this creates a file under [buildPath] at `meta/package`.
///
/// NB: The [buildPath] should probably be e.g. `build/fuchsia/pkg`, and the
/// [appName] should probably be the name of the app from the pubspec file.
Future<bool> init(String buildPath, String appName) {
return _runPMCommand(<String>[
'-o',
buildPath,
'-n',
appName,
'init',
]);
}
/// Updates, signs, and seals a Fuchsia package.
///
/// [buildPath] should be the same [buildPath] passed to [init].
/// [manifestPath] must be a file containing lines formatted as follows:
///
/// data/path/to/file/in/the/package=/path/to/file/on/the/host
///
/// which describe the contents of the Fuchsia package. It must also contain
/// two other entries:
///
/// meta/$APPNAME.cm=/path/to/cm/on/the/host/$APPNAME.cm
/// meta/package=/path/to/package/file/from/init/package
///
/// where $APPNAME is the same [appName] passed to [init], and meta/package
/// is set up to be the file `meta/package` created by [init].
Future<bool> build(String buildPath, String manifestPath) {
return _runPMCommand(<String>[
'-o',
buildPath,
'-m',
manifestPath,
'build',
]);
}
/// Constructs a .far representation of the Fuchsia package.
///
/// When successful, creates a file `app_name-0.far` under [buildPath], which
/// is the Fuchsia package.
///
/// [buildPath] should be the same path passed to [init], and [manifestPath]
/// should be the same manifest passed to [build].
Future<bool> archive(String buildPath, String manifestPath) {
return _runPMCommand(<String>[
'-o',
buildPath,
'-m',
manifestPath,
'archive',
]);
}
/// Initializes a new package repository at [repoPath] to be later served by
/// the 'serve' command.
Future<bool> newrepo(String repoPath) {
return _runPMCommand(<String>[
'newrepo',
'-repo',
repoPath,
]);
}
/// Spawns an http server in a new process for serving Fuchsia packages.
///
/// The argument [repoPath] should have previously been an argument to
/// [newrepo]. The [host] should be the host reported by
/// [FuchsiaFfx.resolve], and [port] should be an unused port for the
/// http server to bind.
Future<Process> serve(String repoPath, String host, int port) async {
final File? pm = globals.fuchsiaArtifacts?.pm;
if (pm == null) {
throwToolExit('Fuchsia pm tool not found');
}
if (isIPv6Address(host.split('%').first)) {
host = '[$host]';
}
final List<String> command = <String>[
pm.path,
'serve',
'-repo',
repoPath,
'-l',
'$host:$port',
'-c',
'2',
];
final Process process = await globals.processUtils.start(command);
process.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen(globals.printTrace);
process.stderr
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen(globals.printError);
return process;
}
/// Publishes a Fuchsia package to a served package repository.
///
/// For a package repo initialized with [newrepo] at [repoPath] and served
/// by [serve], this call publishes the `far` package at [packagePath] to
/// the repo such that it will be visible to devices connecting to the
/// package server.
Future<bool> publish(String repoPath, String packagePath) {
return _runPMCommand(<String>[
'publish',
'-a',
'-r',
repoPath,
'-f',
packagePath,
]);
}
Future<bool> _runPMCommand(List<String> args) async {
final File? pm = globals.fuchsiaArtifacts?.pm;
if (pm == null) {
throwToolExit('Fuchsia pm tool not found');
}
final List<String> command = <String>[pm.path, ...args];
final RunResult result = await globals.processUtils.run(command);
return result.exitCode == 0;
}
}
/// A class for running and retaining state for a Fuchsia package server.
///
/// [FuchsiaPackageServer] takes care of initializing the package repository,
/// spinning up the package server, publishing packages, and shutting down the
/// server.
///
/// Example usage:
/// var server = FuchsiaPackageServer(
/// '/path/to/repo',
/// 'server_name',
/// await FuchsiaFfx.resolve(deviceName),
/// await freshPort());
/// try {
/// await server.start();
/// await server.addPackage(farArchivePath);
/// ...
/// } finally {
/// server.stop();
/// }
class FuchsiaPackageServer {
FuchsiaPackageServer(String repo, this.name, String host, int port)
: _repo = repo, _host = host, _port = port;
static const String deviceHost = 'fuchsia.com';
static const String toolHost = 'flutter-tool';
final String _repo;
final String _host;
final int _port;
Process? _process;
// The name used to reference the server by fuchsia-pkg:// urls.
final String name;
int get port => _port;
/// Uses [FuchsiaPM.newrepo] and [FuchsiaPM.serve] to spin up a new Fuchsia
/// package server.
///
/// Returns false if the repo could not be created or the server could not
/// be spawned, and true otherwise.
Future<bool> start() async {
if (_process != null) {
globals.printError('$this already started!');
return false;
}
// initialize a new repo.
final FuchsiaPM? fuchsiaPM = globals.fuchsiaSdk?.fuchsiaPM;
if (fuchsiaPM == null || !await fuchsiaPM.newrepo(_repo)) {
globals.printError('Failed to create a new package server repo');
return false;
}
_process = await fuchsiaPM.serve(_repo, _host, _port);
// Put a completer on _process.exitCode to watch for error.
unawaited(_process?.exitCode.whenComplete(() {
// If _process is null, then the server was stopped deliberately.
if (_process != null) {
globals.printError('Error running Fuchsia pm tool "serve" command');
}
}));
return true;
}
/// Forcefully stops the package server process by sending it SIGTERM.
void stop() {
if (_process != null) {
_process?.kill();
_process = null;
}
}
/// Uses [FuchsiaPM.publish] to add the Fuchsia 'far' package at
/// [packagePath] to the package server.
///
/// Returns true on success and false if the server wasn't started or the
/// publish command failed.
Future<bool> addPackage(File package) async {
if (_process == null) {
return false;
}
return (await globals.fuchsiaSdk?.fuchsiaPM.publish(_repo, package.path)) ??
false;
}
@override
String toString() {
final String p =
(_process == null) ? 'stopped' : 'running ${_process?.pid}';
return 'FuchsiaPackageServer at $_host:$_port ($p)';
}
}
| flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_pm.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/fuchsia/fuchsia_pm.dart",
"repo_id": "flutter",
"token_count": 2698
} | 750 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import 'package:unified_analytics/unified_analytics.dart';
import '../artifacts.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/process.dart';
import '../base/project_migrator.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../cache.dart';
import '../device.dart';
import '../flutter_manifest.dart';
import '../globals.dart' as globals;
import '../macos/cocoapod_utils.dart';
import '../macos/xcode.dart';
import '../migrations/xcode_project_object_version_migration.dart';
import '../migrations/xcode_script_build_phase_migration.dart';
import '../migrations/xcode_thin_binary_build_phase_input_paths_migration.dart';
import '../project.dart';
import '../reporting/reporting.dart';
import 'application_package.dart';
import 'code_signing.dart';
import 'migrations/host_app_info_plist_migration.dart';
import 'migrations/ios_deployment_target_migration.dart';
import 'migrations/project_base_configuration_migration.dart';
import 'migrations/project_build_location_migration.dart';
import 'migrations/remove_bitcode_migration.dart';
import 'migrations/remove_framework_link_and_embedding_migration.dart';
import 'migrations/xcode_build_system_migration.dart';
import 'xcode_build_settings.dart';
import 'xcodeproj.dart';
import 'xcresult.dart';
const String kConcurrentRunFailureMessage1 = 'database is locked';
const String kConcurrentRunFailureMessage2 = 'there are two concurrent builds running';
/// User message when missing platform required to use Xcode.
///
/// Starting with Xcode 15, the simulator is no longer downloaded with Xcode
/// and must be downloaded and installed separately.
@visibleForTesting
String missingPlatformInstructions(String simulatorVersion) => '''
════════════════════════════════════════════════════════════════════════════════
$simulatorVersion is not installed. To download and install the platform, open
Xcode, select Xcode > Settings > Platforms, and click the GET button for the
required platform.
For more information, please visit:
https://developer.apple.com/documentation/xcode/installing-additional-simulator-runtimes
════════════════════════════════════════════════════════════════════════════════''';
class IMobileDevice {
IMobileDevice({
required Artifacts artifacts,
required Cache cache,
required ProcessManager processManager,
required Logger logger,
}) : _idevicesyslogPath = artifacts.getHostArtifact(HostArtifact.idevicesyslog).path,
_idevicescreenshotPath = artifacts.getHostArtifact(HostArtifact.idevicescreenshot).path,
_dyLdLibEntry = cache.dyLdLibEntry,
_processUtils = ProcessUtils(logger: logger, processManager: processManager),
_processManager = processManager;
/// Create an [IMobileDevice] for testing.
factory IMobileDevice.test({ required ProcessManager processManager }) {
return IMobileDevice(
// ignore: invalid_use_of_visible_for_testing_member
artifacts: Artifacts.test(),
cache: Cache.test(processManager: processManager),
processManager: processManager,
logger: BufferLogger.test(),
);
}
final String _idevicesyslogPath;
final String _idevicescreenshotPath;
final MapEntry<String, String> _dyLdLibEntry;
final ProcessManager _processManager;
final ProcessUtils _processUtils;
late final bool isInstalled = _processManager.canRun(_idevicescreenshotPath);
/// Starts `idevicesyslog` and returns the running process.
Future<Process> startLogger(
String deviceID,
bool isWirelesslyConnected,
) {
return _processUtils.start(
<String>[
_idevicesyslogPath,
'-u',
deviceID,
if (isWirelesslyConnected)
'--network',
],
environment: Map<String, String>.fromEntries(
<MapEntry<String, String>>[_dyLdLibEntry]
),
);
}
/// Captures a screenshot to the specified outputFile.
Future<void> takeScreenshot(
File outputFile,
String deviceID,
DeviceConnectionInterface interfaceType,
) {
return _processUtils.run(
<String>[
_idevicescreenshotPath,
outputFile.path,
'--udid',
deviceID,
if (interfaceType == DeviceConnectionInterface.wireless)
'--network',
],
throwOnError: true,
environment: Map<String, String>.fromEntries(
<MapEntry<String, String>>[_dyLdLibEntry]
),
);
}
}
Future<XcodeBuildResult> buildXcodeProject({
required BuildableIOSApp app,
required BuildInfo buildInfo,
String? targetOverride,
EnvironmentType environmentType = EnvironmentType.physical,
DarwinArch? activeArch,
bool codesign = true,
String? deviceID,
bool configOnly = false,
XcodeBuildAction buildAction = XcodeBuildAction.build,
bool disablePortPublication = false,
}) async {
if (!upgradePbxProjWithFlutterAssets(app.project, globals.logger)) {
return XcodeBuildResult(success: false);
}
final List<ProjectMigrator> migrators = <ProjectMigrator>[
RemoveFrameworkLinkAndEmbeddingMigration(app.project, globals.logger, globals.flutterUsage, globals.analytics),
XcodeBuildSystemMigration(app.project, globals.logger),
ProjectBaseConfigurationMigration(app.project, globals.logger),
ProjectBuildLocationMigration(app.project, globals.logger),
IOSDeploymentTargetMigration(app.project, globals.logger),
XcodeProjectObjectVersionMigration(app.project, globals.logger),
HostAppInfoPlistMigration(app.project, globals.logger),
XcodeScriptBuildPhaseMigration(app.project, globals.logger),
RemoveBitcodeMigration(app.project, globals.logger),
XcodeThinBinaryBuildPhaseInputPathsMigration(app.project, globals.logger),
];
final ProjectMigration migration = ProjectMigration(migrators);
migration.run();
if (!_checkXcodeVersion()) {
return XcodeBuildResult(success: false);
}
await removeFinderExtendedAttributes(app.project.parent.directory, globals.processUtils, globals.logger);
final XcodeProjectInfo? projectInfo = await app.project.projectInfo();
if (projectInfo == null) {
globals.printError('Xcode project not found.');
return XcodeBuildResult(success: false);
}
final String? scheme = projectInfo.schemeFor(buildInfo);
if (scheme == null) {
projectInfo.reportFlavorNotFoundAndExit();
}
final String? configuration = projectInfo.buildConfigurationFor(buildInfo, scheme);
if (configuration == null) {
globals.printError('');
globals.printError('The Xcode project defines build configurations: ${projectInfo.buildConfigurations.join(', ')}');
globals.printError('Flutter expects a build configuration named ${XcodeProjectInfo.expectedBuildConfigurationFor(buildInfo, scheme)} or similar.');
globals.printError('Open Xcode to fix the problem:');
globals.printError(' open ios/Runner.xcworkspace');
globals.printError('1. Click on "Runner" in the project navigator.');
globals.printError('2. Ensure the Runner PROJECT is selected, not the Runner TARGET.');
if (buildInfo.isDebug) {
globals.printError('3. Click the Editor->Add Configuration->Duplicate "Debug" Configuration.');
} else {
globals.printError('3. Click the Editor->Add Configuration->Duplicate "Release" Configuration.');
}
globals.printError('');
globals.printError(' If this option is disabled, it is likely you have the target selected instead');
globals.printError(' of the project; see:');
globals.printError(' https://stackoverflow.com/questions/19842746/adding-a-build-configuration-in-xcode');
globals.printError('');
globals.printError(' If you have created a completely custom set of build configurations,');
globals.printError(' you can set the FLUTTER_BUILD_MODE=${buildInfo.modeName.toLowerCase()}');
globals.printError(' in the .xcconfig file for that configuration and run from Xcode.');
globals.printError('');
globals.printError('4. If you are not using completely custom build configurations, name the newly created configuration ${buildInfo.modeName}.');
return XcodeBuildResult(success: false);
}
final FlutterManifest manifest = app.project.parent.manifest;
final String? buildName = parsedBuildName(manifest: manifest, buildInfo: buildInfo);
final bool buildNameIsMissing = buildName == null || buildName.isEmpty;
if (buildNameIsMissing) {
globals.printStatus('Warning: Missing build name (CFBundleShortVersionString).');
}
final String? buildNumber = parsedBuildNumber(manifest: manifest, buildInfo: buildInfo);
final bool buildNumberIsMissing = buildNumber == null || buildNumber.isEmpty;
if (buildNumberIsMissing) {
globals.printStatus('Warning: Missing build number (CFBundleVersion).');
}
if (buildNameIsMissing || buildNumberIsMissing) {
globals.printError('Action Required: You must set a build name and number in the pubspec.yaml '
'file version field before submitting to the App Store.');
}
Map<String, String>? autoSigningConfigs;
final Map<String, String> buildSettings = await app.project.buildSettingsForBuildInfo(
buildInfo,
environmentType: environmentType,
deviceId: deviceID,
) ?? <String, String>{};
if (codesign && environmentType == EnvironmentType.physical) {
autoSigningConfigs = await getCodeSigningIdentityDevelopmentTeamBuildSetting(
buildSettings: buildSettings,
platform: globals.platform,
processManager: globals.processManager,
logger: globals.logger,
config: globals.config,
terminal: globals.terminal,
);
}
final FlutterProject project = FlutterProject.current();
await updateGeneratedXcodeProperties(
project: project,
targetOverride: targetOverride,
buildInfo: buildInfo,
);
await processPodsIfNeeded(project.ios, getIosBuildDirectory(), buildInfo.mode);
if (configOnly) {
return XcodeBuildResult(success: true);
}
final List<String> buildCommands = <String>[
...globals.xcode!.xcrunCommand(),
'xcodebuild',
'-configuration',
configuration,
];
if (globals.logger.isVerbose) {
// An environment variable to be passed to xcode_backend.sh determining
// whether to echo back executed commands.
buildCommands.add('VERBOSE_SCRIPT_LOGGING=YES');
} else {
// This will print warnings and errors only.
buildCommands.add('-quiet');
}
if (autoSigningConfigs != null) {
for (final MapEntry<String, String> signingConfig in autoSigningConfigs.entries) {
buildCommands.add('${signingConfig.key}=${signingConfig.value}');
}
buildCommands.add('-allowProvisioningUpdates');
buildCommands.add('-allowProvisioningDeviceRegistration');
}
final Directory? workspacePath = app.project.xcodeWorkspace;
if (workspacePath != null) {
buildCommands.addAll(<String>[
'-workspace', workspacePath.basename,
'-scheme', scheme,
if (buildAction != XcodeBuildAction.archive) // dSYM files aren't copied to the archive if BUILD_DIR is set.
'BUILD_DIR=${globals.fs.path.absolute(getIosBuildDirectory())}',
]);
}
// Check if the project contains a watchOS companion app.
final bool hasWatchCompanion = await app.project.containsWatchCompanion(
projectInfo: projectInfo,
buildInfo: buildInfo,
deviceId: deviceID,
);
if (hasWatchCompanion) {
// The -sdk argument has to be omitted if a watchOS companion app exists.
// Otherwise the build will fail as WatchKit dependencies cannot be build using the iOS SDK.
globals.printStatus('Watch companion app found.');
if (environmentType == EnvironmentType.simulator && (deviceID == null || deviceID == '')) {
globals.printError('No simulator device ID has been set.');
globals.printError('A device ID is required to build an app with a watchOS companion app.');
globals.printError('Please run "flutter devices" to get a list of available device IDs');
globals.printError('and specify one using the -d, --device-id flag.');
return XcodeBuildResult(success: false);
}
} else {
if (environmentType == EnvironmentType.physical) {
buildCommands.addAll(<String>['-sdk', 'iphoneos']);
} else {
buildCommands.addAll(<String>['-sdk', 'iphonesimulator']);
}
}
buildCommands.add('-destination');
if (deviceID != null) {
buildCommands.add('id=$deviceID');
} else if (environmentType == EnvironmentType.physical) {
buildCommands.add('generic/platform=iOS');
} else {
buildCommands.add('generic/platform=iOS Simulator');
}
if (activeArch != null) {
final String activeArchName = activeArch.name;
buildCommands.add('ONLY_ACTIVE_ARCH=YES');
// Setting ARCHS to $activeArchName will break the build if a watchOS companion app exists,
// as it cannot be build for the architecture of the Flutter app.
if (!hasWatchCompanion) {
buildCommands.add('ARCHS=$activeArchName');
}
}
if (!codesign) {
buildCommands.addAll(
<String>[
'CODE_SIGNING_ALLOWED=NO',
'CODE_SIGNING_REQUIRED=NO',
'CODE_SIGNING_IDENTITY=""',
],
);
}
Status? buildSubStatus;
Status? initialBuildStatus;
File? scriptOutputPipeFile;
RunResult? buildResult;
XCResult? xcResult;
final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_ios_build_temp_dir');
try {
if (globals.logger.hasTerminal) {
scriptOutputPipeFile = tempDir.childFile('pipe_to_stdout');
globals.os.makePipe(scriptOutputPipeFile.path);
Future<void> listenToScriptOutputLine() async {
final List<String> lines = await scriptOutputPipeFile!.readAsLines();
for (final String line in lines) {
if (line == 'done' || line == 'all done') {
buildSubStatus?.stop();
buildSubStatus = null;
if (line == 'all done') {
return;
}
} else {
initialBuildStatus?.cancel();
initialBuildStatus = null;
buildSubStatus = globals.logger.startProgress(
line,
progressIndicatorPadding: kDefaultStatusPadding - 7,
);
}
}
await listenToScriptOutputLine();
}
// Trigger the start of the pipe -> stdout loop. Ignore exceptions.
unawaited(listenToScriptOutputLine());
buildCommands.add('SCRIPT_OUTPUT_STREAM_FILE=${scriptOutputPipeFile.absolute.path}');
}
final Directory resultBundleDirectory = tempDir.childDirectory(_kResultBundlePath);
buildCommands.addAll(<String>[
'-resultBundlePath',
resultBundleDirectory.absolute.path,
'-resultBundleVersion',
_kResultBundleVersion,
]);
// Adds a setting which xcode_backend.dart will use to skip adding Bonjour
// service settings to the Info.plist.
if (disablePortPublication) {
buildCommands.add('DISABLE_PORT_PUBLICATION=YES');
}
// Don't log analytics for downstream Flutter commands.
// e.g. `flutter build bundle`.
buildCommands.add('FLUTTER_SUPPRESS_ANALYTICS=true');
buildCommands.add('COMPILER_INDEX_STORE_ENABLE=NO');
buildCommands.addAll(environmentVariablesAsXcodeBuildSettings(globals.platform));
if (buildAction == XcodeBuildAction.archive) {
buildCommands.addAll(<String>[
'-archivePath',
globals.fs.path.absolute(app.archiveBundlePath),
'archive',
]);
}
final Stopwatch sw = Stopwatch()..start();
initialBuildStatus = globals.logger.startProgress('Running Xcode build...');
buildResult = await _runBuildWithRetries(buildCommands, app, resultBundleDirectory);
// Notifies listener that no more output is coming.
scriptOutputPipeFile?.writeAsStringSync('all done');
buildSubStatus?.stop();
buildSubStatus = null;
initialBuildStatus?.cancel();
initialBuildStatus = null;
globals.printStatus(
'Xcode ${xcodeBuildActionToString(buildAction)} done.'.padRight(kDefaultStatusPadding + 1)
+ getElapsedAsSeconds(sw.elapsed).padLeft(5),
);
final Duration elapsedDuration = sw.elapsed;
globals.flutterUsage.sendTiming(xcodeBuildActionToString(buildAction), 'xcode-ios', elapsedDuration);
globals.analytics.send(Event.timing(
workflow: xcodeBuildActionToString(buildAction),
variableName: 'xcode-ios',
elapsedMilliseconds: elapsedDuration.inMilliseconds,
));
if (tempDir.existsSync()) {
// Display additional warning and error message from xcresult bundle.
final Directory resultBundle = tempDir.childDirectory(_kResultBundlePath);
if (!resultBundle.existsSync()) {
globals.printTrace('The xcresult bundle are not generated. Displaying xcresult is disabled.');
} else {
// Discard unwanted errors. See: https://github.com/flutter/flutter/issues/95354
final XCResultIssueDiscarder warningDiscarder = XCResultIssueDiscarder(typeMatcher: XCResultIssueType.warning);
final XCResultIssueDiscarder dartBuildErrorDiscarder = XCResultIssueDiscarder(messageMatcher: RegExp(r'Command PhaseScriptExecution failed with a nonzero exit code'));
final XCResultGenerator xcResultGenerator = XCResultGenerator(resultPath: resultBundle.absolute.path, xcode: globals.xcode!, processUtils: globals.processUtils);
xcResult = await xcResultGenerator.generate(issueDiscarders: <XCResultIssueDiscarder>[warningDiscarder, dartBuildErrorDiscarder]);
}
}
} finally {
tempDir.deleteSync(recursive: true);
}
if (buildResult != null && buildResult.exitCode != 0) {
globals.printStatus('Failed to build iOS app');
return XcodeBuildResult(
success: false,
stdout: buildResult.stdout,
stderr: buildResult.stderr,
xcodeBuildExecution: XcodeBuildExecution(
buildCommands: buildCommands,
appDirectory: app.project.hostAppRoot.path,
environmentType: environmentType,
buildSettings: buildSettings,
),
xcResult: xcResult,
);
} else {
String? outputDir;
if (buildAction == XcodeBuildAction.build) {
// If the app contains a watch companion target, the sdk argument of xcodebuild has to be omitted.
// For some reason this leads to TARGET_BUILD_DIR always ending in 'iphoneos' even though the
// actual directory will end with 'iphonesimulator' for simulator builds.
// The value of TARGET_BUILD_DIR is adjusted to accommodate for this effect.
String? targetBuildDir = buildSettings['TARGET_BUILD_DIR'];
if (targetBuildDir == null) {
globals.printError('Xcode build is missing expected TARGET_BUILD_DIR build setting.');
return XcodeBuildResult(success: false);
}
if (hasWatchCompanion && environmentType == EnvironmentType.simulator) {
globals.printTrace('Replacing iphoneos with iphonesimulator in TARGET_BUILD_DIR.');
targetBuildDir = targetBuildDir.replaceFirst('iphoneos', 'iphonesimulator');
}
final String? appBundle = buildSettings['WRAPPER_NAME'];
final String expectedOutputDirectory = globals.fs.path.join(
targetBuildDir,
appBundle,
);
if (globals.fs.directory(expectedOutputDirectory).existsSync()) {
// Copy app folder to a place where other tools can find it without knowing
// the BuildInfo.
outputDir = targetBuildDir.replaceFirst('/$configuration-', '/');
globals.fs.directory(outputDir).createSync(recursive: true);
// rsync instead of copy to maintain timestamps to support incremental
// app install deltas. Use --delete to remove incompatible artifacts
// (for example, kernel binary files produced from previous run).
await globals.processUtils.run(
<String>[
'rsync',
'-8', // Avoid mangling filenames with encodings that do not match the current locale.
'-av',
'--delete',
expectedOutputDirectory,
outputDir,
],
throwOnError: true,
);
outputDir = globals.fs.path.join(
outputDir,
appBundle,
);
} else {
globals.printError('Build succeeded but the expected app at $expectedOutputDirectory not found');
}
} else {
outputDir = globals.fs.path.absolute(app.archiveBundleOutputPath);
if (!globals.fs.isDirectorySync(outputDir)) {
globals.printError('Archive succeeded but the expected xcarchive at $outputDir not found');
}
}
return XcodeBuildResult(
success: true,
output: outputDir,
xcodeBuildExecution: XcodeBuildExecution(
buildCommands: buildCommands,
appDirectory: app.project.hostAppRoot.path,
environmentType: environmentType,
buildSettings: buildSettings,
),
xcResult: xcResult,
);
}
}
/// Extended attributes applied by Finder can cause code signing errors. Remove them.
/// https://developer.apple.com/library/archive/qa/qa1940/_index.html
Future<void> removeFinderExtendedAttributes(FileSystemEntity projectDirectory, ProcessUtils processUtils, Logger logger) async {
final bool success = await processUtils.exitsHappy(
<String>[
'xattr',
'-r',
'-d',
'com.apple.FinderInfo',
projectDirectory.path,
]
);
// Ignore all errors, for example if directory is missing.
if (!success) {
logger.printTrace('Failed to remove xattr com.apple.FinderInfo from ${projectDirectory.path}');
}
}
Future<RunResult?> _runBuildWithRetries(List<String> buildCommands, BuildableIOSApp app, Directory resultBundleDirectory) async {
int buildRetryDelaySeconds = 1;
int remainingTries = 8;
RunResult? buildResult;
while (remainingTries > 0) {
if (resultBundleDirectory.existsSync()) {
resultBundleDirectory.deleteSync(recursive: true);
}
remainingTries--;
buildRetryDelaySeconds *= 2;
buildResult = await globals.processUtils.run(
buildCommands,
workingDirectory: app.project.hostAppRoot.path,
allowReentrantFlutter: true,
);
// If the result is anything other than a concurrent build failure, exit
// the loop after the first build.
if (!_isXcodeConcurrentBuildFailure(buildResult)) {
break;
}
if (remainingTries > 0) {
globals.printStatus('Xcode build failed due to concurrent builds, '
'will retry in $buildRetryDelaySeconds seconds.');
await Future<void>.delayed(Duration(seconds: buildRetryDelaySeconds));
} else {
globals.printStatus(
'Xcode build failed too many times due to concurrent builds, '
'giving up.');
break;
}
}
return buildResult;
}
bool _isXcodeConcurrentBuildFailure(RunResult result) {
return result.exitCode != 0 &&
result.stdout.contains(kConcurrentRunFailureMessage1) &&
result.stdout.contains(kConcurrentRunFailureMessage2);
}
Future<void> diagnoseXcodeBuildFailure(
XcodeBuildResult result,
Usage flutterUsage,
Logger logger,
Analytics analytics,
) async {
final XcodeBuildExecution? xcodeBuildExecution = result.xcodeBuildExecution;
if (xcodeBuildExecution != null
&& xcodeBuildExecution.environmentType == EnvironmentType.physical
&& (result.stdout?.toUpperCase().contains('BITCODE') ?? false)) {
const String label = 'xcode-bitcode-failure';
const String buildType = 'ios';
final String command = xcodeBuildExecution.buildCommands.toString();
final String settings = xcodeBuildExecution.buildSettings.toString();
BuildEvent(
label,
type: buildType,
command: command,
settings: settings,
flutterUsage: flutterUsage,
).send();
analytics.send(Event.flutterBuildInfo(
label: label,
buildType: buildType,
command: command,
settings: settings,
));
}
// Handle errors.
final bool issueDetected = _handleIssues(result.xcResult, logger, xcodeBuildExecution);
if (!issueDetected && xcodeBuildExecution != null) {
// Fallback to use stdout to detect and print issues.
_parseIssueInStdout(xcodeBuildExecution, logger, result);
}
}
/// xcodebuild <buildaction> parameter (see man xcodebuild for details).
///
/// `clean`, `test`, `analyze`, and `install` are not supported.
enum XcodeBuildAction { build, archive }
String xcodeBuildActionToString(XcodeBuildAction action) {
return switch (action) {
XcodeBuildAction.build => 'build',
XcodeBuildAction.archive => 'archive'
};
}
class XcodeBuildResult {
XcodeBuildResult({
required this.success,
this.output,
this.stdout,
this.stderr,
this.xcodeBuildExecution,
this.xcResult
});
final bool success;
final String? output;
final String? stdout;
final String? stderr;
/// The invocation of the build that resulted in this result instance.
final XcodeBuildExecution? xcodeBuildExecution;
/// Parsed information in xcresult bundle.
///
/// Can be null if the bundle is not created during build.
final XCResult? xcResult;
}
/// Describes an invocation of a Xcode build command.
class XcodeBuildExecution {
XcodeBuildExecution({
required this.buildCommands,
required this.appDirectory,
required this.environmentType,
required this.buildSettings,
});
/// The original list of Xcode build commands used to produce this build result.
final List<String> buildCommands;
final String appDirectory;
final EnvironmentType environmentType;
/// The build settings corresponding to the [buildCommands] invocation.
final Map<String, String> buildSettings;
}
final String _xcodeRequirement = 'Xcode $xcodeRequiredVersion or greater is required to develop for iOS.';
bool _checkXcodeVersion() {
if (!globals.platform.isMacOS) {
return false;
}
final XcodeProjectInterpreter? xcodeProjectInterpreter = globals.xcodeProjectInterpreter;
if (xcodeProjectInterpreter?.isInstalled != true) {
globals.printError('Cannot find "xcodebuild". $_xcodeRequirement');
return false;
}
if (globals.xcode?.isRequiredVersionSatisfactory != true) {
globals.printError('Found "${xcodeProjectInterpreter?.versionText}". $_xcodeRequirement');
return false;
}
return true;
}
// TODO(jmagman): Refactor to IOSMigrator.
bool upgradePbxProjWithFlutterAssets(IosProject project, Logger logger) {
final File xcodeProjectFile = project.xcodeProjectInfoFile;
assert(xcodeProjectFile.existsSync());
final List<String> lines = xcodeProjectFile.readAsLinesSync();
final RegExp oldAssets = RegExp(r'\/\* (flutter_assets|app\.flx)');
final StringBuffer buffer = StringBuffer();
final Set<String> printedStatuses = <String>{};
for (final String line in lines) {
final Match? match = oldAssets.firstMatch(line);
if (match != null) {
if (printedStatuses.add(match.group(1)!)) {
logger.printStatus('Removing obsolete reference to ${match.group(1)} from ${project.xcodeProject.basename}');
}
} else {
buffer.writeln(line);
}
}
xcodeProjectFile.writeAsStringSync(buffer.toString());
return true;
}
_XCResultIssueHandlingResult _handleXCResultIssue({required XCResultIssue issue, required Logger logger}) {
// Issue summary from xcresult.
final StringBuffer issueSummaryBuffer = StringBuffer();
issueSummaryBuffer.write(issue.subType ?? 'Unknown');
issueSummaryBuffer.write(' (Xcode): ');
issueSummaryBuffer.writeln(issue.message ?? '');
if (issue.location != null ) {
issueSummaryBuffer.writeln(issue.location);
}
final String issueSummary = issueSummaryBuffer.toString();
switch (issue.type) {
case XCResultIssueType.error:
logger.printError(issueSummary);
case XCResultIssueType.warning:
logger.printWarning(issueSummary);
}
final String? message = issue.message;
if (message == null) {
return _XCResultIssueHandlingResult(requiresProvisioningProfile: false, hasProvisioningProfileIssue: false);
}
// Add more error messages for flutter users for some special errors.
if (message.toLowerCase().contains('requires a provisioning profile.')) {
return _XCResultIssueHandlingResult(requiresProvisioningProfile: true, hasProvisioningProfileIssue: true);
} else if (message.toLowerCase().contains('provisioning profile')) {
return _XCResultIssueHandlingResult(requiresProvisioningProfile: false, hasProvisioningProfileIssue: true);
} else if (message.toLowerCase().contains('ineligible destinations')) {
final String? missingPlatform = _parseMissingPlatform(message);
if (missingPlatform != null) {
return _XCResultIssueHandlingResult(requiresProvisioningProfile: false, hasProvisioningProfileIssue: false, missingPlatform: missingPlatform);
}
}
return _XCResultIssueHandlingResult(requiresProvisioningProfile: false, hasProvisioningProfileIssue: false);
}
// Returns `true` if at least one issue is detected.
bool _handleIssues(XCResult? xcResult, Logger logger, XcodeBuildExecution? xcodeBuildExecution) {
bool requiresProvisioningProfile = false;
bool hasProvisioningProfileIssue = false;
bool issueDetected = false;
String? missingPlatform;
if (xcResult != null && xcResult.parseSuccess) {
for (final XCResultIssue issue in xcResult.issues) {
final _XCResultIssueHandlingResult handlingResult = _handleXCResultIssue(issue: issue, logger: logger);
if (handlingResult.hasProvisioningProfileIssue) {
hasProvisioningProfileIssue = true;
}
if (handlingResult.requiresProvisioningProfile) {
requiresProvisioningProfile = true;
}
missingPlatform = handlingResult.missingPlatform;
issueDetected = true;
}
} else if (xcResult != null) {
globals.printTrace('XCResult parsing error: ${xcResult.parsingErrorMessage}');
}
if (requiresProvisioningProfile) {
logger.printError(noProvisioningProfileInstruction, emphasis: true);
} else if ((!issueDetected || hasProvisioningProfileIssue) && _missingDevelopmentTeam(xcodeBuildExecution)) {
issueDetected = true;
logger.printError(noDevelopmentTeamInstruction, emphasis: true);
} else if (hasProvisioningProfileIssue) {
logger.printError('');
logger.printError('It appears that there was a problem signing your application prior to installation on the device.');
logger.printError('');
logger.printError('Verify that the Bundle Identifier in your project is your signing id in Xcode');
logger.printError(' open ios/Runner.xcworkspace');
logger.printError('');
logger.printError("Also try selecting 'Product > Build' to fix the problem.");
} else if (missingPlatform != null) {
logger.printError(missingPlatformInstructions(missingPlatform), emphasis: true);
}
return issueDetected;
}
// Return 'true' a missing development team issue is detected.
bool _missingDevelopmentTeam(XcodeBuildExecution? xcodeBuildExecution) {
// Make sure the user has specified one of:
// * DEVELOPMENT_TEAM (automatic signing)
// * PROVISIONING_PROFILE (manual signing)
return xcodeBuildExecution != null && xcodeBuildExecution.environmentType == EnvironmentType.physical &&
!<String>['DEVELOPMENT_TEAM', 'PROVISIONING_PROFILE'].any(
xcodeBuildExecution.buildSettings.containsKey);
}
// Detects and handles errors from stdout.
//
// As detecting issues in stdout is not usually accurate, this should be used as a fallback when other issue detecting methods failed.
void _parseIssueInStdout(XcodeBuildExecution xcodeBuildExecution, Logger logger, XcodeBuildResult result) {
final String? stderr = result.stderr;
if (stderr != null && stderr.isNotEmpty) {
logger.printStatus('Error output from Xcode build:\n↳');
logger.printStatus(stderr, indent: 4);
}
final String? stdout = result.stdout;
if (stdout != null && stdout.isNotEmpty) {
logger.printStatus("Xcode's output:\n↳");
logger.printStatus(stdout, indent: 4);
}
if (xcodeBuildExecution.environmentType == EnvironmentType.physical
// May need updating if Xcode changes its outputs.
&& (result.stdout?.contains('requires a provisioning profile. Select a provisioning profile in the Signing & Capabilities editor') ?? false)) {
logger.printError(noProvisioningProfileInstruction, emphasis: true);
}
if (stderr != null && stderr.contains('Ineligible destinations')) {
final String? version = _parseMissingPlatform(stderr);
if (version != null) {
logger.printError(missingPlatformInstructions(version), emphasis: true);
}
}
}
String? _parseMissingPlatform(String message) {
final RegExp pattern = RegExp(r'error:(.*?) is not installed\. To use with Xcode, first download and install the platform');
return pattern.firstMatch(message)?.group(1);
}
// The result of [_handleXCResultIssue].
class _XCResultIssueHandlingResult {
_XCResultIssueHandlingResult({
required this.requiresProvisioningProfile,
required this.hasProvisioningProfileIssue,
this.missingPlatform,
});
// An issue indicates that user didn't provide the provisioning profile.
final bool requiresProvisioningProfile;
// An issue indicates that there is a provisioning profile issue.
final bool hasProvisioningProfileIssue;
final String? missingPlatform;
}
const String _kResultBundlePath = 'temporary_xcresult_bundle';
const String _kResultBundleVersion = '3';
| flutter/packages/flutter_tools/lib/src/ios/mac.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/ios/mac.dart",
"repo_id": "flutter",
"token_count": 11495
} | 751 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:mustache_template/mustache_template.dart';
import '../base/template.dart';
/// An indirection around mustache use to allow google3 to use a different dependency.
class MustacheTemplateRenderer extends TemplateRenderer {
const MustacheTemplateRenderer();
@override
String renderString(String template, dynamic context, {bool htmlEscapeValues = false}) {
return Template(template, htmlEscapeValues: htmlEscapeValues).renderString(context);
}
}
| flutter/packages/flutter_tools/lib/src/isolated/mustache_template.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/isolated/mustache_template.dart",
"repo_id": "flutter",
"token_count": 171
} | 752 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../base/platform.dart';
import '../doctor_validator.dart';
import '../features.dart';
/// The windows-specific implementation of a [Workflow].
///
/// This workflow requires the flutter-desktop-embedding as a sibling
/// repository to the flutter repo.
class LinuxWorkflow implements Workflow {
const LinuxWorkflow({
required Platform platform,
required FeatureFlags featureFlags,
}) : _platform = platform,
_featureFlags = featureFlags;
final Platform _platform;
final FeatureFlags _featureFlags;
@override
bool get appliesToHostPlatform => _platform.isLinux && _featureFlags.isLinuxEnabled;
@override
bool get canLaunchDevices => _platform.isLinux && _featureFlags.isLinuxEnabled;
@override
bool get canListDevices => _platform.isLinux && _featureFlags.isLinuxEnabled;
@override
bool get canListEmulators => false;
}
| flutter/packages/flutter_tools/lib/src/linux/linux_workflow.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/linux/linux_workflow.dart",
"repo_id": "flutter",
"token_count": 290
} | 753 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../../base/file_system.dart';
import '../../base/project_migrator.dart';
import '../../xcode_project.dart';
/// Update the minimum macOS deployment version to the minimum allowed by Xcode without causing a warning.
class MacOSDeploymentTargetMigration extends ProjectMigrator {
MacOSDeploymentTargetMigration(
MacOSProject project,
super.logger,
) : _xcodeProjectInfoFile = project.xcodeProjectInfoFile,
_podfile = project.podfile;
final File _xcodeProjectInfoFile;
final File _podfile;
@override
void migrate() {
if (_xcodeProjectInfoFile.existsSync()) {
processFileLines(_xcodeProjectInfoFile);
} else {
logger.printTrace('Xcode project not found, skipping macOS deployment target version migration.');
}
if (_podfile.existsSync()) {
processFileLines(_podfile);
} else {
logger.printTrace('Podfile not found, skipping global platform macOS version migration.');
}
}
@override
String? migrateLine(String line) {
// Xcode project file changes.
const String deploymentTargetOriginal1011 = 'MACOSX_DEPLOYMENT_TARGET = 10.11;';
const String deploymentTargetOriginal1013 = 'MACOSX_DEPLOYMENT_TARGET = 10.13;';
// Podfile changes.
const String podfilePlatformVersionOriginal1011 = "platform :osx, '10.11'";
const String podfilePlatformVersionOriginal1013 = "platform :osx, '10.13'";
if (line.contains(deploymentTargetOriginal1011)
|| line.contains(deploymentTargetOriginal1013)
|| line.contains(podfilePlatformVersionOriginal1011)
|| line.contains(podfilePlatformVersionOriginal1013)) {
if (!migrationRequired) {
// Only print for the first discovered change found.
logger.printStatus('Updating minimum macOS deployment target to 10.14.');
}
const String deploymentTargetReplacement = 'MACOSX_DEPLOYMENT_TARGET = 10.14;';
const String podfilePlatformVersionReplacement = "platform :osx, '10.14'";
return line
.replaceAll(deploymentTargetOriginal1011, deploymentTargetReplacement)
.replaceAll(deploymentTargetOriginal1013, deploymentTargetReplacement)
.replaceAll(podfilePlatformVersionOriginal1011, podfilePlatformVersionReplacement)
.replaceAll(podfilePlatformVersionOriginal1013, podfilePlatformVersionReplacement);
}
return line;
}
}
| flutter/packages/flutter_tools/lib/src/macos/migrations/macos_deployment_target_migration.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/macos/migrations/macos_deployment_target_migration.dart",
"repo_id": "flutter",
"token_count": 849
} | 754 |
// 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:pub_semver/pub_semver.dart';
import 'package:yaml/yaml.dart';
import 'base/common.dart';
import 'base/file_system.dart';
import 'platform_plugins.dart';
class Plugin {
Plugin({
required this.name,
required this.path,
required this.platforms,
required this.defaultPackagePlatforms,
required this.pluginDartClassPlatforms,
this.flutterConstraint,
required this.dependencies,
required this.isDirectDependency,
this.implementsPackage,
});
/// Parses [Plugin] specification from the provided pluginYaml.
///
/// This currently supports two formats. Legacy and Multi-platform.
///
/// Example of the deprecated Legacy format.
///
/// flutter:
/// plugin:
/// androidPackage: io.flutter.plugins.sample
/// iosPrefix: FLT
/// pluginClass: SamplePlugin
///
/// Example Multi-platform format.
///
/// flutter:
/// plugin:
/// platforms:
/// android:
/// package: io.flutter.plugins.sample
/// pluginClass: SamplePlugin
/// ios:
/// # A plugin implemented through method channels.
/// pluginClass: SamplePlugin
/// linux:
/// # A plugin implemented purely in Dart code.
/// dartPluginClass: SamplePlugin
/// macos:
/// # A plugin implemented with `dart:ffi`.
/// ffiPlugin: true
/// windows:
/// # A plugin using platform-specific Dart and method channels.
/// dartPluginClass: SamplePlugin
/// pluginClass: SamplePlugin
factory Plugin.fromYaml(
String name,
String path,
YamlMap? pluginYaml,
VersionConstraint? flutterConstraint,
List<String> dependencies, {
required FileSystem fileSystem,
Set<String>? appDependencies,
}) {
final List<String> errors = validatePluginYaml(pluginYaml);
if (errors.isNotEmpty) {
throwToolExit('Invalid plugin specification $name.\n${errors.join('\n')}');
}
if (pluginYaml != null && pluginYaml['platforms'] != null) {
return Plugin._fromMultiPlatformYaml(
name,
path,
pluginYaml,
flutterConstraint,
dependencies,
fileSystem,
appDependencies != null && appDependencies.contains(name),
);
}
return Plugin._fromLegacyYaml(
name,
path,
pluginYaml,
flutterConstraint,
dependencies,
fileSystem,
appDependencies != null && appDependencies.contains(name),
);
}
factory Plugin._fromMultiPlatformYaml(
String name,
String path,
YamlMap pluginYaml,
VersionConstraint? flutterConstraint,
List<String> dependencies,
FileSystem fileSystem,
bool isDirectDependency,
) {
assert (pluginYaml['platforms'] != null, 'Invalid multi-platform plugin specification $name.');
final YamlMap platformsYaml = pluginYaml['platforms'] as YamlMap;
assert (_validateMultiPlatformYaml(platformsYaml).isEmpty,
'Invalid multi-platform plugin specification $name.');
final Map<String, PluginPlatform> platforms = <String, PluginPlatform>{};
if (_providesImplementationForPlatform(platformsYaml, AndroidPlugin.kConfigKey)) {
platforms[AndroidPlugin.kConfigKey] = AndroidPlugin.fromYaml(
name,
platformsYaml[AndroidPlugin.kConfigKey] as YamlMap,
path,
fileSystem,
);
}
if (_providesImplementationForPlatform(platformsYaml, IOSPlugin.kConfigKey)) {
platforms[IOSPlugin.kConfigKey] =
IOSPlugin.fromYaml(name, platformsYaml[IOSPlugin.kConfigKey] as YamlMap);
}
if (_providesImplementationForPlatform(platformsYaml, LinuxPlugin.kConfigKey)) {
platforms[LinuxPlugin.kConfigKey] =
LinuxPlugin.fromYaml(name, platformsYaml[LinuxPlugin.kConfigKey] as YamlMap);
}
if (_providesImplementationForPlatform(platformsYaml, MacOSPlugin.kConfigKey)) {
platforms[MacOSPlugin.kConfigKey] =
MacOSPlugin.fromYaml(name, platformsYaml[MacOSPlugin.kConfigKey] as YamlMap);
}
if (_providesImplementationForPlatform(platformsYaml, WebPlugin.kConfigKey)) {
platforms[WebPlugin.kConfigKey] =
WebPlugin.fromYaml(name, platformsYaml[WebPlugin.kConfigKey] as YamlMap);
}
if (_providesImplementationForPlatform(platformsYaml, WindowsPlugin.kConfigKey)) {
platforms[WindowsPlugin.kConfigKey] =
WindowsPlugin.fromYaml(name, platformsYaml[WindowsPlugin.kConfigKey] as YamlMap);
}
// TODO(stuartmorgan): Consider merging web into this common handling; the
// fact that its implementation of Dart-only plugins and default packages
// are separate is legacy.
final List<String> sharedHandlingPlatforms = <String>[
AndroidPlugin.kConfigKey,
IOSPlugin.kConfigKey,
LinuxPlugin.kConfigKey,
MacOSPlugin.kConfigKey,
WindowsPlugin.kConfigKey,
];
final Map<String, String> defaultPackages = <String, String>{};
final Map<String, String> dartPluginClasses = <String, String>{};
for (final String platform in sharedHandlingPlatforms) {
final String? defaultPackage = _getDefaultPackageForPlatform(platformsYaml, platform);
if (defaultPackage != null) {
defaultPackages[platform] = defaultPackage;
}
final String? dartClass = _getPluginDartClassForPlatform(platformsYaml, platform);
if (dartClass != null) {
dartPluginClasses[platform] = dartClass;
}
}
return Plugin(
name: name,
path: path,
platforms: platforms,
defaultPackagePlatforms: defaultPackages,
pluginDartClassPlatforms: dartPluginClasses,
flutterConstraint: flutterConstraint,
dependencies: dependencies,
isDirectDependency: isDirectDependency,
implementsPackage: pluginYaml['implements'] != null ? pluginYaml['implements'] as String : '',
);
}
factory Plugin._fromLegacyYaml(
String name,
String path,
dynamic pluginYaml,
VersionConstraint? flutterConstraint,
List<String> dependencies,
FileSystem fileSystem,
bool isDirectDependency,
) {
final Map<String, PluginPlatform> platforms = <String, PluginPlatform>{};
final String? pluginClass = (pluginYaml as Map<dynamic, dynamic>)['pluginClass'] as String?;
if (pluginClass != null) {
final String? androidPackage = pluginYaml['androidPackage'] as String?;
if (androidPackage != null) {
platforms[AndroidPlugin.kConfigKey] = AndroidPlugin(
name: name,
package: androidPackage,
pluginClass: pluginClass,
pluginPath: path,
fileSystem: fileSystem,
);
}
final String iosPrefix = pluginYaml['iosPrefix'] as String? ?? '';
platforms[IOSPlugin.kConfigKey] =
IOSPlugin(
name: name,
classPrefix: iosPrefix,
pluginClass: pluginClass,
);
}
return Plugin(
name: name,
path: path,
platforms: platforms,
defaultPackagePlatforms: <String, String>{},
pluginDartClassPlatforms: <String, String>{},
flutterConstraint: flutterConstraint,
dependencies: dependencies,
isDirectDependency: isDirectDependency,
);
}
/// Create a YamlMap that represents the supported platforms.
///
/// For example, if the `platforms` contains 'ios' and 'android', the return map looks like:
///
/// android:
/// package: io.flutter.plugins.sample
/// pluginClass: SamplePlugin
/// ios:
/// pluginClass: SamplePlugin
static YamlMap createPlatformsYamlMap(List<String> platforms, String pluginClass, String androidPackage) {
final Map<String, dynamic> map = <String, dynamic>{};
for (final String platform in platforms) {
map[platform] = <String, String>{
'pluginClass': pluginClass,
...platform == 'android' ? <String, String>{'package': androidPackage} : <String, String>{},
};
}
return YamlMap.wrap(map);
}
static List<String> validatePluginYaml(YamlMap? yaml) {
if (yaml == null) {
return <String>['Invalid "plugin" specification.'];
}
final bool usesOldPluginFormat = const <String>{
'androidPackage',
'iosPrefix',
'pluginClass',
}.any(yaml.containsKey);
final bool usesNewPluginFormat = yaml.containsKey('platforms');
if (usesOldPluginFormat && usesNewPluginFormat) {
const String errorMessage =
'The flutter.plugin.platforms key cannot be used in combination with the old '
'flutter.plugin.{androidPackage,iosPrefix,pluginClass} keys. '
'See: https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin';
return <String>[errorMessage];
}
if (!usesOldPluginFormat && !usesNewPluginFormat) {
const String errorMessage =
'Cannot find the `flutter.plugin.platforms` key in the `pubspec.yaml` file. '
'An instruction to format the `pubspec.yaml` can be found here: '
'https://flutter.dev/docs/development/packages-and-plugins/developing-packages#plugin-platforms';
return <String>[errorMessage];
}
if (usesNewPluginFormat) {
if (yaml['platforms'] != null && yaml['platforms'] is! YamlMap) {
const String errorMessage = 'flutter.plugin.platforms should be a map with the platform name as the key';
return <String>[errorMessage];
}
return _validateMultiPlatformYaml(yaml['platforms'] as YamlMap?);
} else {
return _validateLegacyYaml(yaml);
}
}
static List<String> _validateMultiPlatformYaml(YamlMap? yaml) {
bool isInvalid(String key, bool Function(YamlMap) validate) {
if (!yaml!.containsKey(key)) {
return false;
}
final dynamic yamlValue = yaml[key];
if (yamlValue is! YamlMap) {
return true;
}
if (yamlValue.containsKey('default_package')) {
return false;
}
return !validate(yamlValue);
}
if (yaml == null) {
return <String>['Invalid "platforms" specification.'];
}
final List<String> errors = <String>[];
if (isInvalid(AndroidPlugin.kConfigKey, AndroidPlugin.validate)) {
errors.add('Invalid "android" plugin specification.');
}
if (isInvalid(IOSPlugin.kConfigKey, IOSPlugin.validate)) {
errors.add('Invalid "ios" plugin specification.');
}
if (isInvalid(LinuxPlugin.kConfigKey, LinuxPlugin.validate)) {
errors.add('Invalid "linux" plugin specification.');
}
if (isInvalid(MacOSPlugin.kConfigKey, MacOSPlugin.validate)) {
errors.add('Invalid "macos" plugin specification.');
}
if (isInvalid(WindowsPlugin.kConfigKey, WindowsPlugin.validate)) {
errors.add('Invalid "windows" plugin specification.');
}
return errors;
}
static List<String> _validateLegacyYaml(YamlMap yaml) {
final List<String> errors = <String>[];
if (yaml['androidPackage'] != null && yaml['androidPackage'] is! String) {
errors.add('The "androidPackage" must either be null or a string.');
}
if (yaml['iosPrefix'] != null && yaml['iosPrefix'] is! String) {
errors.add('The "iosPrefix" must either be null or a string.');
}
if (yaml['pluginClass'] != null && yaml['pluginClass'] is! String) {
errors.add('The "pluginClass" must either be null or a string..');
}
return errors;
}
static bool _supportsPlatform(YamlMap platformsYaml, String platformKey) {
if (!platformsYaml.containsKey(platformKey)) {
return false;
}
if (platformsYaml[platformKey] is YamlMap) {
return true;
}
return false;
}
static String? _getDefaultPackageForPlatform(YamlMap platformsYaml, String platformKey) {
if (!_supportsPlatform(platformsYaml, platformKey)) {
return null;
}
if ((platformsYaml[platformKey] as YamlMap).containsKey(kDefaultPackage)) {
return (platformsYaml[platformKey] as YamlMap)[kDefaultPackage] as String;
}
return null;
}
static String? _getPluginDartClassForPlatform(YamlMap platformsYaml, String platformKey) {
if (!_supportsPlatform(platformsYaml, platformKey)) {
return null;
}
if ((platformsYaml[platformKey] as YamlMap).containsKey(kDartPluginClass)) {
return (platformsYaml[platformKey] as YamlMap)[kDartPluginClass] as String;
}
return null;
}
static bool _providesImplementationForPlatform(YamlMap platformsYaml, String platformKey) {
if (!_supportsPlatform(platformsYaml, platformKey)) {
return false;
}
if ((platformsYaml[platformKey] as YamlMap).containsKey(kDefaultPackage)) {
return false;
}
return true;
}
final String name;
final String path;
/// The name of the interface package that this plugin implements.
/// If [null], this plugin doesn't implement an interface.
final String? implementsPackage;
/// The required version of Flutter, if specified.
final VersionConstraint? flutterConstraint;
/// The name of the packages this plugin depends on.
final List<String> dependencies;
/// This is a mapping from platform config key to the plugin platform spec.
final Map<String, PluginPlatform> platforms;
/// This is a mapping from platform config key to the default package implementation.
final Map<String, String> defaultPackagePlatforms;
/// This is a mapping from platform config key to the plugin class for the given platform.
final Map<String, String> pluginDartClassPlatforms;
/// Whether this plugin is a direct dependency of the app.
/// If [false], the plugin is a dependency of another plugin.
final bool isDirectDependency;
}
/// Metadata associated with the resolution of a platform interface of a plugin.
class PluginInterfaceResolution {
PluginInterfaceResolution({
required this.plugin,
required this.platform,
});
/// The plugin.
final Plugin plugin;
// The name of the platform that this plugin implements.
final String platform;
Map<String, String> toMap() {
return <String, String> {
'pluginName': plugin.name,
'platform': platform,
'dartClass': plugin.pluginDartClassPlatforms[platform] ?? '',
};
}
@override
String toString() {
return '<PluginInterfaceResolution ${plugin.name} for $platform>';
}
}
| flutter/packages/flutter_tools/lib/src/plugins.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/plugins.dart",
"repo_id": "flutter",
"token_count": 5368
} | 755 |
// 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:convert/convert.dart';
import 'package:crypto/crypto.dart';
import '../convert.dart';
import '../persistent_tool_state.dart';
/// This message is displayed on the first run of the Flutter tool, or anytime
/// that the contents of this string change.
const String _kFlutterFirstRunMessage = '''
╔════════════════════════════════════════════════════════════════════════════╗
║ Welcome to Flutter! - https://flutter.dev ║
║ ║
║ The Flutter tool uses Google Analytics to anonymously report feature usage ║
║ statistics and basic crash reports. This data is used to help improve ║
║ Flutter tools over time. ║
║ ║
║ Flutter tool analytics are not sent on the very first run. To disable ║
║ reporting, type 'flutter config --no-analytics'. To display the current ║
║ setting, type 'flutter config'. If you opt out of analytics, an opt-out ║
║ event will be sent, and then no further information will be sent by the ║
║ Flutter tool. ║
║ ║
║ By downloading the Flutter SDK, you agree to the Google Terms of Service. ║
║ The Google Privacy Policy describes how data is handled in this service. ║
║ ║
║ Moreover, Flutter includes the Dart SDK, which may send usage metrics and ║
║ crash reports to Google. ║
║ ║
║ Read about data we send with crash reports: ║
║ https://flutter.dev/docs/reference/crash-reporting ║
║ ║
║ See Google's privacy policy: ║
║ https://policies.google.com/privacy ║
║ ║
║ To disable animations in this tool, use ║
║ 'flutter config --no-cli-animations'. ║
╚════════════════════════════════════════════════════════════════════════════╝
''';
/// The first run messenger determines whether the first run license terms
/// need to be displayed.
class FirstRunMessenger {
FirstRunMessenger({
required PersistentToolState persistentToolState
}) : _persistentToolState = persistentToolState;
final PersistentToolState _persistentToolState;
/// Whether the license terms should be displayed.
///
/// This is implemented by caching a hash of the previous license terms. This
/// does not update the cache hash value.
///
/// The persistent tool state setting [PersistentToolState.redisplayWelcomeMessage]
/// can also be used to make this return false. This is primarily used to ensure
/// that the license terms are not printed during a `flutter upgrade`, until the
/// user manually runs the tool.
bool shouldDisplayLicenseTerms() {
if (_persistentToolState.shouldRedisplayWelcomeMessage == false) {
return false;
}
final String? oldHash = _persistentToolState.lastActiveLicenseTermsHash;
return oldHash != _currentHash;
}
/// Update the cached license terms hash once the new terms have been displayed.
void confirmLicenseTermsDisplayed() {
_persistentToolState.setLastActiveLicenseTermsHash(_currentHash);
}
/// The hash of the current license representation.
String get _currentHash => hex.encode(md5.convert(utf8.encode(licenseTerms)).bytes);
/// The current license terms.
String get licenseTerms => _kFlutterFirstRunMessage;
}
| flutter/packages/flutter_tools/lib/src/reporting/first_run.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/reporting/first_run.dart",
"repo_id": "flutter",
"token_count": 2006
} | 756 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '../convert.dart';
import 'test_device.dart';
import 'watcher.dart';
/// Prints JSON events when running a test in --machine mode.
class EventPrinter extends TestWatcher {
EventPrinter({required StringSink out, TestWatcher? parent})
: _out = out,
_parent = parent;
final StringSink _out;
final TestWatcher? _parent;
@override
void handleStartedDevice(Uri? vmServiceUri) {
_sendEvent('test.startedProcess',
<String, dynamic>{
'vmServiceUri': vmServiceUri?.toString(),
// TODO(bkonyi): remove references to Observatory
// See https://github.com/flutter/flutter/issues/121271
'observatoryUri': vmServiceUri?.toString()
});
_parent?.handleStartedDevice(vmServiceUri);
}
@override
Future<void> handleTestCrashed(TestDevice testDevice) async {
return _parent?.handleTestCrashed(testDevice);
}
@override
Future<void> handleTestTimedOut(TestDevice testDevice) async {
return _parent?.handleTestTimedOut(testDevice);
}
@override
Future<void> handleFinishedTest(TestDevice testDevice) async {
return _parent?.handleFinishedTest(testDevice);
}
void _sendEvent(String name, [ dynamic params ]) {
final Map<String, dynamic> map = <String, dynamic>{'event': name};
if (params != null) {
map['params'] = params;
}
_send(map);
}
void _send(Map<String, dynamic> command) {
final String encoded = json.encode(command, toEncodable: _jsonEncodeObject);
_out.writeln('\n[$encoded]');
}
dynamic _jsonEncodeObject(dynamic object) {
if (object is Uri) {
return object.toString();
}
return object;
}
}
| flutter/packages/flutter_tools/lib/src/test/event_printer.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/test/event_printer.dart",
"repo_id": "flutter",
"token_count": 665
} | 757 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:vm_service/vm_service.dart' as vm_service;
import 'base/common.dart';
import 'base/error_handling_io.dart';
import 'base/file_system.dart';
import 'base/logger.dart';
import 'base/utils.dart';
import 'convert.dart';
import 'vmservice.dart';
// Names of some of the Timeline events we care about.
const String kFlutterEngineMainEnterEventName = 'FlutterEngineMainEnter';
const String kFrameworkInitEventName = 'Framework initialization';
const String kFirstFrameBuiltEventName = 'Widgets built first useful frame';
const String kFirstFrameRasterizedEventName = 'Rasterized first useful frame';
class Tracing {
Tracing({
required this.vmService,
required Logger logger,
}) : _logger = logger;
static const String firstUsefulFrameEventName = kFirstFrameRasterizedEventName;
final FlutterVmService vmService;
final Logger _logger;
Future<void> startTracing() async {
await vmService.setTimelineFlags(<String>['Compiler', 'Dart', 'Embedder', 'GC']);
await vmService.service.clearVMTimeline();
}
/// Stops tracing; optionally wait for first frame.
Future<Map<String, Object?>> stopTracingAndDownloadTimeline({
bool awaitFirstFrame = false,
}) async {
if (awaitFirstFrame) {
final Status status = _logger.startProgress(
'Waiting for application to render first frame...',
);
try {
final Completer<void> whenFirstFrameRendered = Completer<void>();
try {
await vmService.service.streamListen(vm_service.EventStreams.kExtension);
} on vm_service.RPCError {
// It is safe to ignore this error because we expect an error to be
// thrown if we're already subscribed.
}
final StringBuffer bufferedEvents = StringBuffer();
void Function(String) handleBufferedEvent = bufferedEvents.writeln;
vmService.service.onExtensionEvent.listen((vm_service.Event event) {
handleBufferedEvent('${event.extensionKind}: ${event.extensionData}');
if (event.extensionKind == 'Flutter.FirstFrame') {
whenFirstFrameRendered.complete();
}
});
bool done = false;
final List<FlutterView> views = await vmService.getFlutterViews();
for (final FlutterView view in views) {
final String? uiIsolateId = view.uiIsolate?.id;
if (uiIsolateId != null && await vmService
.flutterAlreadyPaintedFirstUsefulFrame(
isolateId: uiIsolateId,
)) {
done = true;
break;
}
}
if (!done) {
final Timer timer = Timer(const Duration(seconds: 10), () async {
_logger.printStatus('First frame is taking longer than expected...');
for (final FlutterView view in views) {
final String? isolateId = view.uiIsolate?.id;
_logger.printTrace('View ID: ${view.id}');
if (isolateId == null) {
_logger.printTrace('No isolate ID associated with the view.');
continue;
}
final vm_service.Isolate? isolate = await vmService.getIsolateOrNull(isolateId);
if (isolate == null) {
_logger.printTrace('Isolate $isolateId not found.');
continue;
}
_logger.printTrace('Isolate $isolateId state:');
final Map<String, Object?> isolateState = isolate.toJson();
// "libraries" has very long output and is likely unrelated to any first-frame issues.
isolateState.remove('libraries');
_logger.printTrace(jsonEncode(isolateState));
}
_logger.printTrace('Received VM events:');
_logger.printTrace(bufferedEvents.toString());
// Swap to just printing new events instead of buffering.
handleBufferedEvent = _logger.printTrace;
});
await whenFirstFrameRendered.future;
timer.cancel();
}
// The exception is rethrown, so don't catch only Exceptions.
} catch (exception) { // ignore: avoid_catches_without_on_clauses
status.cancel();
rethrow;
}
status.stop();
}
final vm_service.Response? timeline = await vmService.getTimeline();
await vmService.setTimelineFlags(<String>[]);
final Map<String, Object?>? timelineJson = timeline?.json;
if (timelineJson == null) {
throwToolExit(
'The device disconnected before the timeline could be retrieved.',
);
}
return timelineJson;
}
}
/// Download the startup trace information from the given VM Service client and
/// store it to `$output/start_up_info.json`.
Future<void> downloadStartupTrace(FlutterVmService vmService, {
bool awaitFirstFrame = true,
required Logger logger,
required Directory output,
}) async {
final File traceInfoFile = output.childFile('start_up_info.json');
// Delete old startup data, if any.
ErrorHandlingFileSystem.deleteIfExists(traceInfoFile);
// Create "build" directory, if missing.
if (!traceInfoFile.parent.existsSync()) {
traceInfoFile.parent.createSync();
}
final Tracing tracing = Tracing(vmService: vmService, logger: logger);
final Map<String, Object?> timeline = await tracing.stopTracingAndDownloadTimeline(
awaitFirstFrame: awaitFirstFrame,
);
final File traceTimelineFile = output.childFile('start_up_timeline.json');
traceTimelineFile.writeAsStringSync(toPrettyJson(timeline));
int? extractInstantEventTimestamp(String eventName) {
final List<Object?>? traceEvents = timeline['traceEvents'] as List<Object?>?;
if (traceEvents == null) {
return null;
}
final List<Map<String, Object?>> events = List<Map<String, Object?>>.from(traceEvents);
Map<String, Object?>? matchedEvent;
for (final Map<String, Object?> event in events) {
if (event['name'] == eventName) {
matchedEvent = event;
}
}
return matchedEvent == null ? null : (matchedEvent['ts'] as int?);
}
String message = 'No useful metrics were gathered.';
final int? engineEnterTimestampMicros = extractInstantEventTimestamp(kFlutterEngineMainEnterEventName);
final int? frameworkInitTimestampMicros = extractInstantEventTimestamp(kFrameworkInitEventName);
if (engineEnterTimestampMicros == null) {
logger.printTrace('Engine start event is missing in the timeline: $timeline');
throwToolExit('Engine start event is missing in the timeline. Cannot compute startup time.');
}
final Map<String, Object?> traceInfo = <String, Object?>{
'engineEnterTimestampMicros': engineEnterTimestampMicros,
};
if (frameworkInitTimestampMicros != null) {
final int timeToFrameworkInitMicros = frameworkInitTimestampMicros - engineEnterTimestampMicros;
traceInfo['timeToFrameworkInitMicros'] = timeToFrameworkInitMicros;
message = 'Time to framework init: ${timeToFrameworkInitMicros ~/ 1000}ms.';
}
if (awaitFirstFrame) {
final int? firstFrameBuiltTimestampMicros = extractInstantEventTimestamp(kFirstFrameBuiltEventName);
final int? firstFrameRasterizedTimestampMicros = extractInstantEventTimestamp(kFirstFrameRasterizedEventName);
if (firstFrameBuiltTimestampMicros == null || firstFrameRasterizedTimestampMicros == null) {
logger.printTrace('First frame events are missing in the timeline: $timeline');
throwToolExit('First frame events are missing in the timeline. Cannot compute startup time.');
}
// To keep our old benchmarks valid, we'll preserve the
// timeToFirstFrameMicros as the firstFrameBuiltTimestampMicros.
// Additionally, we add timeToFirstFrameRasterizedMicros for a more accurate
// benchmark.
traceInfo['timeToFirstFrameRasterizedMicros'] = firstFrameRasterizedTimestampMicros - engineEnterTimestampMicros;
final int timeToFirstFrameMicros = firstFrameBuiltTimestampMicros - engineEnterTimestampMicros;
traceInfo['timeToFirstFrameMicros'] = timeToFirstFrameMicros;
message = 'Time to first frame: ${timeToFirstFrameMicros ~/ 1000}ms.';
if (frameworkInitTimestampMicros != null) {
traceInfo['timeAfterFrameworkInitMicros'] = firstFrameBuiltTimestampMicros - frameworkInitTimestampMicros;
}
}
traceInfoFile.writeAsStringSync(toPrettyJson(traceInfo));
logger.printStatus(message);
logger.printStatus('Saved startup trace info in ${traceInfoFile.path}.');
}
| flutter/packages/flutter_tools/lib/src/tracing.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/tracing.dart",
"repo_id": "flutter",
"token_count": 3115
} | 758 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:meta/meta.dart';
import 'package:process/process.dart';
import '../application_package.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/logger.dart';
import '../base/os.dart';
import '../base/platform.dart';
import '../base/version.dart';
import '../build_info.dart';
import '../device.dart';
import '../device_port_forwarder.dart';
import '../features.dart';
import '../project.dart';
import 'chrome.dart';
class WebApplicationPackage extends ApplicationPackage {
WebApplicationPackage(this.flutterProject) : super(id: flutterProject.manifest.appName);
final FlutterProject flutterProject;
@override
String get name => flutterProject.manifest.appName;
/// The location of the web source assets.
Directory get webSourcePath => flutterProject.directory.childDirectory('web');
}
/// A web device that supports a chromium browser.
abstract class ChromiumDevice extends Device {
ChromiumDevice({
required String name,
required this.chromeLauncher,
required FileSystem fileSystem,
required Logger logger,
}) : _fileSystem = fileSystem,
_logger = logger,
super(
name,
category: Category.web,
platformType: PlatformType.web,
ephemeral: false,
);
final ChromiumLauncher chromeLauncher;
final FileSystem _fileSystem;
final Logger _logger;
/// The active chrome instance.
Chromium? _chrome;
// This device does not actually support hot reload, but the current implementation of the resident runner
// requires both supportsHotReload and supportsHotRestart to be true in order to allow hot restart.
@override
bool get supportsHotReload => true;
@override
bool get supportsHotRestart => true;
@override
bool get supportsStartPaused => true;
@override
bool get supportsFlutterExit => false;
@override
bool get supportsScreenshot => false;
@override
bool supportsRuntimeMode(BuildMode buildMode) => buildMode != BuildMode.jitRelease;
@override
void clearLogs() { }
DeviceLogReader? _logReader;
@override
DeviceLogReader getLogReader({
ApplicationPackage? app,
bool includePastLogs = false,
}) {
return _logReader ??= NoOpDeviceLogReader(app?.name);
}
@override
Future<bool> installApp(
ApplicationPackage app, {
String? userIdentifier,
}) async => true;
@override
Future<bool> isAppInstalled(
ApplicationPackage app, {
String? userIdentifier,
}) async => true;
@override
Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => true;
@override
Future<bool> get isLocalEmulator async => false;
@override
Future<String?> get emulatorId async => null;
@override
bool isSupported() => chromeLauncher.canFindExecutable();
@override
DevicePortForwarder? get portForwarder => const NoOpDevicePortForwarder();
@override
Future<LaunchResult> startApp(
ApplicationPackage? package, {
String? mainPath,
String? route,
required DebuggingOptions debuggingOptions,
Map<String, Object?> platformArgs = const <String, Object?>{},
bool prebuiltApplication = false,
bool ipv6 = false,
String? userIdentifier,
}) async {
// See [ResidentWebRunner.run] in flutter_tools/lib/src/resident_web_runner.dart
// for the web initialization and server logic.
String url;
if (debuggingOptions.webLaunchUrl != null) {
final RegExp pattern = RegExp(r'^((http)?:\/\/)[^\s]+');
if (pattern.hasMatch(debuggingOptions.webLaunchUrl!)) {
url = debuggingOptions.webLaunchUrl!;
} else {
throwToolExit('"${debuggingOptions.webLaunchUrl}" is not a valid HTTP URL.');
}
} else {
url = platformArgs['uri']! as String;
}
final bool launchChrome = platformArgs['no-launch-chrome'] != true;
if (launchChrome) {
_chrome = await chromeLauncher.launch(
url,
cacheDir: _fileSystem.currentDirectory
.childDirectory('.dart_tool')
.childDirectory('chrome-device'),
headless: debuggingOptions.webRunHeadless,
debugPort: debuggingOptions.webBrowserDebugPort,
webBrowserFlags: debuggingOptions.webBrowserFlags,
);
}
_logger.sendEvent('app.webLaunchUrl', <String, Object>{'url': url, 'launched': launchChrome});
return LaunchResult.succeeded(vmServiceUri: Uri.parse(url));
}
@override
Future<bool> stopApp(
ApplicationPackage? app, {
String? userIdentifier,
}) async {
await _chrome?.close();
return true;
}
@override
Future<TargetPlatform> get targetPlatform async => TargetPlatform.web_javascript;
@override
Future<bool> uninstallApp(
ApplicationPackage app, {
String? userIdentifier,
}) async => true;
@override
bool isSupportedForProject(FlutterProject flutterProject) {
return flutterProject.web.existsSync();
}
@override
Future<void> dispose() async {
_logReader?.dispose();
await portForwarder?.dispose();
}
}
/// The Google Chrome browser based on Chromium.
class GoogleChromeDevice extends ChromiumDevice {
GoogleChromeDevice({
required Platform platform,
required ProcessManager processManager,
required ChromiumLauncher chromiumLauncher,
required super.logger,
required super.fileSystem,
}) : _platform = platform,
_processManager = processManager,
super(
name: 'chrome',
chromeLauncher: chromiumLauncher,
);
final Platform _platform;
final ProcessManager _processManager;
@override
String get name => 'Chrome';
@override
late final Future<String> sdkNameAndVersion = _computeSdkNameAndVersion();
Future<String> _computeSdkNameAndVersion() async {
if (!isSupported()) {
return 'unknown';
}
// See https://bugs.chromium.org/p/chromium/issues/detail?id=158372
String version = 'unknown';
if (_platform.isWindows) {
if (_processManager.canRun('reg')) {
final ProcessResult result = await _processManager.run(<String>[
r'reg', 'query', r'HKEY_CURRENT_USER\Software\Google\Chrome\BLBeacon', '/v', 'version',
]);
if (result.exitCode == 0) {
final List<String> parts = (result.stdout as String).split(RegExp(r'\s+'));
if (parts.length > 2) {
version = 'Google Chrome ${parts[parts.length - 2]}';
}
}
}
} else {
final String chrome = chromeLauncher.findExecutable();
final ProcessResult result = await _processManager.run(<String>[
chrome,
'--version',
]);
if (result.exitCode == 0) {
version = result.stdout as String;
}
}
return version.trim();
}
}
/// The Microsoft Edge browser based on Chromium.
class MicrosoftEdgeDevice extends ChromiumDevice {
MicrosoftEdgeDevice({
required ChromiumLauncher chromiumLauncher,
required super.logger,
required super.fileSystem,
required ProcessManager processManager,
}) : _processManager = processManager,
super(
name: 'edge',
chromeLauncher: chromiumLauncher,
);
final ProcessManager _processManager;
// The first version of Edge with chromium support.
static const int _kFirstChromiumEdgeMajorVersion = 79;
@override
String get name => 'Edge';
Future<bool> _meetsVersionConstraint() async {
final String rawVersion = (await sdkNameAndVersion).replaceFirst('Microsoft Edge ', '');
final Version? version = Version.parse(rawVersion);
if (version == null) {
return false;
}
return version.major >= _kFirstChromiumEdgeMajorVersion;
}
@override
late final Future<String> sdkNameAndVersion = _getSdkNameAndVersion();
Future<String> _getSdkNameAndVersion() async {
if (_processManager.canRun('reg')) {
final ProcessResult result = await _processManager.run(<String>[
r'reg', 'query', r'HKEY_CURRENT_USER\Software\Microsoft\Edge\BLBeacon', '/v', 'version',
]);
if (result.exitCode == 0) {
final List<String> parts = (result.stdout as String).split(RegExp(r'\s+'));
if (parts.length > 2) {
return 'Microsoft Edge ${parts[parts.length - 2]}';
}
}
}
// Return a non-null string so that the tool can validate the version
// does not meet the constraint above in _meetsVersionConstraint.
return '';
}
}
class WebDevices extends PollingDeviceDiscovery {
WebDevices({
required FileSystem fileSystem,
required Logger logger,
required Platform platform,
required ProcessManager processManager,
required FeatureFlags featureFlags,
}) : _featureFlags = featureFlags,
_webServerDevice = WebServerDevice(
logger: logger,
),
super('Chrome') {
final OperatingSystemUtils operatingSystemUtils = OperatingSystemUtils(
fileSystem: fileSystem,
platform: platform,
logger: logger,
processManager: processManager,
);
_chromeDevice = GoogleChromeDevice(
fileSystem: fileSystem,
logger: logger,
platform: platform,
processManager: processManager,
chromiumLauncher: ChromiumLauncher(
browserFinder: findChromeExecutable,
fileSystem: fileSystem,
platform: platform,
processManager: processManager,
operatingSystemUtils: operatingSystemUtils,
logger: logger,
),
);
if (platform.isWindows) {
_edgeDevice = MicrosoftEdgeDevice(
chromiumLauncher: ChromiumLauncher(
browserFinder: findEdgeExecutable,
fileSystem: fileSystem,
platform: platform,
processManager: processManager,
operatingSystemUtils: operatingSystemUtils,
logger: logger,
),
processManager: processManager,
logger: logger,
fileSystem: fileSystem,
);
}
}
late final GoogleChromeDevice _chromeDevice;
final WebServerDevice _webServerDevice;
MicrosoftEdgeDevice? _edgeDevice;
final FeatureFlags _featureFlags;
@override
bool get canListAnything => featureFlags.isWebEnabled;
@override
Future<List<Device>> pollingGetDevices({ Duration? timeout }) async {
if (!_featureFlags.isWebEnabled) {
return <Device>[];
}
final MicrosoftEdgeDevice? edgeDevice = _edgeDevice;
return <Device>[
if (WebServerDevice.showWebServerDevice)
_webServerDevice,
if (_chromeDevice.isSupported())
_chromeDevice,
if (edgeDevice != null && await edgeDevice._meetsVersionConstraint())
edgeDevice,
];
}
@override
bool get supportsPlatform => _featureFlags.isWebEnabled;
@override
List<String> get wellKnownIds => const <String>['chrome', 'web-server', 'edge'];
}
@visibleForTesting
String parseVersionForWindows(String input) {
return input.split(RegExp(r'\w')).last;
}
/// A special device type to allow serving for arbitrary browsers.
class WebServerDevice extends Device {
WebServerDevice({
required Logger logger,
}) : _logger = logger,
super(
'web-server',
platformType: PlatformType.web,
category: Category.web,
ephemeral: false,
);
static const String kWebServerDeviceId = 'web-server';
static bool showWebServerDevice = false;
final Logger _logger;
@override
void clearLogs() { }
@override
Future<String?> get emulatorId async => null;
DeviceLogReader? _logReader;
@override
DeviceLogReader getLogReader({
ApplicationPackage? app,
bool includePastLogs = false,
}) {
return _logReader ??= NoOpDeviceLogReader(app?.name);
}
@override
Future<bool> installApp(
ApplicationPackage app, {
String? userIdentifier,
}) async => true;
@override
Future<bool> isAppInstalled(
ApplicationPackage app, {
String? userIdentifier,
}) async => true;
@override
Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => true;
@override
bool get supportsFlutterExit => false;
@override
bool supportsRuntimeMode(BuildMode buildMode) => buildMode != BuildMode.jitRelease;
@override
Future<bool> get isLocalEmulator async => false;
@override
bool isSupported() => true;
@override
bool isSupportedForProject(FlutterProject flutterProject) {
return flutterProject.web.existsSync();
}
@override
String get name => 'Web Server';
@override
DevicePortForwarder? get portForwarder => const NoOpDevicePortForwarder();
@override
Future<String> get sdkNameAndVersion async => 'Flutter Tools';
@override
Future<LaunchResult> startApp(ApplicationPackage? package, {
String? mainPath,
String? route,
required DebuggingOptions debuggingOptions,
Map<String, Object?> platformArgs = const <String, Object?>{},
bool prebuiltApplication = false,
bool ipv6 = false,
String? userIdentifier,
}) async {
final String? url = platformArgs['uri'] as String?;
if (debuggingOptions.startPaused) {
_logger.printStatus('Waiting for connection from Dart debug extension at $url', emphasis: true);
} else {
_logger.printStatus('$mainPath is being served at $url', emphasis: true);
}
_logger.printStatus(
'The web-server device requires the Dart Debug Chrome extension for debugging. '
'Consider using the Chrome or Edge devices for an improved development workflow.'
);
_logger.sendEvent('app.webLaunchUrl', <String, Object?>{'url': url, 'launched': false});
return LaunchResult.succeeded(vmServiceUri: url != null ? Uri.parse(url): null);
}
@override
Future<bool> stopApp(
ApplicationPackage? app, {
String? userIdentifier,
}) async {
return true;
}
@override
Future<TargetPlatform> get targetPlatform async => TargetPlatform.web_javascript;
@override
Future<bool> uninstallApp(
ApplicationPackage app, {
String? userIdentifier,
}) async {
return true;
}
@override
Future<void> dispose() async {
_logReader?.dispose();
await portForwarder?.dispose();
}
}
| flutter/packages/flutter_tools/lib/src/web/web_device.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/web/web_device.dart",
"repo_id": "flutter",
"token_count": 4959
} | 759 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'base/error_handling_io.dart';
import 'base/file_system.dart';
import 'base/utils.dart';
import 'build_info.dart';
import 'bundle.dart' as bundle;
import 'convert.dart';
import 'flutter_plugins.dart';
import 'globals.dart' as globals;
import 'ios/code_signing.dart';
import 'ios/plist_parser.dart';
import 'ios/xcode_build_settings.dart' as xcode;
import 'ios/xcodeproj.dart';
import 'platform_plugins.dart';
import 'project.dart';
import 'template.dart';
/// Represents an Xcode-based sub-project.
///
/// This defines interfaces common to iOS and macOS projects.
abstract class XcodeBasedProject extends FlutterProjectPlatform {
static const String _defaultHostAppName = 'Runner';
/// The Xcode workspace (.xcworkspace directory) of the host app.
Directory? get xcodeWorkspace {
if (!hostAppRoot.existsSync()) {
return null;
}
return _xcodeDirectoryWithExtension('.xcworkspace');
}
/// The project name (.xcodeproj basename) of the host app.
late final String hostAppProjectName = () {
if (!hostAppRoot.existsSync()) {
return _defaultHostAppName;
}
final Directory? xcodeProjectDirectory = _xcodeDirectoryWithExtension('.xcodeproj');
return xcodeProjectDirectory != null
? xcodeProjectDirectory.fileSystem.path.basenameWithoutExtension(xcodeProjectDirectory.path)
: _defaultHostAppName;
}();
Directory? _xcodeDirectoryWithExtension(String extension) {
final List<FileSystemEntity> contents = hostAppRoot.listSync();
for (final FileSystemEntity entity in contents) {
if (globals.fs.path.extension(entity.path) == extension && !globals.fs.path.basename(entity.path).startsWith('.')) {
return hostAppRoot.childDirectory(entity.basename);
}
}
return null;
}
/// The parent of this project.
FlutterProject get parent;
Directory get hostAppRoot;
/// The default 'Info.plist' file of the host app. The developer can change this location in Xcode.
File get defaultHostInfoPlist => hostAppRoot.childDirectory(_defaultHostAppName).childFile('Info.plist');
/// The Xcode project (.xcodeproj directory) of the host app.
Directory get xcodeProject => hostAppRoot.childDirectory('$hostAppProjectName.xcodeproj');
/// The 'project.pbxproj' file of [xcodeProject].
File get xcodeProjectInfoFile => xcodeProject.childFile('project.pbxproj');
/// The 'Runner.xcscheme' file of [xcodeProject].
File xcodeProjectSchemeFile({String? scheme}) {
final String schemeName = scheme ?? 'Runner';
return xcodeProject.childDirectory('xcshareddata').childDirectory('xcschemes').childFile('$schemeName.xcscheme');
}
File get xcodeProjectWorkspaceData =>
xcodeProject
.childDirectory('project.xcworkspace')
.childFile('contents.xcworkspacedata');
/// Xcode workspace shared data directory for the host app.
Directory? get xcodeWorkspaceSharedData => xcodeWorkspace?.childDirectory('xcshareddata');
/// Xcode workspace shared workspace settings file for the host app.
File? get xcodeWorkspaceSharedSettings => xcodeWorkspaceSharedData?.childFile('WorkspaceSettings.xcsettings');
/// Contains definitions for FLUTTER_ROOT, LOCAL_ENGINE, and more flags for
/// the Xcode build.
File get generatedXcodePropertiesFile;
/// The Flutter-managed Xcode config file for [mode].
File xcodeConfigFor(String mode);
/// The script that exports environment variables needed for Flutter tools.
/// Can be run first in a Xcode Script build phase to make FLUTTER_ROOT,
/// LOCAL_ENGINE, and other Flutter variables available to any flutter
/// tooling (`flutter build`, etc) to convert into flags.
File get generatedEnvironmentVariableExportScript;
/// The CocoaPods 'Podfile'.
File get podfile => hostAppRoot.childFile('Podfile');
/// The CocoaPods 'Podfile.lock'.
File get podfileLock => hostAppRoot.childFile('Podfile.lock');
/// The CocoaPods 'Manifest.lock'.
File get podManifestLock => hostAppRoot.childDirectory('Pods').childFile('Manifest.lock');
/// The CocoaPods generated 'Pods-Runner-frameworks.sh'.
File get podRunnerFrameworksScript => podRunnerTargetSupportFiles
.childFile('Pods-Runner-frameworks.sh');
/// The CocoaPods generated directory 'Pods-Runner'.
Directory get podRunnerTargetSupportFiles => hostAppRoot
.childDirectory('Pods')
.childDirectory('Target Support Files')
.childDirectory('Pods-Runner');
}
/// Represents the iOS sub-project of a Flutter project.
///
/// Instances will reflect the contents of the `ios/` sub-folder of
/// Flutter applications and the `.ios/` sub-folder of Flutter module projects.
class IosProject extends XcodeBasedProject {
IosProject.fromFlutter(this.parent);
@override
final FlutterProject parent;
@override
String get pluginConfigKey => IOSPlugin.kConfigKey;
// build setting keys
static const String kProductBundleIdKey = 'PRODUCT_BUNDLE_IDENTIFIER';
static const String kTeamIdKey = 'DEVELOPMENT_TEAM';
static const String kEntitlementFilePathKey = 'CODE_SIGN_ENTITLEMENTS';
static const String kHostAppBundleNameKey = 'FULL_PRODUCT_NAME';
static final RegExp _productBundleIdPattern = RegExp('^\\s*$kProductBundleIdKey\\s*=\\s*(["\']?)(.*?)\\1;\\s*\$');
static const String _kProductBundleIdVariable = '\$($kProductBundleIdKey)';
static final RegExp _associatedDomainPattern = RegExp(r'^applinks:(.*)');
Directory get ephemeralModuleDirectory => parent.directory.childDirectory('.ios');
Directory get _editableDirectory => parent.directory.childDirectory('ios');
/// This parent folder of `Runner.xcodeproj`.
@override
Directory get hostAppRoot {
if (!isModule || _editableDirectory.existsSync()) {
return _editableDirectory;
}
return ephemeralModuleDirectory;
}
/// The root directory of the iOS wrapping of Flutter and plugins. This is the
/// parent of the `Flutter/` folder into which Flutter artifacts are written
/// during build.
///
/// This is the same as [hostAppRoot] except when the project is
/// a Flutter module with an editable host app.
Directory get _flutterLibRoot => isModule ? ephemeralModuleDirectory : _editableDirectory;
/// True, if the parent Flutter project is a module project.
bool get isModule => parent.isModule;
/// Whether the Flutter application has an iOS project.
bool get exists => hostAppRoot.existsSync();
/// Put generated files here.
Directory get ephemeralDirectory => _flutterLibRoot.childDirectory('Flutter').childDirectory('ephemeral');
@override
File xcodeConfigFor(String mode) => _flutterLibRoot.childDirectory('Flutter').childFile('$mode.xcconfig');
@override
File get generatedEnvironmentVariableExportScript => _flutterLibRoot.childDirectory('Flutter').childFile('flutter_export_environment.sh');
File get appFrameworkInfoPlist => _flutterLibRoot.childDirectory('Flutter').childFile('AppFrameworkInfo.plist');
File get infoPlist => _editableDirectory.childDirectory('Runner').childFile('Info.plist');
Directory get symlinks => _flutterLibRoot.childDirectory('.symlinks');
/// True, if the app project is using swift.
bool get isSwift {
final File appDelegateSwift = _editableDirectory.childDirectory('Runner').childFile('AppDelegate.swift');
return appDelegateSwift.existsSync();
}
/// Do all plugins support arm64 simulators to run natively on an ARM Mac?
Future<bool> pluginsSupportArmSimulator() async {
final Directory podXcodeProject = hostAppRoot
.childDirectory('Pods')
.childDirectory('Pods.xcodeproj');
if (!podXcodeProject.existsSync()) {
// No plugins.
return true;
}
final XcodeProjectInterpreter? xcodeProjectInterpreter = globals.xcodeProjectInterpreter;
if (xcodeProjectInterpreter == null) {
// Xcode isn't installed, don't try to check.
return false;
}
final String? buildSettings = await xcodeProjectInterpreter.pluginsBuildSettingsOutput(podXcodeProject);
// See if any plugins or their dependencies exclude arm64 simulators
// as a valid architecture, usually because a binary is missing that slice.
// Example: EXCLUDED_ARCHS = arm64 i386
// NOT: EXCLUDED_ARCHS = i386
return buildSettings != null && !buildSettings.contains(RegExp('EXCLUDED_ARCHS.*arm64'));
}
@override
bool existsSync() {
return parent.isModule || _editableDirectory.existsSync();
}
/// Outputs universal link related project settings of the iOS sub-project into
/// a json file.
///
/// The return future will resolve to string path to the output file.
Future<String> outputsUniversalLinkSettings({
required String configuration,
required String target,
}) async {
final XcodeProjectBuildContext context = XcodeProjectBuildContext(
configuration: configuration,
target: target,
);
final File file = await parent.buildDirectory
.childDirectory('deeplink_data')
.childFile('universal-link-settings-$configuration-$target.json')
.create(recursive: true);
await file.writeAsString(jsonEncode(<String, Object?>{
'bundleIdentifier': await _productBundleIdentifierWithBuildContext(context),
'teamIdentifier': await _getTeamIdentifier(context),
'associatedDomains': await _getAssociatedDomains(context),
}));
return file.absolute.path;
}
/// The product bundle identifier of the host app, or null if not set or if
/// iOS tooling needed to read it is not installed.
Future<String?> productBundleIdentifier(BuildInfo? buildInfo) async {
if (!existsSync()) {
return null;
}
XcodeProjectBuildContext? buildContext;
final XcodeProjectInfo? info = await projectInfo();
if (info != null) {
final String? scheme = info.schemeFor(buildInfo);
if (scheme == null) {
info.reportFlavorNotFoundAndExit();
}
final String? configuration = info.buildConfigurationFor(
buildInfo,
scheme,
);
buildContext = XcodeProjectBuildContext(
configuration: configuration,
scheme: scheme,
);
}
return _productBundleIdentifierWithBuildContext(buildContext);
}
Future<String?> _productBundleIdentifierWithBuildContext(XcodeProjectBuildContext? buildContext) async {
if (!existsSync()) {
return null;
}
if (_productBundleIdentifiers.containsKey(buildContext)) {
return _productBundleIdentifiers[buildContext];
}
return _productBundleIdentifiers[buildContext] = await _parseProductBundleIdentifier(buildContext);
}
final Map<XcodeProjectBuildContext?, String?> _productBundleIdentifiers = <XcodeProjectBuildContext?, String?>{};
Future<String?> _parseProductBundleIdentifier(XcodeProjectBuildContext? buildContext) async {
String? fromPlist;
final File defaultInfoPlist = defaultHostInfoPlist;
// Users can change the location of the Info.plist.
// Try parsing the default, first.
if (defaultInfoPlist.existsSync()) {
try {
fromPlist = globals.plistParser.getValueFromFile<String>(
defaultHostInfoPlist.path,
PlistParser.kCFBundleIdentifierKey,
);
} on FileNotFoundException {
// iOS tooling not found; likely not running OSX; let [fromPlist] be null
}
if (fromPlist != null && !fromPlist.contains(r'$')) {
// Info.plist has no build variables in product bundle ID.
return fromPlist;
}
}
if (buildContext == null) {
// Getting build settings to evaluate info.Plist requires a context.
return null;
}
final Map<String, String>? allBuildSettings = await _buildSettingsForXcodeProjectBuildContext(buildContext);
if (allBuildSettings != null) {
if (fromPlist != null) {
// Perform variable substitution using build settings.
return substituteXcodeVariables(fromPlist, allBuildSettings);
}
return allBuildSettings[kProductBundleIdKey];
}
// On non-macOS platforms, parse the first PRODUCT_BUNDLE_IDENTIFIER from
// the project file. This can return the wrong bundle identifier if additional
// bundles have been added to the project and are found first, like frameworks
// or companion watchOS projects. However, on non-macOS platforms this is
// only used for display purposes and to regenerate organization names, so
// best-effort is probably fine.
final String? fromPbxproj = firstMatchInFile(xcodeProjectInfoFile, _productBundleIdPattern)?.group(2);
if (fromPbxproj != null && (fromPlist == null || fromPlist == _kProductBundleIdVariable)) {
return fromPbxproj;
}
return null;
}
Future<String?> _getTeamIdentifier(XcodeProjectBuildContext buildContext) async {
final Map<String, String>? buildSettings = await _buildSettingsForXcodeProjectBuildContext(buildContext);
return buildSettings?[kTeamIdKey];
}
Future<List<String>> _getAssociatedDomains(XcodeProjectBuildContext buildContext) async {
final Map<String, String>? buildSettings = await _buildSettingsForXcodeProjectBuildContext(buildContext);
if (buildSettings != null) {
final String? entitlementPath = buildSettings[kEntitlementFilePathKey];
if (entitlementPath != null) {
final File entitlement = hostAppRoot.childFile(entitlementPath);
if (entitlement.existsSync()) {
final List<String>? domains = globals.plistParser.getValueFromFile<List<Object>>(
entitlement.path,
PlistParser.kAssociatedDomainsKey,
)?.cast<String>();
if (domains != null) {
final List<String> result = <String>[];
for (final String domain in domains) {
final RegExpMatch? match = _associatedDomainPattern.firstMatch(domain);
if (match != null) {
result.add(match.group(1)!);
}
}
return result;
}
}
}
}
return const <String>[];
}
/// The bundle name of the host app, `My App.app`.
Future<String?> hostAppBundleName(BuildInfo? buildInfo) async {
if (!existsSync()) {
return null;
}
return _hostAppBundleName ??= await _parseHostAppBundleName(buildInfo);
}
String? _hostAppBundleName;
Future<String> _parseHostAppBundleName(BuildInfo? buildInfo) async {
// The product name and bundle name are derived from the display name, which the user
// is instructed to change in Xcode as part of deploying to the App Store.
// https://flutter.dev/docs/deployment/ios#review-xcode-project-settings
// The only source of truth for the name is Xcode's interpretation of the build settings.
String? productName;
if (globals.xcodeProjectInterpreter?.isInstalled ?? false) {
final Map<String, String>? xcodeBuildSettings = await buildSettingsForBuildInfo(buildInfo);
if (xcodeBuildSettings != null) {
productName = xcodeBuildSettings[kHostAppBundleNameKey];
}
}
if (productName == null) {
globals.printTrace('$kHostAppBundleNameKey not present, defaulting to $hostAppProjectName');
}
return productName ?? '${XcodeBasedProject._defaultHostAppName}.app';
}
/// The build settings for the host app of this project, as a detached map.
///
/// Returns null, if iOS tooling is unavailable.
Future<Map<String, String>?> buildSettingsForBuildInfo(
BuildInfo? buildInfo, {
String? scheme,
String? configuration,
String? target,
EnvironmentType environmentType = EnvironmentType.physical,
String? deviceId,
bool isWatch = false,
}) async {
if (!existsSync()) {
return null;
}
final XcodeProjectInfo? info = await projectInfo();
if (info == null) {
return null;
}
scheme ??= info.schemeFor(buildInfo);
if (scheme == null) {
info.reportFlavorNotFoundAndExit();
}
configuration ??= (await projectInfo())?.buildConfigurationFor(
buildInfo,
scheme,
);
return _buildSettingsForXcodeProjectBuildContext(
XcodeProjectBuildContext(
environmentType: environmentType,
scheme: scheme,
configuration: configuration,
target: target,
deviceId: deviceId,
isWatch: isWatch,
),
);
}
Future<Map<String, String>?> _buildSettingsForXcodeProjectBuildContext(XcodeProjectBuildContext buildContext) async {
if (!existsSync()) {
return null;
}
final Map<String, String>? currentBuildSettings = _buildSettingsByBuildContext[buildContext];
if (currentBuildSettings == null) {
final Map<String, String>? calculatedBuildSettings = await _xcodeProjectBuildSettings(buildContext);
if (calculatedBuildSettings != null) {
_buildSettingsByBuildContext[buildContext] = calculatedBuildSettings;
}
}
return _buildSettingsByBuildContext[buildContext];
}
final Map<XcodeProjectBuildContext, Map<String, String>> _buildSettingsByBuildContext = <XcodeProjectBuildContext, Map<String, String>>{};
Future<XcodeProjectInfo?> projectInfo() async {
final XcodeProjectInterpreter? xcodeProjectInterpreter = globals.xcodeProjectInterpreter;
if (!xcodeProject.existsSync() || xcodeProjectInterpreter == null || !xcodeProjectInterpreter.isInstalled) {
return null;
}
return _projectInfo ??= await xcodeProjectInterpreter.getInfo(hostAppRoot.path);
}
XcodeProjectInfo? _projectInfo;
Future<Map<String, String>?> _xcodeProjectBuildSettings(XcodeProjectBuildContext buildContext) async {
final XcodeProjectInterpreter? xcodeProjectInterpreter = globals.xcodeProjectInterpreter;
if (xcodeProjectInterpreter == null || !xcodeProjectInterpreter.isInstalled) {
return null;
}
final Map<String, String> buildSettings = await xcodeProjectInterpreter.getBuildSettings(
xcodeProject.path,
buildContext: buildContext,
);
if (buildSettings.isNotEmpty) {
// No timeouts, flakes, or errors.
return buildSettings;
}
return null;
}
Future<void> ensureReadyForPlatformSpecificTooling() async {
await _regenerateFromTemplateIfNeeded();
if (!_flutterLibRoot.existsSync()) {
return;
}
await _updateGeneratedXcodeConfigIfNeeded();
}
/// Check if one the [targets] of the project is a watchOS companion app target.
Future<bool> containsWatchCompanion({
required XcodeProjectInfo projectInfo,
required BuildInfo buildInfo,
String? deviceId,
}) async {
final String? bundleIdentifier = await productBundleIdentifier(buildInfo);
// A bundle identifier is required for a companion app.
if (bundleIdentifier == null) {
return false;
}
for (final String target in projectInfo.targets) {
// Create Info.plist file of the target.
final File infoFile = hostAppRoot.childDirectory(target).childFile('Info.plist');
// In older versions of Xcode, if the target was a watchOS companion app,
// the Info.plist file of the target contained the key WKCompanionAppBundleIdentifier.
if (infoFile.existsSync()) {
final String? fromPlist = globals.plistParser.getValueFromFile<String>(infoFile.path, 'WKCompanionAppBundleIdentifier');
if (bundleIdentifier == fromPlist) {
return true;
}
// The key WKCompanionAppBundleIdentifier might contain an xcode variable
// that needs to be substituted before comparing it with bundle id
if (fromPlist != null && fromPlist.contains(r'$')) {
final Map<String, String>? allBuildSettings = await buildSettingsForBuildInfo(buildInfo, deviceId: deviceId);
if (allBuildSettings != null) {
final String substitutedVariable = substituteXcodeVariables(fromPlist, allBuildSettings);
if (substitutedVariable == bundleIdentifier) {
return true;
}
}
}
}
}
// If key not found in Info.plist above, do more expensive check of build settings.
// In newer versions of Xcode, the build settings of the watchOS companion
// app's scheme should contain the key INFOPLIST_KEY_WKCompanionAppBundleIdentifier.
final bool watchIdentifierFound = xcodeProjectInfoFile.readAsStringSync().contains('WKCompanionAppBundleIdentifier');
if (!watchIdentifierFound) {
return false;
}
final String? defaultScheme = projectInfo.schemeFor(buildInfo);
if (defaultScheme == null) {
projectInfo.reportFlavorNotFoundAndExit();
}
for (final String scheme in projectInfo.schemes) {
// the default scheme should not be a watch scheme, so skip it
if (scheme == defaultScheme) {
continue;
}
final Map<String, String>? allBuildSettings = await buildSettingsForBuildInfo(
buildInfo,
deviceId: deviceId,
scheme: scheme,
isWatch: true,
);
if (allBuildSettings != null) {
final String? fromBuild = allBuildSettings['INFOPLIST_KEY_WKCompanionAppBundleIdentifier'];
if (bundleIdentifier == fromBuild) {
return true;
}
if (fromBuild != null && fromBuild.contains(r'$')) {
final String substitutedVariable = substituteXcodeVariables(fromBuild, allBuildSettings);
if (substitutedVariable == bundleIdentifier) {
return true;
}
}
}
}
return false;
}
Future<void> _updateGeneratedXcodeConfigIfNeeded() async {
if (globals.cache.isOlderThanToolsStamp(generatedXcodePropertiesFile)) {
await xcode.updateGeneratedXcodeProperties(
project: parent,
buildInfo: BuildInfo.debug,
targetOverride: bundle.defaultMainPath,
);
}
}
Future<void> _regenerateFromTemplateIfNeeded() async {
if (!isModule) {
return;
}
final bool pubspecChanged = globals.fsUtils.isOlderThanReference(
entity: ephemeralModuleDirectory,
referenceFile: parent.pubspecFile,
);
final bool toolingChanged = globals.cache.isOlderThanToolsStamp(ephemeralModuleDirectory);
if (!pubspecChanged && !toolingChanged) {
return;
}
ErrorHandlingFileSystem.deleteIfExists(ephemeralModuleDirectory, recursive: true);
await _overwriteFromTemplate(
globals.fs.path.join('module', 'ios', 'library'),
ephemeralModuleDirectory,
);
// Add ephemeral host app, if a editable host app does not already exist.
if (!_editableDirectory.existsSync()) {
await _overwriteFromTemplate(
globals.fs.path.join('module', 'ios', 'host_app_ephemeral'),
ephemeralModuleDirectory,
);
if (hasPlugins(parent)) {
await _overwriteFromTemplate(
globals.fs.path.join('module', 'ios', 'host_app_ephemeral_cocoapods'),
ephemeralModuleDirectory,
);
}
}
}
@override
File get generatedXcodePropertiesFile => _flutterLibRoot
.childDirectory('Flutter')
.childFile('Generated.xcconfig');
/// No longer compiled to this location.
///
/// Used only for "flutter clean" to remove old references.
Directory get deprecatedCompiledDartFramework => _flutterLibRoot
.childDirectory('Flutter')
.childDirectory('App.framework');
/// No longer copied to this location.
///
/// Used only for "flutter clean" to remove old references.
Directory get deprecatedProjectFlutterFramework => _flutterLibRoot
.childDirectory('Flutter')
.childDirectory('Flutter.framework');
/// Used only for "flutter clean" to remove old references.
File get flutterPodspec => _flutterLibRoot
.childDirectory('Flutter')
.childFile('Flutter.podspec');
Directory get pluginRegistrantHost {
return isModule
? _flutterLibRoot
.childDirectory('Flutter')
.childDirectory('FlutterPluginRegistrant')
: hostAppRoot.childDirectory(XcodeBasedProject._defaultHostAppName);
}
File get pluginRegistrantHeader {
final Directory registryDirectory = isModule ? pluginRegistrantHost.childDirectory('Classes') : pluginRegistrantHost;
return registryDirectory.childFile('GeneratedPluginRegistrant.h');
}
File get pluginRegistrantImplementation {
final Directory registryDirectory = isModule ? pluginRegistrantHost.childDirectory('Classes') : pluginRegistrantHost;
return registryDirectory.childFile('GeneratedPluginRegistrant.m');
}
Future<void> _overwriteFromTemplate(String path, Directory target) async {
final Template template = await Template.fromName(
path,
fileSystem: globals.fs,
templateManifest: null,
logger: globals.logger,
templateRenderer: globals.templateRenderer,
);
final String iosBundleIdentifier = parent.manifest.iosBundleIdentifier ?? 'com.example.${parent.manifest.appName}';
final String? iosDevelopmentTeam = await getCodeSigningIdentityDevelopmentTeam(
processManager: globals.processManager,
platform: globals.platform,
logger: globals.logger,
config: globals.config,
terminal: globals.terminal,
);
final String projectName = parent.manifest.appName;
// The dart project_name is in snake_case, this variable is the Title Case of the Project Name.
final String titleCaseProjectName = snakeCaseToTitleCase(projectName);
template.render(
target,
<String, Object>{
'ios': true,
'projectName': projectName,
'titleCaseProjectName': titleCaseProjectName,
'iosIdentifier': iosBundleIdentifier,
'hasIosDevelopmentTeam': iosDevelopmentTeam != null && iosDevelopmentTeam.isNotEmpty,
'iosDevelopmentTeam': iosDevelopmentTeam ?? '',
},
printStatusWhenWriting: false,
);
}
}
/// The macOS sub project.
class MacOSProject extends XcodeBasedProject {
MacOSProject.fromFlutter(this.parent);
@override
final FlutterProject parent;
@override
String get pluginConfigKey => MacOSPlugin.kConfigKey;
@override
bool existsSync() => hostAppRoot.existsSync();
@override
Directory get hostAppRoot => parent.directory.childDirectory('macos');
/// The directory in the project that is managed by Flutter. As much as
/// possible, files that are edited by Flutter tooling after initial project
/// creation should live here.
Directory get managedDirectory => hostAppRoot.childDirectory('Flutter');
/// The subdirectory of [managedDirectory] that contains files that are
/// generated on the fly. All generated files that are not intended to be
/// checked in should live here.
Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral');
/// The xcfilelist used to track the inputs for the Flutter script phase in
/// the Xcode build.
File get inputFileList => ephemeralDirectory.childFile('FlutterInputs.xcfilelist');
/// The xcfilelist used to track the outputs for the Flutter script phase in
/// the Xcode build.
File get outputFileList => ephemeralDirectory.childFile('FlutterOutputs.xcfilelist');
@override
File get generatedXcodePropertiesFile => ephemeralDirectory.childFile('Flutter-Generated.xcconfig');
File get pluginRegistrantImplementation => managedDirectory.childFile('GeneratedPluginRegistrant.swift');
@override
File xcodeConfigFor(String mode) => managedDirectory.childFile('Flutter-$mode.xcconfig');
@override
File get generatedEnvironmentVariableExportScript => ephemeralDirectory.childFile('flutter_export_environment.sh');
/// The file where the Xcode build will write the name of the built app.
///
/// Ideally this will be replaced in the future with inspection of the Runner
/// scheme's target.
File get nameFile => ephemeralDirectory.childFile('.app_filename');
Future<void> ensureReadyForPlatformSpecificTooling() async {
// TODO(stuartmorgan): Add create-from-template logic here.
await _updateGeneratedXcodeConfigIfNeeded();
}
Future<void> _updateGeneratedXcodeConfigIfNeeded() async {
if (globals.cache.isOlderThanToolsStamp(generatedXcodePropertiesFile)) {
await xcode.updateGeneratedXcodeProperties(
project: parent,
buildInfo: BuildInfo.debug,
useMacOSConfig: true,
);
}
}
}
| flutter/packages/flutter_tools/lib/src/xcode_project.dart/0 | {
"file_path": "flutter/packages/flutter_tools/lib/src/xcode_project.dart",
"repo_id": "flutter",
"token_count": 9536
} | 760 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| flutter/packages/flutter_tools/templates/app_shared/macos.tmpl/Runner/Configs/Release.xcconfig/0 | {
"file_path": "flutter/packages/flutter_tools/templates/app_shared/macos.tmpl/Runner/Configs/Release.xcconfig",
"repo_id": "flutter",
"token_count": 32
} | 761 |
# Project-level configuration.
cmake_minimum_required(VERSION 3.14)
project({{projectName}} LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "{{projectName}}")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(VERSION 3.14...3.25)
# Define build configuration option.
get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(IS_MULTICONFIG)
set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
CACHE STRING "" FORCE)
else()
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
endif()
# Define settings for the Profile build mode.
set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
# Use Unicode for all projects.
add_definitions(-DUNICODE -D_UNICODE)
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_17)
target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")
target_compile_options(${TARGET} PRIVATE /EHsc)
target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")
target_compile_definitions(${TARGET} PRIVATE "$<$<CONFIG:Debug>:_DEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
{{#withPlatformChannelPluginHook}}
# Enable the test target.
set(include_{{pluginProjectName}}_tests TRUE)
{{/withPlatformChannelPluginHook}}
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# Support files are copied into place next to the executable, so that it can
# run in place. This is done instead of making a separate bundle (as on Linux)
# so that building and running from within Visual Studio will work.
set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")
# Make the "install" step default, as it's required to run.
set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
if(PLUGIN_BUNDLED_LIBRARIES)
install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
CONFIGURATIONS Profile;Release
COMPONENT Runtime)
| flutter/packages/flutter_tools/templates/app_shared/windows.tmpl/CMakeLists.txt.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/app_shared/windows.tmpl/CMakeLists.txt.tmpl",
"repo_id": "flutter",
"token_count": 1609
} | 762 |
// Generated file. Do not edit.
include ':app'
rootProject.name = 'android_generated'
setBinding(new Binding([gradle: this]))
evaluate(new File(settingsDir, 'include_flutter.groovy'))
| flutter/packages/flutter_tools/templates/module/android/host_app_ephemeral/settings.gradle.copy.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/module/android/host_app_ephemeral/settings.gradle.copy.tmpl",
"repo_id": "flutter",
"token_count": 61
} | 763 |
name: {{projectName}}
description: {{description}}
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
#
# This version is used _only_ for the Runner app, which is used if you just do
# a `flutter run` or a `flutter make-host-app-editable`. It has no impact
# on any other native host app that you embed your Flutter project into.
version: 1.0.0+1
environment:
sdk: {{dartSdkVersionBounds}}
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.6
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add Flutter specific assets to your application, add an assets section,
# like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add Flutter specific custom fonts to your application, add a fonts
# section here, in this "flutter" section. Each entry in this list should
# have a "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
# This section identifies your Flutter project as a module meant for
# embedding in a native host app. These identifiers should _not_ ordinarily
# be changed after generation - they are used to ensure that the tooling can
# maintain consistency when adding or modifying assets and plugins.
# They also do not have any bearing on your native host application's
# identifiers, which may be completely independent or the same as these.
module:
androidX: true
androidPackage: {{androidIdentifier}}
iosBundleIdentifier: {{iosIdentifier}}
| flutter/packages/flutter_tools/templates/module/common/pubspec.yaml.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/module/common/pubspec.yaml.tmpl",
"repo_id": "flutter",
"token_count": 1048
} | 764 |
# {{projectName}}
{{description}}
## Getting Started
This project is a starting point for a Flutter
[FFI package](https://docs.flutter.dev/development/platform-integration/c-interop),
a specialized package that includes native code directly invoked with Dart FFI.
## Project structure
This template uses the following structure:
* `src`: Contains the native source code, and a CmakeFile.txt file for building
that source code into a dynamic library.
* `lib`: Contains the Dart code that defines the API of the plugin, and which
calls into the native code using `dart:ffi`.
* `bin`: Contains the `build.dart` that performs the external native builds.
## Building and bundling native code
`build.dart` does the building of native components.
Bundling is done by Flutter based on the output from `build.dart`.
## Binding to native code
To use the native code, bindings in Dart are needed.
To avoid writing these by hand, they are generated from the header file
(`src/{{projectName}}.h`) by `package:ffigen`.
Regenerate the bindings by running `dart run ffigen --config ffigen.yaml`.
## Invoking native code
Very short-running native functions can be directly invoked from any isolate.
For example, see `sum` in `lib/{{projectName}}.dart`.
Longer-running functions should be invoked on a helper isolate to avoid
dropping frames in Flutter applications.
For example, see `sumAsync` in `lib/{{projectName}}.dart`.
## Flutter help
For help getting started with Flutter, view our
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
| flutter/packages/flutter_tools/templates/package_ffi/README.md.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/package_ffi/README.md.tmpl",
"repo_id": "flutter",
"token_count": 439
} | 765 |
// In order to *not* need this ignore, consider extracting the "web" version
// of your plugin as a separate package, instead of inlining it in the same
// package as the core of your plugin.
// ignore: avoid_web_libraries_in_flutter
import 'dart:html' as html show window;
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
import '{{projectName}}_platform_interface.dart';
/// A web implementation of the {{pluginDartClass}}Platform of the {{pluginDartClass}} plugin.
class {{pluginDartClass}}Web extends {{pluginDartClass}}Platform {
/// Constructs a {{pluginDartClass}}Web
{{pluginDartClass}}Web();
static void registerWith(Registrar registrar) {
{{pluginDartClass}}Platform.instance = {{pluginDartClass}}Web();
}
/// Returns a [String] containing the version of the platform.
@override
Future<String?> getPlatformVersion() async {
final version = html.window.navigator.userAgent;
return version;
}
}
| flutter/packages/flutter_tools/templates/plugin/lib/projectName_web.dart.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/plugin/lib/projectName_web.dart.tmpl",
"repo_id": "flutter",
"token_count": 281
} | 766 |
{
"appTitle": "{{projectName}}",
"@appTitle": {
"description": "The title of the application"
}
}
| flutter/packages/flutter_tools/templates/skeleton/lib/src/localization/app_en.arb.tmpl/0 | {
"file_path": "flutter/packages/flutter_tools/templates/skeleton/lib/src/localization/app_en.arb.tmpl",
"repo_id": "flutter",
"token_count": 40
} | 767 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build_ios_framework.dart';
import 'package:flutter_tools/src/commands/build_macos_framework.dart';
import 'package:flutter_tools/src/version.dart';
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fake_process_manager.dart';
import '../../src/fakes.dart';
import '../../src/test_build_system.dart';
void main() {
late MemoryFileSystem memoryFileSystem;
late Directory outputDirectory;
late FakePlatform fakePlatform;
setUpAll(() {
Cache.disableLocking();
});
const String storageBaseUrl = 'https://fake.googleapis.com';
setUp(() {
memoryFileSystem = MemoryFileSystem.test();
fakePlatform = FakePlatform(
operatingSystem: 'macos',
environment: <String, String>{
'FLUTTER_STORAGE_BASE_URL': storageBaseUrl,
},
);
outputDirectory = memoryFileSystem.systemTempDirectory
.createTempSync('flutter_build_framework_test_output.')
.childDirectory('Debug')
..createSync();
});
group('build ios-framework', () {
group('podspec', () {
const String engineRevision = '0123456789abcdef';
late Cache cache;
setUp(() {
final Directory rootOverride = memoryFileSystem.directory('cache');
cache = Cache.test(
rootOverride: rootOverride,
platform: fakePlatform,
fileSystem: memoryFileSystem,
processManager: FakeProcessManager.any(),
);
rootOverride.childDirectory('bin').childDirectory('internal').childFile('engine.version')
..createSync(recursive: true)
..writeAsStringSync(engineRevision);
});
testUsingContext('version unknown', () async {
const String frameworkVersion = '0.0.0-unknown';
final FakeFlutterVersion fakeFlutterVersion = FakeFlutterVersion(frameworkVersion: frameworkVersion);
final BuildIOSFrameworkCommand command = BuildIOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
expect(() => command.produceFlutterPodspec(BuildMode.debug, outputDirectory),
throwsToolExit(message: '--cocoapods is only supported on the beta or stable channel. Detected version is $frameworkVersion'));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('throws when not on a released version', () async {
const String frameworkVersion = 'v1.13.10+hotfix-pre.2';
const GitTagVersion gitTagVersion = GitTagVersion(
x: 1,
y: 13,
z: 10,
hotfix: 13,
commits: 2,
);
final FakeFlutterVersion fakeFlutterVersion = FakeFlutterVersion(
gitTagVersion: gitTagVersion,
frameworkVersion: frameworkVersion,
);
final BuildIOSFrameworkCommand command = BuildIOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
expect(() => command.produceFlutterPodspec(BuildMode.debug, outputDirectory),
throwsToolExit(message: '--cocoapods is only supported on the beta or stable channel. Detected version is $frameworkVersion'));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('throws when license not found', () async {
final FakeFlutterVersion fakeFlutterVersion = FakeFlutterVersion(
gitTagVersion: const GitTagVersion(
x: 1,
y: 13,
z: 10,
hotfix: 13,
commits: 0,
),
);
final BuildIOSFrameworkCommand command = BuildIOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
expect(() => command.produceFlutterPodspec(BuildMode.debug, outputDirectory),
throwsToolExit(message: 'Could not find license'));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
group('is created', () {
const String frameworkVersion = 'v1.13.11+hotfix.13';
const String licenseText = 'This is the license!';
setUp(() {
// cache.getLicenseFile() relies on the flutter root being set.
Cache.flutterRoot ??= getFlutterRoot();
cache.getLicenseFile()
..createSync(recursive: true)
..writeAsStringSync(licenseText);
});
group('on master channel', () {
testUsingContext('created when forced', () async {
const GitTagVersion gitTagVersion = GitTagVersion(
x: 1,
y: 13,
z: 11,
hotfix: 13,
commits: 100,
);
final FakeFlutterVersion fakeFlutterVersion = FakeFlutterVersion(
gitTagVersion: gitTagVersion,
frameworkVersion: frameworkVersion,
);
final BuildIOSFrameworkCommand command = BuildIOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.debug, outputDirectory, force: true);
final File expectedPodspec = outputDirectory.childFile('Flutter.podspec');
expect(expectedPodspec.existsSync(), isTrue);
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
group('not on master channel', () {
late FakeFlutterVersion fakeFlutterVersion;
setUp(() {
const GitTagVersion gitTagVersion = GitTagVersion(
x: 1,
y: 13,
z: 11,
hotfix: 13,
commits: 0,
);
fakeFlutterVersion = FakeFlutterVersion(
gitTagVersion: gitTagVersion,
frameworkVersion: frameworkVersion,
);
});
testUsingContext('contains license and version', () async {
final BuildIOSFrameworkCommand command = BuildIOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.debug, outputDirectory);
final File expectedPodspec = outputDirectory.childFile('Flutter.podspec');
final String podspecContents = expectedPodspec.readAsStringSync();
expect(podspecContents, contains("'1.13.1113'"));
expect(podspecContents, contains('# $frameworkVersion'));
expect(podspecContents, contains(licenseText));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('debug URL', () async {
final BuildIOSFrameworkCommand command = BuildIOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.debug, outputDirectory);
final File expectedPodspec = outputDirectory.childFile('Flutter.podspec');
final String podspecContents = expectedPodspec.readAsStringSync();
expect(podspecContents, contains("'$storageBaseUrl/flutter_infra_release/flutter/$engineRevision/ios/artifacts.zip'"));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('profile URL', () async {
final BuildIOSFrameworkCommand command = BuildIOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.profile, outputDirectory);
final File expectedPodspec = outputDirectory.childFile('Flutter.podspec');
final String podspecContents = expectedPodspec.readAsStringSync();
expect(podspecContents, contains("'$storageBaseUrl/flutter_infra_release/flutter/$engineRevision/ios-profile/artifacts.zip'"));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('release URL', () async {
final BuildIOSFrameworkCommand command = BuildIOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.release, outputDirectory);
final File expectedPodspec = outputDirectory.childFile('Flutter.podspec');
final String podspecContents = expectedPodspec.readAsStringSync();
expect(podspecContents, contains("'$storageBaseUrl/flutter_infra_release/flutter/$engineRevision/ios-release/artifacts.zip'"));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
});
});
});
group('build macos-framework', () {
group('podspec', () {
const String engineRevision = '0123456789abcdef';
late Cache cache;
setUp(() {
final Directory rootOverride = memoryFileSystem.directory('cache');
cache = Cache.test(
rootOverride: rootOverride,
platform: fakePlatform,
fileSystem: memoryFileSystem,
processManager: FakeProcessManager.any(),
);
rootOverride.childDirectory('bin').childDirectory('internal').childFile('engine.version')
..createSync(recursive: true)
..writeAsStringSync(engineRevision);
});
testUsingContext('version unknown', () async {
const String frameworkVersion = '0.0.0-unknown';
final FakeFlutterVersion fakeFlutterVersion = FakeFlutterVersion(frameworkVersion: frameworkVersion);
final BuildMacOSFrameworkCommand command = BuildMacOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
expect(() => command.produceFlutterPodspec(BuildMode.debug, outputDirectory),
throwsToolExit(message: '--cocoapods is only supported on the beta or stable channel. Detected version is $frameworkVersion'));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('throws when not on a released version', () async {
const String frameworkVersion = 'v1.13.10+hotfix-pre.2';
const GitTagVersion gitTagVersion = GitTagVersion(
x: 1,
y: 13,
z: 10,
hotfix: 13,
commits: 2,
);
final FakeFlutterVersion fakeFlutterVersion = FakeFlutterVersion(
gitTagVersion: gitTagVersion,
frameworkVersion: frameworkVersion,
);
final BuildMacOSFrameworkCommand command = BuildMacOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
expect(() => command.produceFlutterPodspec(BuildMode.debug, outputDirectory),
throwsToolExit(message: '--cocoapods is only supported on the beta or stable channel. Detected version is $frameworkVersion'));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('throws when license not found', () async {
final FakeFlutterVersion fakeFlutterVersion = FakeFlutterVersion(
gitTagVersion: const GitTagVersion(
x: 1,
y: 13,
z: 10,
hotfix: 13,
commits: 0,
),
);
final BuildMacOSFrameworkCommand command = BuildMacOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
expect(() => command.produceFlutterPodspec(BuildMode.debug, outputDirectory),
throwsToolExit(message: 'Could not find license'));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
group('is created', () {
const String frameworkVersion = 'v1.13.11+hotfix.13';
const String licenseText = 'This is the license!';
setUp(() {
// cache.getLicenseFile() relies on the flutter root being set.
Cache.flutterRoot ??= getFlutterRoot();
cache.getLicenseFile()
..createSync(recursive: true)
..writeAsStringSync(licenseText);
});
group('on master channel', () {
testUsingContext('created when forced', () async {
const GitTagVersion gitTagVersion = GitTagVersion(
x: 1,
y: 13,
z: 11,
hotfix: 13,
commits: 100,
);
final FakeFlutterVersion fakeFlutterVersion = FakeFlutterVersion(
gitTagVersion: gitTagVersion,
frameworkVersion: frameworkVersion,
);
final BuildMacOSFrameworkCommand command = BuildMacOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.debug, outputDirectory, force: true);
final File expectedPodspec = outputDirectory.childFile('FlutterMacOS.podspec');
expect(expectedPodspec.existsSync(), isTrue);
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
group('not on master channel', () {
late FakeFlutterVersion fakeFlutterVersion;
setUp(() {
const GitTagVersion gitTagVersion = GitTagVersion(
x: 1,
y: 13,
z: 11,
hotfix: 13,
commits: 0,
);
fakeFlutterVersion = FakeFlutterVersion(
gitTagVersion: gitTagVersion,
frameworkVersion: frameworkVersion,
);
});
testUsingContext('contains license and version', () async {
final BuildMacOSFrameworkCommand command = BuildMacOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.debug, outputDirectory);
final File expectedPodspec = outputDirectory.childFile('FlutterMacOS.podspec');
final String podspecContents = expectedPodspec.readAsStringSync();
expect(podspecContents, contains("'1.13.1113'"));
expect(podspecContents, contains('# $frameworkVersion'));
expect(podspecContents, contains(licenseText));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('debug URL', () async {
final BuildMacOSFrameworkCommand command = BuildMacOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.debug, outputDirectory);
final File expectedPodspec = outputDirectory.childFile('FlutterMacOS.podspec');
final String podspecContents = expectedPodspec.readAsStringSync();
expect(podspecContents, contains("'$storageBaseUrl/flutter_infra_release/flutter/$engineRevision/darwin-x64/FlutterMacOS.framework.zip'"));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('profile URL', () async {
final BuildMacOSFrameworkCommand command = BuildMacOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.profile, outputDirectory);
final File expectedPodspec = outputDirectory.childFile('FlutterMacOS.podspec');
final String podspecContents = expectedPodspec.readAsStringSync();
expect(podspecContents, contains("'$storageBaseUrl/flutter_infra_release/flutter/$engineRevision/darwin-x64-profile/FlutterMacOS.framework.zip'"));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('release URL', () async {
final BuildMacOSFrameworkCommand command = BuildMacOSFrameworkCommand(
logger: BufferLogger.test(),
buildSystem: TestBuildSystem.all(BuildResult(success: true)),
platform: fakePlatform,
flutterVersion: fakeFlutterVersion,
cache: cache,
verboseHelp: false,
);
command.produceFlutterPodspec(BuildMode.release, outputDirectory);
final File expectedPodspec = outputDirectory.childFile('FlutterMacOS.podspec');
final String podspecContents = expectedPodspec.readAsStringSync();
expect(podspecContents, contains("'$storageBaseUrl/flutter_infra_release/flutter/$engineRevision/darwin-x64-release/FlutterMacOS.framework.zip'"));
}, overrides: <Type, Generator>{
FileSystem: () => memoryFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
});
});
});
group('XCFrameworks', () {
late MemoryFileSystem fileSystem;
late FakeProcessManager fakeProcessManager;
setUp(() {
fileSystem = MemoryFileSystem.test();
fakeProcessManager = FakeProcessManager.empty();
});
testWithoutContext('created', () async {
final Directory frameworkA = fileSystem.directory('FrameworkA.framework')..createSync();
final Directory frameworkB = fileSystem.directory('FrameworkB.framework')..createSync();
final Directory output = fileSystem.directory('output');
fakeProcessManager.addCommand(FakeCommand(
command: <String>[
'xcrun',
'xcodebuild',
'-create-xcframework',
'-framework',
frameworkA.path,
'-framework',
frameworkB.path,
'-output',
output.childDirectory('Combine.xcframework').path,
],
));
await BuildFrameworkCommand.produceXCFramework(
<Directory>[frameworkA, frameworkB],
'Combine',
output,
fakeProcessManager,
);
expect(fakeProcessManager, hasNoRemainingExpectations);
});
testWithoutContext('created with symbols', () async {
final Directory parentA = fileSystem.directory('FrameworkA')..createSync();
final File dSYMA = parentA.childFile('FrameworkA.framework.dSYM')..createSync();
final Directory frameworkA = parentA.childDirectory('FrameworkA.framework')..createSync();
final Directory parentB = fileSystem.directory('FrameworkB')..createSync();
final File dSYMB = parentB.childFile('FrameworkB.framework.dSYM')..createSync();
final Directory frameworkB = parentB.childDirectory('FrameworkB.framework')..createSync();
final Directory output = fileSystem.directory('output');
fakeProcessManager.addCommand(FakeCommand(
command: <String>[
'xcrun',
'xcodebuild',
'-create-xcframework',
'-framework',
frameworkA.path,
'-debug-symbols',
dSYMA.path,
'-framework',
frameworkB.path,
'-debug-symbols',
dSYMB.path,
'-output',
output.childDirectory('Combine.xcframework').path,
],
));
await BuildFrameworkCommand.produceXCFramework(
<Directory>[frameworkA, frameworkB],
'Combine',
output,
fakeProcessManager,
);
expect(fakeProcessManager, hasNoRemainingExpectations);
});
});
}
| flutter/packages/flutter_tools/test/commands.shard/hermetic/build_darwin_framework_test.dart/0 | {
"file_path": "flutter/packages/flutter_tools/test/commands.shard/hermetic/build_darwin_framework_test.dart",
"repo_id": "flutter",
"token_count": 10018
} | 768 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.