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:math' as math; import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; import 'feedback_tester.dart'; class TestIcon extends StatefulWidget { const TestIcon({ super.key }); @override TestIconState createState() => TestIconState(); } class TestIconState extends State<TestIcon> { late IconThemeData iconTheme; @override Widget build(BuildContext context) { iconTheme = IconTheme.of(context); return const Icon(Icons.add); } } class TestText extends StatefulWidget { const TestText(this.text, { super.key }); final String text; @override TestTextState createState() => TestTextState(); } class TestTextState extends State<TestText> { late TextStyle textStyle; @override Widget build(BuildContext context) { textStyle = DefaultTextStyle.of(context).style; return Text(widget.text); } } void main() { testWidgets('ListTile geometry (LTR)', (WidgetTester tester) async { // See https://material.io/go/design-lists final Key leadingKey = GlobalKey(); final Key trailingKey = GlobalKey(); late bool hasSubtitle; const double leftPadding = 10.0; const double rightPadding = 20.0; Widget buildFrame({ bool dense = false, bool isTwoLine = false, bool isThreeLine = false, TextScaler textScaler = TextScaler.noScaling, TextScaler? subtitleScaler }) { hasSubtitle = isTwoLine || isThreeLine; subtitleScaler ??= textScaler; return MaterialApp( theme: ThemeData(useMaterial3: true), home: MediaQuery( data: MediaQueryData( padding: const EdgeInsets.only(left: leftPadding, right: rightPadding), textScaler: textScaler, ), child: Material( child: Center( child: ListTile( leading: SizedBox(key: leadingKey, width: 24.0, height: 24.0), title: const Text('title'), subtitle: hasSubtitle ? Text('subtitle', textScaler: subtitleScaler) : null, trailing: SizedBox(key: trailingKey, width: 24.0, height: 24.0), dense: dense, isThreeLine: isThreeLine, ), ), ), ), ); } void testChildren() { expect(find.byKey(leadingKey), findsOneWidget); expect(find.text('title'), findsOneWidget); if (hasSubtitle) { expect(find.text('subtitle'), findsOneWidget); } expect(find.byKey(trailingKey), findsOneWidget); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double top(String text) => tester.getTopLeft(find.text(text)).dy; double bottom(String text) => tester.getBottomLeft(find.text(text)).dy; double height(String text) => tester.getRect(find.text(text)).height; double leftKey(Key key) => tester.getTopLeft(find.byKey(key)).dx; double rightKey(Key key) => tester.getTopRight(find.byKey(key)).dx; double widthKey(Key key) => tester.getSize(find.byKey(key)).width; double heightKey(Key key) => tester.getSize(find.byKey(key)).height; // ListTiles are contained by a SafeArea defined like this: // SafeArea(top: false, bottom: false, minimum: contentPadding) // The default contentPadding is 16.0 on the left and 24.0 on the right. void testHorizontalGeometry() { expect(leftKey(leadingKey), math.max(16.0, leftPadding)); expect(left('title'), 40.0 + math.max(16.0, leftPadding)); if (hasSubtitle) { expect(left('subtitle'), 40.0 + math.max(16.0, leftPadding)); } expect(left('title'), rightKey(leadingKey) + 16.0); expect(rightKey(trailingKey), 800.0 - math.max(24.0, rightPadding)); expect(widthKey(trailingKey), 24.0); } void testVerticalGeometry(double expectedHeight) { final Rect tileRect = tester.getRect(find.byType(ListTile)); expect(tileRect.size, Size(800.0, expectedHeight)); expect(top('title'), greaterThanOrEqualTo(tileRect.top)); if (hasSubtitle) { expect(top('subtitle'), greaterThanOrEqualTo(bottom('title'))); expect(bottom('subtitle'), lessThan(tileRect.bottom)); } else { expect(top('title'), equals(tileRect.top + (tileRect.height - height('title')) / 2.0)); } expect(heightKey(trailingKey), 24.0); } await tester.pumpWidget(buildFrame()); testChildren(); testHorizontalGeometry(); testVerticalGeometry(56.0); await tester.pumpWidget(buildFrame(isTwoLine: true)); testChildren(); testHorizontalGeometry(); testVerticalGeometry(72.0); await tester.pumpWidget(buildFrame(isThreeLine: true)); testChildren(); testHorizontalGeometry(); testVerticalGeometry(88.0); await tester.pumpWidget(buildFrame(textScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); testVerticalGeometry(112.0); await tester.pumpWidget(buildFrame(isTwoLine: true, textScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933 testVerticalGeometry(192.0); } // Make sure that the height of a large subtitle is taken into account. await tester.pumpWidget(buildFrame(isTwoLine: true, textScaler: const TextScaler.linear(0.5), subtitleScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933 testVerticalGeometry(108.0); } await tester.pumpWidget(buildFrame(isThreeLine: true, textScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933 testVerticalGeometry(192.0); } }); testWidgets('ListTile geometry (RTL)', (WidgetTester tester) async { const double leftPadding = 10.0; const double rightPadding = 20.0; await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: true), home: const MediaQuery( data: MediaQueryData( padding: EdgeInsets.only(left: leftPadding, right: rightPadding), ), child: Directionality( textDirection: TextDirection.rtl, child: Material( child: Center( child: ListTile( leading: Text('L'), title: Text('title'), trailing: Text('T'), ), ), ), ), ), )); double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; void testHorizontalGeometry() { expect(right('L'), 800.0 - math.max(16.0, rightPadding)); expect(right('title'), 800.0 - 40.0 - math.max(16.0, rightPadding)); expect(left('T'), math.max(24.0, leftPadding)); } testHorizontalGeometry(); }); testWidgets('ListTile.divideTiles', (WidgetTester tester) async { final List<String> titles = <String>[ 'first', 'second', 'third' ]; await tester.pumpWidget(MaterialApp( home: Material( child: Builder( builder: (BuildContext context) { return ListView( children: ListTile.divideTiles( context: context, tiles: titles.map<Widget>((String title) => ListTile(title: Text(title))), ).toList(), ); }, ), ), )); expect(find.text('first'), findsOneWidget); expect(find.text('second'), findsOneWidget); expect(find.text('third'), findsOneWidget); }); testWidgets('ListTile.divideTiles with empty list', (WidgetTester tester) async { final Iterable<Widget> output = ListTile.divideTiles(tiles: <Widget>[], color: Colors.grey); expect(output, isEmpty); }); testWidgets('ListTile.divideTiles with single item list', (WidgetTester tester) async { final Iterable<Widget> output = ListTile.divideTiles(tiles: const <Widget>[SizedBox()], color: Colors.grey); expect(output.single, isA<SizedBox>()); }); testWidgets('ListTile.divideTiles only runs the generator once', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/78879 int callCount = 0; Iterable<Widget> generator() sync* { callCount += 1; yield const Text(''); yield const Text(''); } final List<Widget> output = ListTile.divideTiles(tiles: generator(), color: Colors.grey).toList(); expect(output, hasLength(2)); expect(callCount, 1); }); testWidgets('ListTile semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Material( child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Column( children: <Widget>[ const ListTile( title: Text('one'), ), ListTile( title: const Text('two'), onTap: () {}, ), const ListTile( title: Text('three'), selected: true, ), const ListTile( title: Text('four'), enabled: false, ), ], ), ), ), ), ); expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], label: 'one', ), TestSemantics.rootChild( flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[SemanticsAction.tap], label: 'two', ), TestSemantics.rootChild( flags: <SemanticsFlag>[ SemanticsFlag.isSelected, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, ], label: 'three', ), TestSemantics.rootChild( flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, ], label: 'four', ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true, ), ); semantics.dispose(); }); testWidgets('ListTile contentPadding', (WidgetTester tester) async { Widget buildFrame(TextDirection textDirection) { return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: textDirection, child: Material( child: Container( alignment: Alignment.topLeft, child: const ListTile( contentPadding: EdgeInsetsDirectional.only( start: 10.0, end: 20.0, top: 30.0, bottom: 40.0, ), leading: Text('L'), title: Text('title'), trailing: Text('T'), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; await tester.pumpWidget(buildFrame(TextDirection.ltr)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 126.0)); // 126 = 56 + 30 + 40 expect(left('L'), 10.0); // contentPadding.start = 10 expect(right('T'), 780.0); // 800 - contentPadding.end await tester.pumpWidget(buildFrame(TextDirection.rtl)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 126.0)); // 126 = 56 + 30 + 40 expect(left('T'), 20.0); // contentPadding.end = 20 expect(right('L'), 790.0); // 800 - contentPadding.start }); testWidgets('ListTile wide leading Widget', (WidgetTester tester) async { const Key leadingKey = ValueKey<String>('L'); Widget buildFrame(double leadingWidth, TextDirection textDirection) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Directionality( textDirection: textDirection, child: Material( child: Container( alignment: Alignment.topLeft, child: ListTile( contentPadding: EdgeInsets.zero, leading: SizedBox(key: leadingKey, width: leadingWidth, height: 32.0), title: const Text('title'), subtitle: const Text('subtitle'), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; // textDirection = LTR // Two-line tile's height = 72, leading 24x32 widget is positioned in the center. await tester.pumpWidget(buildFrame(24.0, TextDirection.ltr)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 72.0)); expect(tester.getTopLeft(find.byKey(leadingKey)), const Offset(0.0, 20.0)); expect(tester.getBottomRight(find.byKey(leadingKey)), const Offset(24.0, 20.0 + 32.0)); // Leading widget's width is 20, so default layout: the left edges of the // title and subtitle are at 40dps, leading widget width is 24dp and 16dp // is horizontalTitleGap (contentPadding is zero). expect(left('title'), 40.0); expect(left('subtitle'), 40.0); // If the leading widget is wider than 40 it is separated from the // title and subtitle by 16. await tester.pumpWidget(buildFrame(56.0, TextDirection.ltr)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 72.0)); expect(tester.getTopLeft(find.byKey(leadingKey)), const Offset(0.0, 20.0)); expect(tester.getBottomRight(find.byKey(leadingKey)), const Offset(56.0, 20.0 + 32.0)); expect(left('title'), 72.0); expect(left('subtitle'), 72.0); // Same tests, textDirection = RTL await tester.pumpWidget(buildFrame(24.0, TextDirection.rtl)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 72.0)); expect(tester.getTopRight(find.byKey(leadingKey)), const Offset(800.0, 20.0)); expect(tester.getBottomLeft(find.byKey(leadingKey)), const Offset(800.0 - 24.0, 20.0 + 32.0)); expect(right('title'), 800.0 - 40.0); expect(right('subtitle'), 800.0 - 40.0); await tester.pumpWidget(buildFrame(56.0, TextDirection.rtl)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 72.0)); expect(tester.getTopRight(find.byKey(leadingKey)), const Offset(800.0, 20.0)); expect(tester.getBottomLeft(find.byKey(leadingKey)), const Offset(800.0 - 56.0, 20.0 + 32.0)); expect(right('title'), 800.0 - 72.0); expect(right('subtitle'), 800.0 - 72.0); }); testWidgets('ListTile leading and trailing positions', (WidgetTester tester) async { // This test is based on the redlines at // https://material.io/design/components/lists.html#specs // "ONE"-LINE await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), ), ], ), ), ), ); await tester.pump(const Duration(seconds: 2)); // the text styles are animated when we change dense // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, 328.0)); expect(tester.getRect(find.byType(CircleAvatar).at(0)), const Rect.fromLTWH( 16.0, 144.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 152.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, 328.0 , 800.0, 56.0)); expect(tester.getRect(find.byType(CircleAvatar).at(1)), const Rect.fromLTWH( 16.0, 328.0 + 8.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 328.0 + 16.0, 24.0, 24.0)); // "TWO"-LINE await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A'), ), ], ), ), ), ); if (kIsWeb && !isCanvasKit) { // https://github.com/flutter/flutter/issues/99933 return; } const double height = 300; const double avatarTop = 130.0; const double placeholderTop = 138.0; // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, height)); expect(tester.getRect(find.byType(CircleAvatar).at(0)), const Rect.fromLTWH( 16.0, avatarTop, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, placeholderTop, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, height , 800.0, 72.0)); expect(tester.getRect(find.byType(CircleAvatar).at(1)), const Rect.fromLTWH( 16.0, height + 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, height + 24.0, 24.0, 24.0)); // THREE-LINE await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( isThreeLine: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( isThreeLine: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A'), ), ], ), ), ), ); // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, height)); expect(tester.getRect(find.byType(CircleAvatar).at(0)), const Rect.fromLTWH( 16.0, 8.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 8.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, height , 800.0, 88.0)); expect(tester.getRect(find.byType(CircleAvatar).at(1)), const Rect.fromLTWH( 16.0, height + 8.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, height + 8.0, 24.0, 24.0)); // "ONE-LINE" with Small Leading Widget await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: SizedBox(height: 12.0, width: 24.0, child: Placeholder()), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( leading: SizedBox(height: 12.0, width: 24.0, child: Placeholder()), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), ), ], ), ), ), ); await tester.pump(const Duration(seconds: 2)); // the text styles are animated when we change dense // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, 328.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH( 16.0, 158.0, 24.0, 12.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 152.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, 328.0 , 800.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(2)), const Rect.fromLTWH( 16.0, 328.0 + 22.0, 24.0, 12.0)); expect(tester.getRect(find.byType(Placeholder).at(3)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 328.0 + 16.0, 24.0, 24.0)); }); testWidgets('ListTile leading icon height does not exceed ListTile height', (WidgetTester tester) async { // regression test for https://github.com/flutter/flutter/issues/28765 const SizedBox oversizedWidget = SizedBox(height: 80.0, width: 24.0, child: Placeholder()); // One line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: oversizedWidget, title: Text('A'), ), ListTile( leading: oversizedWidget, title: Text('B'), ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(16.0, 0.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(16.0, 56.0, 24.0, 56.0)); // Two line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: oversizedWidget, title: Text('A'), subtitle: Text('A'), ), ListTile( leading: oversizedWidget, title: Text('B'), subtitle: Text('B'), ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(16.0, 8.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(16.0, 72.0 + 8.0, 24.0, 56.0)); // Three line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: oversizedWidget, title: Text('A'), subtitle: Text('A'), isThreeLine: true, ), ListTile( leading: oversizedWidget, title: Text('B'), subtitle: Text('B'), isThreeLine: true, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(16.0, 8.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(16.0, 88.0 + 8.0, 24.0, 56.0)); }); testWidgets('ListTile trailing icon height does not exceed ListTile height', (WidgetTester tester) async { // regression test for https://github.com/flutter/flutter/issues/28765 const SizedBox oversizedWidget = SizedBox(height: 80.0, width: 24.0, child: Placeholder()); // One line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( trailing: oversizedWidget, title: Text('A'), dense: false, ), ListTile( trailing: oversizedWidget, title: Text('B'), dense: false, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 0.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 56.0, 24.0, 56.0)); // Two line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( trailing: oversizedWidget, title: Text('A'), subtitle: Text('A'), dense: false, ), ListTile( trailing: oversizedWidget, title: Text('B'), subtitle: Text('B'), dense: false, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 8.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 72.0 + 8.0, 24.0, 56.0)); // Three line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: ListView( children: const <Widget>[ ListTile( trailing: oversizedWidget, title: Text('A'), subtitle: Text('A'), isThreeLine: true, dense: false, ), ListTile( trailing: oversizedWidget, title: Text('B'), subtitle: Text('B'), isThreeLine: true, dense: false, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 8.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 24.0, 88.0 + 8.0, 24.0, 56.0)); }); testWidgets('ListTile only accepts focus when enabled', (WidgetTester tester) async { final GlobalKey childKey = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Material( child: ListView( children: <Widget>[ ListTile( title: Text('A', key: childKey), dense: true, onTap: () {}, ), ], ), ), ), ); await tester.pump(); // Let the focus take effect. final FocusNode tileNode = Focus.of(childKey.currentContext!); tileNode.requestFocus(); await tester.pump(); // Let the focus take effect. expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isTrue); expect(tileNode.hasPrimaryFocus, isTrue); await tester.pumpWidget( MaterialApp( home: Material( child: ListView( children: <Widget>[ ListTile( title: Text('A', key: childKey), dense: true, enabled: false, onTap: () {}, ), ], ), ), ), ); expect(tester.binding.focusManager.primaryFocus, isNot(equals(tileNode))); expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isFalse); }); testWidgets('ListTile can autofocus unless disabled.', (WidgetTester tester) async { final GlobalKey childKey = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Material( child: ListView( children: <Widget>[ ListTile( title: Text('A', key: childKey), dense: true, autofocus: true, onTap: () {}, ), ], ), ), ), ); await tester.pump(); expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isTrue); await tester.pumpWidget( MaterialApp( home: Material( child: ListView( children: <Widget>[ ListTile( title: Text('A', key: childKey), dense: true, enabled: false, autofocus: true, onTap: () {}, ), ], ), ), ), ); await tester.pump(); expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isFalse); }); testWidgets('ListTile is focusable and has correct focus color', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'ListTile'); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; Widget buildApp({bool enabled = true}) { return MaterialApp( home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: ListTile( onTap: enabled ? () {} : null, focusColor: Colors.orange[500], autofocus: true, focusNode: focusNode, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( find.byType(Material), paints ..rect() ..rect( color: Colors.orange[500], rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ), ); // Check when the list tile is disabled. await tester.pumpWidget(buildApp(enabled: false)); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isFalse); expect( find.byType(Material), paints ..rect() ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ), ); focusNode.dispose(); }); testWidgets('ListTile can be hovered and has correct hover color', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; Widget buildApp({bool enabled = true}) { return MaterialApp( home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: ListTile( onTap: enabled ? () {} : null, hoverColor: Colors.orange[500], autofocus: true, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pump(); await tester.pumpAndSettle(); expect( find.byType(Material), paints ..rect() ..rect( color: const Color(0x1f000000), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ), ); // Start hovering final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.moveTo(tester.getCenter(find.byType(ListTile))); await tester.pumpWidget(buildApp()); await tester.pump(); await tester.pumpAndSettle(); expect( find.byType(Material), paints ..rect() ..rect( color: const Color(0x1f000000), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..rect( color: Colors.orange[500], rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ), ); await tester.pumpWidget(buildApp(enabled: false)); await tester.pump(); await tester.pumpAndSettle(); expect( find.byType(Material), paints ..rect() ..rect( color: Colors.orange[500]!.withAlpha(0), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ), ); }); testWidgets('ListTile can be splashed and has correct splash color', (WidgetTester tester) async { final Widget buildApp = MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: SizedBox( width: 100, height: 100, child: ListTile( onTap: () {}, splashColor: const Color(0xff88ff88), ), ), ), ), ); await tester.pumpWidget(buildApp); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(ListTile)).center); await tester.pump(const Duration(milliseconds: 200)); expect(find.byType(Material), paints..circle(x: 50, y: 50, color: const Color(0xff88ff88))); await gesture.up(); }); testWidgets('ListTile can be triggered by keyboard shortcuts', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const Key tileKey = Key('ListTile'); bool tapped = false; Widget buildApp({bool enabled = true}) { return MaterialApp( home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 200, height: 100, color: Colors.white, child: ListTile( key: tileKey, onTap: enabled ? () { setState(() { tapped = true; }); } : null, hoverColor: Colors.orange[500], autofocus: true, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); expect(tapped, isTrue); }); testWidgets('ListTile responds to density changes.', (WidgetTester tester) async { const Key key = Key('test'); Future<void> buildTest(VisualDensity visualDensity) async { return tester.pumpWidget( MaterialApp( home: Material( child: Center( child: ListTile( key: key, onTap: () {}, autofocus: true, visualDensity: visualDensity, ), ), ), ), ); } await buildTest(VisualDensity.standard); final RenderBox box = tester.renderObject(find.byKey(key)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(800, 56))); await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(800, 68))); await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(800, 44))); await buildTest(const VisualDensity(horizontal: 3.0, vertical: -3.0)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(800, 44))); }); testWidgets('ListTile shape is painted correctly', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/63877 const ShapeBorder rectShape = RoundedRectangleBorder(); const ShapeBorder stadiumShape = StadiumBorder(); final Color tileColor = Colors.red.shade500; Widget buildListTile(ShapeBorder shape) { return MaterialApp( home: Material( child: Center( child: ListTile(shape: shape, tileColor: tileColor), ), ), ); } // Test rectangle shape await tester.pumpWidget(buildListTile(rectShape)); Rect rect = tester.getRect(find.byType(ListTile)); // Check if a rounded rectangle was painted with the correct color and shape expect( find.byType(Material), paints..rect(color: tileColor, rect: rect), ); // Test stadium shape await tester.pumpWidget(buildListTile(stadiumShape)); rect = tester.getRect(find.byType(ListTile)); // Check if a rounded rectangle was painted with the correct color and shape expect( find.byType(Material), paints..clipRect()..rrect( color: tileColor, rrect: RRect.fromRectAndRadius(rect, Radius.circular(rect.shortestSide / 2.0)), ), ); }); testWidgets('ListTile changes mouse cursor when hovered', (WidgetTester tester) async { // Test ListTile() constructor await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: ListTile( onTap: () {}, mouseCursor: SystemMouseCursors.text, ), ), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: tester.getCenter(find.byType(ListTile))); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); // Test default cursor await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: ListTile( onTap: () {}, ), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); // Test default cursor when disabled await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: ListTile( enabled: false, ), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); // Test default cursor when onTap or onLongPress is null await tester.pumpWidget( const MaterialApp( home: Material( child: Center( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: ListTile(), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }); testWidgets('ListTile onFocusChange callback', (WidgetTester tester) async { final FocusNode node = FocusNode(debugLabel: 'ListTile Focus'); bool gotFocus = false; await tester.pumpWidget( MaterialApp( home: Material( child: ListTile( focusNode: node, onFocusChange: (bool focused) { gotFocus = focused; }, onTap: () {}, ), ), ), ); node.requestFocus(); await tester.pump(); expect(gotFocus, isTrue); expect(node.hasFocus, isTrue); node.unfocus(); await tester.pump(); expect(gotFocus, isFalse); expect(node.hasFocus, isFalse); node.dispose(); }); testWidgets('ListTile respects tileColor & selectedTileColor', (WidgetTester tester) async { bool isSelected = false; final Color tileColor = Colors.green.shade500; final Color selectedTileColor = Colors.red.shade500; await tester.pumpWidget( MaterialApp( home: Material( child: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ListTile( selected: isSelected, selectedTileColor: selectedTileColor, tileColor: tileColor, onTap: () { setState(()=> isSelected = !isSelected); }, title: const Text('Title'), ); }, ), ), ), ), ); // Initially, when isSelected is false, the ListTile should respect tileColor. expect(find.byType(Material), paints..rect(color: tileColor)); // Tap on tile to change isSelected. await tester.tap(find.byType(ListTile)); await tester.pumpAndSettle(); // When isSelected is true, the ListTile should respect selectedTileColor. expect(find.byType(Material), paints..rect(color: selectedTileColor)); }); testWidgets('ListTile shows Material ripple effects on top of tileColor', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/73616 final Color tileColor = Colors.red.shade500; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: ListTile( tileColor: tileColor, onTap: () {}, title: const Text('Title'), ), ), ), ), ); // Before ListTile is tapped, it should be tileColor expect(find.byType(Material), paints..rect(color: tileColor)); // Tap on tile to trigger ink effect and wait for it to be underway. await tester.tap(find.byType(ListTile)); await tester.pump(const Duration(milliseconds: 200)); // After tap, the tile could be drawn in tileColor, with the ripple (circle) on top expect( find.byType(Material), paints ..rect(color: tileColor) ..circle(), ); }); testWidgets('ListTile default tile color', (WidgetTester tester) async { bool isSelected = false; final ThemeData theme = ThemeData(useMaterial3: true); const Color defaultColor = Colors.transparent; await tester.pumpWidget( MaterialApp( theme: theme, home: Material( child: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ListTile( selected: isSelected, onTap: () { setState(()=> isSelected = !isSelected); }, title: const Text('Title'), ); }, ), ), ), ), ); expect(find.byType(Material), paints..rect(color: defaultColor)); // Tap on tile to change isSelected. await tester.tap(find.byType(ListTile)); await tester.pumpAndSettle(); expect(find.byType(Material), paints..rect(color: defaultColor)); }); testWidgets('Default tile color when ListTile is wrapped with an elevated widget', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/117700 bool isSelected = false; final ThemeData theme = ThemeData(useMaterial3: true); const Color defaultColor = Colors.transparent; await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Card( elevation: 8.0, child: ListTile( selected: isSelected, onTap: () { setState(()=> isSelected = !isSelected); }, title: const Text('Title'), ), ); }, ), ), ), ); expect( find.byType(Material), paints ..path(color: const Color(0xff000000)) ..path(color: const Color(0xfff7f2fa)) ..save() ..save(), ); expect(find.byType(Material), paints..rect(color: defaultColor)); // Tap on tile to change isSelected. await tester.tap(find.byType(ListTile)); await tester.pumpAndSettle(); expect( find.byType(Material), paints ..path(color: const Color(0xff000000)) ..path(color: const Color(0xfff7f2fa)) ..save() ..save(), ); expect(find.byType(Material), paints..rect(color: defaultColor)); }); testWidgets('ListTile layout at zero size', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/66636 const Key key = Key('key'); await tester.pumpWidget(const MaterialApp( home: Scaffold( body: SizedBox.shrink( child: ListTile( key: key, tileColor: Colors.green, ), ), ), )); final RenderBox renderBox = tester.renderObject(find.byKey(key)); expect(renderBox.size.width, equals(0.0)); expect(renderBox.size.height, equals(0.0)); }); group('feedback', () { late FeedbackTester feedback; setUp(() { feedback = FeedbackTester(); }); tearDown(() { feedback.dispose(); }); testWidgets('ListTile with disabled feedback', (WidgetTester tester) async { const bool enableFeedback = false; await tester.pumpWidget( MaterialApp( home: Material( child: ListTile( title: const Text('Title'), onTap: () {}, enableFeedback: enableFeedback, ), ), ), ); await tester.tap(find.byType(ListTile)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 0); expect(feedback.hapticCount, 0); }); testWidgets('ListTile with enabled feedback', (WidgetTester tester) async { const bool enableFeedback = true; await tester.pumpWidget( MaterialApp( home: Material( child: ListTile( title: const Text('Title'), onTap: () {}, enableFeedback: enableFeedback, ), ), ), ); await tester.tap(find.byType(ListTile)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 1); expect(feedback.hapticCount, 0); }); testWidgets('ListTile with enabled feedback by default', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: ListTile( title: const Text('Title'), onTap: () {}, ), ), ), ); await tester.tap(find.byType(ListTile)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 1); expect(feedback.hapticCount, 0); }); testWidgets('ListTile with disabled feedback using ListTileTheme', (WidgetTester tester) async { const bool enableFeedbackTheme = false; await tester.pumpWidget( MaterialApp( home: Material( child: ListTileTheme( data: const ListTileThemeData(enableFeedback: enableFeedbackTheme), child: ListTile( title: const Text('Title'), onTap: () {}, ), ), ), ), ); await tester.tap(find.byType(ListTile)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 0); expect(feedback.hapticCount, 0); }); testWidgets('ListTile.enableFeedback overrides ListTileTheme.enableFeedback', (WidgetTester tester) async { const bool enableFeedbackTheme = false; const bool enableFeedback = true; await tester.pumpWidget( MaterialApp( home: Material( child: ListTileTheme( data: const ListTileThemeData(enableFeedback: enableFeedbackTheme), child: ListTile( enableFeedback: enableFeedback, title: const Text('Title'), onTap: () {}, ), ), ), ), ); await tester.tap(find.byType(ListTile)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 1); expect(feedback.hapticCount, 0); }); testWidgets('ListTile.mouseCursor overrides ListTileTheme.mouseCursor', (WidgetTester tester) async { final Key tileKey = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Material( child: ListTileTheme( data: const ListTileThemeData(mouseCursor: MaterialStateMouseCursor.clickable), child: ListTile( key: tileKey, mouseCursor: MaterialStateMouseCursor.textable, title: const Text('Title'), onTap: () {}, ), ), ), ), ); final Offset listTile = tester.getCenter(find.byKey(tileKey)); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(listTile); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); }); }); testWidgets('ListTile horizontalTitleGap = 0.0', (WidgetTester tester) async { Widget buildFrame(TextDirection textDirection, { double? themeHorizontalTitleGap, double? widgetHorizontalTitleGap }) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Directionality( textDirection: textDirection, child: Material( child: ListTileTheme( data: ListTileThemeData(horizontalTitleGap: themeHorizontalTitleGap), child: Container( alignment: Alignment.topLeft, child: ListTile( horizontalTitleGap: widgetHorizontalTitleGap, leading: const Text('L'), title: const Text('title'), trailing: const Text('T'), ), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; await tester.pumpWidget(buildFrame(TextDirection.ltr, widgetHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 40.0); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 40.0); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeHorizontalTitleGap: 10, widgetHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 40.0); await tester.pumpWidget(buildFrame(TextDirection.rtl, widgetHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(right('title'), 760.0); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(right('title'), 760.0); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeHorizontalTitleGap: 10, widgetHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(right('title'), 760.0); }); testWidgets('ListTile horizontalTitleGap = (default) && ListTile minLeadingWidth = (default)', (WidgetTester tester) async { Widget buildFrame(TextDirection textDirection) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Directionality( textDirection: textDirection, child: Material( child: Container( alignment: Alignment.topLeft, child: const ListTile( leading: Text('L'), title: Text('title'), trailing: Text('T'), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; await tester.pumpWidget(buildFrame(TextDirection.ltr)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); // horizontalTitleGap: ListTileDefaultValue.horizontalTitleGap (16.0) expect(left('title'), 56.0); await tester.pumpWidget(buildFrame(TextDirection.rtl)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); // horizontalTitleGap: ListTileDefaultValue.horizontalTitleGap (16.0) expect(right('title'), 744.0); }); testWidgets('ListTile horizontalTitleGap with visualDensity', (WidgetTester tester) async { Widget buildFrame({ double? horizontalTitleGap, VisualDensity? visualDensity, }) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Container( alignment: Alignment.topLeft, child: ListTile( visualDensity: visualDensity, horizontalTitleGap: horizontalTitleGap, leading: const Text('L'), title: const Text('title'), trailing: const Text('T'), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; await tester.pumpWidget(buildFrame( horizontalTitleGap: 10.0, visualDensity: const VisualDensity(horizontal: VisualDensity.minimumDensity), )); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 42.0); // Pump another frame of the same widget to ensure the underlying render // object did not cache the original horizontalTitleGap calculation based on the // visualDensity await tester.pumpWidget(buildFrame( horizontalTitleGap: 10.0, visualDensity: const VisualDensity(horizontal: VisualDensity.minimumDensity), )); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 42.0); }); testWidgets('ListTile minVerticalPadding = 80.0', (WidgetTester tester) async { Widget buildFrame(TextDirection textDirection, { double? themeMinVerticalPadding, double? widgetMinVerticalPadding }) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Directionality( textDirection: textDirection, child: Material( child: ListTileTheme( data: ListTileThemeData(minVerticalPadding: themeMinVerticalPadding), child: Container( alignment: Alignment.topLeft, child: ListTile( minVerticalPadding: widgetMinVerticalPadding, leading: const Text('L'), title: const Text('title'), trailing: const Text('T'), ), ), ), ), ), ); } await tester.pumpWidget(buildFrame(TextDirection.ltr, widgetMinVerticalPadding: 80)); // 80 + 80 + 16(Title) = 176 expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 184.0)); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeMinVerticalPadding: 80)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 184.0)); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeMinVerticalPadding: 0, widgetMinVerticalPadding: 80)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 184.0)); await tester.pumpWidget(buildFrame(TextDirection.rtl, widgetMinVerticalPadding: 80)); // 80 + 80 + 16(Title) = 176 expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 184.0)); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeMinVerticalPadding: 80)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 184.0)); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeMinVerticalPadding: 0, widgetMinVerticalPadding: 80)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 184.0)); }); testWidgets('ListTile minLeadingWidth = 60.0', (WidgetTester tester) async { Widget buildFrame(TextDirection textDirection, { double? themeMinLeadingWidth, double? widgetMinLeadingWidth }) { return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: textDirection, child: Material( child: ListTileTheme( data: ListTileThemeData(minLeadingWidth: themeMinLeadingWidth), child: Container( alignment: Alignment.topLeft, child: ListTile( minLeadingWidth: widgetMinLeadingWidth, leading: const Text('L'), title: const Text('title'), trailing: const Text('T'), ), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; await tester.pumpWidget(buildFrame(TextDirection.ltr, widgetMinLeadingWidth: 60)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); // 92.0 = 16.0(Default contentPadding) + 16.0(Default horizontalTitleGap) + 60.0 expect(left('title'), 92.0); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeMinLeadingWidth: 60)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 92.0); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeMinLeadingWidth: 0, widgetMinLeadingWidth: 60)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 92.0); await tester.pumpWidget(buildFrame(TextDirection.rtl, widgetMinLeadingWidth: 60)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); // 708.0 = 800.0 - (16.0(Default contentPadding) + 16.0(Default horizontalTitleGap) + 60.0) expect(right('title'), 708.0); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeMinLeadingWidth: 60)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(right('title'), 708.0); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeMinLeadingWidth: 0, widgetMinLeadingWidth: 60)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(right('title'), 708.0); }); testWidgets('ListTile minTileHeight', (WidgetTester tester) async { Widget buildFrame(TextDirection textDirection, { double? minTileHeight, }) { return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: textDirection, child: Material( child: Container( alignment: Alignment.topLeft, child: ListTile( minTileHeight: minTileHeight, ), ), ), ), ); } // Default list tile with height = 56.0 await tester.pumpWidget(buildFrame(TextDirection.ltr)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); // Set list tile height = 30.0 await tester.pumpWidget(buildFrame(TextDirection.ltr, minTileHeight: 30)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 30.0)); // Set list tile height = 60.0 await tester.pumpWidget(buildFrame(TextDirection.ltr, minTileHeight: 60)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 60.0)); }); testWidgets('colors are applied to leading and trailing text widgets', (WidgetTester tester) async { final Key leadingKey = UniqueKey(); final Key trailingKey = UniqueKey(); late ThemeData theme; Widget buildFrame({ bool enabled = true, bool selected = false, }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: Builder( builder: (BuildContext context) { theme = Theme.of(context); return ListTile( enabled: enabled, selected: selected, leading: TestText('leading', key: leadingKey), title: const TestText('title'), trailing: TestText('trailing', key: trailingKey), ); }, ), ), ), ); } Color textColor(Key key) => tester.state<TestTextState>(find.byKey(key)).textStyle.color!; await tester.pumpWidget(buildFrame()); // Enabled color should be default bodyMedium color. expect(textColor(leadingKey), theme.textTheme.bodyMedium!.color); expect(textColor(trailingKey), theme.textTheme.bodyMedium!.color); await tester.pumpWidget(buildFrame(selected: true)); // Wait for text color to animate. await tester.pumpAndSettle(); // Selected color should be ThemeData.primaryColor by default. expect(textColor(leadingKey), theme.primaryColor); expect(textColor(trailingKey), theme.primaryColor); await tester.pumpWidget(buildFrame(enabled: false)); // Wait for text color to animate. await tester.pumpAndSettle(); // Disabled color should be ThemeData.disabledColor by default. expect(textColor(leadingKey), theme.disabledColor); expect(textColor(trailingKey), theme.disabledColor); }); testWidgets('selected, enabled ListTile default icon color', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: true); final ColorScheme colorScheme = theme.colorScheme; final Key leadingKey = UniqueKey(); final Key titleKey = UniqueKey(); final Key subtitleKey = UniqueKey(); final Key trailingKey = UniqueKey(); Widget buildFrame({required bool selected }) { return MaterialApp( theme: theme, home: Material( child: Center( child: ListTile( selected: selected, leading: TestIcon(key: leadingKey), title: TestIcon(key: titleKey), subtitle: TestIcon(key: subtitleKey), trailing: TestIcon(key: trailingKey), ), ), ), ); } Color iconColor(Key key) => tester.state<TestIconState>(find.byKey(key)).iconTheme.color!; await tester.pumpWidget(buildFrame(selected: true)); expect(iconColor(leadingKey), colorScheme.primary); expect(iconColor(titleKey), colorScheme.primary); expect(iconColor(subtitleKey), colorScheme.primary); expect(iconColor(trailingKey), colorScheme.primary); await tester.pumpWidget(buildFrame(selected: false)); expect(iconColor(leadingKey), colorScheme.onSurfaceVariant); expect(iconColor(titleKey), colorScheme.onSurfaceVariant); expect(iconColor(subtitleKey), colorScheme.onSurfaceVariant); expect(iconColor(trailingKey), colorScheme.onSurfaceVariant); }); testWidgets('ListTile font size', (WidgetTester tester) async { Widget buildFrame() { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: Center( child: Builder( builder: (BuildContext context) { return const ListTile( leading: TestText('leading'), title: TestText('title'), subtitle: TestText('subtitle') , trailing: TestText('trailing'), ); }, ), ), ), ); } // ListTile default text sizes. await tester.pumpWidget(buildFrame()); final RenderParagraph leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.fontSize, 11.0); final RenderParagraph title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.fontSize, 16.0); final RenderParagraph subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.fontSize, 14.0); final RenderParagraph trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.fontSize, 11.0); }); testWidgets('ListTile text color', (WidgetTester tester) async { Widget buildFrame() { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: Center( child: Builder( builder: (BuildContext context) { return const ListTile( leading: TestText('leading'), title: TestText('title'), subtitle: TestText('subtitle') , trailing: TestText('trailing'), ); }, ), ), ), ); } final ThemeData theme = ThemeData(useMaterial3: true); // ListTile default text colors. await tester.pumpWidget(buildFrame()); final RenderParagraph leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.color, theme.colorScheme.onSurfaceVariant); final RenderParagraph title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.color, theme.colorScheme.onSurface); final RenderParagraph subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.color, theme.colorScheme.onSurfaceVariant); final RenderParagraph trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.color, theme.colorScheme.onSurfaceVariant); }); testWidgets('Default ListTile debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const ListTile().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('ListTile implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const ListTile( leading: Text('leading'), title: Text('title'), subtitle: Text('trailing'), trailing: Text('trailing'), isThreeLine: true, dense: true, visualDensity: VisualDensity.standard, shape: RoundedRectangleBorder(), style: ListTileStyle.list, selectedColor: Color(0xff0000ff), iconColor: Color(0xff00ff00), textColor: Color(0xffff0000), titleTextStyle: TextStyle(fontSize: 22), subtitleTextStyle: TextStyle(fontSize: 18), leadingAndTrailingTextStyle: TextStyle(fontSize: 16), contentPadding: EdgeInsets.zero, enabled: false, selected: true, focusColor: Color(0xff00ffff), hoverColor: Color(0xff0000ff), autofocus: true, tileColor: Color(0xffffff00), selectedTileColor: Color(0xff123456), enableFeedback: false, horizontalTitleGap: 4.0, minVerticalPadding: 2.0, minLeadingWidth: 6.0, titleAlignment: ListTileTitleAlignment.bottom, ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect( description, equalsIgnoringHashCodes(<String>[ 'isThreeLine: THREE_LINE', 'dense: true', 'visualDensity: VisualDensity#00000(h: 0.0, v: 0.0)', 'shape: RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.zero)', 'style: ListTileStyle.list', 'selectedColor: Color(0xff0000ff)', 'iconColor: Color(0xff00ff00)', 'textColor: Color(0xffff0000)', 'titleTextStyle: TextStyle(inherit: true, size: 22.0)', 'subtitleTextStyle: TextStyle(inherit: true, size: 18.0)', 'leadingAndTrailingTextStyle: TextStyle(inherit: true, size: 16.0)', 'contentPadding: EdgeInsets.zero', 'enabled: false', 'selected: true', 'focusColor: Color(0xff00ffff)', 'hoverColor: Color(0xff0000ff)', 'autofocus: true', 'tileColor: Color(0xffffff00)', 'selectedTileColor: Color(0xff123456)', 'enableFeedback: false', 'horizontalTitleGap: 4.0', 'minVerticalPadding: 2.0', 'minLeadingWidth: 6.0', 'titleAlignment: ListTileTitleAlignment.bottom', ]), ); }); testWidgets('ListTile.textColor respects MaterialStateColor', (WidgetTester tester) async { bool enabled = false; bool selected = false; const Color defaultColor = Colors.blue; const Color selectedColor = Colors.green; const Color disabledColor = Colors.red; Widget buildFrame() { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: Center( child: Builder( builder: (BuildContext context) { return ListTile( enabled: enabled, selected: selected, textColor: MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return disabledColor; } if (states.contains(MaterialState.selected)) { return selectedColor; } return defaultColor; }), title: const TestText('title'), subtitle: const TestText('subtitle') , ); }, ), ), ), ); } // Test disabled state. await tester.pumpWidget(buildFrame()); RenderParagraph title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.color, disabledColor); // Test enabled state. enabled = true; await tester.pumpWidget(buildFrame()); await tester.pumpAndSettle(); title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.color, defaultColor); // Test selected state. selected = true; await tester.pumpWidget(buildFrame()); await tester.pumpAndSettle(); title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.color, selectedColor); }); testWidgets('ListTile.iconColor respects MaterialStateColor', (WidgetTester tester) async { bool enabled = false; bool selected = false; const Color defaultColor = Colors.blue; const Color selectedColor = Colors.green; const Color disabledColor = Colors.red; final Key leadingKey = UniqueKey(); Widget buildFrame() { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: Center( child: Builder( builder: (BuildContext context) { return ListTile( enabled: enabled, selected: selected, iconColor: MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return disabledColor; } if (states.contains(MaterialState.selected)) { return selectedColor; } return defaultColor; }), leading: TestIcon(key: leadingKey), ); }, ), ), ), ); } Color iconColor(Key key) => tester.state<TestIconState>(find.byKey(key)).iconTheme.color!; // Test disabled state. await tester.pumpWidget(buildFrame()); expect(iconColor(leadingKey), disabledColor); // Test enabled state. enabled = true; await tester.pumpWidget(buildFrame()); await tester.pumpAndSettle(); expect(iconColor(leadingKey), defaultColor); // Test selected state. selected = true; await tester.pumpWidget(buildFrame()); await tester.pumpAndSettle(); expect(iconColor(leadingKey), selectedColor); }); testWidgets('ListTile.iconColor respects iconColor property with icon buttons Material 3 in presence of IconButtonTheme override', (WidgetTester tester) async { const Color iconButtonThemeColor = Colors.blue; const Color listTileIconColor = Colors.green; const Icon leadingIcon = Icon(Icons.favorite); const Icon trailingIcon = Icon(Icons.close); Widget buildFrame() { return MaterialApp( theme: ThemeData( useMaterial3: true, iconButtonTheme: IconButtonThemeData( style: IconButton.styleFrom( foregroundColor: iconButtonThemeColor, ), ), ), home: Material( child: Center( child: Builder( builder: (BuildContext context) { return ListTile( iconColor: listTileIconColor, leading: IconButton(icon: leadingIcon, onPressed: () {}), trailing: IconButton(icon: trailingIcon, onPressed: () {}), ); }, ), ), ), ); } TextStyle? getIconStyle(WidgetTester tester, IconData icon) => tester.widget<RichText>(find.descendant( of: find.byIcon(icon), matching: find.byType(RichText), ), ).text.style; await tester.pumpWidget(buildFrame()); expect(getIconStyle(tester, leadingIcon.icon!)?.color, listTileIconColor); expect(getIconStyle(tester, trailingIcon.icon!)?.color, listTileIconColor); }); testWidgets('ListTile.dense does not throw assertion', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/pull/116908 Widget buildFrame({required bool useMaterial3}) { return MaterialApp( theme: ThemeData(useMaterial3: useMaterial3), home: Material( child: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return const ListTile( dense: true, title: Text('Title'), ); }, ), ), ), ); } await tester.pumpWidget(buildFrame(useMaterial3: false)); expect(tester.takeException(), isNull); await tester.pumpWidget(buildFrame(useMaterial3: true)); expect(tester.takeException(), isNull); }); testWidgets('titleAlignment position with title widget', (WidgetTester tester) async { final Key leadingKey = GlobalKey(); final Key trailingKey = GlobalKey(); const double leadingHeight = 24.0; const double titleHeight = 50.0; const double trailingHeight = 24.0; const double minVerticalPadding = 10.0; const double tileHeight = minVerticalPadding * 2 + titleHeight; Widget buildFrame({ ListTileTitleAlignment? titleAlignment }) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: Center( child: ListTile( titleAlignment: titleAlignment, minVerticalPadding: minVerticalPadding, leading: SizedBox(key: leadingKey, width: 24.0, height: leadingHeight), title: const SizedBox(width: 20.0, height: titleHeight), trailing: SizedBox(key: trailingKey, width: 24.0, height: trailingHeight), ), ), ), ); } // If [ThemeData.useMaterial3] is true, the default title alignment is // [ListTileTitleAlignment.threeLine], which positions the leading and // trailing widgets center vertically in the tile if the [ListTile.isThreeLine] // property is false. await tester.pumpWidget(buildFrame()); Offset tileOffset = tester.getTopLeft(find.byType(ListTile)); Offset leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); Offset trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are centered vertically in the tile. const double centerPosition = (tileHeight / 2) - (leadingHeight / 2); expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.threeLine] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.threeLine)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are centered vertically in the tile, // If the [ListTile.isThreeLine] property is false. expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.titleHeight] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.titleHeight)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // If the tile height is less than 72.0 pixels, the leading widget is placed // 16.0 pixels below the top of the title widget, and the trailing is centered // vertically in the tile. const double titlePosition = 16.0; expect(leadingOffset.dy - tileOffset.dy, titlePosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.top] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.top)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are placed minVerticalPadding below // the top of the title widget. const double topPosition = minVerticalPadding; expect(leadingOffset.dy - tileOffset.dy, topPosition); expect(trailingOffset.dy - tileOffset.dy, topPosition); // Test [ListTileTitleAlignment.center] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.center)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are centered vertically in the tile. expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.bottom] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.bottom)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are placed minVerticalPadding above // the bottom of the subtitle widget. const double bottomPosition = tileHeight - minVerticalPadding - leadingHeight; expect(leadingOffset.dy - tileOffset.dy, bottomPosition); expect(trailingOffset.dy - tileOffset.dy, bottomPosition); }); testWidgets('titleAlignment position with title and subtitle widgets', (WidgetTester tester) async { final Key leadingKey = GlobalKey(); final Key trailingKey = GlobalKey(); const double leadingHeight = 24.0; const double titleHeight = 50.0; const double subtitleHeight = 50.0; const double trailingHeight = 24.0; const double minVerticalPadding = 10.0; const double tileHeight = minVerticalPadding * 2 + titleHeight + subtitleHeight; Widget buildFrame({ ListTileTitleAlignment? titleAlignment }) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: Center( child: ListTile( titleAlignment: titleAlignment, minVerticalPadding: minVerticalPadding, leading: SizedBox(key: leadingKey, width: 24.0, height: leadingHeight), title: const SizedBox(width: 20.0, height: titleHeight), subtitle: const SizedBox(width: 20.0, height: subtitleHeight), trailing: SizedBox(key: trailingKey, width: 24.0, height: trailingHeight), ), ), ), ); } // If [ThemeData.useMaterial3] is true, the default title alignment is // [ListTileTitleAlignment.threeLine], which positions the leading and // trailing widgets center vertically in the tile if the [ListTile.isThreeLine] // property is false. await tester.pumpWidget(buildFrame()); Offset tileOffset = tester.getTopLeft(find.byType(ListTile)); Offset leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); Offset trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are centered vertically in the tile. const double centerPosition = (tileHeight / 2) - (leadingHeight / 2); expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.threeLine] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.threeLine)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are centered vertically in the tile, // If the [ListTile.isThreeLine] property is false. expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.titleHeight] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.titleHeight)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are positioned 16.0 pixels below the // top of the title widget. const double titlePosition = 16.0; expect(leadingOffset.dy - tileOffset.dy, titlePosition); expect(trailingOffset.dy - tileOffset.dy, titlePosition); // Test [ListTileTitleAlignment.top] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.top)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are placed minVerticalPadding below // the top of the title widget. const double topPosition = minVerticalPadding; expect(leadingOffset.dy - tileOffset.dy, topPosition); expect(trailingOffset.dy - tileOffset.dy, topPosition); // Test [ListTileTitleAlignment.center] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.center)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are centered vertically in the tile. expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.bottom] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.bottom)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are placed minVerticalPadding above // the bottom of the subtitle widget. const double bottomPosition = tileHeight - minVerticalPadding - leadingHeight; expect(leadingOffset.dy - tileOffset.dy, bottomPosition); expect(trailingOffset.dy - tileOffset.dy, bottomPosition); }); testWidgets("ListTile.isThreeLine updates ListTileTitleAlignment.threeLine's alignment", (WidgetTester tester) async { final Key leadingKey = GlobalKey(); final Key trailingKey = GlobalKey(); const double leadingHeight = 24.0; const double titleHeight = 50.0; const double subtitleHeight = 50.0; const double trailingHeight = 24.0; const double minVerticalPadding = 10.0; const double tileHeight = minVerticalPadding * 2 + titleHeight + subtitleHeight; Widget buildFrame({ ListTileTitleAlignment? titleAlignment, bool isThreeLine = false }) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: Center( child: ListTile( titleAlignment: titleAlignment, minVerticalPadding: minVerticalPadding, leading: SizedBox(key: leadingKey, width: 24.0, height: leadingHeight), title: const SizedBox(width: 20.0, height: titleHeight), subtitle: const SizedBox(width: 20.0, height: subtitleHeight), trailing: SizedBox(key: trailingKey, width: 24.0, height: trailingHeight), isThreeLine: isThreeLine, ), ), ), ); } // If [ThemeData.useMaterial3] is true, then title alignment should // default to [ListTileTitleAlignment.threeLine]. await tester.pumpWidget(buildFrame()); Offset tileOffset = tester.getTopLeft(find.byType(ListTile)); Offset leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); Offset trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // By default, leading and trailing widgets are centered vertically // in the tile. const double centerPosition = (tileHeight / 2) - (leadingHeight / 2); expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Set [ListTile.isThreeLine] to true to update the alignment. await tester.pumpWidget(buildFrame(isThreeLine: true)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // The leading and trailing widgets are placed minVerticalPadding // to the top of the tile widget. const double topPosition = minVerticalPadding; expect(leadingOffset.dy - tileOffset.dy, topPosition); expect(trailingOffset.dy - tileOffset.dy, topPosition); }); group('Material 2', () { // These tests are only relevant for Material 2. Once Material 2 // support is deprecated and the APIs are removed, these tests // can be deleted. testWidgets('ListTile geometry (LTR)', (WidgetTester tester) async { // See https://material.io/go/design-lists final Key leadingKey = GlobalKey(); final Key trailingKey = GlobalKey(); late bool hasSubtitle; const double leftPadding = 10.0; const double rightPadding = 20.0; Widget buildFrame({ bool dense = false, bool isTwoLine = false, bool isThreeLine = false, TextScaler textScaler = TextScaler.noScaling, TextScaler? subtitleScaler }) { hasSubtitle = isTwoLine || isThreeLine; subtitleScaler ??= textScaler; return MaterialApp( theme: ThemeData(useMaterial3: false), home: MediaQuery( data: MediaQueryData( padding: const EdgeInsets.only(left: leftPadding, right: rightPadding), textScaler: textScaler, ), child: Material( child: Center( child: ListTile( leading: SizedBox(key: leadingKey, width: 24.0, height: 24.0), title: const Text('title'), subtitle: hasSubtitle ? Text('subtitle', textScaler: subtitleScaler) : null, trailing: SizedBox(key: trailingKey, width: 24.0, height: 24.0), dense: dense, isThreeLine: isThreeLine, ), ), ), ), ); } void testChildren() { expect(find.byKey(leadingKey), findsOneWidget); expect(find.text('title'), findsOneWidget); if (hasSubtitle) { expect(find.text('subtitle'), findsOneWidget); } expect(find.byKey(trailingKey), findsOneWidget); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double top(String text) => tester.getTopLeft(find.text(text)).dy; double bottom(String text) => tester.getBottomLeft(find.text(text)).dy; double height(String text) => tester.getRect(find.text(text)).height; double leftKey(Key key) => tester.getTopLeft(find.byKey(key)).dx; double rightKey(Key key) => tester.getTopRight(find.byKey(key)).dx; double widthKey(Key key) => tester.getSize(find.byKey(key)).width; double heightKey(Key key) => tester.getSize(find.byKey(key)).height; // ListTiles are contained by a SafeArea defined like this: // SafeArea(top: false, bottom: false, minimum: contentPadding) // The default contentPadding is 16.0 on the left and right. void testHorizontalGeometry() { expect(leftKey(leadingKey), math.max(16.0, leftPadding)); expect(left('title'), 56.0 + math.max(16.0, leftPadding)); if (hasSubtitle) { expect(left('subtitle'), 56.0 + math.max(16.0, leftPadding)); } expect(left('title'), rightKey(leadingKey) + 32.0); expect(rightKey(trailingKey), 800.0 - math.max(16.0, rightPadding)); expect(widthKey(trailingKey), 24.0); } void testVerticalGeometry(double expectedHeight) { final Rect tileRect = tester.getRect(find.byType(ListTile)); expect(tileRect.size, Size(800.0, expectedHeight)); expect(top('title'), greaterThanOrEqualTo(tileRect.top)); if (hasSubtitle) { expect(top('subtitle'), greaterThanOrEqualTo(bottom('title'))); expect(bottom('subtitle'), lessThan(tileRect.bottom)); } else { expect(top('title'), equals(tileRect.top + (tileRect.height - height('title')) / 2.0)); } expect(heightKey(trailingKey), 24.0); } await tester.pumpWidget(buildFrame()); testChildren(); testHorizontalGeometry(); testVerticalGeometry(56.0); await tester.pumpWidget(buildFrame(dense: true)); testChildren(); testHorizontalGeometry(); testVerticalGeometry(48.0); await tester.pumpWidget(buildFrame(isTwoLine: true)); testChildren(); testHorizontalGeometry(); testVerticalGeometry(72.0); await tester.pumpWidget(buildFrame(isTwoLine: true, dense: true)); testChildren(); testHorizontalGeometry(); testVerticalGeometry(64.0); await tester.pumpWidget(buildFrame(isThreeLine: true)); testChildren(); testHorizontalGeometry(); testVerticalGeometry(88.0); await tester.pumpWidget(buildFrame(isThreeLine: true, dense: true)); testChildren(); testHorizontalGeometry(); testVerticalGeometry(76.0); await tester.pumpWidget(buildFrame(textScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); testVerticalGeometry(72.0); await tester.pumpWidget(buildFrame(dense: true, textScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); testVerticalGeometry(72.0); await tester.pumpWidget(buildFrame(isTwoLine: true, textScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); testVerticalGeometry(128.0); // Make sure that the height of a large subtitle is taken into account. await tester.pumpWidget(buildFrame(isTwoLine: true, textScaler: const TextScaler.linear(0.5), subtitleScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); testVerticalGeometry(72.0); await tester.pumpWidget(buildFrame(isTwoLine: true, dense: true, textScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); testVerticalGeometry(128.0); await tester.pumpWidget(buildFrame(isThreeLine: true, textScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); testVerticalGeometry(128.0); await tester.pumpWidget(buildFrame(isThreeLine: true, dense: true, textScaler: const TextScaler.linear(4.0))); testChildren(); testHorizontalGeometry(); testVerticalGeometry(128.0); }); testWidgets('ListTile geometry (RTL)', (WidgetTester tester) async { const double leftPadding = 10.0; const double rightPadding = 20.0; await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: false), home: const MediaQuery( data: MediaQueryData( padding: EdgeInsets.only(left: leftPadding, right: rightPadding), ), child: Directionality( textDirection: TextDirection.rtl, child: Material( child: Center( child: ListTile( leading: Text('L'), title: Text('title'), trailing: Text('T'), ), ), ), ), ), )); double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; void testHorizontalGeometry() { expect(right('L'), 800.0 - math.max(16.0, rightPadding)); expect(right('title'), 800.0 - 56.0 - math.max(16.0, rightPadding)); expect(left('T'), math.max(16.0, leftPadding)); } testHorizontalGeometry(); }); testWidgets('ListTile leading and trailing positions', (WidgetTester tester) async { // This test is based on the redlines at // https://material.io/design/components/lists.html#specs // DENSE "ONE"-LINE await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( dense: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( dense: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), ), ], ), ), ), ); // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, 177.0)); expect(tester.getRect(find.byType(CircleAvatar).at(0)), const Rect.fromLTWH( 16.0, 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 16.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, 177.0, 800.0, 48.0)); expect(tester.getRect(find.byType(CircleAvatar).at(1)), const Rect.fromLTWH( 16.0, 177.0 + 4.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 177.0 + 12.0, 24.0, 24.0)); // NON-DENSE "ONE"-LINE await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), ), ], ), ), ), ); await tester.pump(const Duration(seconds: 2)); // the text styles are animated when we change dense // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, 216.0)); expect(tester.getRect(find.byType(CircleAvatar).at(0)), const Rect.fromLTWH( 16.0, 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 16.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, 216.0 , 800.0, 56.0)); expect(tester.getRect(find.byType(CircleAvatar).at(1)), const Rect.fromLTWH( 16.0, 216.0 + 8.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 216.0 + 16.0, 24.0, 24.0)); // DENSE "TWO"-LINE await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( dense: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( dense: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A'), ), ], ), ), ), ); // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, 180.0)); expect(tester.getRect(find.byType(CircleAvatar).at(0)), const Rect.fromLTWH( 16.0, 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 16.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, 180.0, 800.0, 64.0)); expect(tester.getRect(find.byType(CircleAvatar).at(1)), const Rect.fromLTWH( 16.0, 180.0 + 12.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 180.0 + 20.0, 24.0, 24.0)); // NON-DENSE "TWO"-LINE await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A'), ), ], ), ), ), ); // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, 180.0)); expect(tester.getRect(find.byType(CircleAvatar).at(0)), const Rect.fromLTWH( 16.0, 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 16.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, 180.0, 800.0, 72.0)); expect(tester.getRect(find.byType(CircleAvatar).at(1)), const Rect.fromLTWH( 16.0, 180.0 + 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 180.0 + 24.0, 24.0, 24.0)); // DENSE "THREE"-LINE await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( dense: true, isThreeLine: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( dense: true, isThreeLine: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A'), ), ], ), ), ), ); // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, 180.0)); expect(tester.getRect(find.byType(CircleAvatar).at(0)), const Rect.fromLTWH( 16.0, 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 16.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, 180.0, 800.0, 76.0)); expect(tester.getRect(find.byType(CircleAvatar).at(1)), const Rect.fromLTWH( 16.0, 180.0 + 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 180.0 + 16.0, 24.0, 24.0)); // NON-DENSE THREE-LINE await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( isThreeLine: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( isThreeLine: true, leading: CircleAvatar(), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), subtitle: Text('A'), ), ], ), ), ), ); // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, 180.0)); expect(tester.getRect(find.byType(CircleAvatar).at(0)), const Rect.fromLTWH( 16.0, 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 16.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, 180.0, 800.0, 88.0)); expect(tester.getRect(find.byType(CircleAvatar).at(1)), const Rect.fromLTWH( 16.0, 180.0 + 16.0, 40.0, 40.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 180.0 + 16.0, 24.0, 24.0)); // "ONE-LINE" with Small Leading Widget await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: SizedBox(height:12.0, width:24.0, child: Placeholder()), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A\nB\nC\nD\nE\nF\nG\nH\nI\nJ\nK\nL\nM'), ), ListTile( leading: SizedBox(height:12.0, width:24.0, child: Placeholder()), trailing: SizedBox(height: 24.0, width: 24.0, child: Placeholder()), title: Text('A'), ), ], ), ), ), ); await tester.pump(const Duration(seconds: 2)); // the text styles are animated when we change dense // LEFT TOP WIDTH HEIGHT expect(tester.getRect(find.byType(ListTile).at(0)), const Rect.fromLTWH( 0.0, 0.0, 800.0, 216.0)); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH( 16.0, 16.0, 24.0, 12.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 16.0, 24.0, 24.0)); expect(tester.getRect(find.byType(ListTile).at(1)), const Rect.fromLTWH( 0.0, 216.0 , 800.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(2)), const Rect.fromLTWH( 16.0, 216.0 + 16.0, 24.0, 12.0)); expect(tester.getRect(find.byType(Placeholder).at(3)), const Rect.fromLTWH(800.0 - 24.0 - 16.0, 216.0 + 16.0, 24.0, 24.0)); }); testWidgets('ListTile leading icon height does not exceed ListTile height', (WidgetTester tester) async { // regression test for https://github.com/flutter/flutter/issues/28765 const SizedBox oversizedWidget = SizedBox(height: 80.0, width: 24.0, child: Placeholder()); // Dense One line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: oversizedWidget, title: Text('A'), dense: true, ), ListTile( leading: oversizedWidget, title: Text('B'), dense: true, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(16.0, 0.0, 24.0, 48.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(16.0, 48.0, 24.0, 48.0)); // Non-dense One line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: oversizedWidget, title: Text('A'), dense: false, ), ListTile( leading: oversizedWidget, title: Text('B'), dense: false, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(16.0, 0.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(16.0, 56.0, 24.0, 56.0)); // Dense Two line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: oversizedWidget, title: Text('A'), subtitle: Text('A'), dense: true, ), ListTile( leading: oversizedWidget, title: Text('B'), subtitle: Text('B'), dense: true, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(16.0, 8.0, 24.0, 48.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(16.0, 64.0 + 8.0, 24.0, 48.0)); // Non-dense Two line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: oversizedWidget, title: Text('A'), subtitle: Text('A'), dense: false, ), ListTile( leading: oversizedWidget, title: Text('B'), subtitle: Text('B'), dense: false, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(16.0, 8.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(16.0, 72.0 + 8.0, 24.0, 56.0)); // Dense Three line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: oversizedWidget, title: Text('A'), subtitle: Text('A'), isThreeLine: true, dense: true, ), ListTile( leading: oversizedWidget, title: Text('B'), subtitle: Text('B'), isThreeLine: true, dense: true, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(16.0, 16.0, 24.0, 48.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(16.0, 76.0 + 16.0, 24.0, 48.0)); // Non-dense Three line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( leading: oversizedWidget, title: Text('A'), subtitle: Text('A'), isThreeLine: true, dense: false, ), ListTile( leading: oversizedWidget, title: Text('B'), subtitle: Text('B'), isThreeLine: true, dense: false, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(16.0, 16.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(16.0, 88.0 + 16.0, 24.0, 56.0)); }); testWidgets('ListTile trailing icon height does not exceed ListTile height', (WidgetTester tester) async { // regression test for https://github.com/flutter/flutter/issues/28765 const SizedBox oversizedWidget = SizedBox(height: 80.0, width: 24.0, child: Placeholder()); // Dense One line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( trailing: oversizedWidget, title: Text('A'), dense: true, ), ListTile( trailing: oversizedWidget, title: Text('B'), dense: true, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 0, 24.0, 48.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 48.0, 24.0, 48.0)); // Non-dense One line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( trailing: oversizedWidget, title: Text('A'), dense: false, ), ListTile( trailing: oversizedWidget, title: Text('B'), dense: false, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 0.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 56.0, 24.0, 56.0)); // Dense Two line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( trailing: oversizedWidget, title: Text('A'), subtitle: Text('A'), dense: true, ), ListTile( trailing: oversizedWidget, title: Text('B'), subtitle: Text('B'), dense: true, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 8.0, 24.0, 48.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 64.0 + 8.0, 24.0, 48.0)); // Non-dense Two line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( trailing: oversizedWidget, title: Text('A'), subtitle: Text('A'), dense: false, ), ListTile( trailing: oversizedWidget, title: Text('B'), subtitle: Text('B'), dense: false, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 8.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 72.0 + 8.0, 24.0, 56.0)); // Dense Three line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( trailing: oversizedWidget, title: Text('A'), subtitle: Text('A'), isThreeLine: true, dense: true, ), ListTile( trailing: oversizedWidget, title: Text('B'), subtitle: Text('B'), isThreeLine: true, dense: true, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 16.0, 24.0, 48.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 76.0 + 16.0, 24.0, 48.0)); // Non-dense Three line await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: ListView( children: const <Widget>[ ListTile( trailing: oversizedWidget, title: Text('A'), subtitle: Text('A'), isThreeLine: true, dense: false, ), ListTile( trailing: oversizedWidget, title: Text('B'), subtitle: Text('B'), isThreeLine: true, dense: false, ), ], ), ), ), ); expect(tester.getRect(find.byType(Placeholder).at(0)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 16.0, 24.0, 56.0)); expect(tester.getRect(find.byType(Placeholder).at(1)), const Rect.fromLTWH(800.0 - 16.0 - 24.0, 88.0 + 16.0, 24.0, 56.0)); }); testWidgets('ListTile wide leading Widget', (WidgetTester tester) async { const Key leadingKey = ValueKey<String>('L'); Widget buildFrame(double leadingWidth, TextDirection textDirection) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Directionality( textDirection: textDirection, child: Material( child: Container( alignment: Alignment.topLeft, child: ListTile( contentPadding: EdgeInsets.zero, leading: SizedBox(key: leadingKey, width: leadingWidth, height: 32.0), title: const Text('title'), subtitle: const Text('subtitle'), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; // textDirection = LTR // Two-line tile's height = 72, leading 24x32 widget is positioned 16.0 pixels from the top. await tester.pumpWidget(buildFrame(24.0, TextDirection.ltr)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 72.0)); expect(tester.getTopLeft(find.byKey(leadingKey)), const Offset(0.0, 16.0)); expect(tester.getBottomRight(find.byKey(leadingKey)), const Offset(24.0, 16.0 + 32.0)); // Leading widget's width is 20, so default layout: the left edges of the // title and subtitle are at 56dps (contentPadding is zero). expect(left('title'), 56.0); expect(left('subtitle'), 56.0); // If the leading widget is wider than 40 it is separated from the // title and subtitle by 16. await tester.pumpWidget(buildFrame(56.0, TextDirection.ltr)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 72.0)); expect(tester.getTopLeft(find.byKey(leadingKey)), const Offset(0.0, 16.0)); expect(tester.getBottomRight(find.byKey(leadingKey)), const Offset(56.0, 16.0 + 32.0)); expect(left('title'), 72.0); expect(left('subtitle'), 72.0); // Same tests, textDirection = RTL await tester.pumpWidget(buildFrame(24.0, TextDirection.rtl)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 72.0)); expect(tester.getTopRight(find.byKey(leadingKey)), const Offset(800.0, 16.0)); expect(tester.getBottomLeft(find.byKey(leadingKey)), const Offset(800.0 - 24.0, 16.0 + 32.0)); expect(right('title'), 800.0 - 56.0); expect(right('subtitle'), 800.0 - 56.0); await tester.pumpWidget(buildFrame(56.0, TextDirection.rtl)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 72.0)); expect(tester.getTopRight(find.byKey(leadingKey)), const Offset(800.0, 16.0)); expect(tester.getBottomLeft(find.byKey(leadingKey)), const Offset(800.0 - 56.0, 16.0 + 32.0)); expect(right('title'), 800.0 - 72.0); expect(right('subtitle'), 800.0 - 72.0); }); testWidgets('ListTile horizontalTitleGap = 0.0', (WidgetTester tester) async { Widget buildFrame(TextDirection textDirection, { double? themeHorizontalTitleGap, double? widgetHorizontalTitleGap }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Directionality( textDirection: textDirection, child: Material( child: ListTileTheme( data: ListTileThemeData(horizontalTitleGap: themeHorizontalTitleGap), child: Container( alignment: Alignment.topLeft, child: ListTile( horizontalTitleGap: widgetHorizontalTitleGap, leading: const Text('L'), title: const Text('title'), trailing: const Text('T'), ), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; await tester.pumpWidget(buildFrame(TextDirection.ltr, widgetHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 56.0); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 56.0); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeHorizontalTitleGap: 10, widgetHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 56.0); await tester.pumpWidget(buildFrame(TextDirection.rtl, widgetHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(right('title'), 744.0); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(right('title'), 744.0); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeHorizontalTitleGap: 10, widgetHorizontalTitleGap: 0)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(right('title'), 744.0); }); testWidgets('ListTile horizontalTitleGap = (default) && ListTile minLeadingWidth = (default)', (WidgetTester tester) async { Widget buildFrame(TextDirection textDirection) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Directionality( textDirection: textDirection, child: Material( child: Container( alignment: Alignment.topLeft, child: const ListTile( leading: Text('L'), title: Text('title'), trailing: Text('T'), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; double right(String text) => tester.getTopRight(find.text(text)).dx; await tester.pumpWidget(buildFrame(TextDirection.ltr)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); // horizontalTitleGap: ListTileDefaultValue.horizontalTitleGap (16.0) expect(left('title'), 72.0); await tester.pumpWidget(buildFrame(TextDirection.rtl)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); // horizontalTitleGap: ListTileDefaultValue.horizontalTitleGap (16.0) expect(right('title'), 728.0); }); testWidgets('ListTile horizontalTitleGap with visualDensity', (WidgetTester tester) async { Widget buildFrame({ double? horizontalTitleGap, VisualDensity? visualDensity, }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Container( alignment: Alignment.topLeft, child: ListTile( visualDensity: visualDensity, horizontalTitleGap: horizontalTitleGap, leading: const Text('L'), title: const Text('title'), trailing: const Text('T'), ), ), ), ), ); } double left(String text) => tester.getTopLeft(find.text(text)).dx; await tester.pumpWidget(buildFrame( horizontalTitleGap: 10.0, visualDensity: const VisualDensity(horizontal: VisualDensity.minimumDensity), )); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 58.0); // Pump another frame of the same widget to ensure the underlying render // object did not cache the original horizontalTitleGap calculation based on the // visualDensity await tester.pumpWidget(buildFrame( horizontalTitleGap: 10.0, visualDensity: const VisualDensity(horizontal: VisualDensity.minimumDensity), )); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 56.0)); expect(left('title'), 58.0); }); testWidgets('ListTile minVerticalPadding = 80.0', (WidgetTester tester) async { Widget buildFrame(TextDirection textDirection, { double? themeMinVerticalPadding, double? widgetMinVerticalPadding }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Directionality( textDirection: textDirection, child: Material( child: ListTileTheme( data: ListTileThemeData(minVerticalPadding: themeMinVerticalPadding), child: Container( alignment: Alignment.topLeft, child: ListTile( minVerticalPadding: widgetMinVerticalPadding, leading: const Text('L'), title: const Text('title'), trailing: const Text('T'), ), ), ), ), ), ); } await tester.pumpWidget(buildFrame(TextDirection.ltr, widgetMinVerticalPadding: 80)); // 80 + 80 + 16(Title) = 176 expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 176.0)); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeMinVerticalPadding: 80)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 176.0)); await tester.pumpWidget(buildFrame(TextDirection.ltr, themeMinVerticalPadding: 0, widgetMinVerticalPadding: 80)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 176.0)); await tester.pumpWidget(buildFrame(TextDirection.rtl, widgetMinVerticalPadding: 80)); // 80 + 80 + 16(Title) = 176 expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 176.0)); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeMinVerticalPadding: 80)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 176.0)); await tester.pumpWidget(buildFrame(TextDirection.rtl, themeMinVerticalPadding: 0, widgetMinVerticalPadding: 80)); expect(tester.getSize(find.byType(ListTile)), const Size(800.0, 176.0)); }); testWidgets('ListTile font size', (WidgetTester tester) async { Widget buildFrame({ bool dense = false, bool enabled = true, bool selected = false, ListTileStyle? style, }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: Builder( builder: (BuildContext context) { return ListTile( dense: dense, enabled: enabled, selected: selected, style: style, leading: const TestText('leading'), title: const TestText('title'), subtitle: const TestText('subtitle') , trailing: const TestText('trailing'), ); }, ), ), ), ); } // ListTile - ListTileStyle.list (default). await tester.pumpWidget(buildFrame()); RenderParagraph leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.fontSize, 14.0); RenderParagraph title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.fontSize, 16.0); RenderParagraph subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.fontSize, 14.0); RenderParagraph trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.fontSize, 14.0); // ListTile - Densed - ListTileStyle.list (default). await tester.pumpWidget(buildFrame(dense: true)); await tester.pumpAndSettle(); leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.fontSize, 14.0); title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.fontSize, 13.0); subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.fontSize, 12.0); trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.fontSize, 14.0); // ListTile - ListTileStyle.drawer. await tester.pumpWidget(buildFrame(style: ListTileStyle.drawer)); await tester.pumpAndSettle(); leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.fontSize, 14.0); title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.fontSize, 14.0); subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.fontSize, 14.0); trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.fontSize, 14.0); // ListTile - Densed - ListTileStyle.drawer. await tester.pumpWidget(buildFrame(dense: true, style: ListTileStyle.drawer)); await tester.pumpAndSettle(); leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.fontSize, 14.0); title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.fontSize, 13.0); subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.fontSize, 12.0); trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.fontSize, 14.0); }); testWidgets('ListTile text color', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: false); Widget buildFrame({ bool dense = false, bool enabled = true, bool selected = false, ListTileStyle? style, }) { return MaterialApp( theme: theme, home: Material( child: Center( child: Builder( builder: (BuildContext context) { return ListTile( dense: dense, enabled: enabled, selected: selected, style: style, leading: const TestText('leading'), title: const TestText('title'), subtitle: const TestText('subtitle') , trailing: const TestText('trailing'), ); }, ), ), ), ); } // ListTile - ListTileStyle.list (default). await tester.pumpWidget(buildFrame()); RenderParagraph leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.color, theme.textTheme.bodyMedium!.color); RenderParagraph title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.color, theme.textTheme.titleMedium!.color); RenderParagraph subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.color, theme.textTheme.bodySmall!.color); RenderParagraph trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.color, theme.textTheme.bodyMedium!.color); // ListTile - ListTileStyle.drawer. await tester.pumpWidget(buildFrame(style: ListTileStyle.drawer)); await tester.pumpAndSettle(); leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.color, theme.textTheme.bodyMedium!.color); title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.color, theme.textTheme.titleMedium!.color); subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.color, theme.textTheme.bodySmall!.color); trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.color, theme.textTheme.bodyMedium!.color); }); testWidgets('selected, enabled ListTile default icon color, light and dark themes', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/77004 const ColorScheme lightColorScheme = ColorScheme.light(); const ColorScheme darkColorScheme = ColorScheme.dark(); final Key leadingKey = UniqueKey(); final Key titleKey = UniqueKey(); final Key subtitleKey = UniqueKey(); final Key trailingKey = UniqueKey(); Widget buildFrame({ required Brightness brightness, required bool selected }) { final ThemeData theme = brightness == Brightness.light ? ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: false) : ThemeData.from(colorScheme: const ColorScheme.dark(), useMaterial3: false); return MaterialApp( theme: theme, home: Material( child: Center( child: ListTile( selected: selected, leading: TestIcon(key: leadingKey), title: TestIcon(key: titleKey), subtitle: TestIcon(key: subtitleKey), trailing: TestIcon(key: trailingKey), ), ), ), ); } Color iconColor(Key key) => tester.state<TestIconState>(find.byKey(key)).iconTheme.color!; await tester.pumpWidget(buildFrame(brightness: Brightness.light, selected: true)); expect(iconColor(leadingKey), lightColorScheme.primary); expect(iconColor(titleKey), lightColorScheme.primary); expect(iconColor(subtitleKey), lightColorScheme.primary); expect(iconColor(trailingKey), lightColorScheme.primary); await tester.pumpWidget(buildFrame(brightness: Brightness.light, selected: false)); expect(iconColor(leadingKey), Colors.black45); expect(iconColor(titleKey), Colors.black45); expect(iconColor(subtitleKey), Colors.black45); expect(iconColor(trailingKey), Colors.black45); await tester.pumpWidget(buildFrame(brightness: Brightness.dark, selected: true)); await tester.pumpAndSettle(); // Animated theme change expect(iconColor(leadingKey), darkColorScheme.primary); expect(iconColor(titleKey), darkColorScheme.primary); expect(iconColor(subtitleKey), darkColorScheme.primary); expect(iconColor(trailingKey), darkColorScheme.primary); // For this configuration, ListTile defers to the default IconTheme. // The default dark theme's IconTheme has color:white await tester.pumpWidget(buildFrame(brightness: Brightness.dark, selected: false)); expect(iconColor(leadingKey), Colors.white); expect(iconColor(titleKey), Colors.white); expect(iconColor(subtitleKey), Colors.white); expect(iconColor(trailingKey), Colors.white); }); testWidgets('ListTile default tile color', (WidgetTester tester) async { bool isSelected = false; const Color defaultColor = Colors.transparent; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ListTile( selected: isSelected, onTap: () { setState(()=> isSelected = !isSelected); }, title: const Text('Title'), ); }, ), ), ), ), ); expect(find.byType(Material), paints..rect(color: defaultColor)); // Tap on tile to change isSelected. await tester.tap(find.byType(ListTile)); await tester.pumpAndSettle(); expect(find.byType(Material), paints..rect(color: defaultColor)); }); testWidgets('titleAlignment position with title widget', (WidgetTester tester) async { final Key leadingKey = GlobalKey(); final Key trailingKey = GlobalKey(); const double leadingHeight = 24.0; const double titleHeight = 50.0; const double trailingHeight = 24.0; const double minVerticalPadding = 10.0; const double tileHeight = minVerticalPadding * 2 + titleHeight; Widget buildFrame({ ListTileTitleAlignment? titleAlignment }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: ListTile( titleAlignment: titleAlignment, minVerticalPadding: minVerticalPadding, leading: SizedBox(key: leadingKey, width: 24.0, height: leadingHeight), title: const SizedBox(width: 20.0, height: titleHeight), trailing: SizedBox(key: trailingKey, width: 24.0, height: trailingHeight), ), ), ), ); } // If [ThemeData.useMaterial3] is false, the default title alignment is // [ListTileTitleAlignment.titleHeight], If the tile height is less than // 72.0 pixels, the leading is placed 16.0 pixels below the top of // the title widget and the trailing is centered vertically in the tile. await tester.pumpWidget(buildFrame()); Offset tileOffset = tester.getTopLeft(find.byType(ListTile)); Offset leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); Offset trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are centered vertically in the tile. const double titlePosition = 16.0; const double centerPosition = (tileHeight / 2) - (leadingHeight / 2); expect(leadingOffset.dy - tileOffset.dy, titlePosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.threeLine] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.threeLine)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are centered vertically in the tile, // If the [ListTile.isThreeLine] property is false. expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.titleHeight] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.titleHeight)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // If the tile height is less than 72.0 pixels, the leading is placed // 16.0 pixels below the top of the tile widget, and the trailing is // centered vertically in the tile. expect(leadingOffset.dy - tileOffset.dy, titlePosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.top] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.top)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are placed minVerticalPadding below // the top of the title widget. const double topPosition = minVerticalPadding; expect(leadingOffset.dy - tileOffset.dy, topPosition); expect(trailingOffset.dy - tileOffset.dy, topPosition); // Test [ListTileTitleAlignment.center] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.center)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are vertically centered in the tile. expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.bottom] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.bottom)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are placed minVerticalPadding above // the bottom of the subtitle widget. const double bottomPosition = tileHeight - minVerticalPadding - leadingHeight; expect(leadingOffset.dy - tileOffset.dy, bottomPosition); expect(trailingOffset.dy - tileOffset.dy, bottomPosition); }); testWidgets('titleAlignment position with title and subtitle widgets', (WidgetTester tester) async { final Key leadingKey = GlobalKey(); final Key trailingKey = GlobalKey(); const double leadingHeight = 24.0; const double titleHeight = 50.0; const double subtitleHeight = 50.0; const double trailingHeight = 24.0; const double minVerticalPadding = 10.0; const double tileHeight = minVerticalPadding * 2 + titleHeight + subtitleHeight; Widget buildFrame({ ListTileTitleAlignment? titleAlignment }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: ListTile( titleAlignment: titleAlignment, minVerticalPadding: minVerticalPadding, leading: SizedBox(key: leadingKey, width: 24.0, height: leadingHeight), title: const SizedBox(width: 20.0, height: titleHeight), subtitle: const SizedBox(width: 20.0, height: subtitleHeight), trailing: SizedBox(key: trailingKey, width: 24.0, height: trailingHeight), ), ), ), ); } // If [ThemeData.useMaterial3] is false, the default title alignment is // [ListTileTitleAlignment.titleHeight], which positions the leading and // trailing widgets 16.0 pixels below the top of the tile widget. await tester.pumpWidget(buildFrame()); Offset tileOffset = tester.getTopLeft(find.byType(ListTile)); Offset leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); Offset trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are positioned 16.0 pixels below the // top of the tile widget. const double titlePosition = 16.0; expect(leadingOffset.dy - tileOffset.dy, titlePosition); expect(trailingOffset.dy - tileOffset.dy, titlePosition); // Test [ListTileTitleAlignment.threeLine] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.threeLine)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are vertically centered in the tile, // If the [ListTile.isThreeLine] property is false. const double centerPosition = (tileHeight / 2) - (leadingHeight / 2); expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.titleHeight] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.titleHeight)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are positioned 16.0 pixels below the // top of the tile widget. expect(leadingOffset.dy - tileOffset.dy, titlePosition); expect(trailingOffset.dy - tileOffset.dy, titlePosition); // Test [ListTileTitleAlignment.top] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.top)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are placed minVerticalPadding below // the top of the tile widget. const double topPosition = minVerticalPadding; expect(leadingOffset.dy - tileOffset.dy, topPosition); expect(trailingOffset.dy - tileOffset.dy, topPosition); // Test [ListTileTitleAlignment.center] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.center)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are vertically centered in the tile. expect(leadingOffset.dy - tileOffset.dy, centerPosition); expect(trailingOffset.dy - tileOffset.dy, centerPosition); // Test [ListTileTitleAlignment.bottom] alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.bottom)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // Leading and trailing widgets are placed minVerticalPadding above // the bottom of the subtitle widget. const double bottomPosition = tileHeight - minVerticalPadding - leadingHeight; expect(leadingOffset.dy - tileOffset.dy, bottomPosition); expect(trailingOffset.dy - tileOffset.dy, bottomPosition); }); testWidgets("ListTile.isThreeLine updates ListTileTitleAlignment.threeLine's alignment", (WidgetTester tester) async { final Key leadingKey = GlobalKey(); final Key trailingKey = GlobalKey(); const double leadingHeight = 24.0; const double titleHeight = 50.0; const double subtitleHeight = 50.0; const double trailingHeight = 24.0; const double minVerticalPadding = 10.0; const double tileHeight = minVerticalPadding * 2 + titleHeight + subtitleHeight; Widget buildFrame({ ListTileTitleAlignment? titleAlignment, bool isThreeLine = false }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: ListTile( titleAlignment: titleAlignment, minVerticalPadding: minVerticalPadding, leading: SizedBox(key: leadingKey, width: 24.0, height: leadingHeight), title: const SizedBox(width: 20.0, height: titleHeight), subtitle: const SizedBox(width: 20.0, height: subtitleHeight), trailing: SizedBox(key: trailingKey, width: 24.0, height: trailingHeight), isThreeLine: isThreeLine, ), ), ), ); } // Set title alignment to threeLine. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.threeLine)); Offset tileOffset = tester.getTopLeft(find.byType(ListTile)); Offset leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); Offset trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // If title alignment is threeLine and [ListTile.isThreeLine] is false, // leading and trailing widgets are centered vertically in the tile. const double leadingTrailingPosition = (tileHeight / 2) - (leadingHeight / 2); expect(leadingOffset.dy - tileOffset.dy, leadingTrailingPosition); expect(trailingOffset.dy - tileOffset.dy, leadingTrailingPosition); // Set [ListTile.isThreeLine] to true to update the alignment. await tester.pumpWidget(buildFrame(titleAlignment: ListTileTitleAlignment.threeLine, isThreeLine: true)); tileOffset = tester.getTopLeft(find.byType(ListTile)); leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); trailingOffset = tester.getTopRight(find.byKey(trailingKey)); // The leading and trailing widgets are placed minVerticalPadding // to the top of the tile widget. expect(leadingOffset.dy - tileOffset.dy, minVerticalPadding); expect(trailingOffset.dy - tileOffset.dy, minVerticalPadding); }); }); } RenderParagraph _getTextRenderObject(WidgetTester tester, String text) { return tester.renderObject(find.descendant( of: find.byType(ListTile), matching: find.text(text), )); }
flutter/packages/flutter/test/material/list_tile_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/list_tile_test.dart", "repo_id": "flutter", "token_count": 70883 }
720
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // 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/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('copyWith, ==, hashCode basics', () { expect(const NavigationBarThemeData(), const NavigationBarThemeData().copyWith()); expect(const NavigationBarThemeData().hashCode, const NavigationBarThemeData().copyWith().hashCode); }); test('NavigationBarThemeData lerp special cases', () { expect(NavigationBarThemeData.lerp(null, null, 0), null); const NavigationBarThemeData data = NavigationBarThemeData(); expect(identical(NavigationBarThemeData.lerp(data, data, 0.5), data), true); }); testWidgets('Default debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const NavigationBarThemeData().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('Custom debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const NavigationBarThemeData( height: 200.0, backgroundColor: Color(0x00000099), elevation: 20.0, indicatorColor: Color(0x00000098), indicatorShape: CircleBorder(), labelTextStyle: MaterialStatePropertyAll<TextStyle>(TextStyle(fontSize: 7.0)), iconTheme: MaterialStatePropertyAll<IconThemeData>(IconThemeData(color: Color(0x00000097))), labelBehavior: NavigationDestinationLabelBehavior.alwaysHide, overlayColor: MaterialStatePropertyAll<Color>(Color(0x00000096)), ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description[0], 'height: 200.0'); expect(description[1], 'backgroundColor: Color(0x00000099)'); expect(description[2], 'elevation: 20.0'); expect(description[3], 'indicatorColor: Color(0x00000098)'); expect(description[4], 'indicatorShape: CircleBorder(BorderSide(width: 0.0, style: none))'); expect(description[5], 'labelTextStyle: WidgetStatePropertyAll(TextStyle(inherit: true, size: 7.0))'); // Ignore instance address for IconThemeData. expect(description[6].contains('iconTheme: WidgetStatePropertyAll(IconThemeData'), isTrue); expect(description[6].contains('(color: Color(0x00000097))'), isTrue); expect(description[7], 'labelBehavior: NavigationDestinationLabelBehavior.alwaysHide'); expect(description[8], 'overlayColor: WidgetStatePropertyAll(Color(0x00000096))'); }); testWidgets('NavigationBarThemeData values are used when no NavigationBar properties are specified', (WidgetTester tester) async { const double height = 200.0; const Color backgroundColor = Color(0x00000001); const double elevation = 42.0; const Color indicatorColor = Color(0x00000002); const ShapeBorder indicatorShape = CircleBorder(); const double selectedIconSize = 25.0; const double unselectedIconSize = 23.0; const Color selectedIconColor = Color(0x00000003); const Color unselectedIconColor = Color(0x00000004); const double selectedIconOpacity = 0.99; const double unselectedIconOpacity = 0.98; const double selectedLabelFontSize = 13.0; const double unselectedLabelFontSize = 11.0; const NavigationDestinationLabelBehavior labelBehavior = NavigationDestinationLabelBehavior.alwaysShow; await tester.pumpWidget( MaterialApp( home: Scaffold( bottomNavigationBar: NavigationBarTheme( data: NavigationBarThemeData( height: height, backgroundColor: backgroundColor, elevation: elevation, indicatorColor: indicatorColor, indicatorShape: indicatorShape, iconTheme: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return const IconThemeData( size: selectedIconSize, color: selectedIconColor, opacity: selectedIconOpacity, ); } return const IconThemeData( size: unselectedIconSize, color: unselectedIconColor, opacity: unselectedIconOpacity, ); }), labelTextStyle: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.selected)) { return const TextStyle(fontSize: selectedLabelFontSize); } return const TextStyle(fontSize: unselectedLabelFontSize); }), labelBehavior: labelBehavior, ), child: NavigationBar( destinations: _destinations(), ), ), ), ), ); expect(_barHeight(tester), height); expect(_barMaterial(tester).color, backgroundColor); expect(_barMaterial(tester).elevation, elevation); expect(_indicator(tester)?.color, indicatorColor); expect(_indicator(tester)?.shape, indicatorShape); expect(_selectedIconTheme(tester).size, selectedIconSize); expect(_selectedIconTheme(tester).color, selectedIconColor); expect(_selectedIconTheme(tester).opacity, selectedIconOpacity); expect(_unselectedIconTheme(tester).size, unselectedIconSize); expect(_unselectedIconTheme(tester).color, unselectedIconColor); expect(_unselectedIconTheme(tester).opacity, unselectedIconOpacity); expect(_selectedLabelStyle(tester).fontSize, selectedLabelFontSize); expect(_unselectedLabelStyle(tester).fontSize, unselectedLabelFontSize); expect(_labelBehavior(tester), labelBehavior); }); testWidgets('NavigationBar values take priority over NavigationBarThemeData values when both properties are specified', (WidgetTester tester) async { const double height = 200.0; const Color backgroundColor = Color(0x00000001); const double elevation = 42.0; const NavigationDestinationLabelBehavior labelBehavior = NavigationDestinationLabelBehavior.alwaysShow; await tester.pumpWidget( MaterialApp( home: Scaffold( bottomNavigationBar: NavigationBarTheme( data: const NavigationBarThemeData( height: 100.0, elevation: 18.0, backgroundColor: Color(0x00000099), labelBehavior: NavigationDestinationLabelBehavior.alwaysHide, ), child: NavigationBar( height: height, elevation: elevation, backgroundColor: backgroundColor, labelBehavior: labelBehavior, destinations: _destinations(), ), ), ), ), ); expect(_barHeight(tester), height); expect(_barMaterial(tester).color, backgroundColor); expect(_barMaterial(tester).elevation, elevation); expect(_labelBehavior(tester), labelBehavior); }); testWidgets('Custom label style renders ink ripple properly', (WidgetTester tester) async { Widget buildWidget({ NavigationDestinationLabelBehavior? labelBehavior }) { return MaterialApp( theme: ThemeData( navigationBarTheme: const NavigationBarThemeData( labelTextStyle: MaterialStatePropertyAll<TextStyle>( TextStyle(fontSize: 25, color: Color(0xff0000ff)), ), ), useMaterial3: true, ), home: Scaffold( bottomNavigationBar: Center( child: NavigationBar( labelBehavior: labelBehavior, destinations: const <Widget>[ NavigationDestination( icon: SizedBox(), label: 'AC', ), NavigationDestination( icon: SizedBox(), label: 'Alarm', ), ], onDestinationSelected: (int i) { }, ), ), ), ); } await tester.pumpWidget(buildWidget()); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(NavigationDestination).last)); await tester.pumpAndSettle(); await expectLater(find.byType(NavigationBar), matchesGoldenFile('indicator_custom_label_style.png')); }); testWidgets('NavigationBar respects NavigationBarTheme.overlayColor in active/pressed/hovered states', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const Color hoverColor = Color(0xff0000ff); const Color focusColor = Color(0xff00ffff); const Color pressedColor = Color(0xffff00ff); final MaterialStateProperty<Color?> overlayColor = MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.hovered)) { return hoverColor; } if (states.contains(MaterialState.focused)) { return focusColor; } if (states.contains(MaterialState.pressed)) { return pressedColor; } return Colors.transparent; }); await tester.pumpWidget(MaterialApp( theme: ThemeData(navigationBarTheme: NavigationBarThemeData(overlayColor: overlayColor)), home: Scaffold( bottomNavigationBar: RepaintBoundary( child: NavigationBar( destinations: const <Widget>[ NavigationDestination( icon: Icon(Icons.ac_unit), label: 'AC', ), NavigationDestination( icon: Icon(Icons.access_alarm), label: 'Alarm', ), ], onDestinationSelected: (int i) { }, ), ), ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(NavigationIndicator).last)); await tester.pumpAndSettle(); final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); // Test hovered state. expect( inkFeatures, kIsWeb ? (paints..rrect()..rrect()..circle(color: hoverColor)) : (paints..circle(color: hoverColor)), ); await gesture.down(tester.getCenter(find.byType(NavigationIndicator).last)); await tester.pumpAndSettle(); // Test pressed state. expect( inkFeatures, kIsWeb ? (paints..circle()..circle()..circle(color: pressedColor)) : (paints..circle()..circle(color: pressedColor)), ); await gesture.up(); await tester.pumpAndSettle(); // Press tab to focus the navigation bar. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); // Test focused state. expect( inkFeatures, kIsWeb ? (paints..circle()..circle(color: focusColor)) : (paints..circle()..circle(color: focusColor)), ); }); } List<NavigationDestination> _destinations() { return const <NavigationDestination>[ NavigationDestination( icon: Icon(Icons.favorite_border), selectedIcon: Icon(Icons.favorite), label: 'Abc', ), NavigationDestination( icon: Icon(Icons.star_border), selectedIcon: Icon(Icons.star), label: 'Def', ), ]; } double _barHeight(WidgetTester tester) { return tester.getRect( find.byType(NavigationBar), ).height; } Material _barMaterial(WidgetTester tester) { return tester.firstWidget<Material>( find.descendant( of: find.byType(NavigationBar), matching: find.byType(Material), ), ); } ShapeDecoration? _indicator(WidgetTester tester) { return tester.firstWidget<Container>( find.descendant( of: find.byType(FadeTransition), matching: find.byType(Container), ), ).decoration as ShapeDecoration?; } IconThemeData _selectedIconTheme(WidgetTester tester) { return _iconTheme(tester, Icons.favorite); } IconThemeData _unselectedIconTheme(WidgetTester tester) { return _iconTheme(tester, Icons.star_border); } IconThemeData _iconTheme(WidgetTester tester, IconData icon) { return tester.firstWidget<IconTheme>( find.ancestor( of: find.byIcon(icon), matching: find.byType(IconTheme), ), ).data; } TextStyle _selectedLabelStyle(WidgetTester tester) { return tester.widget<RichText>( find.descendant( of: find.text('Abc'), matching: find.byType(RichText), ), ).text.style!; } TextStyle _unselectedLabelStyle(WidgetTester tester) { return tester.widget<RichText>( find.descendant( of: find.text('Def'), matching: find.byType(RichText), ), ).text.style!; } NavigationDestinationLabelBehavior _labelBehavior(WidgetTester tester) { if (_opacityAboveLabel('Abc').evaluate().isNotEmpty && _opacityAboveLabel('Def').evaluate().isNotEmpty) { return _labelOpacity(tester, 'Abc') == 1 ? NavigationDestinationLabelBehavior.onlyShowSelected : NavigationDestinationLabelBehavior.alwaysHide; } else { return NavigationDestinationLabelBehavior.alwaysShow; } } Finder _opacityAboveLabel(String text) { return find.ancestor( of: find.text(text), matching: find.byType(Opacity), ); } // Only valid when labelBehavior != alwaysShow. double _labelOpacity(WidgetTester tester, String text) { final Opacity opacityWidget = tester.widget<Opacity>( find.ancestor( of: find.text(text), matching: find.byType(Opacity), ), ); return opacityWidget.opacity; }
flutter/packages/flutter/test/material/navigation_bar_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/navigation_bar_theme_test.dart", "repo_id": "flutter", "token_count": 5637 }
721
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; import 'feedback_tester.dart'; Widget wrap({Widget? child}) { return MediaQuery( data: const MediaQueryData(), child: Directionality( textDirection: TextDirection.ltr, child: Material(child: child), ), ); } void main() { testWidgets('RadioListTile should initialize according to groupValue', (WidgetTester tester) async { final List<int> values = <int>[0, 1, 2]; int? selectedValue; // Constructor parameters are required for [RadioListTile], but they are // irrelevant when searching with [find.byType]. final Type radioListTileType = const RadioListTile<int>( value: 0, groupValue: 0, onChanged: null, ).runtimeType; List<RadioListTile<int>> generatedRadioListTiles; List<RadioListTile<int>> findTiles() => find .byType(radioListTileType) .evaluate() .map<Widget>((Element element) => element.widget) .cast<RadioListTile<int>>() .toList(); Widget buildFrame() { return wrap( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Scaffold( body: ListView.builder( itemCount: values.length, itemBuilder: (BuildContext context, int index) => RadioListTile<int>( onChanged: (int? value) { setState(() { selectedValue = value; }); }, value: values[index], groupValue: selectedValue, title: Text(values[index].toString()), ), ), ); }, ), ); } await tester.pumpWidget(buildFrame()); generatedRadioListTiles = findTiles(); expect(generatedRadioListTiles[0].checked, equals(false)); expect(generatedRadioListTiles[1].checked, equals(false)); expect(generatedRadioListTiles[2].checked, equals(false)); selectedValue = 1; await tester.pumpWidget(buildFrame()); generatedRadioListTiles = findTiles(); expect(generatedRadioListTiles[0].checked, equals(false)); expect(generatedRadioListTiles[1].checked, equals(true)); expect(generatedRadioListTiles[2].checked, equals(false)); }); testWidgets('RadioListTile simple control test', (WidgetTester tester) async { final Key key = UniqueKey(); final Key titleKey = UniqueKey(); final List<int?> log = <int?>[]; await tester.pumpWidget( wrap( child: RadioListTile<int>( key: key, value: 1, groupValue: 2, onChanged: log.add, title: Text('Title', key: titleKey), ), ), ); await tester.tap(find.byKey(key)); expect(log, equals(<int>[1])); log.clear(); await tester.pumpWidget( wrap( child: RadioListTile<int>( key: key, value: 1, groupValue: 1, onChanged: log.add, activeColor: Colors.green[500], title: Text('Title', key: titleKey), ), ), ); await tester.tap(find.byKey(key)); expect(log, isEmpty); await tester.pumpWidget( wrap( child: RadioListTile<int>( key: key, value: 1, groupValue: 2, onChanged: null, title: Text('Title', key: titleKey), ), ), ); await tester.tap(find.byKey(key)); expect(log, isEmpty); await tester.pumpWidget( wrap( child: RadioListTile<int>( key: key, value: 1, groupValue: 2, onChanged: log.add, title: Text('Title', key: titleKey), ), ), ); await tester.tap(find.byKey(titleKey)); expect(log, equals(<int>[1])); }); testWidgets('RadioListTile control tests', (WidgetTester tester) async { final List<int> values = <int>[0, 1, 2]; int? selectedValue; // Constructor parameters are required for [Radio], but they are irrelevant // when searching with [find.byType]. final Type radioType = const Radio<int>( value: 0, groupValue: 0, onChanged: null, ).runtimeType; final List<dynamic> log = <dynamic>[]; Widget buildFrame() { return wrap( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Scaffold( body: ListView.builder( itemCount: values.length, itemBuilder: (BuildContext context, int index) => RadioListTile<int>( onChanged: (int? value) { log.add(value); setState(() { selectedValue = value; }); }, value: values[index], groupValue: selectedValue, title: Text(values[index].toString()), ), ), ); }, ), ); } // Tests for tapping between [Radio] and [ListTile] await tester.pumpWidget(buildFrame()); await tester.tap(find.text('1')); log.add('-'); await tester.tap(find.byType(radioType).at(2)); expect(log, equals(<dynamic>[1, '-', 2])); log.add('-'); await tester.tap(find.text('1')); log.clear(); selectedValue = null; // Tests for tapping across [Radio]s exclusively await tester.pumpWidget(buildFrame()); await tester.tap(find.byType(radioType).at(1)); log.add('-'); await tester.tap(find.byType(radioType).at(2)); expect(log, equals(<dynamic>[1, '-', 2])); log.clear(); selectedValue = null; // Tests for tapping across [ListTile]s exclusively await tester.pumpWidget(buildFrame()); await tester.tap(find.text('1')); log.add('-'); await tester.tap(find.text('2')); expect(log, equals(<dynamic>[1, '-', 2])); }); testWidgets('Selected RadioListTile should not trigger onChanged', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/30311 final List<int> values = <int>[0, 1, 2]; int? selectedValue; // Constructor parameters are required for [Radio], but they are irrelevant // when searching with [find.byType]. final Type radioType = const Radio<int>( value: 0, groupValue: 0, onChanged: null, ).runtimeType; final List<dynamic> log = <dynamic>[]; Widget buildFrame() { return wrap( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Scaffold( body: ListView.builder( itemCount: values.length, itemBuilder: (BuildContext context, int index) => RadioListTile<int>( onChanged: (int? value) { log.add(value); setState(() { selectedValue = value; }); }, value: values[index], groupValue: selectedValue, title: Text(values[index].toString()), ), ), ); }, ), ); } await tester.pumpWidget(buildFrame()); await tester.tap(find.text('0')); await tester.pump(); expect(log, equals(<int>[0])); await tester.tap(find.text('0')); await tester.pump(); expect(log, equals(<int>[0])); await tester.tap(find.byType(radioType).at(0)); await tester.pump(); expect(log, equals(<int>[0])); }); testWidgets('Selected RadioListTile should trigger onChanged when toggleable', (WidgetTester tester) async { final List<int> values = <int>[0, 1, 2]; int? selectedValue; // Constructor parameters are required for [Radio], but they are irrelevant // when searching with [find.byType]. final Type radioType = const Radio<int>( value: 0, groupValue: 0, onChanged: null, ).runtimeType; final List<dynamic> log = <dynamic>[]; Widget buildFrame() { return wrap( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Scaffold( body: ListView.builder( itemCount: values.length, itemBuilder: (BuildContext context, int index) { return RadioListTile<int>( onChanged: (int? value) { log.add(value); setState(() { selectedValue = value; }); }, toggleable: true, value: values[index], groupValue: selectedValue, title: Text(values[index].toString()), ); }, ), ); }, ), ); } await tester.pumpWidget(buildFrame()); await tester.tap(find.text('0')); await tester.pump(); expect(log, equals(<int>[0])); await tester.tap(find.text('0')); await tester.pump(); expect(log, equals(<int?>[0, null])); await tester.tap(find.byType(radioType).at(0)); await tester.pump(); expect(log, equals(<int?>[0, null, 0])); }); testWidgets('RadioListTile can be toggled when toggleable is set', (WidgetTester tester) async { final Key key = UniqueKey(); final List<int?> log = <int?>[]; await tester.pumpWidget(Material( child: Center( child: Radio<int>( key: key, value: 1, groupValue: 2, onChanged: log.add, toggleable: true, ), ), )); await tester.tap(find.byKey(key)); expect(log, equals(<int>[1])); log.clear(); await tester.pumpWidget(Material( child: Center( child: Radio<int>( key: key, value: 1, groupValue: 1, onChanged: log.add, toggleable: true, ), ), )); await tester.tap(find.byKey(key)); expect(log, equals(<int?>[null])); log.clear(); await tester.pumpWidget(Material( child: Center( child: Radio<int>( key: key, value: 1, groupValue: null, onChanged: log.add, toggleable: true, ), ), )); await tester.tap(find.byKey(key)); expect(log, equals(<int>[1])); }); testWidgets('RadioListTile semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( wrap( child: RadioListTile<int>( value: 1, groupValue: 2, onChanged: (int? i) {}, title: const Text('Title'), ), ), ); expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isInMutuallyExclusiveGroup, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[SemanticsAction.tap], label: 'Title', textDirection: TextDirection.ltr, ), ], ), ignoreRect: true, ignoreTransform: true, ), ); await tester.pumpWidget( wrap( child: RadioListTile<int>( value: 2, groupValue: 2, onChanged: (int? i) {}, title: const Text('Title'), ), ), ); expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.isChecked, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isInMutuallyExclusiveGroup, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[SemanticsAction.tap], label: 'Title', textDirection: TextDirection.ltr, ), ], ), ignoreRect: true, ignoreTransform: true, ), ); await tester.pumpWidget( wrap( child: const RadioListTile<int>( value: 1, groupValue: 2, onChanged: null, title: Text('Title'), ), ), ); expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, SemanticsFlag.isInMutuallyExclusiveGroup, SemanticsFlag.isFocusable, ], label: 'Title', textDirection: TextDirection.ltr, ), ], ), ignoreId: true, ignoreRect: true, ignoreTransform: true, ), ); await tester.pumpWidget( wrap( child: const RadioListTile<int>( value: 2, groupValue: 2, onChanged: null, title: Text('Title'), ), ), ); expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.isChecked, SemanticsFlag.hasEnabledState, SemanticsFlag.isInMutuallyExclusiveGroup, ], label: 'Title', textDirection: TextDirection.ltr, ), ], ), ignoreId: true, ignoreRect: true, ignoreTransform: true, ), ); semantics.dispose(); }); testWidgets('RadioListTile has semantic events', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final Key key = UniqueKey(); dynamic semanticEvent; int? radioValue = 2; tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, (dynamic message) async { semanticEvent = message; }); await tester.pumpWidget( wrap( child: RadioListTile<int>( key: key, value: 1, groupValue: radioValue, onChanged: (int? i) { radioValue = i; }, title: const Text('Title'), ), ), ); await tester.tap(find.byKey(key)); await tester.pump(); final RenderObject object = tester.firstRenderObject(find.byKey(key)); expect(radioValue, 1); expect(semanticEvent, <String, dynamic>{ 'type': 'tap', 'nodeId': object.debugSemantics!.id, 'data': <String, dynamic>{}, }); expect(object.debugSemantics!.getSemanticsData().hasAction(SemanticsAction.tap), true); semantics.dispose(); tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, null); }); testWidgets('RadioListTile can autofocus unless disabled.', (WidgetTester tester) async { final GlobalKey childKey = GlobalKey(); await tester.pumpWidget( wrap( child: RadioListTile<int>( value: 1, groupValue: 2, onChanged: (_) {}, title: Text('Title', key: childKey), autofocus: true, ), ), ); await tester.pump(); expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isTrue); await tester.pumpWidget( wrap( child: RadioListTile<int>( value: 1, groupValue: 2, onChanged: null, title: Text('Title', key: childKey), autofocus: true, ), ), ); await tester.pump(); expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isFalse); }); testWidgets('RadioListTile contentPadding test', (WidgetTester tester) async { final Type radioType = const Radio<bool>( groupValue: true, value: true, onChanged: null, ).runtimeType; await tester.pumpWidget( wrap( child: Center( child: RadioListTile<bool>( groupValue: true, value: true, title: const Text('Title'), onChanged: (_){}, contentPadding: const EdgeInsets.fromLTRB(8, 10, 15, 20), ), ), ), ); final Rect paddingRect = tester.getRect(find.byType(SafeArea)); final Rect radioRect = tester.getRect(find.byType(radioType)); final Rect titleRect = tester.getRect(find.text('Title')); // Get the taller Rect of the Radio and Text widgets final Rect tallerRect = radioRect.height > titleRect.height ? radioRect : titleRect; // Get the extra height between the tallerRect and ListTile height final double extraHeight = 56 - tallerRect.height; // Check for correct top and bottom padding expect(paddingRect.top, tallerRect.top - extraHeight / 2 - 10); //top padding expect(paddingRect.bottom, tallerRect.bottom + extraHeight / 2 + 20); //bottom padding // Check for correct left and right padding expect(paddingRect.left, radioRect.left - 8); //left padding expect(paddingRect.right, titleRect.right + 15); //right padding }); testWidgets('RadioListTile respects shape', (WidgetTester tester) async { const ShapeBorder shapeBorder = RoundedRectangleBorder( borderRadius: BorderRadius.horizontal(right: Radius.circular(100)), ); await tester.pumpWidget(const MaterialApp( home: Material( child: RadioListTile<bool>( value: true, groupValue: true, onChanged: null, title: Text('Title'), shape: shapeBorder, ), ), )); expect(tester.widget<InkWell>(find.byType(InkWell)).customBorder, shapeBorder); }); testWidgets('RadioListTile respects tileColor', (WidgetTester tester) async { final Color tileColor = Colors.red.shade500; await tester.pumpWidget( wrap( child: Center( child: RadioListTile<bool>( value: false, groupValue: true, onChanged: null, title: const Text('Title'), tileColor: tileColor, ), ), ), ); expect(find.byType(Material), paints..rect(color: tileColor)); }); testWidgets('RadioListTile respects selectedTileColor', (WidgetTester tester) async { final Color selectedTileColor = Colors.green.shade500; await tester.pumpWidget( wrap( child: Center( child: RadioListTile<bool>( value: false, groupValue: true, onChanged: null, title: const Text('Title'), selected: true, selectedTileColor: selectedTileColor, ), ), ), ); expect(find.byType(Material), paints..rect(color: selectedTileColor)); }); testWidgets('RadioListTile selected item text Color', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/pull/76906 const Color activeColor = Color(0xff00ff00); Widget buildFrame({ Color? activeColor, Color? fillColor }) { return MaterialApp( theme: ThemeData.light().copyWith( radioTheme: RadioThemeData( fillColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) { return states.contains(MaterialState.selected) ? fillColor : null; }), ), ), home: Scaffold( body: Center( child: RadioListTile<bool>( activeColor: activeColor, selected: true, title: const Text('title'), value: false, groupValue: true, onChanged: (bool? newValue) { }, ), ), ), ); } Color? textColor(String text) { return tester.renderObject<RenderParagraph>(find.text(text)).text.style?.color; } await tester.pumpWidget(buildFrame(fillColor: activeColor)); expect(textColor('title'), activeColor); await tester.pumpWidget(buildFrame(activeColor: activeColor)); expect(textColor('title'), activeColor); }); testWidgets('RadioListTile respects visualDensity', (WidgetTester tester) async { const Key key = Key('test'); Future<void> buildTest(VisualDensity visualDensity) async { return tester.pumpWidget( wrap( child: Center( child: RadioListTile<bool>( key: key, value: false, groupValue: true, onChanged: (bool? value) {}, autofocus: true, visualDensity: visualDensity, ), ), ), ); } await buildTest(VisualDensity.standard); final RenderBox box = tester.renderObject(find.byKey(key)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(800, 56))); }); testWidgets('RadioListTile respects focusNode', (WidgetTester tester) async { final GlobalKey childKey = GlobalKey(); await tester.pumpWidget( wrap( child: Center( child: RadioListTile<bool>( value: false, groupValue: true, title: Text('A', key: childKey), onChanged: (bool? value) {}, ), ), ), ); await tester.pump(); final FocusNode tileNode = Focus.of(childKey.currentContext!); tileNode.requestFocus(); await tester.pump(); // Let the focus take effect. expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isTrue); expect(tileNode.hasPrimaryFocus, isTrue); }); testWidgets('RadioListTile onFocusChange callback', (WidgetTester tester) async { final FocusNode node = FocusNode(debugLabel: 'RadioListTile onFocusChange'); addTearDown(node.dispose); bool gotFocus = false; await tester.pumpWidget( MaterialApp( home: Material( child: RadioListTile<bool>( value: true, focusNode: node, onFocusChange: (bool focused) { gotFocus = focused; }, onChanged: (bool? value) {}, groupValue: true, ), ), ), ); node.requestFocus(); await tester.pump(); expect(gotFocus, isTrue); expect(node.hasFocus, isTrue); node.unfocus(); await tester.pump(); expect(gotFocus, isFalse); expect(node.hasFocus, isFalse); }); testWidgets('Radio changes mouse cursor when hovered', (WidgetTester tester) async { // Test Radio() constructor await tester.pumpWidget( wrap(child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: RadioListTile<int>( mouseCursor: SystemMouseCursors.text, value: 1, onChanged: (int? v) {}, groupValue: 2, ), )), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: tester.getCenter(find.byType(Radio<int>))); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); // Test default cursor await tester.pumpWidget( wrap(child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: RadioListTile<int>( value: 1, onChanged: (int? v) {}, groupValue: 2, ), )), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); // Test default cursor when disabled await tester.pumpWidget(wrap( child: const MouseRegion( cursor: SystemMouseCursors.forbidden, child: RadioListTile<int>( value: 1, onChanged: null, groupValue: 2, ), ), ),); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }); testWidgets('RadioListTile respects fillColor in enabled/disabled states', (WidgetTester tester) async { const Color activeEnabledFillColor = Color(0xFF000001); const Color activeDisabledFillColor = Color(0xFF000002); const Color inactiveEnabledFillColor = Color(0xFF000003); const Color inactiveDisabledFillColor = Color(0xFF000004); Color getFillColor(Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { if (states.contains(MaterialState.selected)) { return activeDisabledFillColor; } return inactiveDisabledFillColor; } if (states.contains(MaterialState.selected)) { return activeEnabledFillColor; } return inactiveEnabledFillColor; } final MaterialStateProperty<Color> fillColor = MaterialStateColor.resolveWith(getFillColor); int? groupValue = 0; Widget buildApp({required bool enabled}) { return wrap( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RadioListTile<int>( value: 0, fillColor: fillColor, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, groupValue: groupValue, ); }) ); } await tester.pumpWidget(buildApp(enabled: true)); // Selected and enabled. await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color: activeEnabledFillColor) ..circle(color: activeEnabledFillColor), ); // Check when the radio isn't selected. groupValue = 1; await tester.pumpWidget(buildApp(enabled: true)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color: inactiveEnabledFillColor, style: PaintingStyle.stroke, strokeWidth: 2.0), ); // Check when the radio is selected, but disabled. groupValue = 0; await tester.pumpWidget(buildApp(enabled: false)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color: activeDisabledFillColor) ..circle(color: activeDisabledFillColor), ); // Check when the radio is unselected and disabled. groupValue = 1; await tester.pumpWidget(buildApp(enabled: false)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color: inactiveDisabledFillColor, style: PaintingStyle.stroke, strokeWidth: 2.0), ); }); testWidgets('RadioListTile respects fillColor in hovered state', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const Color hoveredFillColor = Color(0xFF000001); Color getFillColor(Set<MaterialState> states) { if (states.contains(MaterialState.hovered)) { return hoveredFillColor; } return Colors.transparent; } final MaterialStateProperty<Color> fillColor = MaterialStateColor.resolveWith(getFillColor); int? groupValue = 0; Widget buildApp() { return wrap( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RadioListTile<int>( value: 0, fillColor: fillColor, onChanged: (int? newValue) { setState(() { groupValue = newValue; }); }, groupValue: groupValue, ); }), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); // Start hovering final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(Radio<int>))); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect()..circle() ..circle(color: hoveredFillColor), ); }); testWidgets('Material3 - RadioListTile respects hoverColor', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; int? groupValue = 0; final Color? hoverColor = Colors.orange[500]; final ThemeData theme = ThemeData(useMaterial3: true); Widget buildApp({bool enabled = true}) { return wrap( child: MaterialApp( theme: theme, home: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RadioListTile<int>( value: 0, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, hoverColor: hoverColor, groupValue: groupValue, ); }), ), ); } await tester.pumpWidget(buildApp()); await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color: theme.colorScheme.primary) ..circle(color: theme.colorScheme.primary), ); // Start hovering final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.moveTo(tester.getCenter(find.byType(Radio<int>))); // Check when the radio isn't selected. groupValue = 1; await tester.pumpWidget(buildApp()); await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color: hoverColor) ); // Check when the radio is selected, but disabled. groupValue = 0; await tester.pumpWidget(buildApp(enabled: false)); await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color: theme.colorScheme.onSurface.withOpacity(0.38)) ..circle(color: theme.colorScheme.onSurface.withOpacity(0.38)), ); }); testWidgets('Material3 - RadioListTile respects overlayColor in active/pressed/hovered states', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const Color fillColor = Color(0xFF000000); const Color activePressedOverlayColor = Color(0xFF000001); const Color inactivePressedOverlayColor = Color(0xFF000002); const Color hoverOverlayColor = Color(0xFF000003); const Color hoverColor = Color(0xFF000005); Color? getOverlayColor(Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { if (states.contains(MaterialState.selected)) { return activePressedOverlayColor; } return inactivePressedOverlayColor; } if (states.contains(MaterialState.hovered)) { return hoverOverlayColor; } return null; } Widget buildRadio({bool active = false, bool useOverlay = true}) { return MaterialApp( theme: ThemeData(useMaterial3: true), home: Material( child: RadioListTile<bool>( value: active, groupValue: true, onChanged: (_) { }, fillColor: const MaterialStatePropertyAll<Color>(fillColor), overlayColor: useOverlay ? MaterialStateProperty.resolveWith(getOverlayColor) : null, hoverColor: hoverColor, ), ), ); } await tester.pumpWidget(buildRadio(useOverlay: false)); await tester.press(find.byType(Radio<bool>)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..rect(color: const Color(0x00000000)) ..rect(color: const Color(0x66bcbcbc)) ..circle( color: fillColor.withAlpha(kRadialReactionAlpha), radius: 20.0, ), reason: 'Default inactive pressed Radio should have overlay color from fillColor', ); await tester.pumpWidget(buildRadio(active: true, useOverlay: false)); await tester.press(find.byType(Radio<bool>)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..rect(color: const Color(0x00000000)) ..rect(color: const Color(0x66bcbcbc)) ..circle( color: fillColor.withAlpha(kRadialReactionAlpha), radius: 20.0, ), reason: 'Default active pressed Radio should have overlay color from fillColor', ); await tester.pumpWidget(buildRadio()); await tester.press(find.byType(Radio<bool>)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..rect(color: const Color(0x00000000)) ..rect(color: const Color(0x66bcbcbc)) ..circle( color: inactivePressedOverlayColor, radius: 20.0, ), reason: 'Inactive pressed Radio should have overlay color: $inactivePressedOverlayColor', ); await tester.pumpWidget(buildRadio(active: true)); await tester.press(find.byType(Radio<bool>)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..rect(color: const Color(0x00000000)) ..rect(color: const Color(0x66bcbcbc)) ..circle( color: activePressedOverlayColor, radius: 20.0, ), reason: 'Active pressed Radio should have overlay color: $activePressedOverlayColor', ); // Start hovering. final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(Radio<bool>))); await tester.pumpAndSettle(); await tester.pumpWidget(Container()); await tester.pumpWidget(buildRadio()); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..rect(color: const Color(0x00000000)) ..rect(color: const Color(0x0a000000)) ..circle( color: hoverOverlayColor, radius: 20.0, ), reason: 'Hovered Radio should use overlay color $hoverOverlayColor over $hoverColor', ); }); testWidgets('RadioListTile respects splashRadius', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const double splashRadius = 30; Widget buildApp() { return wrap( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RadioListTile<int>( value: 0, onChanged: (_) {}, hoverColor: Colors.orange[500], groupValue: 0, splashRadius: splashRadius, ); }), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(Radio<int>))); await tester.pumpAndSettle(); expect( Material.of(tester.element( find.byWidgetPredicate((Widget widget) => widget is Radio<int>), )), paints..circle(color: Colors.orange[500], radius: splashRadius), ); }); testWidgets('Radio respects materialTapTargetSize', (WidgetTester tester) async { await tester.pumpWidget( wrap(child: RadioListTile<bool>( groupValue: true, value: true, onChanged: (bool? newValue) { }, )), ); // default test expect(tester.getSize(find.byType(Radio<bool>)), const Size(40.0, 40.0)); await tester.pumpWidget( wrap(child: RadioListTile<bool>( materialTapTargetSize: MaterialTapTargetSize.padded, groupValue: true, value: true, onChanged: (bool? newValue) { }, )), ); expect(tester.getSize(find.byType(Radio<bool>)), const Size(48.0, 48.0)); }); testWidgets('RadioListTile.control widget should not request focus on traversal', (WidgetTester tester) async { final GlobalKey firstChildKey = GlobalKey(); final GlobalKey secondChildKey = GlobalKey(); await tester.pumpWidget( MaterialApp( home: Material( child: Column( children: <Widget>[ RadioListTile<bool>( value: true, groupValue: true, onChanged: (bool? value) {}, title: Text('Hey', key: firstChildKey), ), RadioListTile<bool>( value: true, groupValue: true, onChanged: (bool? value) {}, title: Text('There', key: secondChildKey), ), ], ), ), ), ); await tester.pump(); Focus.of(firstChildKey.currentContext!).requestFocus(); await tester.pump(); expect(Focus.of(firstChildKey.currentContext!).hasPrimaryFocus, isTrue); Focus.of(firstChildKey.currentContext!).nextFocus(); await tester.pump(); expect(Focus.of(firstChildKey.currentContext!).hasPrimaryFocus, isFalse); expect(Focus.of(secondChildKey.currentContext!).hasPrimaryFocus, isTrue); }); testWidgets('RadioListTile.adaptive shows the correct radio platform widget', (WidgetTester tester) async { Widget buildApp(TargetPlatform platform) { return MaterialApp( theme: ThemeData(platform: platform), home: Material( child: Center( child: RadioListTile<int>.adaptive( value: 1, groupValue: 2, onChanged: (_) {}, ), ), ), ); } for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.iOS, TargetPlatform.macOS ]) { await tester.pumpWidget(buildApp(platform)); await tester.pumpAndSettle(); expect(find.byType(CupertinoRadio<int>), findsOneWidget); } for (final TargetPlatform platform in <TargetPlatform>[ TargetPlatform.android, TargetPlatform.fuchsia, TargetPlatform.linux, TargetPlatform.windows ]) { await tester.pumpWidget(buildApp(platform)); await tester.pumpAndSettle(); expect(find.byType(CupertinoRadio<int>), findsNothing); } }); group('feedback', () { late FeedbackTester feedback; setUp(() { feedback = FeedbackTester(); }); tearDown(() { feedback.dispose(); }); testWidgets('RadioListTile respects enableFeedback', (WidgetTester tester) async { const Key key = Key('test'); Future<void> buildTest(bool enableFeedback) async { return tester.pumpWidget( wrap( child: Center( child: RadioListTile<bool>( key: key, value: false, groupValue: true, selected: true, onChanged: (bool? value) {}, enableFeedback: enableFeedback, ), ), ), ); } await buildTest(false); await tester.tap(find.byKey(key)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 0); expect(feedback.hapticCount, 0); await buildTest(true); await tester.tap(find.byKey(key)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 1); expect(feedback.hapticCount, 0); }); }); group('Material 2', () { // These tests are only relevant for Material 2. Once Material 2 // support is deprecated and the APIs are removed, these tests // can be deleted. testWidgets('Material2 - RadioListTile respects overlayColor in active/pressed/hovered states', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const Color fillColor = Color(0xFF000000); const Color activePressedOverlayColor = Color(0xFF000001); const Color inactivePressedOverlayColor = Color(0xFF000002); const Color hoverOverlayColor = Color(0xFF000003); const Color hoverColor = Color(0xFF000005); Color? getOverlayColor(Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { if (states.contains(MaterialState.selected)) { return activePressedOverlayColor; } return inactivePressedOverlayColor; } if (states.contains(MaterialState.hovered)) { return hoverOverlayColor; } return null; } Widget buildRadio({bool active = false, bool useOverlay = true}) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: RadioListTile<bool>( value: active, groupValue: true, onChanged: (_) { }, fillColor: const MaterialStatePropertyAll<Color>(fillColor), overlayColor: useOverlay ? MaterialStateProperty.resolveWith(getOverlayColor) : null, hoverColor: hoverColor, ), ), ); } await tester.pumpWidget(buildRadio(useOverlay: false)); await tester.press(find.byType(Radio<bool>)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..circle() ..circle( color: fillColor.withAlpha(kRadialReactionAlpha), radius: 20, ), reason: 'Default inactive pressed Radio should have overlay color from fillColor', ); await tester.pumpWidget(buildRadio(active: true, useOverlay: false)); await tester.press(find.byType(Radio<bool>)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..circle() ..circle( color: fillColor.withAlpha(kRadialReactionAlpha), radius: 20, ), reason: 'Default active pressed Radio should have overlay color from fillColor', ); await tester.pumpWidget(buildRadio()); await tester.press(find.byType(Radio<bool>)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..circle() ..circle( color: inactivePressedOverlayColor, radius: 20, ), reason: 'Inactive pressed Radio should have overlay color: $inactivePressedOverlayColor', ); // Start hovering. final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(Radio<bool>))); await tester.pumpAndSettle(); await tester.pumpWidget(Container()); await tester.pumpWidget(buildRadio()); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..circle( color: hoverOverlayColor, radius: 20, ), reason: 'Hovered Radio should use overlay color $hoverOverlayColor over $hoverColor', ); }); testWidgets('Material2 - RadioListTile respects hoverColor', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; int? groupValue = 0; final Color? hoverColor = Colors.orange[500]; Widget buildApp({bool enabled = true}) { return wrap( child: MaterialApp( theme: ThemeData(useMaterial3: false), home: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return RadioListTile<int>( value: 0, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, hoverColor: hoverColor, groupValue: groupValue, ); }), ), ); } await tester.pumpWidget(buildApp()); await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color:const Color(0xff2196f3)) ..circle(color:const Color(0xff2196f3)), ); // Start hovering final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.moveTo(tester.getCenter(find.byType(Radio<int>))); // Check when the radio isn't selected. groupValue = 1; await tester.pumpWidget(buildApp()); await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color: hoverColor) ); // Check when the radio is selected, but disabled. groupValue = 0; await tester.pumpWidget(buildApp(enabled: false)); await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<int>))), paints ..rect() ..circle(color:const Color(0x61000000)) ..circle(color:const Color(0x61000000)), ); }); }); }
flutter/packages/flutter/test/material/radio_list_tile_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/radio_list_tile_test.dart", "repo_id": "flutter", "token_count": 20875 }
722
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('SegmentedButtonThemeData copyWith, ==, hashCode basics', () { expect(const SegmentedButtonThemeData(), const SegmentedButtonThemeData().copyWith()); expect(const SegmentedButtonThemeData().hashCode, const SegmentedButtonThemeData().copyWith().hashCode); const SegmentedButtonThemeData custom = SegmentedButtonThemeData( style: ButtonStyle(backgroundColor: MaterialStatePropertyAll<Color>(Colors.green)), selectedIcon: Icon(Icons.error), ); final SegmentedButtonThemeData copy = const SegmentedButtonThemeData().copyWith( style: custom.style, selectedIcon: custom.selectedIcon, ); expect(copy, custom); }); test('SegmentedButtonThemeData lerp special cases', () { expect(SegmentedButtonThemeData.lerp(null, null, 0), const SegmentedButtonThemeData()); const SegmentedButtonThemeData theme = SegmentedButtonThemeData(); expect(identical(SegmentedButtonThemeData.lerp(theme, theme, 0.5), theme), true); }); testWidgets('Default SegmentedButtonThemeData debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const SegmentedButtonThemeData().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('With no other configuration, defaults are used', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: Center( child: SegmentedButton<int>( segments: const <ButtonSegment<int>>[ ButtonSegment<int>(value: 1, label: Text('1')), ButtonSegment<int>(value: 2, label: Text('2')), ButtonSegment<int>(value: 3, label: Text('3'), enabled: false), ], selected: const <int>{2}, onSelectionChanged: (Set<int> selected) { }, ), ), ), ), ); // Test first segment, should be enabled { final Finder text = find.text('1'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.check)); final Material material = tester.widget<Material>(parent); expect(material.color, Colors.transparent); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, theme.colorScheme.onSurface); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsNothing); } // Test second segment, should be enabled and selected { final Finder text = find.text('2'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.check)); final Material material = tester.widget<Material>(parent); expect(material.color, theme.colorScheme.secondaryContainer); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, theme.colorScheme.onSecondaryContainer); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsOneWidget); } // Test last segment, should be disabled { final Finder text = find.text('3'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.check)); final Material material = tester.widget<Material>(parent); expect(material.color, Colors.transparent); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, theme.colorScheme.onSurface.withOpacity(0.38)); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsNothing); } }); testWidgets('ThemeData.segmentedButtonTheme overrides defaults', (WidgetTester tester) async { final ThemeData theme = ThemeData( useMaterial3: true, segmentedButtonTheme: SegmentedButtonThemeData( style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.blue; } if (states.contains(MaterialState.selected)) { return Colors.purple; } return null; }), foregroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.yellow; } if (states.contains(MaterialState.selected)) { return Colors.brown; } else { return Colors.cyan; } }), ), selectedIcon: const Icon(Icons.error), ), ); await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: Center( child: SegmentedButton<int>( segments: const <ButtonSegment<int>>[ ButtonSegment<int>(value: 1, label: Text('1')), ButtonSegment<int>(value: 2, label: Text('2')), ButtonSegment<int>(value: 3, label: Text('3'), enabled: false), ], selected: const <int>{2}, onSelectionChanged: (Set<int> selected) { }, ), ), ), ), ); // Test first segment, should be enabled { final Finder text = find.text('1'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.error)); final Material material = tester.widget<Material>(parent); expect(material.color, Colors.transparent); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, Colors.cyan); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsNothing); } // Test second segment, should be enabled and selected { final Finder text = find.text('2'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.error)); final Material material = tester.widget<Material>(parent); expect(material.color, Colors.purple); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, Colors.brown); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsOneWidget); } // Test last segment, should be disabled { final Finder text = find.text('3'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.error)); final Material material = tester.widget<Material>(parent); expect(material.color, Colors.blue); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, Colors.yellow); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsNothing); } }); testWidgets('SegmentedButtonTheme overrides ThemeData and defaults', (WidgetTester tester) async { final SegmentedButtonThemeData global = SegmentedButtonThemeData( style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.blue; } if (states.contains(MaterialState.selected)) { return Colors.purple; } return null; }), foregroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.yellow; } if (states.contains(MaterialState.selected)) { return Colors.brown; } else { return Colors.cyan; } }), ), selectedIcon: const Icon(Icons.error), ); final SegmentedButtonThemeData segmentedTheme = SegmentedButtonThemeData( style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.lightBlue; } if (states.contains(MaterialState.selected)) { return Colors.lightGreen; } return null; }), foregroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.lime; } if (states.contains(MaterialState.selected)) { return Colors.amber; } else { return Colors.deepPurple; } }), ), selectedIcon: const Icon(Icons.plus_one), ); final ThemeData theme = ThemeData( useMaterial3: true, segmentedButtonTheme: global, ); await tester.pumpWidget( MaterialApp( theme: theme, home: SegmentedButtonTheme( data: segmentedTheme, child: Scaffold( body: Center( child: SegmentedButton<int>( segments: const <ButtonSegment<int>>[ ButtonSegment<int>(value: 1, label: Text('1')), ButtonSegment<int>(value: 2, label: Text('2')), ButtonSegment<int>(value: 3, label: Text('3'), enabled: false), ], selected: const <int>{2}, onSelectionChanged: (Set<int> selected) { }, ), ), ), ), ), ); // Test first segment, should be enabled { final Finder text = find.text('1'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.plus_one)); final Material material = tester.widget<Material>(parent); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderRadius, null); expect(material.color, Colors.transparent); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, Colors.deepPurple); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsNothing); } // Test second segment, should be enabled and selected { final Finder text = find.text('2'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.plus_one)); final Material material = tester.widget<Material>(parent); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderRadius, null); expect(material.color, Colors.lightGreen); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, Colors.amber); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsOneWidget); } // Test last segment, should be disabled { final Finder text = find.text('3'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.plus_one)); final Material material = tester.widget<Material>(parent); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderRadius, null); expect(material.color, Colors.lightBlue); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, Colors.lime); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsNothing); } }); testWidgets('Widget parameters overrides SegmentedTheme, ThemeData and defaults', (WidgetTester tester) async { final SegmentedButtonThemeData global = SegmentedButtonThemeData( style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.blue; } if (states.contains(MaterialState.selected)) { return Colors.purple; } return null; }), foregroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.yellow; } if (states.contains(MaterialState.selected)) { return Colors.brown; } else { return Colors.cyan; } }), ), selectedIcon: const Icon(Icons.error), ); final SegmentedButtonThemeData segmentedTheme = SegmentedButtonThemeData( style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.lightBlue; } if (states.contains(MaterialState.selected)) { return Colors.lightGreen; } return null; }), foregroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.lime; } if (states.contains(MaterialState.selected)) { return Colors.amber; } else { return Colors.deepPurple; } }), ), selectedIcon: const Icon(Icons.plus_one), ); final ThemeData theme = ThemeData( useMaterial3: true, segmentedButtonTheme: global, ); await tester.pumpWidget( MaterialApp( theme: theme, home: SegmentedButtonTheme( data: segmentedTheme, child: Scaffold( body: Center( child: SegmentedButton<int>( segments: const <ButtonSegment<int>>[ ButtonSegment<int>(value: 1, label: Text('1')), ButtonSegment<int>(value: 2, label: Text('2')), ButtonSegment<int>(value: 3, label: Text('3'), enabled: false), ], selected: const <int>{2}, onSelectionChanged: (Set<int> selected) { }, style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.black12; } if (states.contains(MaterialState.selected)) { return Colors.grey; } return null; }), foregroundColor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.amberAccent; } if (states.contains(MaterialState.selected)) { return Colors.deepOrange; } else { return Colors.deepPurpleAccent; } }), ), selectedIcon: const Icon(Icons.alarm), ), ), ), ), ), ); // Test first segment, should be enabled { final Finder text = find.text('1'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.alarm)); final Material material = tester.widget<Material>(parent); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderRadius, null); expect(material.color, Colors.transparent); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, Colors.deepPurpleAccent); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsNothing); } // Test second segment, should be enabled and selected { final Finder text = find.text('2'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.alarm)); final Material material = tester.widget<Material>(parent); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderRadius, null); expect(material.color, Colors.grey); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, Colors.deepOrange); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsOneWidget); } // Test last segment, should be disabled { final Finder text = find.text('3'); final Finder parent = find.ancestor(of: text, matching: find.byType(Material)).first; final Finder selectedIcon = find.descendant(of: parent, matching: find.byIcon(Icons.alarm)); final Material material = tester.widget<Material>(parent); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderRadius, null); expect(material.color, Colors.black12); expect(material.shape, const RoundedRectangleBorder()); expect(material.textStyle!.color, Colors.amberAccent); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(selectedIcon, findsNothing); } }); }
flutter/packages/flutter/test/material/segmented_button_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/segmented_button_theme_test.dart", "repo_id": "flutter", "token_count": 8065 }
723
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; // This returns render paragraph of the Tab label text. RenderParagraph getTabText(WidgetTester tester, String text) { return tester.renderObject<RenderParagraph>(find.descendant( of: find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_TabStyle'), matching: find.text(text), )); } // This creates and returns a TabController. TabController createTabController({ required int length, required TickerProvider vsync, int initialIndex = 0, Duration? animationDuration, }) { final TabController result = TabController( length: length, vsync: vsync, initialIndex: initialIndex, animationDuration: animationDuration, ); addTearDown(result.dispose); return result; } // This widget is used to test widget state in the tabs_test.dart file. class TabStateMarker extends StatefulWidget { const TabStateMarker({ super.key, this.child }); final Widget? child; @override TabStateMarkerState createState() => TabStateMarkerState(); } class TabStateMarkerState extends State<TabStateMarker> { String? marker; @override Widget build(BuildContext context) { return widget.child ?? Container(); } } // Tab controller builder for TabControllerFrame widget. typedef TabControllerFrameBuilder = Widget Function(BuildContext context, TabController controller); // This widget creates a TabController and passes it to the builder. class TabControllerFrame extends StatefulWidget { const TabControllerFrame({ super.key, required this.length, this.initialIndex = 0, required this.builder, }); final int length; final int initialIndex; final TabControllerFrameBuilder builder; @override TabControllerFrameState createState() => TabControllerFrameState(); } class TabControllerFrameState extends State<TabControllerFrame> with SingleTickerProviderStateMixin { late TabController _controller; @override void initState() { super.initState(); _controller = TabController( vsync: this, length: widget.length, initialIndex: widget.initialIndex, ); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return widget.builder(context, _controller); } } // Test utility class to test tab indicator drawing. class TabIndicatorRecordingCanvas extends TestRecordingCanvas { TabIndicatorRecordingCanvas(this.indicatorColor); final Color indicatorColor; late Rect indicatorRect; @override void drawLine(Offset p1, Offset p2, Paint paint) { // Assuming that the indicatorWeight is 2.0, the default. const double indicatorWeight = 2.0; if (paint.color == indicatorColor) { indicatorRect = Rect.fromPoints(p1, p2).inflate(indicatorWeight / 2.0); } } } // This creates a Fake implementation of ScrollMetrics. class TabMockScrollMetrics extends Fake implements ScrollMetrics { } class TabBarTestScrollPhysics extends ScrollPhysics { const TabBarTestScrollPhysics({ super.parent }); @override TabBarTestScrollPhysics applyTo(ScrollPhysics? ancestor) { return TabBarTestScrollPhysics(parent: buildParent(ancestor)); } @override double applyPhysicsToUserOffset(ScrollMetrics position, double offset) { return offset == 10 ? 20 : offset; } static final SpringDescription _kDefaultSpring = SpringDescription.withDampingRatio( mass: 0.5, stiffness: 500.0, ratio: 1.1, ); @override SpringDescription get spring => _kDefaultSpring; } // This widget is used to log the lifecycle of the TabBarView children. class TabBody extends StatefulWidget { const TabBody({ super.key, required this.index, required this.log, this.marker = '', }); final int index; final List<String> log; final String marker; @override State<TabBody> createState() => TabBodyState(); } class TabBodyState extends State<TabBody> { @override void initState() { widget.log.add('init: ${widget.index}'); super.initState(); } @override void didUpdateWidget(TabBody oldWidget) { super.didUpdateWidget(oldWidget); // To keep the logging straight, widgets must not change their index. assert(oldWidget.index == widget.index); } @override void dispose() { widget.log.add('dispose: ${widget.index}'); super.dispose(); } @override Widget build(BuildContext context) { return Center( child: widget.marker.isEmpty ? Text('${widget.index}') : Text('${widget.index}-${widget.marker}'), ); } } // This widget is used to test the lifecycle of the TabBarView children with Ink widget. class TabKeepAliveInk extends StatefulWidget { const TabKeepAliveInk({ super.key, required this.title }); final String title; @override State<StatefulWidget> createState() => _TabKeepAliveInkState(); } class _TabKeepAliveInkState extends State<TabKeepAliveInk> with AutomaticKeepAliveClientMixin { @override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); return Ink( child: Text(widget.title), ); } } // This widget is used to test the lifecycle of the TabBarView children. class TabAlwaysKeepAliveWidget extends StatefulWidget { const TabAlwaysKeepAliveWidget({super.key}); static String text = 'AlwaysKeepAlive'; @override State<TabAlwaysKeepAliveWidget> createState() => _TabAlwaysKeepAliveWidgetState(); } class _TabAlwaysKeepAliveWidgetState extends State<TabAlwaysKeepAliveWidget> with AutomaticKeepAliveClientMixin { @override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); return Text(TabAlwaysKeepAliveWidget.text); } }
flutter/packages/flutter/test/material/tabs_utils.dart/0
{ "file_path": "flutter/packages/flutter/test/material/tabs_utils.dart", "repo_id": "flutter", "token_count": 1894 }
724
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; const Duration defaultButtonDuration = Duration(milliseconds: 200); void main() { group('FloatingActionButton', () { const BoxConstraints defaultFABConstraints = BoxConstraints.tightFor(width: 56.0, height: 56.0); const ShapeBorder defaultFABShape = CircleBorder(); const ShapeBorder defaultFABShapeM3 = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))); const EdgeInsets defaultFABPadding = EdgeInsets.zero; testWidgets('Material2 - theme: ThemeData.light(), enabled: true', (WidgetTester tester) async { final ThemeData theme = ThemeData.light(useMaterial3: false); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: FloatingActionButton( onPressed: () { }, // button.enabled == true child: const Icon(Icons.add), ), ), ), ); final RawMaterialButton raw = tester.widget<RawMaterialButton>(find.byType(RawMaterialButton)); expect(raw.enabled, true); expect(raw.textStyle!.color, const Color(0xffffffff)); expect(raw.fillColor, const Color(0xff2196f3)); expect(raw.elevation, 6.0); expect(raw.highlightElevation, 12.0); expect(raw.disabledElevation, 6.0); expect(raw.constraints, defaultFABConstraints); expect(raw.padding, defaultFABPadding); expect(raw.shape, defaultFABShape); expect(raw.animationDuration, defaultButtonDuration); expect(raw.materialTapTargetSize, MaterialTapTargetSize.padded); }); testWidgets('Material3 - theme: ThemeData.light(), enabled: true', (WidgetTester tester) async { final ThemeData theme = ThemeData.light(useMaterial3: true); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: FloatingActionButton( onPressed: () { }, // button.enabled == true child: const Icon(Icons.add), ), ), ), ); final RawMaterialButton raw = tester.widget<RawMaterialButton>(find.byType(RawMaterialButton)); expect(raw.enabled, true); expect(raw.textStyle!.color, theme.colorScheme.onPrimaryContainer); expect(raw.fillColor, theme.colorScheme.primaryContainer); expect(raw.elevation, 6.0); expect(raw.highlightElevation, 6.0); expect(raw.disabledElevation, 6.0); expect(raw.constraints, defaultFABConstraints); expect(raw.padding, defaultFABPadding); expect(raw.shape, defaultFABShapeM3); expect(raw.animationDuration, defaultButtonDuration); expect(raw.materialTapTargetSize, MaterialTapTargetSize.padded); }); testWidgets('Material2 - theme: ThemeData.light(), enabled: false', (WidgetTester tester) async { final ThemeData theme = ThemeData.light(useMaterial3: false); await tester.pumpWidget( MaterialApp( theme: theme, home: const Center( child: FloatingActionButton( onPressed: null, // button.enabled == false child: Icon(Icons.add), ), ), ), ); final RawMaterialButton raw = tester.widget<RawMaterialButton>(find.byType(RawMaterialButton)); expect(raw.enabled, false); expect(raw.textStyle!.color, const Color(0xffffffff)); expect(raw.fillColor, const Color(0xff2196f3)); // highlightColor, disabled button can't be pressed // splashColor, disabled button doesn't splash expect(raw.elevation, 6.0); expect(raw.highlightElevation, 12.0); expect(raw.disabledElevation, 6.0); expect(raw.constraints, defaultFABConstraints); expect(raw.padding, defaultFABPadding); expect(raw.shape, defaultFABShape); expect(raw.animationDuration, defaultButtonDuration); expect(raw.materialTapTargetSize, MaterialTapTargetSize.padded); }); testWidgets('Material3 - theme: ThemeData.light(), enabled: false', (WidgetTester tester) async { final ThemeData theme = ThemeData.light(useMaterial3: true); await tester.pumpWidget( MaterialApp( theme: theme, home: const Center( child: FloatingActionButton( onPressed: null, // button.enabled == false child: Icon(Icons.add), ), ), ), ); final RawMaterialButton raw = tester.widget<RawMaterialButton>(find.byType(RawMaterialButton)); expect(raw.enabled, false); expect(raw.textStyle!.color, theme.colorScheme.onPrimaryContainer); expect(raw.fillColor, theme.colorScheme.primaryContainer); // highlightColor, disabled button can't be pressed // splashColor, disabled button doesn't splash expect(raw.elevation, 6.0); expect(raw.highlightElevation, 6.0); expect(raw.disabledElevation, 6.0); expect(raw.constraints, defaultFABConstraints); expect(raw.padding, defaultFABPadding); expect(raw.shape, defaultFABShapeM3); expect(raw.animationDuration, defaultButtonDuration); expect(raw.materialTapTargetSize, MaterialTapTargetSize.padded); }); }); }
flutter/packages/flutter/test/material/theme_defaults_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/theme_defaults_test.dart", "repo_id": "flutter", "token_count": 2165 }
725
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:js_interop'; import 'package:web/web.dart' as web; /// Defines a new property on an Object. @JS('Object.defineProperty') external void objectDefineProperty(JSAny o, String symbol, JSAny desc); void createGetter(JSAny mock, String key, JSAny? Function() get) { objectDefineProperty( mock, key, <String, JSFunction>{ 'get': (() => get()).toJS, }.jsify()!, ); } @JS() @staticInterop @anonymous class DomXMLHttpRequestMock { external factory DomXMLHttpRequestMock({ JSFunction? open, JSString responseType, JSNumber timeout, JSBoolean withCredentials, JSFunction? send, JSFunction? setRequestHeader, JSFunction addEventListener, }); } typedef _DartDomEventListener = JSVoid Function(web.Event event); class TestHttpRequest { TestHttpRequest() { _mock = DomXMLHttpRequestMock( open: open.toJS, send: send.toJS, setRequestHeader: setRequestHeader.toJS, addEventListener: addEventListener.toJS, ); final JSAny mock = _mock as JSAny; createGetter(mock, 'headers', () => headers.jsify()); createGetter(mock, 'responseHeaders', () => responseHeaders.jsify()); createGetter(mock, 'status', () => status.toJS); createGetter(mock, 'response', () => response.jsify()); } late DomXMLHttpRequestMock _mock; MockEvent? mockEvent; Map<String, String> headers = <String, String>{}; int status = -1; Object? response; Map<String, String> get responseHeaders => headers; JSVoid open(String method, String url, bool async) {} JSVoid send() {} JSVoid setRequestHeader(String name, String value) { headers[name] = value; } JSVoid addEventListener(String type, web.EventListener listener) { if (type == mockEvent?.type) { final _DartDomEventListener dartListener = (listener as JSExportedDartFunction).toDart as _DartDomEventListener; dartListener(mockEvent!.event); } } web.XMLHttpRequest getMock() => _mock as web.XMLHttpRequest; } class MockEvent { MockEvent(this.type, this.event); final String type; final web.Event event; }
flutter/packages/flutter/test/painting/_test_http_request.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/_test_http_request.dart", "repo_id": "flutter", "token_count": 838 }
726
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:ui' as ui show ColorFilter, Image; import 'package:fake_async/fake_async.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; import '../image_data.dart'; import '../painting/mocks_for_image_cache.dart'; import '../rendering/rendering_tester.dart'; class TestCanvas implements Canvas { final List<Invocation> invocations = <Invocation>[]; @override void noSuchMethod(Invocation invocation) { invocations.add(invocation); } } class SynchronousTestImageProvider extends ImageProvider<int> { const SynchronousTestImageProvider(this.image); final ui.Image image; @override Future<int> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<int>(1); } @override ImageStreamCompleter loadImage(int key, ImageDecoderCallback decode) { return OneFrameImageStreamCompleter( SynchronousFuture<ImageInfo>(TestImageInfo(key, image: image)), ); } } class SynchronousErrorTestImageProvider extends ImageProvider<int> { const SynchronousErrorTestImageProvider(this.throwable); final Object throwable; @override Future<int> obtainKey(ImageConfiguration configuration) { throw throwable; } @override ImageStreamCompleter loadImage(int key, ImageDecoderCallback decode) { throw throwable; } } class AsyncTestImageProvider extends ImageProvider<int> { AsyncTestImageProvider(this.image); final ui.Image image; @override Future<int> obtainKey(ImageConfiguration configuration) { return Future<int>.value(2); } @override ImageStreamCompleter loadImage(int key, ImageDecoderCallback decode) { return OneFrameImageStreamCompleter( Future<ImageInfo>.value(TestImageInfo(key, image: image)), ); } } class DelayedImageProvider extends ImageProvider<DelayedImageProvider> { DelayedImageProvider(this.image); final ui.Image image; final Completer<ImageInfo> _completer = Completer<ImageInfo>(); @override Future<DelayedImageProvider> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<DelayedImageProvider>(this); } @override ImageStreamCompleter loadImage(DelayedImageProvider key, ImageDecoderCallback decode) { return OneFrameImageStreamCompleter(_completer.future); } Future<void> complete() async { _completer.complete(ImageInfo(image: image)); } @override String toString() => '${describeIdentity(this)}()'; } class MultiFrameImageProvider extends ImageProvider<MultiFrameImageProvider> { MultiFrameImageProvider(this.completer); final MultiImageCompleter completer; @override Future<MultiFrameImageProvider> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<MultiFrameImageProvider>(this); } @override ImageStreamCompleter loadImage(MultiFrameImageProvider key, ImageDecoderCallback decode) { return completer; } @override String toString() => '${describeIdentity(this)}()'; } class MultiImageCompleter extends ImageStreamCompleter { void testSetImage(ImageInfo info) { setImage(info); } } void main() { TestRenderingFlutterBinding.ensureInitialized(); test('Decoration.lerp()', () { const BoxDecoration a = BoxDecoration(color: Color(0xFFFFFFFF)); const BoxDecoration b = BoxDecoration(color: Color(0x00000000)); BoxDecoration c = Decoration.lerp(a, b, 0.0)! as BoxDecoration; expect(c.color, equals(a.color)); c = Decoration.lerp(a, b, 0.25)! as BoxDecoration; expect(c.color, equals(Color.lerp(const Color(0xFFFFFFFF), const Color(0x00000000), 0.25))); c = Decoration.lerp(a, b, 1.0)! as BoxDecoration; expect(c.color, equals(b.color)); }); test('Decoration.lerp identical a,b', () { expect(Decoration.lerp(null, null, 0), null); const Decoration decoration = BoxDecoration(); expect(identical(Decoration.lerp(decoration, decoration, 0.5), decoration), true); }); test('Decoration equality', () { const BoxDecoration a = BoxDecoration( color: Color(0xFFFFFFFF), boxShadow: <BoxShadow>[BoxShadow()], ); const BoxDecoration b = BoxDecoration( color: Color(0xFFFFFFFF), boxShadow: <BoxShadow>[BoxShadow()], ); expect(a.hashCode, equals(b.hashCode)); expect(a, equals(b)); }); test('BoxDecorationImageListenerSync', () async { final ui.Image image = await createTestImage(width: 100, height: 100); final ImageProvider imageProvider = SynchronousTestImageProvider(image); final DecorationImage backgroundImage = DecorationImage(image: imageProvider); final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage); bool onChangedCalled = false; final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { onChangedCalled = true; }); final TestCanvas canvas = TestCanvas(); const ImageConfiguration imageConfiguration = ImageConfiguration(size: Size.zero); boxPainter.paint(canvas, Offset.zero, imageConfiguration); // The onChanged callback should not be invoked during the call to boxPainter.paint expect(onChangedCalled, equals(false)); }); test('BoxDecorationImageListenerAsync', () async { final ui.Image image = await createTestImage(width: 10, height: 10); FakeAsync().run((FakeAsync async) { final ImageProvider imageProvider = AsyncTestImageProvider(image); final DecorationImage backgroundImage = DecorationImage(image: imageProvider); final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage); bool onChangedCalled = false; final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { onChangedCalled = true; }); final TestCanvas canvas = TestCanvas(); const ImageConfiguration imageConfiguration = ImageConfiguration(size: Size.zero); boxPainter.paint(canvas, Offset.zero, imageConfiguration); // The onChanged callback should be invoked asynchronously. expect(onChangedCalled, equals(false)); async.flushMicrotasks(); expect(onChangedCalled, equals(true)); }); }); test('BoxDecorationImageListener does not change when image is clone', () async { final ui.Image image1 = await createTestImage(width: 10, height: 10, cache: false); final ui.Image image2 = await createTestImage(width: 10, height: 10, cache: false); final MultiImageCompleter completer = MultiImageCompleter(); final MultiFrameImageProvider imageProvider = MultiFrameImageProvider(completer); final DecorationImage backgroundImage = DecorationImage(image: imageProvider); final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage); bool onChangedCalled = false; final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { onChangedCalled = true; }); final TestCanvas canvas = TestCanvas(); const ImageConfiguration imageConfiguration = ImageConfiguration(size: Size.zero); boxPainter.paint(canvas, Offset.zero, imageConfiguration); // The onChanged callback should be invoked asynchronously. expect(onChangedCalled, equals(false)); completer.testSetImage(ImageInfo(image: image1.clone())); await null; expect(onChangedCalled, equals(true)); onChangedCalled = false; completer.testSetImage(ImageInfo(image: image1.clone())); await null; expect(onChangedCalled, equals(false)); completer.testSetImage(ImageInfo(image: image2.clone())); await null; expect(onChangedCalled, equals(true)); }); // Regression test for https://github.com/flutter/flutter/issues/7289. // A reference test would be better. test('BoxDecoration backgroundImage clip', () async { final ui.Image image = await createTestImage(width: 100, height: 100); void testDecoration({ BoxShape shape = BoxShape.rectangle, BorderRadius? borderRadius, required bool expectClip }) { FakeAsync().run((FakeAsync async) async { final DelayedImageProvider imageProvider = DelayedImageProvider(image); final DecorationImage backgroundImage = DecorationImage(image: imageProvider); final BoxDecoration boxDecoration = BoxDecoration( shape: shape, borderRadius: borderRadius, image: backgroundImage, ); final TestCanvas canvas = TestCanvas(); const ImageConfiguration imageConfiguration = ImageConfiguration( size: Size(100.0, 100.0), ); bool onChangedCalled = false; final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { onChangedCalled = true; }); // _BoxDecorationPainter._paintDecorationImage() resolves the background // image and adds a listener to the resolved image stream. boxPainter.paint(canvas, Offset.zero, imageConfiguration); await imageProvider.complete(); // Run the listener which calls onChanged() which saves an internal // reference to the TestImage. async.flushMicrotasks(); expect(onChangedCalled, isTrue); boxPainter.paint(canvas, Offset.zero, imageConfiguration); // We expect a clip to precede the drawImageRect call. final List<Invocation> commands = canvas.invocations.where((Invocation invocation) { return invocation.memberName == #clipPath || invocation.memberName == #drawImageRect; }).toList(); if (expectClip) { // We expect a clip to precede the drawImageRect call. expect(commands.length, 2); expect(commands[0].memberName, equals(#clipPath)); expect(commands[1].memberName, equals(#drawImageRect)); } else { expect(commands.length, 1); expect(commands[0].memberName, equals(#drawImageRect)); } }); } testDecoration(shape: BoxShape.circle, expectClip: true); testDecoration(borderRadius: const BorderRadius.all(Radius.circular(16.0)), expectClip: true); testDecoration(expectClip: false); }); test('DecorationImage test', () async { const ColorFilter colorFilter = ui.ColorFilter.mode(Color(0xFF00FF00), BlendMode.src); final ui.Image image = await createTestImage(width: 100, height: 100); final DecorationImage backgroundImage = DecorationImage( image: SynchronousTestImageProvider(image), colorFilter: colorFilter, fit: BoxFit.contain, alignment: Alignment.bottomLeft, centerSlice: const Rect.fromLTWH(10.0, 20.0, 30.0, 40.0), repeat: ImageRepeat.repeatY, opacity: 0.5, filterQuality: FilterQuality.high, invertColors: true, isAntiAlias: true, ); final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage); final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { assert(false); }); final TestCanvas canvas = TestCanvas(); boxPainter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0))); final Invocation call = canvas.invocations.singleWhere((Invocation call) => call.memberName == #drawImageNine); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); expect(call.positionalArguments[0], isA<ui.Image>()); expect(call.positionalArguments[1], const Rect.fromLTRB(10.0, 20.0, 40.0, 60.0)); expect(call.positionalArguments[2], const Rect.fromLTRB(0.0, 0.0, 100.0, 100.0)); expect(call.positionalArguments[3], isA<Paint>()); final Paint paint = call.positionalArguments[3] as Paint; expect(paint.colorFilter, colorFilter); expect(paint.color, const Color(0x7F000000)); // 0.5 opacity expect(paint.filterQuality, FilterQuality.high); expect(paint.isAntiAlias, true); expect(paint.invertColors, isTrue); }); test('DecorationImage.toString', () async { expect( DecorationImage( image: SynchronousTestImageProvider( await createTestImage(width: 100, height: 100), ), opacity: 0.99, scale: 2.01, ).toString(), 'DecorationImage(SynchronousTestImageProvider(), Alignment.center, scale 2.0, opacity 1.0, FilterQuality.low)', ); }); test('DecorationImage with null textDirection configuration should throw Error', () async { const ColorFilter colorFilter = ui.ColorFilter.mode(Color(0xFF00FF00), BlendMode.src); final ui.Image image = await createTestImage(width: 100, height: 100); final DecorationImage backgroundImage = DecorationImage( image: SynchronousTestImageProvider(image), colorFilter: colorFilter, fit: BoxFit.contain, centerSlice: const Rect.fromLTWH(10.0, 20.0, 30.0, 40.0), repeat: ImageRepeat.repeatY, matchTextDirection: true, scale: 0.5, opacity: 0.5, invertColors: true, isAntiAlias: true, ); final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage); final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { assert(false); }); final TestCanvas canvas = TestCanvas(); late FlutterError error; try { boxPainter.paint(canvas, Offset.zero, const ImageConfiguration( size: Size(100.0, 100.0), )); } on FlutterError catch (e) { error = e; } expect(error, isNotNull); expect(error.diagnostics.length, 4); expect(error.diagnostics[2], isA<DiagnosticsProperty<DecorationImage>>()); expect(error.diagnostics[3], isA<DiagnosticsProperty<ImageConfiguration>>()); expect(error.toStringDeep(), 'FlutterError\n' ' DecorationImage.matchTextDirection can only be used when a\n' ' TextDirection is available.\n' ' When DecorationImagePainter.paint() was called, there was no text\n' ' direction provided in the ImageConfiguration object to match.\n' ' The DecorationImage was:\n' ' DecorationImage(SynchronousTestImageProvider(),\n' ' ColorFilter.mode(Color(0xff00ff00), BlendMode.src),\n' ' BoxFit.contain, Alignment.center, centerSlice:\n' ' Rect.fromLTRB(10.0, 20.0, 40.0, 60.0), ImageRepeat.repeatY,\n' ' match text direction, scale 0.5, opacity 0.5,\n' ' FilterQuality.low, invert colors, use anti-aliasing)\n' ' The ImageConfiguration was:\n' ' ImageConfiguration(size: Size(100.0, 100.0))\n', ); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87364 test('DecorationImage - error listener', () async { late String exception; final DecorationImage backgroundImage = DecorationImage( image: const SynchronousErrorTestImageProvider('threw'), onError: (dynamic error, StackTrace? stackTrace) { exception = error as String; }, ); backgroundImage.createPainter(() { }).paint( TestCanvas(), Rect.largest, Path(), ImageConfiguration.empty, ); // Yield so that the exception callback gets called before we check it. await null; expect(exception, 'threw'); }); test('BoxDecoration.lerp - shapes', () { // We don't lerp the shape, we just switch from one to the other at t=0.5. // (Use a ShapeDecoration and ShapeBorder if you want to lerp the shapes...) expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), -1.0, ), const BoxDecoration(), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 0.0, ), const BoxDecoration(), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 0.25, ), const BoxDecoration(), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 0.75, ), const BoxDecoration(shape: BoxShape.circle), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 1.0, ), const BoxDecoration(shape: BoxShape.circle), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(shape: BoxShape.circle), 2.0, ), const BoxDecoration(shape: BoxShape.circle), ); }); test('BoxDecoration.lerp - gradients', () { const Gradient gradient = LinearGradient(colors: <Color>[ Color(0x00000000), Color(0xFFFFFFFF) ]); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(gradient: gradient), -1.0, ), const BoxDecoration(gradient: LinearGradient(colors: <Color>[ Color(0x00000000), Color(0x00FFFFFF) ])), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(gradient: gradient), 0.0, ), const BoxDecoration(), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(gradient: gradient), 0.25, ), const BoxDecoration(gradient: LinearGradient(colors: <Color>[ Color(0x00000000), Color(0x40FFFFFF) ])), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(gradient: gradient), 0.75, ), const BoxDecoration(gradient: LinearGradient(colors: <Color>[ Color(0x00000000), Color(0xBFFFFFFF) ])), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(gradient: gradient), 1.0, ), const BoxDecoration(gradient: gradient), ); expect( BoxDecoration.lerp( const BoxDecoration(), const BoxDecoration(gradient: gradient), 2.0, ), const BoxDecoration(gradient: gradient), ); }); test('Decoration.lerp with unrelated decorations', () { expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.0), isA<FlutterLogoDecoration>()); expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.25), isA<FlutterLogoDecoration>()); expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 0.75), isA<BoxDecoration>()); expect(Decoration.lerp(const FlutterLogoDecoration(), const BoxDecoration(), 1.0), isA<BoxDecoration>()); }); test('paintImage BoxFit.none scale test', () async { for (double scale = 1.0; scale <= 4.0; scale += 1.0) { final TestCanvas canvas = TestCanvas(); const Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 250.0); final ui.Image image = await createTestImage(width: 100, height: 100); paintImage( canvas: canvas, rect: outputRect, image: image, scale: scale, alignment: Alignment.bottomRight, fit: BoxFit.none, ); const Size imageSize = Size(100.0, 100.0); final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); expect(call.positionalArguments[0], isA<ui.Image>()); // sourceRect should contain all pixels of the source image expect(call.positionalArguments[1], Offset.zero & imageSize); // Image should be scaled down (divided by scale) // and be positioned in the bottom right of the outputRect final Size expectedTileSize = imageSize / scale; final Rect expectedTileRect = Rect.fromPoints( outputRect.bottomRight.translate(-expectedTileSize.width, -expectedTileSize.height), outputRect.bottomRight, ); expect(call.positionalArguments[2], expectedTileRect); expect(call.positionalArguments[3], isA<Paint>()); } }); test('paintImage BoxFit.scaleDown scale test', () async { for (double scale = 1.0; scale <= 4.0; scale += 1.0) { final TestCanvas canvas = TestCanvas(); // container size > scaled image size const Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 250.0); final ui.Image image = await createTestImage(width: 100, height: 100); paintImage( canvas: canvas, rect: outputRect, image: image, scale: scale, alignment: Alignment.bottomRight, fit: BoxFit.scaleDown, ); const Size imageSize = Size(100.0, 100.0); final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); expect(call.positionalArguments[0], isA<ui.Image>()); // sourceRect should contain all pixels of the source image expect(call.positionalArguments[1], Offset.zero & imageSize); // Image should be scaled down (divided by scale) // and be positioned in the bottom right of the outputRect final Size expectedTileSize = imageSize / scale; final Rect expectedTileRect = Rect.fromPoints( outputRect.bottomRight.translate(-expectedTileSize.width, -expectedTileSize.height), outputRect.bottomRight, ); expect(call.positionalArguments[2], expectedTileRect); expect(call.positionalArguments[3], isA<Paint>()); } }); test('paintImage BoxFit.scaleDown test', () async { final TestCanvas canvas = TestCanvas(); // container height (20 px) < scaled image height (50 px) const Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 20.0); final ui.Image image = await createTestImage(width: 100, height: 100); paintImage( canvas: canvas, rect: outputRect, image: image, scale: 2.0, alignment: Alignment.bottomRight, fit: BoxFit.scaleDown, ); const Size imageSize = Size(100.0, 100.0); final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); expect(call.positionalArguments[0], isA<ui.Image>()); // sourceRect should contain all pixels of the source image expect(call.positionalArguments[1], Offset.zero & imageSize); // Image should be scaled down to fit in height // and be positioned in the bottom right of the outputRect const Size expectedTileSize = Size(20.0, 20.0); final Rect expectedTileRect = Rect.fromPoints( outputRect.bottomRight.translate(-expectedTileSize.width, -expectedTileSize.height), outputRect.bottomRight, ); expect(call.positionalArguments[2], expectedTileRect); expect(call.positionalArguments[3], isA<Paint>()); }); test('paintImage boxFit, scale and alignment test', () async { const List<BoxFit> boxFits = <BoxFit>[ BoxFit.contain, BoxFit.cover, BoxFit.fitWidth, BoxFit.fitWidth, BoxFit.fitHeight, BoxFit.none, BoxFit.scaleDown, ]; for (final BoxFit boxFit in boxFits) { final TestCanvas canvas = TestCanvas(); const Rect outputRect = Rect.fromLTWH(30.0, 30.0, 250.0, 250.0); final ui.Image image = await createTestImage(width: 100, height: 100); paintImage( canvas: canvas, rect: outputRect, image: image, scale: 3.0, fit: boxFit, ); final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); // Image should be positioned in the center of the container // ignore: avoid_dynamic_calls expect(call.positionalArguments[2].center, outputRect.center); } }); test('paintImage with repeatX and fitHeight', () async { final TestCanvas canvas = TestCanvas(); // Paint a square image into an output rect that is twice as wide as it is // tall. Two copies of the image should be painted, one next to the other. const Rect outputRect = Rect.fromLTWH(30.0, 30.0, 400.0, 200.0); final ui.Image image = await createTestImage(width: 100, height: 100); paintImage( canvas: canvas, rect: outputRect, image: image, alignment: Alignment.topLeft, fit: BoxFit.fitHeight, repeat: ImageRepeat.repeatX, ); const Size imageSize = Size(100.0, 100.0); final List<Invocation> calls = canvas.invocations.where((Invocation call) => call.memberName == #drawImageRect).toList(); final Set<Rect> tileRects = <Rect>{}; expect(calls, hasLength(2)); for (final Invocation call in calls) { expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); expect(call.positionalArguments[0], isA<ui.Image>()); // sourceRect should contain all pixels of the source image expect(call.positionalArguments[1], Offset.zero & imageSize); tileRects.add(call.positionalArguments[2] as Rect); expect(call.positionalArguments[3], isA<Paint>()); } expect(tileRects, <Rect>{const Rect.fromLTWH(30.0, 30.0, 200.0, 200.0), const Rect.fromLTWH(230.0, 30.0, 200.0, 200.0)}); }); test('paintImage with repeatY and fitWidth', () async { final TestCanvas canvas = TestCanvas(); // Paint a square image into an output rect that is twice as tall as it is // wide. Two copies of the image should be painted, one above the other. const Rect outputRect = Rect.fromLTWH(30.0, 30.0, 200.0, 400.0); final ui.Image image = await createTestImage(width: 100, height: 100); paintImage( canvas: canvas, rect: outputRect, image: image, alignment: Alignment.topLeft, fit: BoxFit.fitWidth, repeat: ImageRepeat.repeatY, ); const Size imageSize = Size(100.0, 100.0); final List<Invocation> calls = canvas.invocations.where((Invocation call) => call.memberName == #drawImageRect).toList(); final Set<Rect> tileRects = <Rect>{}; expect(calls, hasLength(2)); for (final Invocation call in calls) { expect(call.isMethod, isTrue); expect(call.positionalArguments, hasLength(4)); expect(call.positionalArguments[0], isA<ui.Image>()); // sourceRect should contain all pixels of the source image expect(call.positionalArguments[1], Offset.zero & imageSize); tileRects.add(call.positionalArguments[2] as Rect); expect(call.positionalArguments[3], isA<Paint>()); } expect(tileRects, <Rect>{const Rect.fromLTWH(30.0, 30.0, 200.0, 200.0), const Rect.fromLTWH(30.0, 230.0, 200.0, 200.0)}); }); test('DecorationImage scale test', () async { final ui.Image image = await createTestImage(width: 100, height: 100); final DecorationImage backgroundImage = DecorationImage( image: SynchronousTestImageProvider(image), scale: 4, alignment: Alignment.topLeft, ); final BoxDecoration boxDecoration = BoxDecoration(image: backgroundImage); final BoxPainter boxPainter = boxDecoration.createBoxPainter(() { assert(false); }); final TestCanvas canvas = TestCanvas(); boxPainter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0))); final Invocation call = canvas.invocations.firstWhere((Invocation call) => call.memberName == #drawImageRect); // The image should scale down to Size(25.0, 25.0) from Size(100.0, 100.0) // considering DecorationImage scale to be 4.0 and Image scale to be 1.0. // ignore: avoid_dynamic_calls expect(call.positionalArguments[2].size, const Size(25.0, 25.0)); expect(call.positionalArguments[2], const Rect.fromLTRB(0.0, 0.0, 25.0, 25.0)); }); test('DecorationImagePainter disposes of image when disposed', () async { final ImageProvider provider = MemoryImage(Uint8List.fromList(kTransparentImage)); final ImageStream stream = provider.resolve(ImageConfiguration.empty); final Completer<ImageInfo> infoCompleter = Completer<ImageInfo>(); void listener(ImageInfo image, bool syncCall) { assert(!infoCompleter.isCompleted); infoCompleter.complete(image); } stream.addListener(ImageStreamListener(listener)); final ImageInfo info = await infoCompleter.future; final int baselineRefCount = info.image.debugGetOpenHandleStackTraces()!.length; final DecorationImagePainter painter = DecorationImage(image: provider).createPainter(() {}); final Canvas canvas = TestCanvas(); painter.paint(canvas, Rect.zero, Path(), ImageConfiguration.empty); expect(info.image.debugGetOpenHandleStackTraces()!.length, baselineRefCount + 1); painter.dispose(); expect(info.image.debugGetOpenHandleStackTraces()!.length, baselineRefCount); info.dispose(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87442 }
flutter/packages/flutter/test/painting/decoration_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/decoration_test.dart", "repo_id": "flutter", "token_count": 10570 }
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 'dart:async'; import 'dart:typed_data'; import 'dart:ui' as ui; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; import '../image_data.dart'; import '../rendering/rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); tearDown(() { PaintingBinding.instance.imageCache.clear(); PaintingBinding.instance.imageCache.clearLiveImages(); }); group('ResizeImage', () { group('resizing', () { test('upscales to the correct dimensions', () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage imageProvider = MemoryImage(bytes); final Size rawImageSize = await _resolveAndGetSize(imageProvider); expect(rawImageSize, const Size(1, 1)); const Size resizeDims = Size(14, 7); final ResizeImage resizedImage = ResizeImage(MemoryImage(bytes), width: resizeDims.width.round(), height: resizeDims.height.round(), allowUpscaling: true); const ImageConfiguration resizeConfig = ImageConfiguration(size: resizeDims); final Size resizedImageSize = await _resolveAndGetSize(resizedImage, configuration: resizeConfig); expect(resizedImageSize, resizeDims); }); test('downscales to the correct dimensions', () async { final Uint8List bytes = Uint8List.fromList(kBlueSquarePng); final MemoryImage imageProvider = MemoryImage(bytes); final Size rawImageSize = await _resolveAndGetSize(imageProvider); expect(rawImageSize, const Size(50, 50)); const Size resizeDims = Size(25, 25); final ResizeImage resizedImage = ResizeImage(MemoryImage(bytes), width: resizeDims.width.round(), height: resizeDims.height.round(), allowUpscaling: true); const ImageConfiguration resizeConfig = ImageConfiguration(size: resizeDims); final Size resizedImageSize = await _resolveAndGetSize(resizedImage, configuration: resizeConfig); expect(resizedImageSize, resizeDims); }); test('refuses upscaling when allowUpscaling=false', () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage imageProvider = MemoryImage(bytes); final Size rawImageSize = await _resolveAndGetSize(imageProvider); expect(rawImageSize, const Size(1, 1)); const Size resizeDims = Size(50, 50); final ResizeImage resizedImage = ResizeImage(MemoryImage(bytes), width: resizeDims.width.round(), height: resizeDims.height.round()); const ImageConfiguration resizeConfig = ImageConfiguration(size: resizeDims); final Size resizedImageSize = await _resolveAndGetSize(resizedImage, configuration: resizeConfig); expect(resizedImageSize, const Size(1, 1)); }); group('with policy=fit and allowResize=false', () { test('constrains square image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 50, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains square image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 50, height: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains square image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains square image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains square image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, height: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 25)); }); test('constrains portrait image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 60, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 50)); }); test('constrains portrait image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 60, height: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(12, 25)); }); test('constrains portrait image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(12, 25)); }); test('constrains portrait image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 50)); }); test('constrains portrait image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, height: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(12, 25)); }); test('constrains landscape image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 60, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 12)); }); test('constrains landscape image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 60, height: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(50, 25)); }); test('constrains landscape image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 12)); }); test('constrains landscape image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(25, 12)); }); test('constrains landscape image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, height: 25, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(50, 25)); }); test('leaves image as-is if constraints are bigger than image', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 120, height: 100, policy: ResizeImagePolicy.fit); await _expectImageSize(resizedImage, const Size(50, 50)); }); }); group('with policy=fit and allowResize=true', () { test('constrains square image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains square image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains square image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains square image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains square image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 100)); }); test('constrains portrait image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, height: 250, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains portrait image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 400, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains portrait image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains portrait image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains portrait image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBluePortraitPng)); await _expectImageSize(rawImage, const Size(50, 100)); final ResizeImage resizedImage = ResizeImage(rawImage, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(100, 200)); }); test('constrains landscape image to bounded portrait rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, height: 400, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('constrains landscape image to bounded landscape rect', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 250, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('constrains landscape image to bounded square', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, height: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('constrains landscape image to bounded width', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 200, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('constrains landscape image to bounded height', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueLandscapePng)); await _expectImageSize(rawImage, const Size(100, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, height: 100, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(200, 100)); }); test('shrinks image if constraints are smaller than image', () async { final MemoryImage rawImage = MemoryImage(Uint8List.fromList(kBlueSquarePng)); await _expectImageSize(rawImage, const Size(50, 50)); final ResizeImage resizedImage = ResizeImage(rawImage, width: 25, height: 30, policy: ResizeImagePolicy.fit, allowUpscaling: true); await _expectImageSize(resizedImage, const Size(25, 25)); }); }); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/73120); test('does not resize when no size is passed', () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage imageProvider = MemoryImage(bytes); final Size rawImageSize = await _resolveAndGetSize(imageProvider); expect(rawImageSize, const Size(1, 1)); final ImageProvider<Object> resizedImage = ResizeImage.resizeIfNeeded(null, null, imageProvider); final Size resizedImageSize = await _resolveAndGetSize(resizedImage); expect(resizedImageSize, const Size(1, 1)); }); test('stores values', () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage memoryImage = MemoryImage(bytes); memoryImage.resolve(ImageConfiguration.empty); final ResizeImage resizeImage = ResizeImage(memoryImage, width: 10, height: 20); expect(resizeImage.width, 10); expect(resizeImage.height, 20); expect(resizeImage.imageProvider, memoryImage); expect(memoryImage.resolve(ImageConfiguration.empty) != resizeImage.resolve(ImageConfiguration.empty), true); }); test('takes one dim', () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage memoryImage = MemoryImage(bytes); final ResizeImage resizeImage = ResizeImage(memoryImage, width: 10); expect(resizeImage.width, 10); expect(resizeImage.height, null); expect(resizeImage.imageProvider, memoryImage); expect(memoryImage.resolve(ImageConfiguration.empty) != resizeImage.resolve(ImageConfiguration.empty), true); }); test('forms closure', () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage memoryImage = MemoryImage(bytes); final ResizeImage resizeImage = ResizeImage(memoryImage, width: 123, height: 321, allowUpscaling: true); Future<ui.Codec> decode(ui.ImmutableBuffer buffer, {ui.TargetImageSizeCallback? getTargetSize}) { return PaintingBinding.instance.instantiateImageCodecWithSize(buffer, getTargetSize: (int intrinsicWidth, int intrinsicHeight) { expect(getTargetSize, isNotNull); final ui.TargetImageSize targetSize = getTargetSize!(intrinsicWidth, intrinsicHeight); expect(targetSize.width, 123); expect(targetSize.height, 321); return targetSize; }); } resizeImage.loadImage(await resizeImage.obtainKey(ImageConfiguration.empty), decode); }); test('handles sync obtainKey', () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final MemoryImage memoryImage = MemoryImage(bytes); final ResizeImage resizeImage = ResizeImage(memoryImage, width: 123, height: 321); bool isAsync = false; bool keyObtained = false; resizeImage.obtainKey(ImageConfiguration.empty).then((Object key) { keyObtained = true; expect(isAsync, false); }); isAsync = true; expect(isAsync, true); expect(keyObtained, true); }); test('handles async obtainKey', () async { final Uint8List bytes = Uint8List.fromList(kTransparentImage); final _AsyncKeyMemoryImage memoryImage = _AsyncKeyMemoryImage(bytes); final ResizeImage resizeImage = ResizeImage(memoryImage, width: 123, height: 321); bool isAsync = false; final Completer<void> completer = Completer<void>(); resizeImage.obtainKey(ImageConfiguration.empty).then((Object key) { try { expect(isAsync, true); } finally { completer.complete(); } }); isAsync = true; await completer.future; expect(isAsync, true); }); }); } Future<void> _expectImageSize(ImageProvider<Object> imageProvider, Size size) async { final Size actualSize = await _resolveAndGetSize(imageProvider); expect(actualSize, size); } Future<Size> _resolveAndGetSize( ImageProvider imageProvider, { ImageConfiguration configuration = ImageConfiguration.empty, }) async { final ImageStream stream = imageProvider.resolve(configuration); final Completer<Size> completer = Completer<Size>(); final ImageStreamListener listener = ImageStreamListener((ImageInfo image, bool synchronousCall) { final int height = image.image.height; final int width = image.image.width; completer.complete(Size(width.toDouble(), height.toDouble())); } ); stream.addListener(listener); return completer.future; } // This version of MemoryImage guarantees obtainKey returns a future that has not been // completed synchronously. class _AsyncKeyMemoryImage extends MemoryImage { const _AsyncKeyMemoryImage(super.bytes); @override Future<MemoryImage> obtainKey(ImageConfiguration configuration) { return Future<MemoryImage>(() => this); } }
flutter/packages/flutter/test/painting/image_provider_resize_image_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/image_provider_resize_image_test.dart", "repo_id": "flutter", "token_count": 8019 }
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:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; import '../rendering/rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); test('ShapeDecoration constructor', () { const Color colorR = Color(0xffff0000); const Color colorG = Color(0xff00ff00); const Gradient gradient = LinearGradient(colors: <Color>[colorR, colorG]); expect(const ShapeDecoration(shape: Border()), const ShapeDecoration(shape: Border())); expect(() => ShapeDecoration(color: colorR, gradient: nonconst(gradient), shape: const Border()), throwsAssertionError); expect( ShapeDecoration.fromBoxDecoration(const BoxDecoration(shape: BoxShape.circle)), const ShapeDecoration(shape: CircleBorder()), ); expect( ShapeDecoration.fromBoxDecoration(BoxDecoration(borderRadius: BorderRadiusDirectional.circular(100.0))), ShapeDecoration(shape: RoundedRectangleBorder(borderRadius: BorderRadiusDirectional.circular(100.0))), ); expect( ShapeDecoration.fromBoxDecoration(BoxDecoration(shape: BoxShape.circle, border: Border.all(color: colorG))), const ShapeDecoration(shape: CircleBorder(side: BorderSide(color: colorG))), ); expect( ShapeDecoration.fromBoxDecoration(BoxDecoration(border: Border.all(color: colorR))), ShapeDecoration(shape: Border.all(color: colorR)), ); expect( ShapeDecoration.fromBoxDecoration(const BoxDecoration(border: BorderDirectional(start: BorderSide()))), const ShapeDecoration(shape: BorderDirectional(start: BorderSide())), ); }); test('ShapeDecoration.lerp identical a,b', () { expect(ShapeDecoration.lerp(null, null, 0), null); const ShapeDecoration shape = ShapeDecoration(shape: CircleBorder()); expect(identical(ShapeDecoration.lerp(shape, shape, 0.5), shape), true); }); test('ShapeDecoration.lerp null a,b', () { const Decoration a = ShapeDecoration(shape: CircleBorder()); const Decoration b = ShapeDecoration(shape: RoundedRectangleBorder()); expect(Decoration.lerp(a, null, 0.0), a); expect(Decoration.lerp(null, b, 0.0), b); expect(Decoration.lerp(null, null, 0.0), null); }); test('ShapeDecoration.lerp and hit test', () { const Decoration a = ShapeDecoration(shape: CircleBorder()); const Decoration b = ShapeDecoration(shape: RoundedRectangleBorder()); const Decoration c = ShapeDecoration(shape: OvalBorder()); expect(Decoration.lerp(a, b, 0.0), a); expect(Decoration.lerp(a, b, 1.0), b); expect(Decoration.lerp(a, c, 0.0), a); expect(Decoration.lerp(a, c, 1.0), c); expect(Decoration.lerp(b, c, 0.0), b); expect(Decoration.lerp(b, c, 1.0), c); const Size size = Size(200.0, 100.0); // at t=0.5, width will be 150 (x=25 to x=175). expect(a.hitTest(size, const Offset(20.0, 50.0)), isFalse); expect(c.hitTest(size, const Offset(50, 5.0)), isFalse); expect(c.hitTest(size, const Offset(5, 30.0)), isFalse); expect(Decoration.lerp(a, b, 0.1)!.hitTest(size, const Offset(20.0, 50.0)), isFalse); expect(Decoration.lerp(a, b, 0.5)!.hitTest(size, const Offset(20.0, 50.0)), isFalse); expect(Decoration.lerp(a, b, 0.9)!.hitTest(size, const Offset(20.0, 50.0)), isTrue); expect(Decoration.lerp(a, c, 0.1)!.hitTest(size, const Offset(30.0, 50.0)), isFalse); expect(Decoration.lerp(a, c, 0.5)!.hitTest(size, const Offset(30.0, 50.0)), isTrue); expect(Decoration.lerp(a, c, 0.9)!.hitTest(size, const Offset(30.0, 50.0)), isTrue); expect(Decoration.lerp(b, c, 0.1)!.hitTest(size, const Offset(45.0, 10.0)), isTrue); expect(Decoration.lerp(b, c, 0.5)!.hitTest(size, const Offset(30.0, 10.0)), isTrue); expect(Decoration.lerp(b, c, 0.9)!.hitTest(size, const Offset(10.0, 30.0)), isTrue); expect(b.hitTest(size, const Offset(20.0, 50.0)), isTrue); }); test('ShapeDecoration.image RTL test', () async { final ui.Image image = await createTestImage(width: 100, height: 200); final List<int> log = <int>[]; final ShapeDecoration decoration = ShapeDecoration( shape: const CircleBorder(), image: DecorationImage( image: TestImageProvider(image), alignment: AlignmentDirectional.bottomEnd, ), ); final BoxPainter painter = decoration.createBoxPainter(() { log.add(0); }); expect((Canvas canvas) => painter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0))), paintsAssertion); expect( (Canvas canvas) { return painter.paint( canvas, const Offset(20.0, -40.0), const ImageConfiguration( size: Size(1000.0, 1000.0), textDirection: TextDirection.rtl, ), ); }, paints ..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 100.0, 200.0), destination: const Rect.fromLTRB(20.0, 1000.0 - 40.0 - 200.0, 20.0 + 100.0, 1000.0 - 40.0)), ); expect( (Canvas canvas) { return painter.paint( canvas, Offset.zero, const ImageConfiguration( size: Size(100.0, 200.0), textDirection: TextDirection.ltr, ), ); }, isNot(paints..image()), // we always use drawImageRect ); expect(log, isEmpty); }); test('ShapeDecoration.getClipPath', () { const ShapeDecoration decoration = ShapeDecoration(shape: CircleBorder()); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0); final Path clipPath = decoration.getClipPath(rect, TextDirection.ltr); final Matcher isLookLikeExpectedPath = isPathThat( includes: const <Offset>[ Offset(50.0, 10.0), ], excludes: const <Offset>[ Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0), ], ); expect(clipPath, isLookLikeExpectedPath); }); test('ShapeDecoration.getClipPath for oval', () { const ShapeDecoration decoration = ShapeDecoration(shape: OvalBorder()); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 50.0); final Path clipPath = decoration.getClipPath(rect, TextDirection.ltr); final Matcher isLookLikeExpectedPath = isPathThat( includes: const <Offset>[ Offset(50.0, 10.0), ], excludes: const <Offset>[ Offset(1.0, 1.0), Offset(15.0, 1.0), Offset(99.0, 19.0), ], ); expect(clipPath, isLookLikeExpectedPath); }); } class TestImageProvider extends ImageProvider<TestImageProvider> { TestImageProvider(this.image); final ui.Image image; @override Future<TestImageProvider> obtainKey(ImageConfiguration configuration) { return SynchronousFuture<TestImageProvider>(this); } @override ImageStreamCompleter loadImage(TestImageProvider key, ImageDecoderCallback decode) { return OneFrameImageStreamCompleter( SynchronousFuture<ImageInfo>(ImageInfo(image: image)), ); } }
flutter/packages/flutter/test/painting/shape_decoration_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/shape_decoration_test.dart", "repo_id": "flutter", "token_count": 2757 }
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/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final TextSelectionDelegate delegate = _FakeEditableTextState(); test('editable intrinsics', () { final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), text: '12345', ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, locale: const Locale('ja', 'JP'), offset: ViewportOffset.zero(), textSelectionDelegate: delegate, ); expect(editable.getMinIntrinsicWidth(double.infinity), 50.0); // The width includes the width of the cursor (1.0). expect(editable.getMaxIntrinsicWidth(double.infinity), 52.0); expect(editable.getMinIntrinsicHeight(double.infinity), 10.0); expect(editable.getMaxIntrinsicHeight(double.infinity), 10.0); expect( editable.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( 'RenderEditable#00000 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE DETACHED\n' ' │ parentData: MISSING\n' ' │ constraints: MISSING\n' ' │ size: MISSING\n' ' │ cursorColor: null\n' ' │ showCursor: ValueNotifier<bool>#00000(false)\n' ' │ maxLines: 1\n' ' │ minLines: null\n' ' │ selectionColor: null\n' ' │ locale: ja_JP\n' ' │ selection: null\n' ' │ offset: _FixedViewportOffset#00000(offset: 0.0)\n' ' ╘═╦══ text ═══\n' ' ║ TextSpan:\n' ' ║ inherit: true\n' ' ║ size: 10.0\n' ' ║ height: 1.0x\n' ' ║ "12345"\n' ' ╚═══════════\n', ), ); }); test('textScaler affects intrinsics', () { final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(fontSize: 10), text: 'Hello World', ), textDirection: TextDirection.ltr, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), offset: ViewportOffset.zero(), textSelectionDelegate: delegate, ); expect(editable.getMaxIntrinsicWidth(double.infinity), 110 + 2); editable.textScaler = const TextScaler.linear(2); expect(editable.getMaxIntrinsicWidth(double.infinity), 220 + 2); }); test('maxLines affects intrinsics', () { final RenderEditable editable = RenderEditable( text: TextSpan( style: const TextStyle(fontSize: 10), text: List<String>.filled(5, 'A').join('\n'), ), textDirection: TextDirection.ltr, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), offset: ViewportOffset.zero(), textSelectionDelegate: delegate, maxLines: null, ); expect(editable.getMaxIntrinsicHeight(double.infinity), 50); editable.maxLines = 1; expect(editable.getMaxIntrinsicHeight(double.infinity), 10); }); test('strutStyle affects intrinsics', () { final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(fontSize: 10), text: 'Hello World', ), textDirection: TextDirection.ltr, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), offset: ViewportOffset.zero(), textSelectionDelegate: delegate, ); expect(editable.getMaxIntrinsicHeight(double.infinity), 10); editable.strutStyle = const StrutStyle(fontSize: 100, forceStrutHeight: true); expect(editable.getMaxIntrinsicHeight(double.infinity), 100); }, skip: kIsWeb && !isCanvasKit); // [intended] strut spport for HTML renderer https://github.com/flutter/flutter/issues/32243. } class _FakeEditableTextState with TextSelectionDelegate { @override TextEditingValue textEditingValue = TextEditingValue.empty; TextSelection? selection; @override void hideToolbar([bool hideHandles = true]) { } @override void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause cause) { selection = value.selection; } @override void bringIntoView(TextPosition position) { } @override void cutSelection(SelectionChangedCause cause) { } @override Future<void> pasteText(SelectionChangedCause cause) { return Future<void>.value(); } @override void selectAll(SelectionChangedCause cause) { } @override void copySelection(SelectionChangedCause cause) { } }
flutter/packages/flutter/test/rendering/editable_intrinsics_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/editable_intrinsics_test.dart", "repo_id": "flutter", "token_count": 1879 }
730
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart' show TestDefaultBinaryMessengerBinding; class _TestHitTester extends RenderBox { _TestHitTester(this.hitTestOverride); final BoxHitTest hitTestOverride; @override bool hitTest(BoxHitTestResult result, {required ui.Offset position}) { return hitTestOverride(result, position); } } // A binding used to test MouseTracker, allowing the test to override hit test // searching. class TestMouseTrackerFlutterBinding extends BindingBase with SchedulerBinding, ServicesBinding, GestureBinding, SemanticsBinding, RendererBinding, TestDefaultBinaryMessengerBinding { @override void initInstances() { super.initInstances(); postFrameCallbacks = <void Function(Duration)>[]; } late final RenderView _renderView = RenderView( view: platformDispatcher.implicitView!, ); late final PipelineOwner _pipelineOwner = PipelineOwner( onSemanticsUpdate: (ui.SemanticsUpdate _) { assert(false); }, ); void setHitTest(BoxHitTest hitTest) { if (_pipelineOwner.rootNode == null) { _pipelineOwner.rootNode = _renderView; rootPipelineOwner.adoptChild(_pipelineOwner); addRenderView(_renderView); } _renderView.child = _TestHitTester(hitTest); } SchedulerPhase? _overridePhase; @override SchedulerPhase get schedulerPhase => _overridePhase ?? super.schedulerPhase; // Manually schedule a post-frame check. // // In real apps this is done by the renderer binding, but in tests we have to // bypass the phase assertion of [MouseTracker.schedulePostFrameCheck]. void scheduleMouseTrackerPostFrameCheck() { final SchedulerPhase? lastPhase = _overridePhase; _overridePhase = SchedulerPhase.persistentCallbacks; addPostFrameCallback((_) { mouseTracker.updateAllDevices(); }); _overridePhase = lastPhase; } List<void Function(Duration)> postFrameCallbacks = <void Function(Duration)>[]; // Proxy post-frame callbacks. @override void addPostFrameCallback(void Function(Duration) callback, {String debugLabel = 'callback'}) { postFrameCallbacks.add(callback); } void flushPostFrameCallbacks(Duration duration) { for (final void Function(Duration) callback in postFrameCallbacks) { callback(duration); } postFrameCallbacks.clear(); } } // An object that mocks the behavior of a render object with [MouseTrackerAnnotation]. class TestAnnotationTarget with Diagnosticable implements MouseTrackerAnnotation, HitTestTarget { const TestAnnotationTarget({this.onEnter, this.onHover, this.onExit, this.cursor = MouseCursor.defer, this.validForMouseTracker = true}); @override final PointerEnterEventListener? onEnter; final PointerHoverEventListener? onHover; @override final PointerExitEventListener? onExit; @override final MouseCursor cursor; @override final bool validForMouseTracker; @override void handleEvent(PointerEvent event, HitTestEntry entry) { if (event is PointerHoverEvent) { onHover?.call(event); } } } // A hit test entry that can be assigned with a [TestAnnotationTarget] and an // optional transform matrix. class TestAnnotationEntry extends HitTestEntry<TestAnnotationTarget> { TestAnnotationEntry(super.target, [Matrix4? transform]) : transform = transform ?? Matrix4.identity(); @override final Matrix4 transform; }
flutter/packages/flutter/test/rendering/mouse_tracker_test_utils.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/mouse_tracker_test_utils.dart", "repo_id": "flutter", "token_count": 1170 }
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 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('RenderConstrainedBox getters and setters', () { final RenderConstrainedBox box = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(height: 10.0)); expect(box.additionalConstraints, const BoxConstraints(minHeight: 10.0, maxHeight: 10.0)); box.additionalConstraints = const BoxConstraints.tightFor(width: 10.0); expect(box.additionalConstraints, const BoxConstraints(minWidth: 10.0, maxWidth: 10.0)); }); test('RenderLimitedBox getters and setters', () { final RenderLimitedBox box = RenderLimitedBox(); expect(box.maxWidth, double.infinity); expect(box.maxHeight, double.infinity); box.maxWidth = 0.0; box.maxHeight = 1.0; expect(box.maxHeight, 1.0); expect(box.maxWidth, 0.0); }); test('RenderAspectRatio getters and setters', () { final RenderAspectRatio box = RenderAspectRatio(aspectRatio: 1.0); expect(box.aspectRatio, 1.0); box.aspectRatio = 0.2; expect(box.aspectRatio, 0.2); box.aspectRatio = 1.2; expect(box.aspectRatio, 1.2); }); test('RenderIntrinsicWidth getters and setters', () { final RenderIntrinsicWidth box = RenderIntrinsicWidth(); expect(box.stepWidth, isNull); box.stepWidth = 10.0; expect(box.stepWidth, 10.0); expect(box.stepHeight, isNull); box.stepHeight = 10.0; expect(box.stepHeight, 10.0); }); test('RenderOpacity getters and setters', () { final RenderOpacity box = RenderOpacity(); expect(box.opacity, 1.0); box.opacity = 0.0; expect(box.opacity, 0.0); }); test('RenderShaderMask getters and setters', () { Shader callback1(Rect bounds) { assert(false); // The test should not call this. const LinearGradient gradient = LinearGradient(colors: <Color>[Colors.red]); return gradient.createShader(Rect.zero); } Shader callback2(Rect bounds) { assert(false); // The test should not call this. const LinearGradient gradient = LinearGradient(colors: <Color>[Colors.blue]); return gradient.createShader(Rect.zero); } final RenderShaderMask box = RenderShaderMask(shaderCallback: callback1); expect(box.shaderCallback, equals(callback1)); box.shaderCallback = callback2; expect(box.shaderCallback, equals(callback2)); expect(box.blendMode, BlendMode.modulate); box.blendMode = BlendMode.colorBurn; expect(box.blendMode, BlendMode.colorBurn); }); }
flutter/packages/flutter/test/rendering/proxy_getters_and_setters_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/proxy_getters_and_setters_test.dart", "repo_id": "flutter", "token_count": 998 }
732
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/animation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; class TestRenderSliverBoxChildManager extends RenderSliverBoxChildManager { TestRenderSliverBoxChildManager({ required this.children, }); late RenderSliverList _renderObject; List<RenderBox> children; RenderSliverList createRenderObject() { _renderObject = RenderSliverList(childManager: this); return _renderObject; } int? _currentlyUpdatingChildIndex; @override void createChild(int index, { required RenderBox? after }) { if (index < 0 || index >= children.length) { return; } try { _currentlyUpdatingChildIndex = index; _renderObject.insert(children[index], after: after); } finally { _currentlyUpdatingChildIndex = null; } } @override void removeChild(RenderBox child) { _renderObject.remove(child); } @override double estimateMaxScrollOffset( SliverConstraints constraints, { int? firstIndex, int? lastIndex, double? leadingScrollOffset, double? trailingScrollOffset, }) { assert(lastIndex! >= firstIndex!); return children.length * (trailingScrollOffset! - leadingScrollOffset!) / (lastIndex! - firstIndex! + 1); } @override int get childCount => children.length; @override void didAdoptChild(RenderBox child) { assert(_currentlyUpdatingChildIndex != null); final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData; childParentData.index = _currentlyUpdatingChildIndex; } @override void setDidUnderflow(bool value) { } } class ViewportOffsetSpy extends ViewportOffset { ViewportOffsetSpy(this._pixels); double _pixels; @override double get pixels => _pixels; @override bool get hasPixels => true; bool corrected = false; @override bool applyViewportDimension(double viewportDimension) => true; @override bool applyContentDimensions(double minScrollExtent, double maxScrollExtent) => true; @override void correctBy(double correction) { _pixels += correction; corrected = true; } @override void jumpTo(double pixels) { // Do nothing, not required in test. } @override Future<void> animateTo( double to, { required Duration duration, required Curve curve, }) async { // Do nothing, not required in test. } @override ScrollDirection get userScrollDirection => ScrollDirection.idle; @override bool get allowImplicitScrolling => false; } void main() { TestRenderingFlutterBinding.ensureInitialized(); test('RenderSliverList basic test - down', () { RenderObject inner; RenderBox a, b, c, d, e; final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager( children: <RenderBox>[ a = RenderSizedBox(const Size(100.0, 400.0)), b = RenderSizedBox(const Size(100.0, 400.0)), c = RenderSizedBox(const Size(100.0, 400.0)), d = RenderSizedBox(const Size(100.0, 400.0)), e = RenderSizedBox(const Size(100.0, 400.0)), ], ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), cacheExtent: 0.0, children: <RenderSliver>[ inner = childManager.createRenderObject(), ], ); layout(root); expect(root.size.width, equals(800.0)); expect(root.size.height, equals(600.0)); expect(a.localToGlobal(Offset.zero), Offset.zero); expect(b.localToGlobal(Offset.zero), const Offset(0.0, 400.0)); expect(c.attached, false); expect(d.attached, false); expect(e.attached, false); // make sure that layout is stable by laying out again inner.markNeedsLayout(); pumpFrame(); expect(a.localToGlobal(Offset.zero), Offset.zero); expect(b.localToGlobal(Offset.zero), const Offset(0.0, 400.0)); expect(c.attached, false); expect(d.attached, false); expect(e.attached, false); // now try various scroll offsets root.offset = ViewportOffset.fixed(200.0); pumpFrame(); expect(a.localToGlobal(Offset.zero), const Offset(0.0, -200.0)); expect(b.localToGlobal(Offset.zero), const Offset(0.0, 200.0)); expect(c.attached, false); expect(d.attached, false); expect(e.attached, false); root.offset = ViewportOffset.fixed(600.0); pumpFrame(); expect(a.attached, false); expect(b.localToGlobal(Offset.zero), const Offset(0.0, -200.0)); expect(c.localToGlobal(Offset.zero), const Offset(0.0, 200.0)); expect(d.attached, false); expect(e.attached, false); root.offset = ViewportOffset.fixed(900.0); pumpFrame(); expect(a.attached, false); expect(b.attached, false); expect(c.localToGlobal(Offset.zero), const Offset(0.0, -100.0)); expect(d.localToGlobal(Offset.zero), const Offset(0.0, 300.0)); expect(e.attached, false); // try going back up root.offset = ViewportOffset.fixed(200.0); pumpFrame(); expect(a.localToGlobal(Offset.zero), const Offset(0.0, -200.0)); expect(b.localToGlobal(Offset.zero), const Offset(0.0, 200.0)); expect(c.attached, false); expect(d.attached, false); expect(e.attached, false); }); test('RenderSliverList basic test - up', () { RenderObject inner; RenderBox a, b, c, d, e; final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager( children: <RenderBox>[ a = RenderSizedBox(const Size(100.0, 400.0)), b = RenderSizedBox(const Size(100.0, 400.0)), c = RenderSizedBox(const Size(100.0, 400.0)), d = RenderSizedBox(const Size(100.0, 400.0)), e = RenderSizedBox(const Size(100.0, 400.0)), ], ); final RenderViewport root = RenderViewport( axisDirection: AxisDirection.up, crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), children: <RenderSliver>[ inner = childManager.createRenderObject(), ], cacheExtent: 0.0, ); layout(root); expect(root.size.width, equals(800.0)); expect(root.size.height, equals(600.0)); expect(a.localToGlobal(Offset.zero), const Offset(0.0, 200.0)); expect(b.localToGlobal(Offset.zero), const Offset(0.0, -200.0)); expect(c.attached, false); expect(d.attached, false); expect(e.attached, false); // make sure that layout is stable by laying out again inner.markNeedsLayout(); pumpFrame(); expect(a.localToGlobal(Offset.zero), const Offset(0.0, 200.0)); expect(b.localToGlobal(Offset.zero), const Offset(0.0, -200.0)); expect(c.attached, false); expect(d.attached, false); expect(e.attached, false); // now try various scroll offsets root.offset = ViewportOffset.fixed(200.0); pumpFrame(); expect(a.localToGlobal(Offset.zero), const Offset(0.0, 400.0)); expect(b.localToGlobal(Offset.zero), Offset.zero); expect(c.attached, false); expect(d.attached, false); expect(e.attached, false); root.offset = ViewportOffset.fixed(600.0); pumpFrame(); expect(a.attached, false); expect(b.localToGlobal(Offset.zero), const Offset(0.0, 400.0)); expect(c.localToGlobal(Offset.zero), Offset.zero); expect(d.attached, false); expect(e.attached, false); root.offset = ViewportOffset.fixed(900.0); pumpFrame(); expect(a.attached, false); expect(b.attached, false); expect(c.localToGlobal(Offset.zero), const Offset(0.0, 300.0)); expect(d.localToGlobal(Offset.zero), const Offset(0.0, -100.0)); expect(e.attached, false); // try going back up root.offset = ViewportOffset.fixed(200.0); pumpFrame(); expect(a.localToGlobal(Offset.zero), const Offset(0.0, 400.0)); expect(b.localToGlobal(Offset.zero), Offset.zero); expect(c.attached, false); expect(d.attached, false); expect(e.attached, false); }); test('SliverList - no zero scroll offset correction', () { RenderSliverList inner; RenderBox a; final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager( children: <RenderBox>[ a = RenderSizedBox(const Size(100.0, 400.0)), RenderSizedBox(const Size(100.0, 400.0)), RenderSizedBox(const Size(100.0, 400.0)), RenderSizedBox(const Size(100.0, 400.0)), RenderSizedBox(const Size(100.0, 400.0)), ], ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), children: <RenderSliver>[ inner = childManager.createRenderObject(), ], ); layout(root); final SliverMultiBoxAdaptorParentData parentData = a.parentData! as SliverMultiBoxAdaptorParentData; parentData.layoutOffset = 0.001; root.offset = ViewportOffset.fixed(900.0); pumpFrame(); root.offset = ViewportOffset.fixed(0.0); pumpFrame(); expect(inner.geometry?.scrollOffsetCorrection, isNull); }); test('SliverList - no correction when tiny double precision error', () { RenderSliverList inner; RenderBox a; final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager( children: <RenderBox>[ a = RenderSizedBox(const Size(100.0, 400.0)), RenderSizedBox(const Size(100.0, 400.0)), RenderSizedBox(const Size(100.0, 400.0)), RenderSizedBox(const Size(100.0, 400.0)), RenderSizedBox(const Size(100.0, 400.0)), ], ); inner = childManager.createRenderObject(); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), children: <RenderSliver>[ inner, ], ); layout(root); final SliverMultiBoxAdaptorParentData parentData = a.parentData! as SliverMultiBoxAdaptorParentData; // Simulate double precision error. parentData.layoutOffset = -0.0000000000001; root.offset = ViewportOffset.fixed(900.0); pumpFrame(); final ViewportOffsetSpy spy = ViewportOffsetSpy(0.0); root.offset = spy; pumpFrame(); expect(spy.corrected, false); }); test('SliverMultiBoxAdaptorParentData.toString', () { final SliverMultiBoxAdaptorParentData candidate = SliverMultiBoxAdaptorParentData(); expect(candidate.keepAlive, isFalse); expect(candidate.index, isNull); expect(candidate.toString(), 'index=null; layoutOffset=None'); candidate.keepAlive = true; expect(candidate.toString(), 'index=null; keepAlive; layoutOffset=None'); candidate.keepAlive = false; expect(candidate.toString(), 'index=null; layoutOffset=None'); candidate.index = 0; expect(candidate.toString(), 'index=0; layoutOffset=None'); candidate.index = 1; expect(candidate.toString(), 'index=1; layoutOffset=None'); candidate.index = -1; expect(candidate.toString(), 'index=-1; layoutOffset=None'); candidate.layoutOffset = 100.0; expect(candidate.toString(), 'index=-1; layoutOffset=100.0'); }); }
flutter/packages/flutter/test/rendering/slivers_block_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/slivers_block_test.dart", "repo_id": "flutter", "token_count": 4243 }
733
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/scheduler.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); test('scheduleForcedFrame sets up frame callbacks', () async { SchedulerBinding.instance.scheduleForcedFrame(); expect(SchedulerBinding.instance.platformDispatcher.onBeginFrame, isNotNull); }); test('debugAssertNoTimeDilation does not throw if time dilate already reset', () async { timeDilation = 2.0; timeDilation = 1.0; SchedulerBinding.instance.debugAssertNoTimeDilation('reason'); // no error }); test('debugAssertNoTimeDilation throw if time dilate not reset', () async { timeDilation = 3.0; expect( () => SchedulerBinding.instance.debugAssertNoTimeDilation('reason'), throwsA(isA<FlutterError>().having((FlutterError e) => e.message, 'message', 'reason')), ); timeDilation = 1.0; }); test('Adding a persistent frame callback during a persistent frame callback', () { bool calledBack = false; SchedulerBinding.instance.addPersistentFrameCallback((Duration timeStamp) { if (!calledBack) { SchedulerBinding.instance.addPersistentFrameCallback((Duration timeStamp) { calledBack = true; }); } }); SchedulerBinding.instance.handleBeginFrame(null); SchedulerBinding.instance.handleDrawFrame(); expect(calledBack, false); SchedulerBinding.instance.handleBeginFrame(null); SchedulerBinding.instance.handleDrawFrame(); expect(calledBack, true); }); }
flutter/packages/flutter/test/scheduler/binding_test.dart/0
{ "file_path": "flutter/packages/flutter/test/scheduler/binding_test.dart", "repo_id": "flutter", "token_count": 585 }
734
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class TestAssetBundle extends CachingAssetBundle { Map<String, int> loadCallCount = <String, int>{}; @override Future<ByteData> load(String key) async { loadCallCount[key] = (loadCallCount[key] ?? 0) + 1; if (key == 'AssetManifest.json') { return ByteData.sublistView(utf8.encode('{"one": ["one"]}')); } if (key == 'AssetManifest.bin') { return const StandardMessageCodec() .encodeMessage(<String, Object>{'one': <Object>[]})!; } if (key == 'AssetManifest.bin.json') { // Encode the manifest data that will be used by the app final ByteData data = const StandardMessageCodec().encodeMessage(<String, Object> {'one': <Object>[]})!; // Simulate the behavior of NetworkAssetBundle.load here, for web tests return ByteData.sublistView( utf8.encode( json.encode( base64.encode( // Encode only the actual bytes of the buffer, and no more... data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes) ) ) ) ); } if (key == 'counter') { return ByteData.sublistView(utf8.encode(loadCallCount[key]!.toString())); } if (key == 'one') { return ByteData(1)..setInt8(0, 49); } throw FlutterError('key not found'); } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('Caching asset bundle test', () async { final TestAssetBundle bundle = TestAssetBundle(); final ByteData assetData = await bundle.load('one'); expect(assetData.getInt8(0), equals(49)); expect(bundle.loadCallCount['one'], 1); final String assetString = await bundle.loadString('one'); expect(assetString, equals('1')); expect(bundle.loadCallCount['one'], 2); late Object loadException; try { await bundle.loadString('foo'); } catch (e) { loadException = e; } expect(loadException, isFlutterError); }); group('CachingAssetBundle caching behavior', () { test('caches results for loadString, loadStructuredData, and loadBinaryStructuredData', () async { final TestAssetBundle bundle = TestAssetBundle(); final String firstLoadStringResult = await bundle.loadString('counter'); final String secondLoadStringResult = await bundle.loadString('counter'); expect(firstLoadStringResult, '1'); expect(secondLoadStringResult, '1'); final String firstLoadStructuredDataResult = await bundle.loadStructuredData('AssetManifest.json', (String value) => Future<String>.value('one')); final String secondLoadStructuredDataResult = await bundle.loadStructuredData('AssetManifest.json', (String value) => Future<String>.value('two')); expect(firstLoadStructuredDataResult, 'one'); expect(secondLoadStructuredDataResult, 'one'); final String firstLoadStructuredBinaryDataResult = await bundle.loadStructuredBinaryData('AssetManifest.bin', (ByteData value) => Future<String>.value('one')); final String secondLoadStructuredBinaryDataResult = await bundle.loadStructuredBinaryData('AssetManifest.bin', (ByteData value) => Future<String>.value('two')); expect(firstLoadStructuredBinaryDataResult, 'one'); expect(secondLoadStructuredBinaryDataResult, 'one'); }); test("clear clears all cached values'", () async { final TestAssetBundle bundle = TestAssetBundle(); await bundle.loadString('counter'); bundle.clear(); final String secondLoadStringResult = await bundle.loadString('counter'); expect(secondLoadStringResult, '2'); await bundle.loadStructuredData('AssetManifest.json', (String value) => Future<String>.value('one')); bundle.clear(); final String secondLoadStructuredDataResult = await bundle.loadStructuredData('AssetManifest.json', (String value) => Future<String>.value('two')); expect(secondLoadStructuredDataResult, 'two'); await bundle.loadStructuredBinaryData('AssetManifest.bin', (ByteData value) => Future<String>.value('one')); bundle.clear(); final String secondLoadStructuredBinaryDataResult = await bundle.loadStructuredBinaryData('AssetManifest.bin', (ByteData value) => Future<String>.value('two')); expect(secondLoadStructuredBinaryDataResult, 'two'); }); test('evict evicts a particular key from the cache', () async { final TestAssetBundle bundle = TestAssetBundle(); await bundle.loadString('counter'); bundle.evict('counter'); final String secondLoadStringResult = await bundle.loadString('counter'); expect(secondLoadStringResult, '2'); await bundle.loadStructuredData('AssetManifest.json', (String value) => Future<String>.value('one')); bundle.evict('AssetManifest.json'); final String secondLoadStructuredDataResult = await bundle.loadStructuredData('AssetManifest.json', (String value) => Future<String>.value('two')); expect(secondLoadStructuredDataResult, 'two'); await bundle.loadStructuredBinaryData('AssetManifest.bin', (ByteData value) => Future<String>.value('one')); bundle.evict('AssetManifest.bin'); final String secondLoadStructuredBinaryDataResult = await bundle.loadStructuredBinaryData('AssetManifest.bin', (ByteData value) => Future<String>.value('two')); expect(secondLoadStructuredBinaryDataResult, 'two'); }); test('for a given key, subsequent loadStructuredData calls are synchronous after the first call resolves', () async { final TestAssetBundle bundle = TestAssetBundle(); await bundle.loadStructuredData('one', (String data) => SynchronousFuture<int>(1)); final Future<int> data = bundle.loadStructuredData('one', (String data) => SynchronousFuture<int>(2)); expect(data, isA<SynchronousFuture<int>>()); expect(await data, 1); }); test('for a given key, subsequent loadStructuredBinaryData calls are synchronous after the first call resolves', () async { final TestAssetBundle bundle = TestAssetBundle(); await bundle.loadStructuredBinaryData('one', (ByteData data) => 1); final Future<int> data = bundle.loadStructuredBinaryData('one', (ByteData data) => 2); expect(data, isA<SynchronousFuture<int>>()); expect(await data, 1); }); testWidgets('loadStructuredData handles exceptions correctly', (WidgetTester tester) async { final TestAssetBundle bundle = TestAssetBundle(); try { await bundle.loadStructuredData('AssetManifest.json', (String value) => Future<String>.error('what do they say?')); fail('expected exception did not happen'); } catch (e) { expect(e.toString(), contains('what do they say?')); } }); testWidgets('loadStructuredBinaryData handles exceptions correctly', (WidgetTester tester) async { final TestAssetBundle bundle = TestAssetBundle(); try { await bundle.loadStructuredBinaryData('AssetManifest.bin', (ByteData value) => Future<String>.error('buy more crystals')); fail('expected exception did not happen'); } catch (e) { expect(e.toString(), contains('buy more crystals')); } }); }); test('AssetImage.obtainKey succeeds with ImageConfiguration.empty', () async { // This is a regression test for https://github.com/flutter/flutter/issues/12392 final AssetImage assetImage = AssetImage('one', bundle: TestAssetBundle()); final AssetBundleImageKey key = await assetImage.obtainKey(ImageConfiguration.empty); expect(key.name, 'one'); expect(key.scale, 1.0); }); test('NetworkAssetBundle control test', () async { final Uri uri = Uri.http('example.org', '/path'); final NetworkAssetBundle bundle = NetworkAssetBundle(uri); late FlutterError error; try { await bundle.load('key'); } on FlutterError catch (e) { error = e; } expect(error, isNotNull); expect(error.diagnostics.length, 2); expect(error.diagnostics.last, isA<IntProperty>()); expect( error.toStringDeep(), 'FlutterError\n' ' Unable to load asset: "key".\n' ' HTTP status code: 400\n', ); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/39998 test('toString works as intended', () { final Uri uri = Uri.http('example.org', '/path'); final NetworkAssetBundle bundle = NetworkAssetBundle(uri); expect(bundle.toString(), 'NetworkAssetBundle#${shortHash(bundle)}($uri)'); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/39998 test('Throws expected exceptions when loading not exists asset', () async { late final FlutterError error; try { await rootBundle.load('not-exists'); } on FlutterError catch (e) { error = e; } expect( error.message, equals( 'Unable to load asset: "not-exists".\n' 'The asset does not exist or has empty data.', ), ); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/56314 test('loadStructuredBinaryData correctly loads ByteData', () async { final TestAssetBundle bundle = TestAssetBundle(); final Map<Object?, Object?> assetManifest = await bundle.loadStructuredBinaryData('AssetManifest.bin', (ByteData data) => const StandardMessageCodec().decodeMessage(data) as Map<Object?, Object?>); expect(assetManifest.keys.toList(), equals(<String>['one'])); expect(assetManifest['one'], <Object>[]); }); }
flutter/packages/flutter/test/services/asset_bundle_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/asset_bundle_test.dart", "repo_id": "flutter", "token_count": 3390 }
735
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('The Web physical key mapping do not have entries without a Chrome code.', () { // Regression test for https://github.com/flutter/flutter/pull/106074. // There is an entry called KBD_ILLUM_DOWN in dom_code_data.inc, but it // has an empty "Code" column. This entry should not be present in the // web mapping. expect(kWebToPhysicalKey['KbdIllumDown'], isNull); }); }
flutter/packages/flutter/test/services/keyboard_maps_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/keyboard_maps_test.dart", "repo_id": "flutter", "token_count": 211 }
736
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/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); } test('System navigator control test - platform messages', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { log.add(methodCall); return null; }); await verify(() => SystemNavigator.pop(), <Object>[ isMethodCall('SystemNavigator.pop', arguments: null), ]); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null); }); test('System navigator control test - navigation messages', () async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async { log.add(methodCall); return null; }); await verify(() => SystemNavigator.selectSingleEntryHistory(), <Object>[ isMethodCall('selectSingleEntryHistory', arguments: null), ]); await verify(() => SystemNavigator.selectMultiEntryHistory(), <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), ]); await verify(() => SystemNavigator.routeInformationUpdated(location: 'a'), <Object>[ isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': null, 'replace': false }), ]); await verify(() => SystemNavigator.routeInformationUpdated(location: 'a', state: true), <Object>[ isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': true, 'replace': false }), ]); await verify(() => SystemNavigator.routeInformationUpdated(location: 'a', state: true, replace: true), <Object>[ isMethodCall('routeInformationUpdated', arguments: <String, dynamic>{ 'uri': 'a', 'state': true, 'replace': true }), ]); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.navigation, null); }); }
flutter/packages/flutter/test/services/system_navigator_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/system_navigator_test.dart", "repo_id": "flutter", "token_count": 780 }
737
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('ImageFiltered avoids repainting child as it animates', (WidgetTester tester) async { RenderTestObject.paintCount = 0; await tester.pumpWidget( ColoredBox( color: Colors.red, child: ImageFiltered( imageFilter: ImageFilter.blur(sigmaX: 5, sigmaY: 5), child: const TestWidget(), ), ) ); expect(RenderTestObject.paintCount, 1); await tester.pumpWidget( ColoredBox( color: Colors.red, child: ImageFiltered( imageFilter: ImageFilter.blur(sigmaX: 6, sigmaY: 6), child: const TestWidget(), ), ) ); expect(RenderTestObject.paintCount, 1); }); } class TestWidget extends SingleChildRenderObjectWidget { const TestWidget({super.key, super.child}); @override RenderObject createRenderObject(BuildContext context) { return RenderTestObject(); } } class RenderTestObject extends RenderProxyBox { static int paintCount = 0; @override void paint(PaintingContext context, Offset offset) { paintCount += 1; super.paint(context, offset); } }
flutter/packages/flutter/test/widgets/animated_image_filtered_repaint_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/animated_image_filtered_repaint_test.dart", "repo_id": "flutter", "token_count": 543 }
738
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class User { const User({ required this.email, required this.name, }); final String email; final String name; @override String toString() { return '$name, $email'; } } void main() { const List<String> kOptions = <String>[ 'aardvark', 'bobcat', 'chameleon', 'dingo', 'elephant', 'flamingo', 'goose', 'hippopotamus', 'iguana', 'jaguar', 'koala', 'lemur', 'mouse', 'northern white rhinoceros', ]; const List<User> kOptionsUsers = <User>[ User(name: 'Alice', email: '[email protected]'), User(name: 'Bob', email: '[email protected]'), User(name: 'Charlie', email: '[email protected]'), ]; testWidgets('can filter and select a list of string options', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; late AutocompleteOnSelected<String> lastOnSelected; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( key: fieldKey, focusNode: focusNode, controller: textEditingController, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; lastOnSelected = onSelected; return Container(key: optionsKey); }, ), ), ), ); // The field is always rendered, but the options are not unless needed. expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // Focus the empty field. All the options are displayed. focusNode.requestFocus(); await tester.pump(); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, kOptions.length); // Enter text. The options are filtered by the text. textEditingController.value = const TextEditingValue( text: 'ele', selection: TextSelection(baseOffset: 3, extentOffset: 3), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 2); expect(lastOptions.elementAt(0), 'chameleon'); expect(lastOptions.elementAt(1), 'elephant'); // Select an option. The options hide and the field updates to show the // selection. final String selection = lastOptions.elementAt(1); lastOnSelected(selection); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); expect(textEditingController.text, selection); // Modify the field text. The options appear again and are filtered. textEditingController.value = const TextEditingValue( text: 'e', selection: TextSelection(baseOffset: 1, extentOffset: 1), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 6); expect(lastOptions.elementAt(0), 'chameleon'); expect(lastOptions.elementAt(1), 'elephant'); expect(lastOptions.elementAt(2), 'goose'); expect(lastOptions.elementAt(3), 'lemur'); expect(lastOptions.elementAt(4), 'mouse'); expect(lastOptions.elementAt(5), 'northern white rhinoceros'); }); testWidgets('tapping on an option selects it', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( key: fieldKey, focusNode: focusNode, controller: textEditingController, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; return Material( elevation: 4.0, child: ListView.builder( key: optionsKey, padding: const EdgeInsets.all(8.0), itemCount: options.length, itemBuilder: (BuildContext context, int index) { final String option = options.elementAt(index); return GestureDetector( onTap: () { onSelected(option); }, child: ListTile( title: Text(option), ), ); }, ), ); }, ), ), ), ); // The field is always rendered, but the options are not unless needed. expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // Tap on the text field to open the options. await tester.tap(find.byKey(fieldKey)); await tester.pump(); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, kOptions.length); await tester.tap(find.text(kOptions[2])); await tester.pump(); expect(find.byKey(optionsKey), findsNothing); expect(textEditingController.text, equals(kOptions[2])); }); testWidgets('can filter and select a list of custom User options', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<User> lastOptions; late AutocompleteOnSelected<User> lastOnSelected; late User lastUserSelected; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<User>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptionsUsers.where((User option) { return option.toString().contains(textEditingValue.text.toLowerCase()); }); }, onSelected: (User selected) { lastUserSelected = selected; }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( key: fieldKey, focusNode: focusNode, controller: fieldTextEditingController, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<User> onSelected, Iterable<User> options) { lastOptions = options; lastOnSelected = onSelected; return Container(key: optionsKey); }, ), ), ), ); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // Enter text. The options are filtered by the text. focusNode.requestFocus(); textEditingController.value = const TextEditingValue( text: 'example', selection: TextSelection(baseOffset: 7, extentOffset: 7), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 2); expect(lastOptions.elementAt(0), kOptionsUsers[0]); expect(lastOptions.elementAt(1), kOptionsUsers[1]); // Select an option. The options hide and onSelected is called. final User selection = lastOptions.elementAt(1); lastOnSelected(selection); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); expect(lastUserSelected, selection); expect(textEditingController.text, selection.toString()); // Modify the field text. The options appear again and are filtered, this // time by name instead of email. textEditingController.value = const TextEditingValue( text: 'B', selection: TextSelection(baseOffset: 1, extentOffset: 1), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 1); expect(lastOptions.elementAt(0), kOptionsUsers[1]); }); testWidgets('can specify a custom display string for a list of custom User options', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<User> lastOptions; late AutocompleteOnSelected<User> lastOnSelected; late User lastUserSelected; String displayStringForOption(User option) => option.name; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<User>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptionsUsers.where((User option) { return option .toString() .contains(textEditingValue.text.toLowerCase()); }); }, displayStringForOption: displayStringForOption, onSelected: (User selected) { lastUserSelected = selected; }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { textEditingController = fieldTextEditingController; focusNode = fieldFocusNode; return TextField( key: fieldKey, focusNode: focusNode, controller: fieldTextEditingController, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<User> onSelected, Iterable<User> options) { lastOptions = options; lastOnSelected = onSelected; return Container(key: optionsKey); }, ), ), ), ); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // Enter text. The options are filtered by the text. focusNode.requestFocus(); textEditingController.value = const TextEditingValue( text: 'example', selection: TextSelection(baseOffset: 7, extentOffset: 7), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 2); expect(lastOptions.elementAt(0), kOptionsUsers[0]); expect(lastOptions.elementAt(1), kOptionsUsers[1]); // Select an option. The options hide and onSelected is called. The field // has its text set to the selection's display string. final User selection = lastOptions.elementAt(1); lastOnSelected(selection); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); expect(lastUserSelected, selection); expect(textEditingController.text, selection.name); // Modify the field text. The options appear again and are filtered, this // time by name instead of email. textEditingController.value = const TextEditingValue( text: 'B', selection: TextSelection(baseOffset: 1, extentOffset: 1), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 1); expect(lastOptions.elementAt(0), kOptionsUsers[1]); }); testWidgets('onFieldSubmitted selects the first option', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; late VoidCallback lastOnFieldSubmitted; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { textEditingController = fieldTextEditingController; focusNode = fieldFocusNode; lastOnFieldSubmitted = onFieldSubmitted; return TextField( key: fieldKey, focusNode: focusNode, controller: fieldTextEditingController, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; return Container(key: optionsKey); }, ), ), ), ); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // Enter text. The options are filtered by the text. focusNode.requestFocus(); textEditingController.value = const TextEditingValue( text: 'ele', selection: TextSelection(baseOffset: 3, extentOffset: 3), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 2); expect(lastOptions.elementAt(0), 'chameleon'); expect(lastOptions.elementAt(1), 'elephant'); // Select the current string, as if the field was submitted. The options // hide and the field updates to show the selection. lastOnFieldSubmitted(); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); expect(textEditingController.text, lastOptions.elementAt(0)); }); group('optionsViewOpenDirection', () { testWidgets('unset (default behavior): open downward', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], fieldViewBuilder: (BuildContext context, TextEditingController controller, FocusNode focusNode, VoidCallback onFieldSubmitted) { return TextField(controller: controller, focusNode: focusNode); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return const Text('a'); }, ), ), ), ), ); await tester.showKeyboard(find.byType(TextField)); expect(tester.getBottomLeft(find.byType(TextField)), offsetMoreOrLessEquals(tester.getTopLeft(find.text('a')))); }); testWidgets('down: open downward', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: RawAutocomplete<String>( optionsViewOpenDirection: OptionsViewOpenDirection.down, // ignore: avoid_redundant_argument_values optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], fieldViewBuilder: (BuildContext context, TextEditingController controller, FocusNode focusNode, VoidCallback onFieldSubmitted) { return TextField(controller: controller, focusNode: focusNode); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return const Text('a'); }, ), ), ), ), ); await tester.showKeyboard(find.byType(TextField)); expect(tester.getBottomLeft(find.byType(TextField)), offsetMoreOrLessEquals(tester.getTopLeft(find.text('a')))); }); testWidgets('up: open upward', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: RawAutocomplete<String>( optionsViewOpenDirection: OptionsViewOpenDirection.up, optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], fieldViewBuilder: (BuildContext context, TextEditingController controller, FocusNode focusNode, VoidCallback onFieldSubmitted) { return TextField(controller: controller, focusNode: focusNode); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return const Text('a'); }, ), ), ), ), ); await tester.showKeyboard(find.byType(TextField)); expect(tester.getTopLeft(find.byType(TextField)), offsetMoreOrLessEquals(tester.getBottomLeft(find.text('a')))); }); group('fieldViewBuilder not passed', () { testWidgets('down', (WidgetTester tester) async { final GlobalKey autocompleteKey = GlobalKey(); final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ TextField(controller: controller, focusNode: focusNode), RawAutocomplete<String>( key: autocompleteKey, textEditingController: controller, focusNode: focusNode, optionsViewOpenDirection: OptionsViewOpenDirection.down, // ignore: avoid_redundant_argument_values optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return const Text('a'); }, ), ], ), ), ), ); await tester.showKeyboard(find.byType(TextField)); expect(tester.getBottomLeft(find.byKey(autocompleteKey)), offsetMoreOrLessEquals(tester.getTopLeft(find.text('a')))); }); testWidgets('up', (WidgetTester tester) async { final GlobalKey autocompleteKey = GlobalKey(); final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ RawAutocomplete<String>( key: autocompleteKey, textEditingController: controller, focusNode: focusNode, optionsViewOpenDirection: OptionsViewOpenDirection.up, optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'], optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return const Text('a'); }, ), TextField(controller: controller, focusNode: focusNode), ], ), ), ), ); await tester.showKeyboard(find.byType(TextField)); expect(tester.getTopLeft(find.byKey(autocompleteKey)), offsetMoreOrLessEquals(tester.getBottomLeft(find.text('a')))); }); }); }); testWidgets('options follow field when it moves', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late StateSetter setState; Alignment alignment = Alignment.center; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return Align( alignment: alignment, child: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextFormField( controller: fieldTextEditingController, focusNode: focusNode, key: fieldKey, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return Container(key: optionsKey); }, ), ); }, ), ), ), ); // Field is shown but not options. expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // Enter text to show the options. focusNode.requestFocus(); textEditingController.value = const TextEditingValue( text: 'ele', selection: TextSelection(baseOffset: 3, extentOffset: 3), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); // Options are just below the field. final Offset optionsOffset = tester.getTopLeft(find.byKey(optionsKey)); Offset fieldOffset = tester.getTopLeft(find.byKey(fieldKey)); final Size fieldSize = tester.getSize(find.byKey(fieldKey)); expect(optionsOffset.dy, fieldOffset.dy + fieldSize.height); // Move the field (similar to as if the keyboard opened). The options move // to follow the field. setState(() { alignment = Alignment.topCenter; }); await tester.pump(); fieldOffset = tester.getTopLeft(find.byKey(fieldKey)); final Offset optionsOffsetOpen = tester.getTopLeft(find.byKey(optionsKey)); expect(optionsOffsetOpen.dy, isNot(equals(optionsOffset.dy))); expect(optionsOffsetOpen.dy, fieldOffset.dy + fieldSize.height); }); testWidgets('can prevent options from showing by returning an empty iterable', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { if (textEditingValue.text == '') { return const Iterable<String>.empty(); } return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( key: fieldKey, focusNode: focusNode, controller: fieldTextEditingController, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; return Container(key: optionsKey); }, ), ), ), ); // The field is always rendered, but the options are not unless needed. expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // Focus the empty field. The options are not displayed because // optionsBuilder returns nothing for an empty field query. focusNode.requestFocus(); textEditingController.value = const TextEditingValue( selection: TextSelection(baseOffset: 0, extentOffset: 0), ); await tester.pump(); expect(find.byKey(optionsKey), findsNothing); // Enter text. Now the options appear, filtered by the text. textEditingController.value = const TextEditingValue( text: 'ele', selection: TextSelection(baseOffset: 3, extentOffset: 3), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 2); expect(lastOptions.elementAt(0), 'chameleon'); expect(lastOptions.elementAt(1), 'elephant'); }); testWidgets('can create a field outside of fieldViewBuilder', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); final GlobalKey autocompleteKey = GlobalKey(); late Iterable<String> lastOptions; final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final TextEditingController textEditingController = TextEditingController(); addTearDown(textEditingController.dispose); await tester.pumpWidget( MaterialApp( home: Scaffold( appBar: AppBar( // This is where the real field is being built. title: TextFormField( key: fieldKey, controller: textEditingController, focusNode: focusNode, onFieldSubmitted: (String value) { RawAutocomplete.onFieldSubmitted(autocompleteKey); }, ), ), body: RawAutocomplete<String>( key: autocompleteKey, focusNode: focusNode, textEditingController: textEditingController, optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; return Container(key: optionsKey); }, ), ), ), ); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // Enter text. The options are filtered by the text. focusNode.requestFocus(); textEditingController.value = const TextEditingValue( text: 'ele', selection: TextSelection(baseOffset: 3, extentOffset: 3), ); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 2); expect(lastOptions.elementAt(0), 'chameleon'); expect(lastOptions.elementAt(1), 'elephant'); // Submit the field. The options hide and the field updates to show the // selection. await tester.showKeyboard(find.byType(TextFormField)); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); expect(textEditingController.text, lastOptions.elementAt(0)); }); testWidgets('initialValue sets initial text field value', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; late AutocompleteOnSelected<String> lastOnSelected; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( // Should initialize text field with 'lem'. initialValue: const TextEditingValue(text: 'lem'), optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( key: fieldKey, focusNode: focusNode, controller: textEditingController, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; lastOnSelected = onSelected; return Container(key: optionsKey); }, ), ), ), ); // The field is always rendered, but the options are not unless needed. expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // The text editing controller value starts off with initialized value. expect(textEditingController.text, 'lem'); // Focus the empty field. All the options are displayed. focusNode.requestFocus(); await tester.pump(); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.elementAt(0), 'lemur'); // Select an option. The options hide and the field updates to show the // selection. final String selection = lastOptions.elementAt(0); lastOnSelected(selection); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); expect(textEditingController.text, selection); }); testWidgets('initialValue cannot be defined if TextEditingController is defined', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final TextEditingController textEditingController = TextEditingController(); addTearDown(textEditingController.dispose); expect( () { RawAutocomplete<String>( focusNode: focusNode, // Both [initialValue] and [textEditingController] cannot be // simultaneously defined. initialValue: const TextEditingValue(text: 'lemur'), textEditingController: textEditingController, optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return Container(); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { return TextField( focusNode: focusNode, controller: textEditingController, ); }, ); }, throwsAssertionError, ); }); testWidgets('support asynchronous options builder', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late FocusNode focusNode; late TextEditingController textEditingController; Iterable<String>? lastOptions; Duration? delay; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) async { final Iterable<String> options = kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); if (delay == null) { return options; } return Future<Iterable<String>>.delayed(delay, () => options); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( key: fieldKey, focusNode: focusNode, controller: textEditingController, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; return Container(key: optionsKey); }, ), ), ) ); // Enter text to build the options with delay. focusNode.requestFocus(); delay = const Duration(milliseconds: 500); await tester.enterText(find.byKey(fieldKey), 'go'); await tester.pumpAndSettle(); // The options have not yet been built. expect(find.byKey(optionsKey), findsNothing); expect(lastOptions, isNull); // Await asynchronous options builder. await tester.pumpAndSettle(delay); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions, <String>['dingo', 'flamingo', 'goose']); // Enter text to rebuild the options without delay. delay = null; await tester.enterText(find.byKey(fieldKey), 'ngo'); await tester.pump(); expect(lastOptions, <String>['dingo', 'flamingo']); }); testWidgets('can navigate options with the keyboard', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextFormField( key: fieldKey, focusNode: focusNode, controller: textEditingController, onFieldSubmitted: (String value) { onFieldSubmitted(); }, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; return Container(key: optionsKey); }, ), ), ), ); // Enter text. The options are filtered by the text. focusNode.requestFocus(); await tester.enterText(find.byKey(fieldKey), 'ele'); await tester.pumpAndSettle(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 2); expect(lastOptions.elementAt(0), 'chameleon'); expect(lastOptions.elementAt(1), 'elephant'); // Move the highlighted option to the second item 'elephant' and select it await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Can't use the key event for enter to submit to the text field using // the test framework, so this appears to be the equivalent. await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); expect(textEditingController.text, 'elephant'); // Modify the field text. The options appear again and are filtered. focusNode.requestFocus(); textEditingController.clear(); await tester.enterText(find.byKey(fieldKey), 'e'); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 6); expect(lastOptions.elementAt(0), 'chameleon'); expect(lastOptions.elementAt(1), 'elephant'); expect(lastOptions.elementAt(2), 'goose'); expect(lastOptions.elementAt(3), 'lemur'); expect(lastOptions.elementAt(4), 'mouse'); expect(lastOptions.elementAt(5), 'northern white rhinoceros'); // The selection should wrap at the top and bottom. Move up to 'mouse' // and then back down to 'goose' and select it. await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); expect(textEditingController.text, 'goose'); }); testWidgets('can hide and show options with the keyboard', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextFormField( key: fieldKey, focusNode: focusNode, controller: textEditingController, onFieldSubmitted: (String value) { onFieldSubmitted(); }, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; return Container(key: optionsKey); }, ), ), ), ); // Enter text. The options are filtered by the text. focusNode.requestFocus(); await tester.enterText(find.byKey(fieldKey), 'ele'); await tester.pumpAndSettle(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 2); expect(lastOptions.elementAt(0), 'chameleon'); expect(lastOptions.elementAt(1), 'elephant'); // Hide the options. await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); // Show the options again by pressing arrow keys await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); expect(find.byKey(optionsKey), findsOneWidget); await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pump(); expect(find.byKey(optionsKey), findsNothing); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); expect(find.byKey(optionsKey), findsOneWidget); await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pump(); expect(find.byKey(optionsKey), findsNothing); // Show the options again by re-focusing the field. focusNode.unfocus(); await tester.pump(); expect(find.byKey(optionsKey), findsNothing); focusNode.requestFocus(); await tester.pump(); expect(find.byKey(optionsKey), findsOneWidget); await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pump(); expect(find.byKey(optionsKey), findsNothing); // Show the options again by editing the text (but not when selecting text // or moving the caret). await tester.enterText(find.byKey(fieldKey), 'elep'); await tester.pump(); expect(find.byKey(optionsKey), findsOneWidget); await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pump(); expect(find.byKey(optionsKey), findsNothing); textEditingController.selection = TextSelection.fromPosition(const TextPosition(offset: 3)); await tester.pump(); expect(find.byKey(optionsKey), findsNothing); }); testWidgets('re-invokes DismissIntent if options not shown', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late FocusNode focusNode; bool wrappingActionInvoked = false; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Actions( actions: <Type, Action<Intent>>{ DismissIntent: CallbackAction<DismissIntent>( onInvoke: (_) => wrappingActionInvoked = true, ), }, child: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; return TextFormField( key: fieldKey, focusNode: focusNode, controller: fieldTextEditingController, onFieldSubmitted: (String value) { onFieldSubmitted(); }, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { return Container(key: optionsKey); }, ), ), ), ), ); // Enter text to show options. focusNode.requestFocus(); await tester.enterText(find.byKey(fieldKey), 'ele'); await tester.pumpAndSettle(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); // Hide the options. await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); expect(wrappingActionInvoked, false); // Ensure the wrapping Actions can receive the DismissIntent. await tester.sendKeyEvent(LogicalKeyboardKey.escape); expect(wrappingActionInvoked, true); }); testWidgets('optionsViewBuilders can use AutocompleteHighlightedOption to highlight selected option', (WidgetTester tester) async { final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late Iterable<String> lastOptions; late int lastHighlighted; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextFormField( key: fieldKey, focusNode: focusNode, controller: textEditingController, onFieldSubmitted: (String value) { onFieldSubmitted(); }, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOptions = options; lastHighlighted = AutocompleteHighlightedOption.of(context); return Container(key: optionsKey); }, ), ), ), ); // Enter text. The options are filtered by the text. focusNode.requestFocus(); await tester.enterText(find.byKey(fieldKey), 'e'); await tester.pump(); expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsOneWidget); expect(lastOptions.length, 6); expect(lastOptions.elementAt(0), 'chameleon'); expect(lastOptions.elementAt(1), 'elephant'); expect(lastOptions.elementAt(2), 'goose'); expect(lastOptions.elementAt(3), 'lemur'); expect(lastOptions.elementAt(4), 'mouse'); expect(lastOptions.elementAt(5), 'northern white rhinoceros'); // Move the highlighted option down and check the highlighted index expect(lastHighlighted, 0); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); expect(lastHighlighted, 1); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); expect(lastHighlighted, 2); await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); await tester.pump(); expect(lastHighlighted, 3); // And move it back up await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); expect(lastHighlighted, 2); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); expect(lastHighlighted, 1); await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); expect(lastHighlighted, 0); // Going back up should wrap around await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); await tester.pump(); expect(lastHighlighted, 5); }); testWidgets('floating menu goes away on select', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/99749. final GlobalKey fieldKey = GlobalKey(); final GlobalKey optionsKey = GlobalKey(); late AutocompleteOnSelected<String> lastOnSelected; late FocusNode focusNode; late TextEditingController textEditingController; await tester.pumpWidget( MaterialApp( home: Scaffold( body: RawAutocomplete<String>( optionsBuilder: (TextEditingValue textEditingValue) { return kOptions.where((String option) { return option.contains(textEditingValue.text.toLowerCase()); }); }, fieldViewBuilder: (BuildContext context, TextEditingController fieldTextEditingController, FocusNode fieldFocusNode, VoidCallback onFieldSubmitted) { focusNode = fieldFocusNode; textEditingController = fieldTextEditingController; return TextField( key: fieldKey, focusNode: focusNode, controller: textEditingController, ); }, optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) { lastOnSelected = onSelected; return Container(key: optionsKey); }, ), ), ), ); // The field is always rendered, but the options are not unless needed. expect(find.byKey(fieldKey), findsOneWidget); expect(find.byKey(optionsKey), findsNothing); await tester.enterText(find.byKey(fieldKey), kOptions[0]); await tester.pumpAndSettle(); expect(find.byKey(optionsKey), findsOneWidget); // Pretend that the only option is selected. This does not change the // text in the text field. lastOnSelected(kOptions[0]); await tester.pump(); expect(find.byKey(optionsKey), findsNothing); }); }
flutter/packages/flutter/test/widgets/autocomplete_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/autocomplete_test.dart", "repo_id": "flutter", "token_count": 21048 }
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:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Sliver in a box', (WidgetTester tester) async { await tester.pumpWidget( DecoratedBox( decoration: const BoxDecoration(), child: SliverList( delegate: SliverChildListDelegate(const <Widget>[]), ), ), ); expect(tester.takeException(), isFlutterError); await tester.pumpWidget( Row( children: <Widget>[ SliverList( delegate: SliverChildListDelegate(const <Widget>[]), ), ], ), ); expect(tester.takeException(), isFlutterError); }); testWidgets('Box in a sliver', (WidgetTester tester) async { late ViewportOffset offset1; addTearDown(() => offset1.dispose()); await tester.pumpWidget( Viewport( crossAxisDirection: AxisDirection.right, offset: offset1 = ViewportOffset.zero(), slivers: const <Widget>[ SizedBox(), ], ), ); expect(tester.takeException(), isFlutterError); late ViewportOffset offset2; addTearDown(() => offset2.dispose()); await tester.pumpWidget( Viewport( crossAxisDirection: AxisDirection.right, offset: offset2 = ViewportOffset.zero(), slivers: const <Widget>[ SliverPadding( padding: EdgeInsets.zero, sliver: SizedBox(), ), ], ), ); expect(tester.takeException(), isFlutterError); }); }
flutter/packages/flutter/test/widgets/box_sliver_mismatch_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/box_sliver_mismatch_test.dart", "repo_id": "flutter", "token_count": 745 }
740
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestCustomPainter extends CustomPainter { TestCustomPainter({ required this.log, this.name }); final List<String?> log; final String? name; @override void paint(Canvas canvas, Size size) { log.add(name); } @override bool shouldRepaint(TestCustomPainter oldPainter) => true; } class MockCanvas extends Fake implements Canvas { int saveCount = 0; int saveCountDelta = 1; @override int getSaveCount() { return saveCount += saveCountDelta; } @override void save() { } } class MockPaintingContext extends Fake implements PaintingContext { @override final MockCanvas canvas = MockCanvas(); } void main() { testWidgets('Control test for custom painting', (WidgetTester tester) async { final List<String?> log = <String?>[]; await tester.pumpWidget(CustomPaint( painter: TestCustomPainter( log: log, name: 'background', ), foregroundPainter: TestCustomPainter( log: log, name: 'foreground', ), child: CustomPaint( painter: TestCustomPainter( log: log, name: 'child', ), ), )); expect(log, equals(<String>['background', 'child', 'foreground'])); }); testWidgets('Throws FlutterError on custom painter incorrect restore/save calls', (WidgetTester tester) async { final GlobalKey target = GlobalKey(); final List<String?> log = <String?>[]; await tester.pumpWidget(CustomPaint( key: target, isComplex: true, painter: TestCustomPainter(log: log), )); final RenderCustomPaint renderCustom = target.currentContext!.findRenderObject()! as RenderCustomPaint; final MockPaintingContext paintingContext = MockPaintingContext(); final MockCanvas canvas = paintingContext.canvas; FlutterError getError() { late FlutterError error; try { renderCustom.paint(paintingContext, Offset.zero); } on FlutterError catch (e) { error = e; } return error; } FlutterError error = getError(); expect(error.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' The TestCustomPainter#00000() custom painter called canvas.save()\n' ' or canvas.saveLayer() at least 1 more time than it called\n' ' canvas.restore().\n' ' This leaves the canvas in an inconsistent state and will probably\n' ' result in a broken display.\n' ' You must pair each call to save()/saveLayer() with a later\n' ' matching call to restore().\n', )); canvas.saveCountDelta = -1; error = getError(); expect(error.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' The TestCustomPainter#00000() custom painter called\n' ' canvas.restore() 1 more time than it called canvas.save() or\n' ' canvas.saveLayer().\n' ' This leaves the canvas in an inconsistent state and will result\n' ' in a broken display.\n' ' You should only call restore() if you first called save() or\n' ' saveLayer().\n', )); canvas.saveCountDelta = 2; error = getError(); expect(error.toStringDeep(), contains('2 more times')); canvas.saveCountDelta = -2; error = getError(); expect(error.toStringDeep(), contains('2 more times')); }); testWidgets('CustomPaint sizing', (WidgetTester tester) async { final GlobalKey target = GlobalKey(); await tester.pumpWidget(Center( child: CustomPaint(key: target), )); expect(target.currentContext!.size, Size.zero); await tester.pumpWidget(Center( child: CustomPaint(key: target, child: Container()), )); expect(target.currentContext!.size, const Size(800.0, 600.0)); await tester.pumpWidget(Center( child: CustomPaint(key: target, size: const Size(20.0, 20.0)), )); expect(target.currentContext!.size, const Size(20.0, 20.0)); await tester.pumpWidget(Center( child: CustomPaint(key: target, size: const Size(2000.0, 100.0)), )); expect(target.currentContext!.size, const Size(800.0, 100.0)); await tester.pumpWidget(Center( child: CustomPaint(key: target, child: Container()), )); expect(target.currentContext!.size, const Size(800.0, 600.0)); await tester.pumpWidget(Center( child: CustomPaint(key: target, child: const SizedBox.shrink()), )); expect(target.currentContext!.size, Size.zero); }); testWidgets('Raster cache hints', (WidgetTester tester) async { final GlobalKey target = GlobalKey(); final List<String?> log = <String?>[]; await tester.pumpWidget(CustomPaint( key: target, isComplex: true, painter: TestCustomPainter(log: log), )); RenderCustomPaint renderCustom = target.currentContext!.findRenderObject()! as RenderCustomPaint; expect(renderCustom.isComplex, true); expect(renderCustom.willChange, false); await tester.pumpWidget(CustomPaint( key: target, willChange: true, foregroundPainter: TestCustomPainter(log: log), )); renderCustom = target.currentContext!.findRenderObject()! as RenderCustomPaint; expect(renderCustom.isComplex, false); expect(renderCustom.willChange, true); }); test('Raster cache hints cannot be set with null painters', () { expect(() => CustomPaint(isComplex: true), throwsAssertionError); expect(() => CustomPaint(willChange: true), throwsAssertionError); }); test('RenderCustomPaint consults preferred size for intrinsics when it has no child', () { final RenderCustomPaint inner = RenderCustomPaint(preferredSize: const Size(20, 30)); expect(inner.getMinIntrinsicWidth(double.infinity), 20); expect(inner.getMaxIntrinsicWidth(double.infinity), 20); expect(inner.getMinIntrinsicHeight(double.infinity), 30); expect(inner.getMaxIntrinsicHeight(double.infinity), 30); }); test('RenderCustomPaint does not return infinity for its intrinsics', () { final RenderCustomPaint inner = RenderCustomPaint(preferredSize: Size.infinite); expect(inner.getMinIntrinsicWidth(double.infinity), 0); expect(inner.getMaxIntrinsicWidth(double.infinity), 0); expect(inner.getMinIntrinsicHeight(double.infinity), 0); expect(inner.getMaxIntrinsicHeight(double.infinity), 0); }); }
flutter/packages/flutter/test/widgets/custom_paint_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/custom_paint_test.dart", "repo_id": "flutter", "token_count": 2388 }
741
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { Widget boilerplateWidget(VoidCallback? onButtonPressed, { DraggableScrollableController? controller, int itemCount = 100, double initialChildSize = .5, double maxChildSize = 1.0, double minChildSize = .25, bool snap = false, List<double>? snapSizes, Duration? snapAnimationDuration, double? itemExtent, Key? containerKey, Key? stackKey, NotificationListenerCallback<ScrollNotification>? onScrollNotification, NotificationListenerCallback<DraggableScrollableNotification>? onDraggableScrollableNotification, bool ignoreController = false, bool shouldCloseOnMinExtent = true, }) { return Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Stack( key: stackKey, children: <Widget>[ TextButton( onPressed: onButtonPressed, child: const Text('TapHere'), ), DraggableScrollableActuator( child: DraggableScrollableSheet( controller: controller, maxChildSize: maxChildSize, minChildSize: minChildSize, initialChildSize: initialChildSize, snap: snap, snapSizes: snapSizes, snapAnimationDuration: snapAnimationDuration, shouldCloseOnMinExtent: shouldCloseOnMinExtent, builder: (BuildContext context, ScrollController scrollController) { return NotificationListener<ScrollNotification>( onNotification: onScrollNotification, child: NotificationListener<DraggableScrollableNotification>( onNotification: onDraggableScrollableNotification, child:ColoredBox( key: containerKey, color: const Color(0xFFABCDEF), child: ListView.builder( controller: ignoreController ? null : scrollController, itemExtent: itemExtent, itemCount: itemCount, itemBuilder: (BuildContext context, int index) => Text('Item $index'), ), ), ) ); }, ), ), ], ), ), ); } testWidgets('Do not crash when replacing scroll position during the drag', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/89681 bool showScrollbars = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Align( alignment: Alignment.bottomCenter, child: DraggableScrollableSheet( initialChildSize: 0.7, minChildSize: 0.2, maxChildSize: 0.9, expand: false, builder: (BuildContext context, ScrollController scrollController) { showScrollbars = !showScrollbars; // Change the scroll behavior will trigger scroll position replace. final ScrollBehavior behavior = const ScrollBehavior().copyWith(scrollbars: showScrollbars); return ScrollConfiguration( behavior: behavior, child: ListView.separated( physics: const BouncingScrollPhysics(), controller: scrollController, separatorBuilder: (_, __) => const Divider(), itemCount: 100, itemBuilder: (_, int index) => SizedBox( height: 100, child: ColoredBox( color: Colors.primaries[index % Colors.primaries.length], child: Text('Item $index'), ), ), ), ); }, ), ), ), ), ); await tester.fling(find.text('Item 1'), const Offset(0, 200), 350); await tester.pumpAndSettle(); // Go without throw. }); testWidgets('Scrolls correct amount when maxChildSize < 1.0', (WidgetTester tester) async { const Key key = ValueKey<String>('container'); await tester.pumpWidget(boilerplateWidget( null, maxChildSize: .6, initialChildSize: .25, itemExtent: 25.0, containerKey: key, )); expect(tester.getRect(find.byKey(key)), const Rect.fromLTRB(0.0, 450.0, 800.0, 600.0)); await tester.drag(find.text('Item 5'), const Offset(0, -125)); await tester.pumpAndSettle(); expect(tester.getRect(find.byKey(key)), const Rect.fromLTRB(0.0, 325.0, 800.0, 600.0)); }); testWidgets('Scrolls correct amount when maxChildSize == 1.0', (WidgetTester tester) async { const Key key = ValueKey<String>('container'); await tester.pumpWidget(boilerplateWidget( null, initialChildSize: .25, itemExtent: 25.0, containerKey: key, )); expect(tester.getRect(find.byKey(key)), const Rect.fromLTRB(0.0, 450.0, 800.0, 600.0)); await tester.drag(find.text('Item 5'), const Offset(0, -125)); await tester.pumpAndSettle(); expect(tester.getRect(find.byKey(key)), const Rect.fromLTRB(0.0, 325.0, 800.0, 600.0)); }); testWidgets('Invalid snap targets throw assertion errors.', (WidgetTester tester) async { await tester.pumpWidget(boilerplateWidget( null, maxChildSize: .8, snapSizes: <double>[.9], )); expect(tester.takeException(), isAssertionError); await tester.pumpWidget(boilerplateWidget( null, snapSizes: <double>[.1], )); expect(tester.takeException(), isAssertionError); await tester.pumpWidget(boilerplateWidget( null, snapSizes: <double>[.6, .6, .9], )); expect(tester.takeException(), isAssertionError); }); group('Scroll Physics', () { testWidgets('Can be dragged up without covering its container', (WidgetTester tester) async { int taps = 0; await tester.pumpWidget(boilerplateWidget(() => taps++)); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere')); expect(taps, 1); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 31'), findsNothing); await tester.drag(find.text('Item 1'), const Offset(0, -200)); await tester.pumpAndSettle(); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere')); expect(taps, 2); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 31'), findsOneWidget); }, variant: TargetPlatformVariant.all()); testWidgets('Can be dragged down when not full height', (WidgetTester tester) async { await tester.pumpWidget(boilerplateWidget(null)); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 36'), findsNothing); await tester.drag(find.text('Item 1'), const Offset(0, 325)); await tester.pumpAndSettle(); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsNothing); expect(find.text('Item 36'), findsNothing); }, variant: TargetPlatformVariant.all()); testWidgets('Can be dragged down when list is shorter than full height', (WidgetTester tester) async { await tester.pumpWidget(boilerplateWidget(null, itemCount: 30, initialChildSize: .25)); expect(find.text('Item 1').hitTestable(), findsOneWidget); expect(find.text('Item 29').hitTestable(), findsNothing); await tester.drag(find.text('Item 1'), const Offset(0, -325)); await tester.pumpAndSettle(); expect(find.text('Item 1').hitTestable(), findsOneWidget); expect(find.text('Item 29').hitTestable(), findsOneWidget); await tester.drag(find.text('Item 1'), const Offset(0, 325)); await tester.pumpAndSettle(); expect(find.text('Item 1').hitTestable(), findsOneWidget); expect(find.text('Item 29').hitTestable(), findsNothing); }, variant: TargetPlatformVariant.all()); testWidgets('Can be dragged up and cover its container and scroll in single motion, and then dragged back down', (WidgetTester tester) async { int taps = 0; await tester.pumpWidget(boilerplateWidget(() => taps++)); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere')); expect(taps, 1); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 36'), findsNothing); await tester.drag(find.text('Item 1'), const Offset(0, -325)); await tester.pumpAndSettle(); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere'), warnIfMissed: false); expect(taps, 1); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 36'), findsOneWidget); await tester.dragFrom(const Offset(20, 20), const Offset(0, 325)); await tester.pumpAndSettle(); await tester.tap(find.text('TapHere')); expect(taps, 2); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 18'), findsOneWidget); expect(find.text('Item 36'), findsNothing); }, variant: TargetPlatformVariant.all()); testWidgets('Can be flung up gently', (WidgetTester tester) async { int taps = 0; await tester.pumpWidget(boilerplateWidget(() => taps++)); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere')); expect(taps, 1); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 36'), findsNothing); expect(find.text('Item 70'), findsNothing); await tester.fling(find.text('Item 1'), const Offset(0, -200), 350); await tester.pumpAndSettle(); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere')); expect(taps, 2); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 36'), findsOneWidget); expect(find.text('Item 70'), findsNothing); }, variant: TargetPlatformVariant.all()); testWidgets('Can be flung up', (WidgetTester tester) async { int taps = 0; await tester.pumpWidget(boilerplateWidget(() => taps++)); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere')); expect(taps, 1); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 70'), findsNothing); await tester.fling(find.text('Item 1'), const Offset(0, -200), 2000); await tester.pumpAndSettle(); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere'), warnIfMissed: false); expect(taps, 1); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 21'), findsNothing); if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { expect(find.text('Item 40'), findsOneWidget); } else { expect(find.text('Item 70'), findsOneWidget); } }, variant: TargetPlatformVariant.all()); testWidgets('Can be flung down when not full height', (WidgetTester tester) async { await tester.pumpWidget(boilerplateWidget(null)); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 36'), findsNothing); await tester.fling(find.text('Item 1'), const Offset(0, 325), 2000); await tester.pumpAndSettle(); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsNothing); expect(find.text('Item 36'), findsNothing); }, variant: TargetPlatformVariant.all()); testWidgets('Can be flung up and then back down', (WidgetTester tester) async { int taps = 0; await tester.pumpWidget(boilerplateWidget(() => taps++)); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere')); expect(taps, 1); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 70'), findsNothing); await tester.fling(find.text('Item 1'), const Offset(0, -200), 2000); await tester.pumpAndSettle(); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere'), warnIfMissed: false); expect(taps, 1); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 21'), findsNothing); if (debugDefaultTargetPlatformOverride == TargetPlatform.macOS) { expect(find.text('Item 40'), findsOneWidget); await tester.fling(find.text('Item 40'), const Offset(0, 200), 2000); } else { expect(find.text('Item 70'), findsOneWidget); await tester.fling(find.text('Item 70'), const Offset(0, 200), 2000); } await tester.pumpAndSettle(); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere'), warnIfMissed: false); expect(taps, 1); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsOneWidget); expect(find.text('Item 70'), findsNothing); await tester.fling(find.text('Item 1'), const Offset(0, 200), 2000); await tester.pumpAndSettle(); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere')); expect(taps, 2); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 21'), findsNothing); expect(find.text('Item 70'), findsNothing); }, variant: TargetPlatformVariant.all()); testWidgets('Ballistic animation on fling can be interrupted', (WidgetTester tester) async { int taps = 0; await tester.pumpWidget(boilerplateWidget(() => taps++)); expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere')); expect(taps, 1); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 31'), findsNothing); expect(find.text('Item 70'), findsNothing); await tester.fling(find.text('Item 1'), const Offset(0, -200), 2000); // Don't pump and settle because we want to interrupt the ballistic scrolling animation. expect(find.text('TapHere'), findsOneWidget); await tester.tap(find.text('TapHere'), warnIfMissed: false); expect(taps, 2); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 31'), findsOneWidget); expect(find.text('Item 70'), findsNothing); // Use `dragFrom` here because calling `drag` on a list item without // first calling `pumpAndSettle` fails with a hit test error. await tester.dragFrom(const Offset(0, 200), const Offset(0, 200)); await tester.pumpAndSettle(); // Verify that the ballistic animation has canceled and the sheet has // returned to it's original position. await tester.tap(find.text('TapHere')); expect(taps, 3); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 31'), findsNothing); expect(find.text('Item 70'), findsNothing); }, variant: TargetPlatformVariant.all()); testWidgets('Ballistic animation on fling should not leak Ticker', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/101061 await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Align( alignment: Alignment.bottomCenter, child: DraggableScrollableSheet( initialChildSize: 0.8, minChildSize: 0.2, maxChildSize: 0.9, expand: false, builder: (_, ScrollController scrollController) { return ListView.separated( physics: const BouncingScrollPhysics(), controller: scrollController, separatorBuilder: (_, __) => const Divider(), itemCount: 100, itemBuilder: (_, int index) => SizedBox( height: 100, child: ColoredBox( color: Colors.primaries[index % Colors.primaries.length], child: Text('Item $index'), ), ), ); }, ), ), ), ), ); await tester.flingFrom( tester.getCenter(find.text('Item 1')), const Offset(0, 50), 10000, ); // Pumps several times to let the DraggableScrollableSheet react to scroll position changes. const int numberOfPumpsBeforeError = 22; for (int i = 0; i < numberOfPumpsBeforeError; i++) { await tester.pump(const Duration(milliseconds: 10)); } // Dispose the DraggableScrollableSheet await tester.pumpWidget(const SizedBox.shrink()); // When a Ticker leaks an exception is thrown expect(tester.takeException(), isNull); }); }); testWidgets('Does not snap away from initial child on build', (WidgetTester tester) async { const Key containerKey = ValueKey<String>('container'); const Key stackKey = ValueKey<String>('stack'); await tester.pumpWidget(boilerplateWidget(null, snap: true, initialChildSize: .7, containerKey: containerKey, stackKey: stackKey, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; // The sheet should not have snapped. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.7, precisionErrorTolerance, )); }, variant: TargetPlatformVariant.all()); for (final bool useActuator in <bool>[false, true]) { testWidgets('Does not snap away from initial child on ${useActuator ? 'actuator' : 'controller'}.reset()', (WidgetTester tester) async { const Key containerKey = ValueKey<String>('container'); const Key stackKey = ValueKey<String>('stack'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(boilerplateWidget( null, controller: controller, snap: true, containerKey: containerKey, stackKey: stackKey, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; await tester.drag(find.text('Item 1'), Offset(0, -.4 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(1.0, precisionErrorTolerance), ); if (useActuator) { DraggableScrollableActuator.reset(tester.element(find.byKey(containerKey))); } else { controller.reset(); } await tester.pumpAndSettle(); // The sheet should have reset without snapping away from initial child. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.5, precisionErrorTolerance), ); }); } for (final Duration? snapAnimationDuration in <Duration?>[null, const Duration(seconds: 2)]) { testWidgets( 'Zero velocity drag snaps to nearest snap target with ' 'snapAnimationDuration: $snapAnimationDuration', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); await tester.pumpWidget(boilerplateWidget(null, snap: true, stackKey: stackKey, containerKey: containerKey, snapSizes: <double>[.25, .5, .75, 1.0], snapAnimationDuration: snapAnimationDuration )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; // We are dragging up, but we'll snap down because we're closer to .75 than 1. await tester.drag(find.text('Item 1'), Offset(0, -.35 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.75, precisionErrorTolerance), ); // Drag up and snap up. await tester.drag(find.text('Item 1'), Offset(0, -.2 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(1.0, precisionErrorTolerance), ); // Drag down and snap up. await tester.drag(find.text('Item 1'), Offset(0, .1 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(1.0, precisionErrorTolerance), ); // Drag down and snap down. await tester.drag(find.text('Item 1'), Offset(0, .45 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.5, precisionErrorTolerance), ); // Fling up with negligible velocity and snap down. await tester.fling(find.text('Item 1'), Offset(0, .1 * screenHeight), 1); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.5, precisionErrorTolerance), ); }, variant: TargetPlatformVariant.all()); } for (final List<double>? snapSizes in <List<double>?>[null, <double>[]]) { testWidgets('Setting snapSizes to $snapSizes resolves to min and max', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); await tester.pumpWidget(boilerplateWidget(null, snap: true, stackKey: stackKey, containerKey: containerKey, snapSizes: snapSizes, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; await tester.drag(find.text('Item 1'), Offset(0, -.4 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(1.0, precisionErrorTolerance, )); await tester.drag(find.text('Item 1'), Offset(0, .7 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.25, precisionErrorTolerance), ); }, variant: TargetPlatformVariant.all()); } testWidgets('Min and max are implicitly added to snapSizes', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); await tester.pumpWidget(boilerplateWidget(null, snap: true, stackKey: stackKey, containerKey: containerKey, snapSizes: <double>[.5], )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; await tester.drag(find.text('Item 1'), Offset(0, -.4 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(1.0, precisionErrorTolerance), ); await tester.drag(find.text('Item 1'), Offset(0, .7 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.25, precisionErrorTolerance), ); }, variant: TargetPlatformVariant.all()); testWidgets('Changes to widget parameters are propagated', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); await tester.pumpWidget(boilerplateWidget( null, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.5, precisionErrorTolerance), ); // Pump the same widget but with a new initial child size. await tester.pumpWidget(boilerplateWidget( null, stackKey: stackKey, containerKey: containerKey, initialChildSize: .6, )); await tester.pumpAndSettle(); // We jump to the new initial size because the sheet hasn't changed yet. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); // Pump the same widget but with a new max child size. await tester.pumpWidget(boilerplateWidget( null, stackKey: stackKey, containerKey: containerKey, initialChildSize: .6, maxChildSize: .9 )); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); await tester.drag(find.text('Item 1'), Offset(0, -.6 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.9, precisionErrorTolerance), ); // Pump the same widget but with a new max child size and initial size. await tester.pumpWidget(boilerplateWidget( null, stackKey: stackKey, containerKey: containerKey, maxChildSize: .8, initialChildSize: .7, )); await tester.pumpAndSettle(); // The max child size has been reduced, we should be rebuilt at the new // max of .8. We changed the initial size again, but the sheet has already // been changed so the new initial is ignored. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.8, precisionErrorTolerance), ); await tester.drag(find.text('Item 1'), Offset(0, .2 * screenHeight)); // Pump the same widget but with snapping enabled. await tester.pumpWidget(boilerplateWidget( null, snap: true, stackKey: stackKey, containerKey: containerKey, maxChildSize: .8, snapSizes: <double>[.5], )); await tester.pumpAndSettle(); // Sheet snaps immediately on a change to snap. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.5, precisionErrorTolerance), ); final List<double> snapSizes = <double>[.6]; // Change the snap sizes. await tester.pumpWidget(boilerplateWidget( null, snap: true, stackKey: stackKey, containerKey: containerKey, maxChildSize: .8, snapSizes: snapSizes, )); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); }, variant: TargetPlatformVariant.all()); testWidgets('Fling snaps in direction of momentum', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); await tester.pumpWidget(boilerplateWidget(null, snap: true, stackKey: stackKey, containerKey: containerKey, snapSizes: <double>[.5, .75], )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; await tester.fling(find.text('Item 1'), Offset(0, -.1 * screenHeight), 1000); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.75, precisionErrorTolerance), ); await tester.fling(find.text('Item 1'), Offset(0, .3 * screenHeight), 1000); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.25, precisionErrorTolerance), ); }, variant: TargetPlatformVariant.all()); testWidgets("Changing parameters with an un-listened controller doesn't throw", (WidgetTester tester) async { await tester.pumpWidget(boilerplateWidget( null, snap: true, // Will prevent the sheet's child from listening to the controller. ignoreController: true, )); await tester.pumpAndSettle(); await tester.pumpWidget(boilerplateWidget( null, snap: true, )); await tester.pumpAndSettle(); }, variant: TargetPlatformVariant.all()); testWidgets('Transitioning between scrollable children sharing a scroll controller will not throw', (WidgetTester tester) async { int s = 0; await tester.pumpWidget(MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return Scaffold( body: DraggableScrollableSheet( initialChildSize: 0.25, snap: true, snapSizes: const <double>[0.25, 0.5, 1.0], builder: (BuildContext context, ScrollController scrollController) { return PrimaryScrollController( controller: scrollController, child: AnimatedSwitcher( duration: const Duration(milliseconds: 500), child: (s.isEven) ? ListView( children: <Widget>[ ElevatedButton( onPressed: () => setState(() => ++s), child: const Text('Switch to 2'), ), Container( height: 400, color: Colors.blue, ), ], ) : SingleChildScrollView( child: Column( children: <Widget>[ ElevatedButton( onPressed: () => setState(() => ++s), child: const Text('Switch to 1'), ), Container( height: 400, color: Colors.blue, ), ], ) ), ), ); }, ), ); }, ), )); // Trigger the AnimatedSwitcher between ListViews await tester.tap(find.text('Switch to 2')); await tester.pump(); // Completes without throwing }); testWidgets('ScrollNotification correctly dispatched when flung without covering its container', (WidgetTester tester) async { final List<Type> notificationTypes = <Type>[]; await tester.pumpWidget(boilerplateWidget( null, onScrollNotification: (ScrollNotification notification) { notificationTypes.add(notification.runtimeType); return false; }, )); await tester.fling(find.text('Item 1'), const Offset(0, -200), 200); await tester.pumpAndSettle(); // TODO(itome): Make sure UserScrollNotification and ScrollUpdateNotification are called correctly. final List<Type> types = <Type>[ ScrollStartNotification, ScrollEndNotification, ]; expect(notificationTypes, equals(types)); }); testWidgets('ScrollNotification correctly dispatched when flung with contents scroll', (WidgetTester tester) async { final List<Type> notificationTypes = <Type>[]; await tester.pumpWidget(boilerplateWidget( null, onScrollNotification: (ScrollNotification notification) { notificationTypes.add(notification.runtimeType); return false; }, )); await tester.flingFrom(const Offset(0, 325), const Offset(0, -325), 200); await tester.pumpAndSettle(); final List<Type> types = <Type>[ ScrollStartNotification, UserScrollNotification, ...List<Type>.filled(5, ScrollUpdateNotification), ScrollEndNotification, UserScrollNotification, ]; expect(notificationTypes, types); }); testWidgets('Emits DraggableScrollableNotification with shouldCloseOnMinExtent set to non-default value', (WidgetTester tester) async { DraggableScrollableNotification? receivedNotification; await tester.pumpWidget(boilerplateWidget( null, shouldCloseOnMinExtent: false, onDraggableScrollableNotification: (DraggableScrollableNotification notification) { receivedNotification = notification; return false; }, )); await tester.flingFrom(const Offset(0, 325), const Offset(0, -325), 200); await tester.pumpAndSettle(); expect(receivedNotification!.shouldCloseOnMinExtent, isFalse); }); testWidgets('Do not crash when remove the tree during animation.', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/89214 await tester.pumpWidget(boilerplateWidget( null, onScrollNotification: (ScrollNotification notification) { return false; }, )); await tester.flingFrom(const Offset(0, 325), const Offset(0, 325), 200); // The animation is running. await tester.pumpWidget(const SizedBox.shrink()); expect(tester.takeException(), isNull); }); for (final bool shouldAnimate in <bool>[true, false]) { testWidgets('Can ${shouldAnimate ? 'animate' : 'jump'} to arbitrary positions', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; // Use a local helper to animate so we can share code across a jumpTo test // and an animateTo test. void goTo(double size) => shouldAnimate ? controller.animateTo(size, duration: const Duration(milliseconds: 200), curve: Curves.linear) : controller.jumpTo(size); // If we're animating, pump will call four times, two of which are for the // animation duration. final int expectedPumpCount = shouldAnimate ? 4 : 2; goTo(.6); expect(await tester.pumpAndSettle(), expectedPumpCount); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 20'), findsOneWidget); expect(find.text('Item 70'), findsNothing); goTo(.4); expect(await tester.pumpAndSettle(), expectedPumpCount); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.4, precisionErrorTolerance), ); expect(find.text('Item 1'), findsOneWidget); expect(find.text('Item 20'), findsNothing); expect(find.text('Item 70'), findsNothing); await tester.fling(find.text('Item 1'), Offset(0, -screenHeight), 100); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(1, precisionErrorTolerance), ); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 20'), findsOneWidget); expect(find.text('Item 70'), findsNothing); // Programmatic control does not affect the inner scrollable's position. goTo(.8); expect(await tester.pumpAndSettle(), expectedPumpCount); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.8, precisionErrorTolerance), ); expect(find.text('Item 1'), findsNothing); expect(find.text('Item 20'), findsOneWidget); expect(find.text('Item 70'), findsNothing); // Attempting to move to a size too big or too small instead moves to the // min or max child size. goTo(.5); await tester.pumpAndSettle(); goTo(0); expect(await tester.pumpAndSettle(), expectedPumpCount); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.25, precisionErrorTolerance), ); }); } testWidgets('Can animateTo with a nonlinear curve', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; controller.animateTo(.6, curve: Curves.linear, duration: const Duration(milliseconds: 100)); // We need to call one pump first to get the animation to start. await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.55, precisionErrorTolerance), ); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); controller.animateTo(.7, curve: const Interval(.5, 1), duration: const Duration(milliseconds: 100)); await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); // The curve should result in the sheet not moving for the first 50 ms. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); await tester.pump(const Duration(milliseconds: 25)); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.65, precisionErrorTolerance), ); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.7, precisionErrorTolerance), ); }); testWidgets('Can animateTo with a Curves.easeInOutBack curve begin min-size', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(boilerplateWidget( null, initialChildSize: 0.25, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; controller.animateTo(.6, curve: Curves.easeInOutBack, duration: const Duration(milliseconds: 500)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); }); testWidgets('Can reuse a controller after the old controller is disposed', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); // Pump a new sheet with the same controller. This will dispose of the old sheet first. await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; controller.jumpTo(.6); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); }); testWidgets('animateTo interrupts other animations', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, ), )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; await tester.flingFrom(Offset(0, .5*screenHeight), Offset(0, -.5*screenHeight), 2000); // Wait until `flinFrom` finished dragging, but before the scrollable goes ballistic. await tester.pump(const Duration(seconds: 1)); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(1, precisionErrorTolerance), ); expect(find.text('Item 1'), findsOneWidget); controller.animateTo(.9, duration: const Duration(milliseconds: 200), curve: Curves.linear); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.9, precisionErrorTolerance), ); // The ballistic animation should have been canceled so item 1 should still be visible. expect(find.text('Item 1'), findsOneWidget); }); testWidgets('Other animations interrupt animateTo', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, ), )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; controller.animateTo(1, duration: const Duration(milliseconds: 200), curve: Curves.linear); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.75, precisionErrorTolerance), ); // Interrupt animation and drag downward. await tester.drag(find.text('Item 1'), Offset(0, .1 * screenHeight)); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.65, precisionErrorTolerance), ); }); testWidgets('animateTo can be interrupted by other animateTo or jumpTo', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, ), )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; controller.animateTo(1, duration: const Duration(milliseconds: 200), curve: Curves.linear); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.75, precisionErrorTolerance), ); // Interrupt animation with a new `animateTo`. controller.animateTo(.25, duration: const Duration(milliseconds: 200), curve: Curves.linear); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.5, precisionErrorTolerance), ); // Interrupt animation with a jump. controller.jumpTo(.6); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); }); testWidgets('Can get size and pixels', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; expect(controller.sizeToPixels(.25), .25*screenHeight); expect(controller.pixelsToSize(.25*screenHeight), .25); controller.animateTo(.6, duration: const Duration(milliseconds: 200), curve: Curves.linear); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); expect(controller.size, closeTo(.6, precisionErrorTolerance)); expect(controller.pixels, closeTo(.6*screenHeight, precisionErrorTolerance)); await tester.drag(find.text('Item 5'), Offset(0, .2*screenHeight)); expect(controller.size, closeTo(.4, precisionErrorTolerance)); expect(controller.pixels, closeTo(.4*screenHeight, precisionErrorTolerance)); }); testWidgets('Cannot attach a controller to multiple sheets', (WidgetTester tester) async { final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ boilerplateWidget( null, controller: controller, ), boilerplateWidget( null, controller: controller, ), ], ), ), phase: EnginePhase.build); expect(tester.takeException(), isAssertionError); }); testWidgets('Can listen for changes in sheet size', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final List<double> loggedSizes = <double>[]; final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); controller.addListener(() { loggedSizes.add(controller.size); }); await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester .getSize(find.byKey(stackKey)) .height; // The initial size shouldn't be logged because no change has occurred yet. expect(loggedSizes.isEmpty, true); await tester.drag(find.text('Item 1'), Offset(0, .1 * screenHeight), touchSlopY: 0); await tester.pumpAndSettle(); expect(loggedSizes, <double>[.4].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); await tester.timedDrag(find.text('Item 1'), Offset(0, -.1 * screenHeight), const Duration(seconds: 1), frequency: 2); await tester.pumpAndSettle(); expect(loggedSizes, <double>[.45, .5].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); controller.jumpTo(.6); await tester.pumpAndSettle(); expect(loggedSizes, <double>[.6].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); controller.animateTo(1, duration: const Duration(milliseconds: 400), curve: Curves.linear); await tester.pumpAndSettle(); expect(loggedSizes, <double>[.7, .8, .9, 1].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); DraggableScrollableActuator.reset(tester.element(find.byKey(containerKey))); await tester.pumpAndSettle(); expect(loggedSizes, <double>[.5].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); }); testWidgets('Listener does not fire on parameter change and persists after change', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final List<double> loggedSizes = <double>[]; final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); controller.addListener(() { loggedSizes.add(controller.size); }); await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester .getSize(find.byKey(stackKey)) .height; expect(loggedSizes.isEmpty, true); await tester.drag(find.text('Item 1'), Offset(0, .1 * screenHeight), touchSlopY: 0); await tester.pumpAndSettle(); expect(loggedSizes, <double>[.4].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); // Update a parameter without forcing a change in the current size. await tester.pumpWidget(boilerplateWidget( null, minChildSize: .1, controller: controller, stackKey: stackKey, containerKey: containerKey, )); expect(loggedSizes.isEmpty, true); await tester.drag(find.text('Item 1'), Offset(0, .1 * screenHeight), touchSlopY: 0); await tester.pumpAndSettle(); expect(loggedSizes, <double>[.3].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); }); testWidgets('Listener fires if a parameter change forces a change in size', (WidgetTester tester) async { const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final List<double> loggedSizes = <double>[]; final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); controller.addListener(() { loggedSizes.add(controller.size); }); await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester .getSize(find.byKey(stackKey)) .height; expect(loggedSizes.isEmpty, true); // Set a new `initialChildSize` which will trigger a size change because we // haven't moved away initial size yet. await tester.pumpWidget(boilerplateWidget( null, initialChildSize: .6, controller: controller, stackKey: stackKey, containerKey: containerKey, )); expect(loggedSizes, <double>[.6].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); // Move away from initial child size. await tester.drag(find.text('Item 1'), Offset(0, .3 * screenHeight), touchSlopY: 0); await tester.pumpAndSettle(); expect(loggedSizes, <double>[.3].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); // Set a `minChildSize` greater than the current size. await tester.pumpWidget(boilerplateWidget( null, minChildSize: .4, controller: controller, stackKey: stackKey, containerKey: containerKey, )); expect(loggedSizes, <double>[.4].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); }); testWidgets('Invalid controller interactions throw assertion errors', (WidgetTester tester) async { final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); // Can't use a controller before attaching it. expect(() => controller.jumpTo(.1), throwsAssertionError); expect(() => controller.pixels, throwsAssertionError); expect(() => controller.size, throwsAssertionError); expect(() => controller.pixelsToSize(0), throwsAssertionError); expect(() => controller.sizeToPixels(0), throwsAssertionError); await tester.pumpWidget(boilerplateWidget( null, controller: controller, )); // Can't jump or animate to invalid sizes. expect(() => controller.jumpTo(-1), throwsAssertionError); expect(() => controller.jumpTo(1.1), throwsAssertionError); expect( () => controller.animateTo(-1, duration: const Duration(milliseconds: 1), curve: Curves.linear), throwsAssertionError, ); expect( () => controller.animateTo(1.1, duration: const Duration(milliseconds: 1), curve: Curves.linear), throwsAssertionError, ); // Can't use animateTo with a zero duration. expect(() => controller.animateTo(.5, duration: Duration.zero, curve: Curves.linear), throwsAssertionError); }); testWidgets('DraggableScrollableController must be attached before using any of its parameters', (WidgetTester tester) async { final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); expect(controller.isAttached, false); expect(()=>controller.size, throwsAssertionError); final Widget boilerplate = boilerplateWidget( null, minChildSize: 0.4, controller: controller, ); await tester.pumpWidget(boilerplate); expect(controller.isAttached, true); expect(controller.size, isNotNull); }); testWidgets('DraggableScrollableController.animateTo after detach', (WidgetTester tester) async { final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(boilerplateWidget(() {}, controller: controller)); controller.animateTo(0.0, curve: Curves.linear, duration: const Duration(milliseconds: 200)); await tester.pump(); // Dispose the DraggableScrollableSheet await tester.pumpWidget(const SizedBox.shrink()); // Controller should be detached and no exception should be thrown expect(controller.isAttached, false); expect(tester.takeException(), isNull); }); testWidgets('DraggableScrollableSheet should not reset programmatic drag on rebuild', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/101114 const Key stackKey = ValueKey<String>('stack'); const Key containerKey = ValueKey<String>('container'); final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); await tester.pumpAndSettle(); final double screenHeight = tester.getSize(find.byKey(stackKey)).height; controller.jumpTo(.6); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); // Force an arbitrary rebuild by pushing a new widget. await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); // Sheet remains at .6. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); controller.reset(); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.5, precisionErrorTolerance), ); controller.animateTo( .6, curve: Curves.linear, duration: const Duration(milliseconds: 200), ); await tester.pumpAndSettle(); expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); // Force an arbitrary rebuild by pushing a new widget. await tester.pumpWidget(boilerplateWidget( null, controller: controller, stackKey: stackKey, containerKey: containerKey, )); // Sheet remains at .6. expect( tester.getSize(find.byKey(containerKey)).height / screenHeight, closeTo(.6, precisionErrorTolerance), ); }); testWidgets('DraggableScrollableSheet should respect NeverScrollableScrollPhysics', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/121021 final DraggableScrollableController controller = DraggableScrollableController(); addTearDown(controller.dispose); Widget buildFrame(ScrollPhysics? physics) { return MaterialApp( home: Scaffold( body: DraggableScrollableSheet( controller: controller, initialChildSize: 0.25, builder: (BuildContext context, ScrollController scrollController) { return ListView( physics: physics, controller: scrollController, children: <Widget>[ const Text('Drag me!'), Container( height: 10000.0, color: Colors.blue, ), ], ); }, ), ), ); } await tester.pumpWidget(buildFrame(const NeverScrollableScrollPhysics())); final double initPixels = controller.pixels; await tester.drag(find.text('Drag me!'), const Offset(0, -300)); await tester.pumpAndSettle(); //Should not allow user scrolling. expect(controller.pixels, initPixels); await tester.pumpWidget(buildFrame(null)); await tester.drag(find.text('Drag me!'), const Offset(0, -300.0)); await tester.pumpAndSettle(); //Allow user scrolling. expect(controller.pixels, initPixels + 300.0); }); testWidgets('DraggableScrollableSheet should not rebuild every frame while dragging', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/67219 int buildCount = 0; await tester.pumpWidget(MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) => Scaffold( body: DraggableScrollableSheet( initialChildSize: 0.25, snap: true, snapSizes: const <double>[0.25, 0.5, 1.0], builder: (BuildContext context, ScrollController scrollController) { buildCount++; return ListView( controller: scrollController, children: <Widget>[ const Text('Drag me!'), ElevatedButton( onPressed: () => setState(() {}), child: const Text('Rebuild'), ), Container( height: 10000, color: Colors.blue, ), ], ); }, ), ), ), )); expect(buildCount, 1); await tester.fling(find.text('Drag me!'), const Offset(0, -300), 300); await tester.pumpAndSettle(); // No need to rebuild the scrollable sheet, as only position has changed. expect(buildCount, 1); await tester.tap(find.text('Rebuild')); await tester.pump(); // DraggableScrollableSheet has rebuilt, so expect the builder to be called. expect(buildCount, 2); }); testWidgets('DraggableScrollableSheet controller can be changed', (WidgetTester tester) async { final DraggableScrollableController controller1 = DraggableScrollableController(); addTearDown(controller1.dispose); final DraggableScrollableController controller2 = DraggableScrollableController(); addTearDown(controller2.dispose); final List<double> loggedSizes = <double>[]; DraggableScrollableController controller = controller1; await tester.pumpWidget(MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) => Scaffold( body: DraggableScrollableSheet( initialChildSize: 0.25, snap: true, snapSizes: const <double>[0.25, 0.5, 1.0], controller: controller, builder: (BuildContext context, ScrollController scrollController) { return ListView( controller: scrollController, children: <Widget>[ ElevatedButton( onPressed: () => setState(() { controller = controller2; }), child: const Text('Switch controller'), ), Container( height: 10000, color: Colors.blue, ), ], ); }, ), ), ), )); expect(controller1.isAttached, true); expect(controller2.isAttached, false); controller1.addListener(() { loggedSizes.add(controller1.size); }); controller1.jumpTo(0.5); expect(loggedSizes, <double>[0.5].map((double v) => closeTo(v, precisionErrorTolerance))); loggedSizes.clear(); await tester.tap(find.text('Switch controller')); await tester.pump(); expect(controller1.isAttached, false); expect(controller2.isAttached, true); controller2.addListener(() { loggedSizes.add(controller2.size); }); controller2.jumpTo(1.0); expect(loggedSizes, <double>[1.0].map((double v) => closeTo(v, precisionErrorTolerance))); }); testWidgets('DraggableScrollableSheet controller can be changed while animating', (WidgetTester tester) async { final DraggableScrollableController controller1 = DraggableScrollableController(); addTearDown(controller1.dispose); final DraggableScrollableController controller2 = DraggableScrollableController(); addTearDown(controller2.dispose); DraggableScrollableController controller = controller1; await tester.pumpWidget(MaterialApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) => Scaffold( body: DraggableScrollableSheet( initialChildSize: 0.25, snap: true, snapSizes: const <double>[0.25, 0.5, 1.0], controller: controller, builder: (BuildContext context, ScrollController scrollController) { return ListView( controller: scrollController, children: <Widget>[ ElevatedButton( onPressed: () => setState(() { controller = controller2; }), child: const Text('Switch controller'), ), Container( height: 10000, color: Colors.blue, ), ], ); }, ), ), ), )); expect(controller1.isAttached, true); expect(controller2.isAttached, false); controller1.animateTo(0.5, curve: Curves.linear, duration: const Duration(milliseconds: 200)); await tester.pump(); await tester.tap(find.text('Switch controller')); await tester.pump(); expect(controller1.isAttached, false); expect(controller2.isAttached, true); controller2.animateTo(1.0, curve: Curves.linear, duration: const Duration(milliseconds: 200)); await tester.pump(); await tester.pumpWidget(const SizedBox.shrink()); expect(controller1.isAttached, false); expect(controller2.isAttached, false); }); testWidgets('$DraggableScrollableController dispatches creation in constructor.', (WidgetTester widgetTester) async { await expectLater( await memoryEvents(() async => DraggableScrollableController().dispose(), DraggableScrollableController), areCreateAndDispose, ); }); }
flutter/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/draggable_scrollable_sheet_test.dart", "repo_id": "flutter", "token_count": 26264 }
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:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestFlowDelegate extends FlowDelegate { TestFlowDelegate({required this.startOffset}) : super(repaint: startOffset); final Animation<double> startOffset; @override BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) { return constraints.loosen(); } @override void paintChildren(FlowPaintingContext context) { double dy = startOffset.value; for (int i = 0; i < context.childCount; ++i) { context.paintChild(i, transform: Matrix4.translationValues(0.0, dy, 0.0)); dy += 0.75 * context.getChildSize(i)!.height; } } @override bool shouldRepaint(TestFlowDelegate oldDelegate) => startOffset == oldDelegate.startOffset; } class OpacityFlowDelegate extends FlowDelegate { OpacityFlowDelegate(this.opacity); double opacity; @override void paintChildren(FlowPaintingContext context) { for (int i = 0; i < context.childCount; ++i) { context.paintChild(i, opacity: opacity); } } @override bool shouldRepaint(OpacityFlowDelegate oldDelegate) => opacity != oldDelegate.opacity; } // OpacityFlowDelegate that paints one of its children twice class DuplicatePainterOpacityFlowDelegate extends OpacityFlowDelegate { DuplicatePainterOpacityFlowDelegate(super.opacity); @override void paintChildren(FlowPaintingContext context) { for (int i = 0; i < context.childCount; ++i) { context.paintChild(i, opacity: opacity); } if (context.childCount > 0) { context.paintChild(0, opacity: opacity); } } } void main() { testWidgets('Flow control test', (WidgetTester tester) async { final AnimationController startOffset = AnimationController.unbounded( vsync: tester, ); addTearDown(startOffset.dispose); final List<int> log = <int>[]; Widget buildBox(int i) { return GestureDetector( onTap: () { log.add(i); }, child: Container( width: 100.0, height: 100.0, color: const Color(0xFF0000FF), child: Text('$i', textDirection: TextDirection.ltr), ), ); } await tester.pumpWidget( Flow( delegate: TestFlowDelegate(startOffset: startOffset), children: <Widget>[ buildBox(0), buildBox(1), buildBox(2), buildBox(3), buildBox(4), buildBox(5), buildBox(6), ], ), ); await tester.tap(find.text('0')); expect(log, equals(<int>[0])); await tester.tap(find.text('1')); expect(log, equals(<int>[0, 1])); await tester.tap(find.text('2')); expect(log, equals(<int>[0, 1, 2])); log.clear(); await tester.tapAt(const Offset(20.0, 90.0)); expect(log, equals(<int>[1])); startOffset.value = 50.0; await tester.pump(); log.clear(); await tester.tapAt(const Offset(20.0, 90.0)); expect(log, equals(<int>[0])); }); testWidgets('paintChild gets called twice', (WidgetTester tester) async { await tester.pumpWidget( Flow( delegate: DuplicatePainterOpacityFlowDelegate(1.0), children: const <Widget>[ SizedBox(width: 100.0, height: 100.0), SizedBox(width: 100.0, height: 100.0), ], ), ); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); final FlutterError error = exception as FlutterError; expect(error.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' Cannot call paintChild twice for the same child.\n' ' The flow delegate of type DuplicatePainterOpacityFlowDelegate\n' ' attempted to paint child 0 multiple times, which is not\n' ' permitted.\n', )); }); testWidgets('Flow opacity layer', (WidgetTester tester) async { const double opacity = 0.2; await tester.pumpWidget( Flow( delegate: OpacityFlowDelegate(opacity), children: const <Widget>[ SizedBox(width: 100.0, height: 100.0), ], ), ); ContainerLayer? layer = RendererBinding.instance.renderView.debugLayer; while (layer != null && layer is! OpacityLayer) { layer = layer.firstChild as ContainerLayer?; } expect(layer, isA<OpacityLayer>()); final OpacityLayer? opacityLayer = layer as OpacityLayer?; expect(opacityLayer!.alpha, equals(opacity * 255)); expect(layer!.firstChild, isA<TransformLayer>()); }); testWidgets('Flow can set and update clipBehavior', (WidgetTester tester) async { const double opacity = 0.2; await tester.pumpWidget( Flow( delegate: OpacityFlowDelegate(opacity), children: const <Widget>[ SizedBox(width: 100.0, height: 100.0), ], ), ); // By default, clipBehavior should be Clip.hardEdge final RenderFlow renderObject = tester.renderObject(find.byType(Flow)); expect(renderObject.clipBehavior, equals(Clip.hardEdge)); for (final Clip clip in Clip.values) { await tester.pumpWidget( Flow( delegate: OpacityFlowDelegate(opacity), clipBehavior: clip, children: const <Widget>[ SizedBox(width: 100.0, height: 100.0), ], ), ); expect(renderObject.clipBehavior, clip); } }); testWidgets('Flow.unwrapped can set and update clipBehavior', (WidgetTester tester) async { const double opacity = 0.2; await tester.pumpWidget( Flow.unwrapped( delegate: OpacityFlowDelegate(opacity), children: const <Widget>[ SizedBox(width: 100.0, height: 100.0), ], ), ); // By default, clipBehavior should be Clip.hardEdge final RenderFlow renderObject = tester.renderObject(find.byType(Flow)); expect(renderObject.clipBehavior, equals(Clip.hardEdge)); for (final Clip clip in Clip.values) { await tester.pumpWidget( Flow.unwrapped( delegate: OpacityFlowDelegate(opacity), clipBehavior: clip, children: const <Widget>[ SizedBox(width: 100.0, height: 100.0), ], ), ); expect(renderObject.clipBehavior, clip); } }); }
flutter/packages/flutter/test/widgets/flow_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/flow_test.dart", "repo_id": "flutter", "token_count": 2625 }
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 'dart:ui' as ui; import 'package:flutter/cupertino.dart'; 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 '../painting/image_test_utils.dart' show TestImageProvider; Future<ui.Image> createTestImage() { final ui.Paint paint = ui.Paint() ..style = ui.PaintingStyle.stroke ..strokeWidth = 1.0; final ui.PictureRecorder recorder = ui.PictureRecorder(); final ui.Canvas pictureCanvas = ui.Canvas(recorder); pictureCanvas.drawCircle(Offset.zero, 20.0, paint); final ui.Picture picture = recorder.endRecording(); return picture.toImage(300, 300); } Key firstKey = const Key('first'); Key secondKey = const Key('second'); Key thirdKey = const Key('third'); Key simpleKey = const Key('simple'); Key homeRouteKey = const Key('homeRoute'); Key routeTwoKey = const Key('routeTwo'); Key routeThreeKey = const Key('routeThree'); bool transitionFromUserGestures = false; final Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{ '/': (BuildContext context) => Material( child: ListView( key: homeRouteKey, children: <Widget>[ const SizedBox(height: 100.0, width: 100.0), Card(child: Hero( tag: 'a', transitionOnUserGestures: transitionFromUserGestures, child: SizedBox(height: 100.0, width: 100.0, key: firstKey), )), const SizedBox(height: 100.0, width: 100.0), TextButton( child: const Text('two'), onPressed: () { Navigator.pushNamed(context, '/two'); }, ), TextButton( child: const Text('twoInset'), onPressed: () { Navigator.pushNamed(context, '/twoInset'); }, ), TextButton( child: const Text('simple'), onPressed: () { Navigator.pushNamed(context, '/simple'); }, ), ], ), ), '/two': (BuildContext context) => Material( child: ListView( key: routeTwoKey, children: <Widget>[ TextButton( child: const Text('pop'), onPressed: () { Navigator.pop(context); }, ), const SizedBox(height: 150.0, width: 150.0), Card(child: Hero( tag: 'a', transitionOnUserGestures: transitionFromUserGestures, child: SizedBox(height: 150.0, width: 150.0, key: secondKey), )), const SizedBox(height: 150.0, width: 150.0), TextButton( child: const Text('three'), onPressed: () { Navigator.push(context, ThreeRoute()); }, ), ], ), ), // This route is the same as /two except that Hero 'a' is shifted to the right by // 50 pixels. When the hero's in-flight bounds between / and /twoInset are animated // using MaterialRectArcTween (the default) they'll follow a different path // then when the flight starts at /twoInset and returns to /. '/twoInset': (BuildContext context) => Material( child: ListView( key: routeTwoKey, children: <Widget>[ TextButton( child: const Text('pop'), onPressed: () { Navigator.pop(context); }, ), const SizedBox(height: 150.0, width: 150.0), Card( child: Padding( padding: const EdgeInsets.only(left: 50.0), child: Hero( tag: 'a', transitionOnUserGestures: transitionFromUserGestures, child: SizedBox(height: 150.0, width: 150.0, key: secondKey), ), ), ), const SizedBox(height: 150.0, width: 150.0), TextButton( child: const Text('three'), onPressed: () { Navigator.push(context, ThreeRoute()); }, ), ], ), ), // This route is the same as /two except that Hero 'a' is shifted to the right by // 50 pixels. When the hero's in-flight bounds between / and /twoInset are animated // using MaterialRectArcTween (the default) they'll follow a different path // then when the flight starts at /twoInset and returns to /. '/simple': (BuildContext context) => CupertinoPageScaffold( child: Center( child: Hero( tag: 'a', transitionOnUserGestures: transitionFromUserGestures, child: SizedBox(height: 150.0, width: 150.0, key: simpleKey), ), ), ), }; class ThreeRoute extends MaterialPageRoute<void> { ThreeRoute() : super(builder: (BuildContext context) { return Material( key: routeThreeKey, child: ListView( children: <Widget>[ const SizedBox(height: 200.0, width: 200.0), Card(child: Hero(tag: 'a', child: SizedBox(height: 200.0, width: 200.0, key: thirdKey))), const SizedBox(height: 200.0, width: 200.0), ], ), ); }); } class MutatingRoute extends MaterialPageRoute<void> { MutatingRoute() : super(builder: (BuildContext context) { return Hero(tag: 'a', key: UniqueKey(), child: const Text('MutatingRoute')); }); void markNeedsBuild() { setState(() { // Trigger a rebuild }); } } class _SimpleStatefulWidget extends StatefulWidget { const _SimpleStatefulWidget({ super.key }); @override _SimpleState createState() => _SimpleState(); } class _SimpleState extends State<_SimpleStatefulWidget> { int state = 0; @override Widget build(BuildContext context) => Text(state.toString()); } class MyStatefulWidget extends StatefulWidget { const MyStatefulWidget({ super.key, this.value = '123' }); final String value; @override MyStatefulWidgetState createState() => MyStatefulWidgetState(); } class MyStatefulWidgetState extends State<MyStatefulWidget> { @override Widget build(BuildContext context) => Text(widget.value); } Future<void> main() async { final ui.Image testImage = await createTestImage(); setUp(() { transitionFromUserGestures = false; }); testWidgets('Heroes animate', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp(routes: routes)); // the initial setup. expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), findsNothing); await tester.tap(find.text('two')); await tester.pump(); // begin navigation // at this stage, the second route is offstage, so that we can form the // hero party. expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey, skipOffstage: false), isOffstage); expect(find.byKey(secondKey, skipOffstage: false), isInCard); await tester.pump(); // at this stage, the heroes have just gone on their journey, we are // seeing them at t=16ms. The original page no longer contains the hero. expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), findsOneWidget); expect(find.byKey(secondKey), isNotInCard); expect(find.byKey(secondKey), isOnstage); await tester.pump(); // t=32ms for the journey. Surely they are still at it. expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), findsOneWidget); expect(find.byKey(secondKey), findsOneWidget); expect(find.byKey(secondKey), isNotInCard); expect(find.byKey(secondKey), isOnstage); await tester.pump(const Duration(seconds: 1)); // t=1.032s for the journey. The journey has ended (it ends this frame, in // fact). The hero should now be in the new page, onstage. The original // widget will be back as well now (though not visible). expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); await tester.pump(); // Should not change anything. expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); // Now move on to view 3 await tester.tap(find.text('three')); await tester.pump(); // begin navigation // at this stage, the second route is offstage, so that we can form the // hero party. expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); expect(find.byKey(thirdKey, skipOffstage: false), isOffstage); expect(find.byKey(thirdKey, skipOffstage: false), isInCard); await tester.pump(); // at this stage, the heroes have just gone on their journey, we are // seeing them at t=16ms. The original page no longer contains the hero. expect(find.byKey(secondKey), findsNothing); expect(find.byKey(thirdKey), isOnstage); expect(find.byKey(thirdKey), isNotInCard); await tester.pump(); // t=32ms for the journey. Surely they are still at it. expect(find.byKey(secondKey), findsNothing); expect(find.byKey(thirdKey), isOnstage); expect(find.byKey(thirdKey), isNotInCard); await tester.pump(const Duration(seconds: 1)); // t=1.032s for the journey. The journey has ended (it ends this frame, in // fact). The hero should now be in the new page, onstage. expect(find.byKey(secondKey), findsNothing); expect(find.byKey(thirdKey), isOnstage); expect(find.byKey(thirdKey), isInCard); await tester.pump(); // Should not change anything. expect(find.byKey(secondKey), findsNothing); expect(find.byKey(thirdKey), isOnstage); expect(find.byKey(thirdKey), isInCard); }); testWidgets('Heroes still animate after hero controller is swapped.', (WidgetTester tester) async { final GlobalKey<NavigatorState> key = GlobalKey<NavigatorState>(); final UniqueKey heroKey = UniqueKey(); final HeroController controller1 = HeroController(); addTearDown(controller1.dispose); await tester.pumpWidget( HeroControllerScope( controller: controller1, child: TestDependencies( child: Navigator( key: key, initialRoute: 'navigator1', onGenerateRoute: (RouteSettings s) { return MaterialPageRoute<void>( builder: (BuildContext c) { return Hero( tag: 'hero', child: Container(), flightShuttleBuilder: ( BuildContext flightContext, Animation<double> animation, HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, ) { return Container(key: heroKey); }, ); }, settings: s, ); }, ), ), ), ); key.currentState!.push(MaterialPageRoute<void>( builder: (BuildContext c) { return Hero( tag: 'hero', child: Container(), flightShuttleBuilder: ( BuildContext flightContext, Animation<double> animation, HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, ) { return Container(key: heroKey); }, ); }, )); expect(find.byKey(heroKey), findsNothing); // Begins the navigation await tester.pump(); await tester.pump(const Duration(milliseconds: 30)); expect(find.byKey(heroKey), isOnstage); final HeroController controller2 = HeroController(); addTearDown(controller2.dispose); // Pumps a new hero controller. await tester.pumpWidget( HeroControllerScope( controller: controller2, child: TestDependencies( child: Navigator( key: key, initialRoute: 'navigator1', onGenerateRoute: (RouteSettings s) { return MaterialPageRoute<void>( builder: (BuildContext c) { return Hero( tag: 'hero', child: Container(), flightShuttleBuilder: ( BuildContext flightContext, Animation<double> animation, HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, ) { return Container(key: heroKey); }, ); }, settings: s, ); }, ), ), ), ); // The original animation still flies. expect(find.byKey(heroKey), isOnstage); // Waits for the animation finishes. await tester.pumpAndSettle(); expect(find.byKey(heroKey), findsNothing); }); testWidgets('Heroes animate should hide original hero', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp(routes: routes)); // Checks initial state. expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), findsNothing); await tester.tap(find.text('two')); await tester.pumpAndSettle(); // Waits for transition finishes. expect(find.byKey(firstKey), findsNothing); final Offstage first = tester.widget( find.ancestor( of: find.byKey(firstKey, skipOffstage: false), matching: find.byType(Offstage, skipOffstage: false), ).first, ); // Original hero should stay hidden. expect(first.offstage, isTrue); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); }); testWidgets('Destination hero is rebuilt midflight', (WidgetTester tester) async { final MutatingRoute route = MutatingRoute(); await tester.pumpWidget(MaterialApp( home: Material( child: ListView( children: <Widget>[ const Hero(tag: 'a', child: Text('foo')), Builder(builder: (BuildContext context) { return TextButton(child: const Text('two'), onPressed: () => Navigator.push(context, route)); }), ], ), ), )); await tester.tap(find.text('two')); await tester.pump(const Duration(milliseconds: 10)); route.markNeedsBuild(); await tester.pump(const Duration(milliseconds: 10)); await tester.pump(const Duration(seconds: 1)); }); testWidgets('Heroes animation is fastOutSlowIn', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp(routes: routes)); await tester.tap(find.text('two')); await tester.pump(); // begin navigation // Expect the height of the secondKey Hero to vary from 100 to 150 // over duration and according to curve. const Duration duration = Duration(milliseconds: 300); const Curve curve = Curves.fastOutSlowIn; final double initialHeight = tester.getSize(find.byKey(firstKey, skipOffstage: false)).height; final double finalHeight = tester.getSize(find.byKey(secondKey, skipOffstage: false)).height; final double deltaHeight = finalHeight - initialHeight; const double epsilon = 0.001; await tester.pump(duration * 0.25); expect( tester.getSize(find.byKey(secondKey)).height, moreOrLessEquals(curve.transform(0.25) * deltaHeight + initialHeight, epsilon: epsilon), ); await tester.pump(duration * 0.25); expect( tester.getSize(find.byKey(secondKey)).height, moreOrLessEquals(curve.transform(0.50) * deltaHeight + initialHeight, epsilon: epsilon), ); await tester.pump(duration * 0.25); expect( tester.getSize(find.byKey(secondKey)).height, moreOrLessEquals(curve.transform(0.75) * deltaHeight + initialHeight, epsilon: epsilon), ); await tester.pump(duration * 0.25); expect( tester.getSize(find.byKey(secondKey)).height, moreOrLessEquals(curve.transform(1.0) * deltaHeight + initialHeight, epsilon: epsilon), ); }); testWidgets('Heroes are not interactive', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(MaterialApp( home: Center( child: Hero( tag: 'foo', child: GestureDetector( onTap: () { log.add('foo'); }, child: const SizedBox( width: 100.0, height: 100.0, child: Text('foo'), ), ), ), ), routes: <String, WidgetBuilder>{ '/next': (BuildContext context) { return Align( alignment: Alignment.topLeft, child: Hero( tag: 'foo', child: GestureDetector( onTap: () { log.add('bar'); }, child: const SizedBox( width: 100.0, height: 150.0, child: Text('bar'), ), ), ), ); }, }, )); expect(log, isEmpty); await tester.tap(find.text('foo')); expect(log, equals(<String>['foo'])); log.clear(); final NavigatorState navigator = tester.state(find.byType(Navigator)); navigator.pushNamed('/next'); expect(log, isEmpty); await tester.tap(find.text('foo', skipOffstage: false), warnIfMissed: false); expect(log, isEmpty); await tester.pump(const Duration(milliseconds: 10)); await tester.tap(find.text('foo', skipOffstage: false), warnIfMissed: false); expect(log, isEmpty); await tester.tap(find.text('bar', skipOffstage: false), warnIfMissed: false); expect(log, isEmpty); await tester.pump(const Duration(milliseconds: 10)); expect(find.text('foo'), findsNothing); await tester.tap(find.text('bar', skipOffstage: false), warnIfMissed: false); expect(log, isEmpty); await tester.pump(const Duration(seconds: 1)); expect(find.text('foo'), findsNothing); await tester.tap(find.text('bar')); expect(log, equals(<String>['bar'])); }); testWidgets('Popping on first frame does not cause hero observer to crash', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( settings: settings, builder: (BuildContext context) => Hero(tag: 'test', child: Container()), ); }, )); await tester.pump(); final Finder heroes = find.byType(Hero); expect(heroes, findsOneWidget); Navigator.pushNamed(heroes.evaluate().first, 'test'); await tester.pump(); // adds the new page to the tree... Navigator.pop(heroes.evaluate().first); await tester.pump(); // ...and removes it straight away (since it's already at 0.0) }); testWidgets('Overlapping starting and ending a hero transition works ok', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( settings: settings, builder: (BuildContext context) => Hero(tag: 'test', child: Container()), ); }, )); await tester.pump(); final Finder heroes = find.byType(Hero); expect(heroes, findsOneWidget); Navigator.pushNamed(heroes.evaluate().first, 'test'); await tester.pump(); await tester.pump(const Duration(hours: 1)); Navigator.pushNamed(heroes.evaluate().first, 'test'); await tester.pump(); await tester.pump(const Duration(hours: 1)); Navigator.pop(heroes.evaluate().first); await tester.pump(); Navigator.pop(heroes.evaluate().first); await tester.pump(const Duration(hours: 1)); // so the first transition is finished, but the second hasn't started await tester.pump(); }); testWidgets('One route, two heroes, same tag, throws', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: ListView( children: <Widget>[ const Hero(tag: 'a', child: Text('a')), const Hero(tag: 'a', child: Text('a too')), Builder( builder: (BuildContext context) { return TextButton( child: const Text('push'), onPressed: () { Navigator.push(context, PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) { return const Text('fail'); }, )); }, ); }, ), ], ), ), )); await tester.tap(find.text('push')); await tester.pump(); final dynamic exception = tester.takeException(); expect(exception, isFlutterError); final FlutterError error = exception as FlutterError; expect(error.diagnostics.length, 3); final DiagnosticsNode last = error.diagnostics.last; expect(last, isA<DiagnosticsProperty<StatefulElement>>()); expect( last.toStringDeep(), equalsIgnoringHashCodes( '# Here is the subtree for one of the offending heroes: Hero\n', ), ); expect(last.style, DiagnosticsTreeStyle.dense); expect( error.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' There are multiple heroes that share the same tag within a\n' ' subtree.\n' ' Within each subtree for which heroes are to be animated (i.e. a\n' ' PageRoute subtree), each Hero must have a unique non-null tag.\n' ' In this case, multiple heroes had the following tag: a\n' ' ├# Here is the subtree for one of the offending heroes: Hero\n', ), ); }); testWidgets('Hero push transition interrupted by a pop', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( routes: routes, )); // Initially the firstKey Card on the '/' route is visible expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), findsNothing); // Pushes MaterialPageRoute '/two'. await tester.tap(find.text('two')); // Start the flight of Hero 'a' from route '/' to route '/two'. Route '/two' // is now offstage. await tester.pump(); final double initialHeight = tester.getSize(find.byKey(firstKey)).height; final double finalHeight = tester.getSize(find.byKey(secondKey, skipOffstage: false)).height; expect(finalHeight, greaterThan(initialHeight)); // simplify the checks below // Build the first hero animation frame in the navigator's overlay. await tester.pump(); // At this point the hero widgets have been replaced by placeholders // and the destination hero has been moved to the overlay. expect(find.descendant(of: find.byKey(homeRouteKey), matching: find.byKey(firstKey)), findsNothing); expect(find.descendant(of: find.byKey(routeTwoKey), matching: find.byKey(secondKey)), findsNothing); expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), isOnstage); // The duration of a MaterialPageRoute's transition is 300ms. // At 150ms Hero 'a' is mid-flight. await tester.pump(const Duration(milliseconds: 150)); final double height150ms = tester.getSize(find.byKey(secondKey)).height; expect(height150ms, greaterThan(initialHeight)); expect(height150ms, lessThan(finalHeight)); // Pop route '/two' before the push transition to '/two' has finished. await tester.tap(find.text('pop')); // Restart the flight of Hero 'a'. Now it's flying from route '/two' to // route '/'. await tester.pump(); // After flying in the opposite direction for 50ms Hero 'a' will // be smaller than it was, but bigger than its initial size. await tester.pump(const Duration(milliseconds: 50)); final double height100ms = tester.getSize(find.byKey(secondKey)).height; expect(height100ms, lessThan(height150ms)); expect(finalHeight, greaterThan(height100ms)); // Hero a's return flight at 149ms. The outgoing (push) flight took // 150ms so we should be just about back to where Hero 'a' started. const double epsilon = 0.001; await tester.pump(const Duration(milliseconds: 99)); moreOrLessEquals(tester.getSize(find.byKey(secondKey)).height - initialHeight, epsilon: epsilon); // The flight is finished. We're back to where we started. await tester.pump(const Duration(milliseconds: 300)); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), findsNothing); }); testWidgets('Hero pop transition interrupted by a push', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( routes: routes, theme: ThemeData(pageTransitionsTheme: const PageTransitionsTheme( builders: <TargetPlatform, PageTransitionsBuilder>{ TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), }, )), ), ); // Pushes MaterialPageRoute '/two'. await tester.tap(find.text('two')); await tester.pump(); await tester.pump(const Duration(seconds: 1)); // Now the secondKey Card on the '/2' route is visible expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); expect(find.byKey(firstKey), findsNothing); // Pop MaterialPageRoute '/two'. await tester.tap(find.text('pop')); // Start the flight of Hero 'a' from route '/two' to route '/'. Route '/two' // is now offstage. await tester.pump(); final double initialHeight = tester.getSize(find.byKey(secondKey)).height; final double finalHeight = tester.getSize(find.byKey(firstKey, skipOffstage: false)).height; expect(finalHeight, lessThan(initialHeight)); // simplify the checks below // Build the first hero animation frame in the navigator's overlay. await tester.pump(); // At this point the hero widgets have been replaced by placeholders // and the destination hero has been moved to the overlay. expect(find.descendant(of: find.byKey(homeRouteKey), matching: find.byKey(firstKey)), findsNothing); expect(find.descendant(of: find.byKey(routeTwoKey), matching: find.byKey(secondKey)), findsNothing); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(secondKey), findsNothing); // The duration of a MaterialPageRoute's transition is 300ms. // At 150ms Hero 'a' is mid-flight. await tester.pump(const Duration(milliseconds: 150)); final double height150ms = tester.getSize(find.byKey(firstKey)).height; expect(height150ms, lessThan(initialHeight)); expect(height150ms, greaterThan(finalHeight)); // Push route '/two' before the pop transition from '/two' has finished. await tester.tap(find.text('two')); // Restart the flight of Hero 'a'. Now it's flying from route '/' to // route '/two'. await tester.pump(); // After flying in the opposite direction for 50ms Hero 'a' will // be smaller than it was, but bigger than its initial size. await tester.pump(const Duration(milliseconds: 50)); final double height200ms = tester.getSize(find.byKey(firstKey)).height; expect(height200ms, greaterThan(height150ms)); expect(finalHeight, lessThan(height200ms)); // Hero a's return flight at 149ms. The outgoing (push) flight took // 150ms so we should be just about back to where Hero 'a' started. const double epsilon = 0.001; await tester.pump(const Duration(milliseconds: 99)); moreOrLessEquals(tester.getSize(find.byKey(firstKey)).height - initialHeight, epsilon: epsilon); // The flight is finished. We're back to where we started. await tester.pump(const Duration(milliseconds: 300)); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); expect(find.byKey(firstKey), findsNothing); }); testWidgets('Destination hero disappears mid-flight', (WidgetTester tester) async { const Key homeHeroKey = Key('home hero'); const Key routeHeroKey = Key('route hero'); bool routeIncludesHero = true; late StateSetter heroCardSetState; // Show a 200x200 Hero tagged 'H', with key routeHeroKey final MaterialPageRoute<void> route = MaterialPageRoute<void>( builder: (BuildContext context) { return Material( child: ListView( children: <Widget>[ StatefulBuilder( builder: (BuildContext context, StateSetter setState) { heroCardSetState = setState; return Card( child: routeIncludesHero ? const Hero(tag: 'H', child: SizedBox(key: routeHeroKey, height: 200.0, width: 200.0)) : const SizedBox(height: 200.0, width: 200.0), ); }, ), TextButton( child: const Text('POP'), onPressed: () { Navigator.pop(context); }, ), ], ), ); }, ); // Show a 100x100 Hero tagged 'H' with key homeHeroKey await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { // Navigator.push() needs context return ListView( children: <Widget> [ const Card( child: Hero(tag: 'H', child: SizedBox(key: homeHeroKey, height: 100.0, width: 100.0)), ), TextButton( child: const Text('PUSH'), onPressed: () { Navigator.push(context, route); }, ), ], ); }, ), ), ), ); // Pushes route await tester.tap(find.text('PUSH')); await tester.pump(); await tester.pump(); final double initialHeight = tester.getSize(find.byKey(routeHeroKey)).height; await tester.pump(const Duration(milliseconds: 10)); double midflightHeight = tester.getSize(find.byKey(routeHeroKey)).height; expect(midflightHeight, greaterThan(initialHeight)); expect(midflightHeight, lessThan(200.0)); await tester.pump(const Duration(milliseconds: 300)); await tester.pump(); double finalHeight = tester.getSize(find.byKey(routeHeroKey)).height; expect(finalHeight, 200.0); // Complete the flight await tester.pump(const Duration(milliseconds: 100)); // Rebuild route with its Hero heroCardSetState(() { routeIncludesHero = true; }); await tester.pump(); // Pops route await tester.tap(find.text('POP')); await tester.pump(); await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); midflightHeight = tester.getSize(find.byKey(homeHeroKey)).height; expect(midflightHeight, lessThan(finalHeight)); expect(midflightHeight, greaterThan(100.0)); // Remove the destination hero midflight heroCardSetState(() { routeIncludesHero = false; }); await tester.pump(); await tester.pump(const Duration(milliseconds: 300)); finalHeight = tester.getSize(find.byKey(homeHeroKey)).height; expect(finalHeight, 100.0); }); testWidgets('Destination hero scrolls mid-flight', (WidgetTester tester) async { const Key homeHeroKey = Key('home hero'); const Key routeHeroKey = Key('route hero'); const Key routeContainerKey = Key('route hero container'); // Show a 200x200 Hero tagged 'H', with key routeHeroKey final MaterialPageRoute<void> route = MaterialPageRoute<void>( builder: (BuildContext context) { return Material( child: ListView( children: <Widget>[ const SizedBox(height: 100.0), // This container will appear at Y=100 Container( key: routeContainerKey, child: const Hero(tag: 'H', child: SizedBox(key: routeHeroKey, height: 200.0, width: 200.0)), ), TextButton( child: const Text('POP'), onPressed: () { Navigator.pop(context); }, ), const SizedBox(height: 600.0), ], ), ); }, ); // Show a 100x100 Hero tagged 'H' with key homeHeroKey await tester.pumpWidget( MaterialApp( theme: ThemeData( pageTransitionsTheme: const PageTransitionsTheme( builders: <TargetPlatform, PageTransitionsBuilder>{ TargetPlatform.android: FadeUpwardsPageTransitionsBuilder(), }, ), ), home: Scaffold( body: Builder( builder: (BuildContext context) { // Navigator.push() needs context return ListView( children: <Widget> [ const SizedBox(height: 200.0), // This container will appear at Y=200 const Hero(tag: 'H', child: SizedBox(key: homeHeroKey, height: 100.0, width: 100.0)), TextButton( child: const Text('PUSH'), onPressed: () { Navigator.push(context, route); }, ), const SizedBox(height: 600.0), ], ); }, ), ), ), ); // Pushes route await tester.tap(find.text('PUSH')); await tester.pump(); await tester.pump(); final double initialY = tester.getTopLeft(find.byKey(routeHeroKey)).dy; expect(initialY, 200.0); await tester.pump(const Duration(milliseconds: 100)); final double yAt100ms = tester.getTopLeft(find.byKey(routeHeroKey)).dy; expect(yAt100ms, lessThan(200.0)); expect(yAt100ms, greaterThan(100.0)); // Scroll the target upwards by 25 pixels. The Hero flight's Y coordinate // will be redirected from 100 to 75. await tester.drag(find.byKey(routeContainerKey), const Offset(0.0, -25.0), warnIfMissed: false); // the container itself wouldn't be hit await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); final double yAt110ms = tester.getTopLeft(find.byKey(routeHeroKey)).dy; expect(yAt110ms, lessThan(yAt100ms)); expect(yAt110ms, greaterThan(75.0)); await tester.pump(const Duration(milliseconds: 300)); await tester.pump(); final double finalHeroY = tester.getTopLeft(find.byKey(routeHeroKey)).dy; expect(finalHeroY, 75.0); // 100 less 25 for the scroll }); testWidgets('Destination hero scrolls out of view mid-flight', (WidgetTester tester) async { const Key homeHeroKey = Key('home hero'); const Key routeHeroKey = Key('route hero'); const Key routeContainerKey = Key('route hero container'); // Show a 200x200 Hero tagged 'H', with key routeHeroKey final MaterialPageRoute<void> route = MaterialPageRoute<void>( builder: (BuildContext context) { return Material( child: ListView( cacheExtent: 0.0, children: <Widget>[ const SizedBox(height: 100.0), // This container will appear at Y=100 Container( key: routeContainerKey, child: const Hero(tag: 'H', child: SizedBox(key: routeHeroKey, height: 200.0, width: 200.0)), ), const SizedBox(height: 800.0), ], ), ); }, ); // Show a 100x100 Hero tagged 'H' with key homeHeroKey await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { // Navigator.push() needs context return ListView( children: <Widget> [ const SizedBox(height: 200.0), // This container will appear at Y=200 const Hero(tag: 'H', child: SizedBox(key: homeHeroKey, height: 100.0, width: 100.0)), TextButton( child: const Text('PUSH'), onPressed: () { Navigator.push(context, route); }, ), ], ); }, ), ), ), ); // Pushes route await tester.tap(find.text('PUSH')); await tester.pump(); await tester.pump(); final double initialY = tester.getTopLeft(find.byKey(routeHeroKey)).dy; expect(initialY, 200.0); await tester.pump(const Duration(milliseconds: 100)); final double yAt100ms = tester.getTopLeft(find.byKey(routeHeroKey)).dy; expect(yAt100ms, lessThan(200.0)); expect(yAt100ms, greaterThan(100.0)); await tester.drag(find.byKey(routeContainerKey), const Offset(0.0, -400.0), warnIfMissed: false); // the container itself wouldn't be hit await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); expect(find.byKey(routeContainerKey), findsNothing); // Scrolled off the top // Flight continues (the hero will fade out) even though the destination // no longer exists. final double yAt110ms = tester.getTopLeft(find.byKey(routeHeroKey)).dy; expect(yAt110ms, lessThan(yAt100ms)); expect(yAt110ms, greaterThan(100.0)); await tester.pump(const Duration(milliseconds: 300)); await tester.pump(); expect(find.byKey(routeHeroKey), findsNothing); }); testWidgets('Aborted flight', (WidgetTester tester) async { // See https://github.com/flutter/flutter/issues/5798 const Key heroABKey = Key('AB hero'); const Key heroBCKey = Key('BC hero'); // Show a 150x150 Hero tagged 'BC' final MaterialPageRoute<void> routeC = MaterialPageRoute<void>( builder: (BuildContext context) { return Material( child: ListView( children: const <Widget>[ // This container will appear at Y=0 Hero( tag: 'BC', child: SizedBox( key: heroBCKey, height: 150.0, child: Text('Hero'), ), ), SizedBox(height: 800.0), ], ), ); }, ); // Show a height=200 Hero tagged 'AB' and a height=50 Hero tagged 'BC' final MaterialPageRoute<void> routeB = MaterialPageRoute<void>( builder: (BuildContext context) { return Material( child: ListView( children: <Widget>[ const SizedBox(height: 100.0), // This container will appear at Y=100 const Hero( tag: 'AB', child: SizedBox( key: heroABKey, height: 200.0, child: Text('Hero'), ), ), TextButton( child: const Text('PUSH C'), onPressed: () { Navigator.push(context, routeC); }, ), const Hero( tag: 'BC', child: SizedBox( height: 150.0, child: Text('Hero'), ), ), const SizedBox(height: 800.0), ], ), ); }, ); // Show a 100x100 Hero tagged 'AB' with key heroABKey await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { // Navigator.push() needs context return ListView( children: <Widget> [ const SizedBox(height: 200.0), // This container will appear at Y=200 const Hero( tag: 'AB', child: SizedBox( height: 100.0, width: 100.0, child: Text('Hero'), ), ), TextButton( child: const Text('PUSH B'), onPressed: () { Navigator.push(context, routeB); }, ), ], ); }, ), ), ), ); // Pushes routeB await tester.tap(find.text('PUSH B')); await tester.pump(); await tester.pump(); final double initialY = tester.getTopLeft(find.byKey(heroABKey)).dy; expect(initialY, 200.0); await tester.pump(const Duration(milliseconds: 200)); final double yAt200ms = tester.getTopLeft(find.byKey(heroABKey)).dy; // Hero AB is mid flight. expect(yAt200ms, lessThan(200.0)); expect(yAt200ms, greaterThan(100.0)); // Pushes route C, causes hero AB's flight to abort, hero BC's flight to start await tester.tap(find.text('PUSH C')); await tester.pump(); await tester.pump(); // Hero AB's aborted flight finishes where it was expected although // it's been faded out. await tester.pump(const Duration(milliseconds: 100)); expect(tester.getTopLeft(find.byKey(heroABKey)).dy, 100.0); bool isVisible(RenderObject node) { RenderObject? currentNode = node; while (currentNode != null) { if (currentNode is RenderAnimatedOpacity && currentNode.opacity.value == 0) { return false; } currentNode = currentNode.parent; } return true; } // Of all heroes only one should be visible now. final Iterable<RenderObject> renderObjects = find.text('Hero').evaluate().map((Element e) => e.renderObject!); expect(renderObjects.where(isVisible).length, 1); // Hero BC's flight finishes normally. await tester.pump(const Duration(milliseconds: 300)); expect(tester.getTopLeft(find.byKey(heroBCKey)).dy, 0.0); }); testWidgets('Stateful hero child state survives flight', (WidgetTester tester) async { final MaterialPageRoute<void> route = MaterialPageRoute<void>( builder: (BuildContext context) { return Material( child: ListView( children: <Widget>[ const Card( child: Hero( tag: 'H', child: SizedBox( height: 200.0, child: MyStatefulWidget(value: '456'), ), ), ), TextButton( child: const Text('POP'), onPressed: () { Navigator.pop(context); }, ), ], ), ); }, ); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { // Navigator.push() needs context return ListView( children: <Widget> [ const Card( child: Hero( tag: 'H', child: SizedBox( height: 100.0, child: MyStatefulWidget(value: '456'), ), ), ), TextButton( child: const Text('PUSH'), onPressed: () { Navigator.push(context, route); }, ), ], ); }, ), ), ), ); expect(find.text('456'), findsOneWidget); // Push route. await tester.tap(find.text('PUSH')); await tester.pump(); await tester.pump(); // Push flight underway. await tester.pump(const Duration(milliseconds: 100)); // Visible in the hero animation. expect(find.text('456'), findsOneWidget); // Push flight finished. await tester.pump(const Duration(milliseconds: 300)); expect(find.text('456'), findsOneWidget); // Pop route. await tester.tap(find.text('POP')); await tester.pump(); await tester.pump(); // Pop flight underway. await tester.pump(const Duration(milliseconds: 100)); expect(find.text('456'), findsOneWidget); // Pop flight finished await tester.pump(const Duration(milliseconds: 300)); expect(find.text('456'), findsOneWidget); }); testWidgets('Hero createRectTween', (WidgetTester tester) async { RectTween createRectTween(Rect? begin, Rect? end) { return MaterialRectCenterArcTween(begin: begin, end: end); } final Map<String, WidgetBuilder> createRectTweenHeroRoutes = <String, WidgetBuilder>{ '/': (BuildContext context) => Material( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Hero( tag: 'a', createRectTween: createRectTween, child: SizedBox(height: 100.0, width: 100.0, key: firstKey), ), TextButton( child: const Text('two'), onPressed: () { Navigator.pushNamed(context, '/two'); }, ), ], ), ), '/two': (BuildContext context) => Material( child: Column( children: <Widget>[ SizedBox( height: 200.0, child: TextButton( child: const Text('pop'), onPressed: () { Navigator.pop(context); }, ), ), Hero( tag: 'a', createRectTween: createRectTween, child: SizedBox(height: 200.0, width: 100.0, key: secondKey), ), ], ), ), }; await tester.pumpWidget(MaterialApp(routes: createRectTweenHeroRoutes)); expect(tester.getCenter(find.byKey(firstKey)), const Offset(50.0, 50.0)); const double epsilon = 0.001; const Duration duration = Duration(milliseconds: 300); const Curve curve = Curves.fastOutSlowIn; final MaterialPointArcTween pushCenterTween = MaterialPointArcTween( begin: const Offset(50.0, 50.0), end: const Offset(400.0, 300.0), ); await tester.tap(find.text('two')); await tester.pump(); // begin navigation // Verify that the center of the secondKey Hero flies along the // pushCenterTween arc for the push /two flight. await tester.pump(); expect(tester.getCenter(find.byKey(secondKey)), const Offset(50.0, 50.0)); await tester.pump(duration * 0.25); Offset actualHeroCenter = tester.getCenter(find.byKey(secondKey)); Offset predictedHeroCenter = pushCenterTween.lerp(curve.transform(0.25)); expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter)); await tester.pump(duration * 0.25); actualHeroCenter = tester.getCenter(find.byKey(secondKey)); predictedHeroCenter = pushCenterTween.lerp(curve.transform(0.5)); expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter)); await tester.pump(duration * 0.25); actualHeroCenter = tester.getCenter(find.byKey(secondKey)); predictedHeroCenter = pushCenterTween.lerp(curve.transform(0.75)); expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter)); await tester.pumpAndSettle(); expect(tester.getCenter(find.byKey(secondKey)), const Offset(400.0, 300.0)); // Verify that the center of the firstKey Hero flies along the // pushCenterTween arc for the pop /two flight. await tester.tap(find.text('pop')); await tester.pump(); // begin navigation final MaterialPointArcTween popCenterTween = MaterialPointArcTween( begin: const Offset(400.0, 300.0), end: const Offset(50.0, 50.0), ); await tester.pump(); expect(tester.getCenter(find.byKey(firstKey)), const Offset(400.0, 300.0)); await tester.pump(duration * 0.25); actualHeroCenter = tester.getCenter(find.byKey(firstKey)); predictedHeroCenter = popCenterTween.lerp(curve.transform(0.25)); expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter)); await tester.pump(duration * 0.25); actualHeroCenter = tester.getCenter(find.byKey(firstKey)); predictedHeroCenter = popCenterTween.lerp(curve.transform(0.5)); expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter)); await tester.pump(duration * 0.25); actualHeroCenter = tester.getCenter(find.byKey(firstKey)); predictedHeroCenter = popCenterTween.lerp(curve.transform(0.75)); expect(actualHeroCenter, within<Offset>(distance: epsilon, from: predictedHeroCenter)); await tester.pumpAndSettle(); expect(tester.getCenter(find.byKey(firstKey)), const Offset(50.0, 50.0)); }); testWidgets('Hero createRectTween for Navigator that is not full screen', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/25272 RectTween createRectTween(Rect? begin, Rect? end) { return RectTween(begin: begin, end: end); } final Map<String, WidgetBuilder> createRectTweenHeroRoutes = <String, WidgetBuilder>{ '/': (BuildContext context) => Material( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Hero( tag: 'a', createRectTween: createRectTween, child: SizedBox(height: 100.0, width: 100.0, key: firstKey), ), TextButton( child: const Text('two'), onPressed: () { Navigator.pushNamed(context, '/two'); }, ), ], ), ), '/two': (BuildContext context) => Material( child: Column( children: <Widget>[ SizedBox( height: 200.0, child: TextButton( child: const Text('pop'), onPressed: () { Navigator.pop(context); }, ), ), Hero( tag: 'a', createRectTween: createRectTween, child: SizedBox(height: 200.0, width: 100.0, key: secondKey), ), ], ), ), }; const double leftPadding = 10.0; // MaterialApp and its Navigator are offset from the left await tester.pumpWidget(Padding( padding: const EdgeInsets.only(left: leftPadding), child: MaterialApp(routes: createRectTweenHeroRoutes), )); expect(tester.getCenter(find.byKey(firstKey)), const Offset(leftPadding + 50.0, 50.0)); const double epsilon = 0.001; const Duration duration = Duration(milliseconds: 300); const Curve curve = Curves.fastOutSlowIn; final RectTween pushRectTween = RectTween( begin: const Rect.fromLTWH(leftPadding, 0.0, 100.0, 100.0), end: const Rect.fromLTWH(350.0 + leftPadding / 2, 200.0, 100.0, 200.0), ); await tester.tap(find.text('two')); await tester.pump(); // begin navigation // Verify that the rect of the secondKey Hero transforms as the // pushRectTween rect for the push /two flight. await tester.pump(); expect(tester.getCenter(find.byKey(secondKey)), const Offset(50.0 + leftPadding, 50.0)); await tester.pump(duration * 0.25); Rect actualHeroRect = tester.getRect(find.byKey(secondKey)); Rect predictedHeroRect = pushRectTween.lerp(curve.transform(0.25))!; expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect)); await tester.pump(duration * 0.25); actualHeroRect = tester.getRect(find.byKey(secondKey)); predictedHeroRect = pushRectTween.lerp(curve.transform(0.5))!; expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect)); await tester.pump(duration * 0.25); actualHeroRect = tester.getRect(find.byKey(secondKey)); predictedHeroRect = pushRectTween.lerp(curve.transform(0.75))!; expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect)); await tester.pumpAndSettle(); expect(tester.getCenter(find.byKey(secondKey)), const Offset(400.0 + leftPadding / 2, 300.0)); // Verify that the rect of the firstKey Hero transforms as the // pushRectTween rect for the pop /two flight. await tester.tap(find.text('pop')); await tester.pump(); // begin navigation final RectTween popRectTween = RectTween( begin: const Rect.fromLTWH(350.0 + leftPadding / 2, 200.0, 100.0, 200.0), end: const Rect.fromLTWH(leftPadding, 0.0, 100.0, 100.0), ); await tester.pump(); expect(tester.getCenter(find.byKey(firstKey)), const Offset(400.0 + leftPadding / 2, 300.0)); await tester.pump(duration * 0.25); actualHeroRect = tester.getRect(find.byKey(firstKey)); predictedHeroRect = popRectTween.lerp(curve.transform(0.25))!; expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect)); await tester.pump(duration * 0.25); actualHeroRect = tester.getRect(find.byKey(firstKey)); predictedHeroRect = popRectTween.lerp(curve.transform(0.5))!; expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect)); await tester.pump(duration * 0.25); actualHeroRect = tester.getRect(find.byKey(firstKey)); predictedHeroRect = popRectTween.lerp(curve.transform(0.75))!; expect(actualHeroRect, within<Rect>(distance: epsilon, from: predictedHeroRect)); await tester.pumpAndSettle(); expect(tester.getCenter(find.byKey(firstKey)), const Offset(50.0 + leftPadding, 50.0)); }); testWidgets('Pop interrupts push, reverses flight', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp(routes: routes)); await tester.tap(find.text('twoInset')); await tester.pump(); // begin navigation from / to /twoInset. const double epsilon = 0.001; const Duration duration = Duration(milliseconds: 300); await tester.pump(); final double x0 = tester.getTopLeft(find.byKey(secondKey)).dx; // Flight begins with the secondKey Hero widget lined up with the firstKey widget. expect(x0, 4.0); await tester.pump(duration * 0.1); final double x1 = tester.getTopLeft(find.byKey(secondKey)).dx; await tester.pump(duration * 0.1); final double x2 = tester.getTopLeft(find.byKey(secondKey)).dx; await tester.pump(duration * 0.1); final double x3 = tester.getTopLeft(find.byKey(secondKey)).dx; await tester.pump(duration * 0.1); final double x4 = tester.getTopLeft(find.byKey(secondKey)).dx; // Pop route /twoInset before the push transition from / to /twoInset has finished. await tester.tap(find.text('pop')); // We expect the hero to take the same path as it did flying from / // to /twoInset as it does now, flying from '/twoInset' back to /. The most // important checks below are the first (x4) and last (x0): the hero should // not jump from where it was when the push transition was interrupted by a // pop, and it should end up where the push started. await tester.pump(); expect(tester.getTopLeft(find.byKey(secondKey)).dx, moreOrLessEquals(x4, epsilon: epsilon)); await tester.pump(duration * 0.1); expect(tester.getTopLeft(find.byKey(secondKey)).dx, moreOrLessEquals(x3, epsilon: epsilon)); await tester.pump(duration * 0.1); expect(tester.getTopLeft(find.byKey(secondKey)).dx, moreOrLessEquals(x2, epsilon: epsilon)); await tester.pump(duration * 0.1); expect(tester.getTopLeft(find.byKey(secondKey)).dx, moreOrLessEquals(x1, epsilon: epsilon)); await tester.pump(duration * 0.1); expect(tester.getTopLeft(find.byKey(secondKey)).dx, moreOrLessEquals(x0, epsilon: epsilon)); // Below: show that a different pop Hero path is in fact taken after // a completed push transition. // Complete the pop transition and we're back to showing /. await tester.pumpAndSettle(); expect(tester.getTopLeft(find.byKey(firstKey)).dx, 4.0); // Card contents are inset by 4.0. // Push /twoInset and wait for the transition to finish. await tester.tap(find.text('twoInset')); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.byKey(secondKey)).dx, 54.0); // Start the pop transition from /twoInset to /. await tester.tap(find.text('pop')); await tester.pump(); // Now the firstKey widget is the flying hero widget and it starts // out lined up with the secondKey widget. await tester.pump(); expect(tester.getTopLeft(find.byKey(firstKey)).dx, 54.0); // x0-x4 are the top left x coordinates for the beginning 40% of // the incoming flight. Advance the outgoing flight to the same // place. await tester.pump(duration * 0.6); await tester.pump(duration * 0.1); expect(tester.getTopLeft(find.byKey(firstKey)).dx, isNot(moreOrLessEquals(x4, epsilon: epsilon))); await tester.pump(duration * 0.1); expect(tester.getTopLeft(find.byKey(firstKey)).dx, isNot(moreOrLessEquals(x3, epsilon: epsilon))); // At this point the flight path arcs do start to get pretty close so // there's no point in comparing them. await tester.pump(duration * 0.1); // After the remaining 40% of the incoming flight is complete, we // expect to end up where the outgoing flight started. await tester.pump(duration * 0.1); expect(tester.getTopLeft(find.byKey(firstKey)).dx, x0); }); testWidgets('Can override flight shuttle in to hero', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: ListView( children: <Widget>[ const Hero(tag: 'a', child: Text('foo')), Builder(builder: (BuildContext context) { return TextButton( child: const Text('two'), onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>( builder: (BuildContext context) { return Material( child: Hero( tag: 'a', child: const Text('bar'), flightShuttleBuilder: ( BuildContext flightContext, Animation<double> animation, HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, ) { return const Text('baz'); }, ), ); }, )), ); }), ], ), ), )); await tester.tap(find.text('two')); await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); expect(find.text('foo'), findsNothing); expect(find.text('bar'), findsNothing); expect(find.text('baz'), findsOneWidget); }); testWidgets('Can override flight shuttle in from hero', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: ListView( children: <Widget>[ Hero( tag: 'a', child: const Text('foo'), flightShuttleBuilder: ( BuildContext flightContext, Animation<double> animation, HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, ) { return const Text('baz'); }, ), Builder(builder: (BuildContext context) { return TextButton( child: const Text('two'), onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>( builder: (BuildContext context) { return const Material( child: Hero(tag: 'a', child: Text('bar')), ); }, )), ); }), ], ), ), )); await tester.tap(find.text('two')); await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); expect(find.text('foo'), findsNothing); expect(find.text('bar'), findsNothing); expect(find.text('baz'), findsOneWidget); }); // Regression test for https://github.com/flutter/flutter/issues/77720. testWidgets("toHero's shuttle builder over fromHero's shuttle builder", (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: ListView( children: <Widget>[ Hero( tag: 'a', child: const Text('foo'), flightShuttleBuilder: ( BuildContext flightContext, Animation<double> animation, HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, ) { return const Text('fromHero text'); }, ), Builder(builder: (BuildContext context) { return TextButton( child: const Text('two'), onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>( builder: (BuildContext context) { return Material( child: Hero( tag: 'a', child: const Text('bar'), flightShuttleBuilder: ( BuildContext flightContext, Animation<double> animation, HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, ) { return const Text('toHero text'); }, ), ); }, )), ); }), ], ), ), )); await tester.tap(find.text('two')); await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); expect(find.text('foo'), findsNothing); expect(find.text('bar'), findsNothing); expect(find.text('fromHero text'), findsNothing); expect(find.text('toHero text'), findsOneWidget); }); testWidgets('Can override flight launch pads', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: ListView( children: <Widget>[ Hero( tag: 'a', child: const Text('Batman'), placeholderBuilder: (BuildContext context, Size heroSize, Widget child) { return const Text('Venom'); }, ), Builder(builder: (BuildContext context) { return TextButton( child: const Text('two'), onPressed: () => Navigator.push<void>(context, MaterialPageRoute<void>( builder: (BuildContext context) { return Material( child: Hero( tag: 'a', child: const Text('Wolverine'), placeholderBuilder: (BuildContext context, Size size, Widget child) { return const Text('Joker'); }, ), ); }, )), ); }), ], ), ), )); await tester.tap(find.text('two')); await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); expect(find.text('Batman'), findsNothing); // This shows up once but in the Hero because by default, the destination // Hero child is the widget in flight. expect(find.text('Wolverine'), findsOneWidget); expect(find.text('Venom'), findsOneWidget); expect(find.text('Joker'), findsOneWidget); }); testWidgets('Heroes do not transition on back gestures by default', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( routes: routes, )); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), findsNothing); await tester.tap(find.text('two')); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); await gesture.moveBy(const Offset(20.0, 0.0)); await gesture.moveBy(const Offset(180.0, 0.0)); await gesture.up(); await tester.pump(); await tester.pump(); // Both Heroes exist and are seated in their normal parents. expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); // To make sure the hero had all chances of starting. await tester.pump(const Duration(milliseconds: 100)); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Heroes can transition on gesture in one frame', (WidgetTester tester) async { transitionFromUserGestures = true; await tester.pumpWidget(MaterialApp( routes: routes, )); await tester.tap(find.text('two')); await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); await gesture.moveBy(const Offset(200.0, 0.0)); await tester.pump(); // We're going to page 1 so page 1's Hero is lifted into flight. expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isNotInCard); expect(find.byKey(secondKey), findsNothing); // Move further along. await gesture.moveBy(const Offset(500.0, 0.0)); await tester.pump(); // Same results. expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isNotInCard); expect(find.byKey(secondKey), findsNothing); await gesture.up(); // Finish transition. await tester.pump(); await tester.pump(const Duration(milliseconds: 500)); // Hero A is back in the card. expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Heroes animate should hide destination hero and display original hero in case of dismissed', (WidgetTester tester) async { transitionFromUserGestures = true; await tester.pumpWidget(MaterialApp( routes: routes, )); await tester.tap(find.text('two')); await tester.pumpAndSettle(); expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); await gesture.moveBy(const Offset(50.0, 0.0)); await tester.pump(); // It will only register the drag if we move a second time. await gesture.moveBy(const Offset(50.0, 0.0)); await tester.pump(); // We're going to page 1 so page 1's Hero is lifted into flight. expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isNotInCard); expect(find.byKey(secondKey), findsNothing); // Dismisses hero transition. await gesture.up(); await tester.pump(); await tester.pumpAndSettle(); // We goes back to second page. expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('Handles transitions when a non-default initial route is set', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( routes: routes, initialRoute: '/two', )); expect(tester.takeException(), isNull); expect(find.text('two'), findsNothing); expect(find.text('three'), findsOneWidget); }); testWidgets('Can push/pop on outer Navigator if nested Navigator contains Heroes', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/28042. const String heroTag = 'You are my hero!'; final GlobalKey<NavigatorState> rootNavigator = GlobalKey(); final GlobalKey<NavigatorState> nestedNavigator = GlobalKey(); final Key nestedRouteHeroBottom = UniqueKey(); final Key nestedRouteHeroTop = UniqueKey(); await tester.pumpWidget( MaterialApp( navigatorKey: rootNavigator, home: Navigator( key: nestedNavigator, onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute<void>( builder: (BuildContext context) { return Hero( tag: heroTag, child: Placeholder( key: nestedRouteHeroBottom, ), ); }, ); }, ), ), ); nestedNavigator.currentState!.push(MaterialPageRoute<void>( builder: (BuildContext context) { return Hero( tag: heroTag, child: Placeholder( key: nestedRouteHeroTop, ), ); }, )); await tester.pumpAndSettle(); // Both heroes are in the tree, one is offstage expect(find.byKey(nestedRouteHeroTop), findsOneWidget); expect(find.byKey(nestedRouteHeroBottom), findsNothing); expect(find.byKey(nestedRouteHeroBottom, skipOffstage: false), findsOneWidget); rootNavigator.currentState!.push(MaterialPageRoute<void>( builder: (BuildContext context) { return const Text('Foo'); }, )); await tester.pumpAndSettle(); expect(find.text('Foo'), findsOneWidget); // Both heroes are still in the tree, both are offstage. expect(find.byKey(nestedRouteHeroBottom), findsNothing); expect(find.byKey(nestedRouteHeroTop), findsNothing); expect(find.byKey(nestedRouteHeroBottom, skipOffstage: false), findsOneWidget); expect(find.byKey(nestedRouteHeroTop, skipOffstage: false), findsOneWidget); // Doesn't crash. expect(tester.takeException(), isNull); rootNavigator.currentState!.pop(); await tester.pumpAndSettle(); expect(find.text('Foo'), findsNothing); // Both heroes are in the tree, one is offstage expect(find.byKey(nestedRouteHeroTop), findsOneWidget); expect(find.byKey(nestedRouteHeroBottom), findsNothing); expect(find.byKey(nestedRouteHeroBottom, skipOffstage: false), findsOneWidget); }); testWidgets('Can hero from route in root Navigator to route in nested Navigator', (WidgetTester tester) async { const String heroTag = 'foo'; final GlobalKey<NavigatorState> rootNavigator = GlobalKey(); final Key smallContainer = UniqueKey(); final Key largeContainer = UniqueKey(); await tester.pumpWidget( MaterialApp( navigatorKey: rootNavigator, home: Center( child: Card( child: Hero( tag: heroTag, child: Container( key: largeContainer, color: Colors.red, height: 200.0, width: 200.0, ), ), ), ), ), ); // The initial setup. expect(find.byKey(largeContainer), isOnstage); expect(find.byKey(largeContainer), isInCard); expect(find.byKey(smallContainer, skipOffstage: false), findsNothing); rootNavigator.currentState!.push( MaterialPageRoute<void>( builder: (BuildContext context) { return Center( child: Card( child: Hero( tag: heroTag, child: Container( key: smallContainer, color: Colors.red, height: 100.0, width: 100.0, ), ), ), ); }, ), ); await tester.pump(); // The second route exists offstage. expect(find.byKey(largeContainer), isOnstage); expect(find.byKey(largeContainer), isInCard); expect(find.byKey(smallContainer, skipOffstage: false), isOffstage); expect(find.byKey(smallContainer, skipOffstage: false), isInCard); await tester.pump(); // The hero started flying. expect(find.byKey(largeContainer), findsNothing); expect(find.byKey(smallContainer), isOnstage); expect(find.byKey(smallContainer), isNotInCard); await tester.pump(const Duration(milliseconds: 100)); // The hero is in-flight. expect(find.byKey(largeContainer), findsNothing); expect(find.byKey(smallContainer), isOnstage); expect(find.byKey(smallContainer), isNotInCard); final Size size = tester.getSize(find.byKey(smallContainer)); expect(size.height, greaterThan(100)); expect(size.width, greaterThan(100)); expect(size.height, lessThan(200)); expect(size.width, lessThan(200)); await tester.pumpAndSettle(); // The transition has ended. expect(find.byKey(largeContainer), findsNothing); expect(find.byKey(smallContainer), isOnstage); expect(find.byKey(smallContainer), isInCard); expect(tester.getSize(find.byKey(smallContainer)), const Size(100,100)); }); testWidgets('Hero within a Hero, throws', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Hero( tag: 'a', child: Hero( tag: 'b', child: Text('Child of a Hero'), ), ), ), ), ); expect(tester.takeException(), isAssertionError); }); testWidgets('Can push/pop on outer Navigator if nested Navigators contains same Heroes', (WidgetTester tester) async { const String heroTag = 'foo'; final GlobalKey<NavigatorState> rootNavigator = GlobalKey<NavigatorState>(); final Key rootRouteHero = UniqueKey(); final Key nestedRouteHeroOne = UniqueKey(); final Key nestedRouteHeroTwo = UniqueKey(); final List<Key> keys = <Key>[nestedRouteHeroOne, nestedRouteHeroTwo]; await tester.pumpWidget( CupertinoApp( navigatorKey: rootNavigator, home: CupertinoTabScaffold( tabBar: CupertinoTabBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem(icon: Icon(Icons.home)), BottomNavigationBarItem(icon: Icon(Icons.favorite)), ], ), tabBuilder: (BuildContext context, int index) { return CupertinoTabView( builder: (BuildContext context) => Hero( tag: heroTag, child: Placeholder( key: keys[index], ), ), ); }, ), ), ); // Show both tabs to init. await tester.tap(find.byIcon(Icons.home)); await tester.pump(); await tester.tap(find.byIcon(Icons.favorite)); await tester.pump(); // Inner heroes are in the tree, one is offstage. expect(find.byKey(nestedRouteHeroTwo), findsOneWidget); expect(find.byKey(nestedRouteHeroOne), findsNothing); expect(find.byKey(nestedRouteHeroOne, skipOffstage: false), findsOneWidget); // Root hero is not in the tree. expect(find.byKey(rootRouteHero), findsNothing); rootNavigator.currentState!.push( MaterialPageRoute<void>( builder: (BuildContext context) => Hero( tag: heroTag, child: Placeholder( key: rootRouteHero, ), ), ), ); await tester.pumpAndSettle(); // Inner heroes are still in the tree, both are offstage. expect(find.byKey(nestedRouteHeroOne), findsNothing); expect(find.byKey(nestedRouteHeroTwo), findsNothing); expect(find.byKey(nestedRouteHeroOne, skipOffstage: false), findsOneWidget); expect(find.byKey(nestedRouteHeroTwo, skipOffstage: false), findsOneWidget); // Root hero is in the tree. expect(find.byKey(rootRouteHero), findsOneWidget); // Doesn't crash. expect(tester.takeException(), isNull); rootNavigator.currentState!.pop(); await tester.pumpAndSettle(); // Root hero is not in the tree expect(find.byKey(rootRouteHero), findsNothing); // Both heroes are in the tree, one is offstage expect(find.byKey(nestedRouteHeroTwo), findsOneWidget); expect(find.byKey(nestedRouteHeroOne), findsNothing); expect(find.byKey(nestedRouteHeroOne, skipOffstage: false), findsOneWidget); }); testWidgets('Hero within a Hero subtree, throws', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Material( child: Hero( tag: 'a', child: Hero( tag: 'b', child: Text('Child of a Hero'), ), ), ), ), ); expect(tester.takeException(), isAssertionError); }); testWidgets('Hero within a Hero subtree with Builder, throws', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: Hero( tag: 'a', child: Builder( builder: (BuildContext context) { return const Hero( tag: 'b', child: Text('Child of a Hero'), ); }, ), ), ), ), ); expect(tester.takeException(),isAssertionError); }); testWidgets('Hero within a Hero subtree with LayoutBuilder, throws', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Material( child: Hero( tag: 'a', child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return const Hero( tag: 'b', child: Text('Child of a Hero'), ); }, ), ), ), ), ); expect(tester.takeException(), isAssertionError); }); testWidgets('Heroes fly on pushReplacement', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/28041. const String heroTag = 'foo'; final GlobalKey<NavigatorState> navigator = GlobalKey(); final Key smallContainer = UniqueKey(); final Key largeContainer = UniqueKey(); await tester.pumpWidget( MaterialApp( navigatorKey: navigator, home: Center( child: Card( child: Hero( tag: heroTag, child: Container( key: largeContainer, color: Colors.red, height: 200.0, width: 200.0, ), ), ), ), ), ); // The initial setup. expect(find.byKey(largeContainer), isOnstage); expect(find.byKey(largeContainer), isInCard); expect(find.byKey(smallContainer, skipOffstage: false), findsNothing); navigator.currentState!.pushReplacement( MaterialPageRoute<void>( builder: (BuildContext context) { return Center( child: Card( child: Hero( tag: heroTag, child: Container( key: smallContainer, color: Colors.red, height: 100.0, width: 100.0, ), ), ), ); }, ), ); await tester.pump(); // The second route exists offstage. expect(find.byKey(largeContainer), isOnstage); expect(find.byKey(largeContainer), isInCard); expect(find.byKey(smallContainer, skipOffstage: false), isOffstage); expect(find.byKey(smallContainer, skipOffstage: false), isInCard); await tester.pump(); // The hero started flying. expect(find.byKey(largeContainer), findsNothing); expect(find.byKey(smallContainer), isOnstage); expect(find.byKey(smallContainer), isNotInCard); await tester.pump(const Duration(milliseconds: 100)); // The hero is in-flight. expect(find.byKey(largeContainer), findsNothing); expect(find.byKey(smallContainer), isOnstage); expect(find.byKey(smallContainer), isNotInCard); final Size size = tester.getSize(find.byKey(smallContainer)); expect(size.height, greaterThan(100)); expect(size.width, greaterThan(100)); expect(size.height, lessThan(200)); expect(size.width, lessThan(200)); await tester.pumpAndSettle(); // The transition has ended. expect(find.byKey(largeContainer), findsNothing); expect(find.byKey(smallContainer), isOnstage); expect(find.byKey(smallContainer), isInCard); expect(tester.getSize(find.byKey(smallContainer)), const Size(100,100)); }); testWidgets('On an iOS back swipe and snap, only a single flight should take place', (WidgetTester tester) async { int shuttlesBuilt = 0; Widget shuttleBuilder( BuildContext flightContext, Animation<double> animation, HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext, ) { shuttlesBuilt += 1; return const Text("I'm flying in a jetplane"); } final GlobalKey<NavigatorState> navigatorKey = GlobalKey(); await tester.pumpWidget( CupertinoApp( navigatorKey: navigatorKey, home: Hero( tag: navigatorKey, // Since we're popping, only the destination route's builder is used. flightShuttleBuilder: shuttleBuilder, transitionOnUserGestures: true, child: const Text('1'), ), ), ); final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>( builder: (BuildContext context) { return CupertinoPageScaffold( child: Hero( tag: navigatorKey, transitionOnUserGestures: true, child: const Text('2'), ), ); }, ); navigatorKey.currentState!.push(route2); await tester.pumpAndSettle(); expect(shuttlesBuilt, 1); final TestGesture gesture = await tester.startGesture(const Offset(5.0, 200.0)); await gesture.moveBy(const Offset(500.0, 0.0)); await tester.pump(); // Starting the back swipe creates a new hero shuttle. expect(shuttlesBuilt, 2); await gesture.up(); await tester.pump(); // After the lift, no additional shuttles should be created since it's the // same hero flight. expect(shuttlesBuilt, 2); // Did go far enough to snap out of this route. await tester.pump(const Duration(milliseconds: 301)); expect(find.text('2'), findsNothing); // Still one shuttle. expect(shuttlesBuilt, 2); }); testWidgets( "From hero's state should be preserved, " 'heroes work well with child widgets that has global keys', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey(); final GlobalKey<_SimpleState> key1 = GlobalKey<_SimpleState>(); final GlobalKey key2 = GlobalKey(); await tester.pumpWidget( CupertinoApp( navigatorKey: navigatorKey, home: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Hero( tag: 'hero', transitionOnUserGestures: true, child: _SimpleStatefulWidget(key: key1), ), const SizedBox( width: 10, height: 10, child: Text('1'), ), ], ), ), ); final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>( builder: (BuildContext context) { return CupertinoPageScaffold( child: Hero( tag: 'hero', transitionOnUserGestures: true, // key2 is a `GlobalKey`. The hero animation should not // assert by having the same global keyed widget in more // than one place in the tree. child: _SimpleStatefulWidget(key: key2), ), ); }, ); final _SimpleState state1 = key1.currentState!; state1.state = 1; navigatorKey.currentState!.push(route2); await tester.pump(); expect(state1.mounted, isTrue); await tester.pumpAndSettle(); expect(state1.state, 1); // The element should be mounted and unique. expect(state1.mounted, isTrue); navigatorKey.currentState!.pop(); await tester.pumpAndSettle(); // State is preserved. expect(state1.state, 1); // The element should be mounted and unique. expect(state1.mounted, isTrue); }, ); testWidgets( "Hero works with images that don't have both width and height specified", // Regression test for https://github.com/flutter/flutter/issues/32356 // and https://github.com/flutter/flutter/issues/31503 (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey(); const Key imageKey1 = Key('image1'); const Key imageKey2 = Key('image2'); final TestImageProvider imageProvider = TestImageProvider(testImage); await tester.pumpWidget( CupertinoApp( navigatorKey: navigatorKey, home: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Hero( tag: 'hero', transitionOnUserGestures: true, child: SizedBox( width: 100, child: Image( image: imageProvider, key: imageKey1, ), ), ), const SizedBox( width: 10, height: 10, child: Text('1'), ), ], ), ), ); final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>( builder: (BuildContext context) { return CupertinoPageScaffold( child: Hero( tag: 'hero', transitionOnUserGestures: true, child: Image( image: imageProvider, key: imageKey2, ), ), ); }, ); // Load image before measuring the `Rect` of the `RenderImage`. imageProvider.complete(); await tester.pump(); final RenderImage renderImage = tester.renderObject( find.descendant(of: find.byKey(imageKey1), matching: find.byType(RawImage)), ); // Before push image1 should be laid out correctly. expect(renderImage.size, const Size(100, 100)); navigatorKey.currentState!.push(route2); await tester.pump(); final TestGesture gesture = await tester.startGesture(const Offset(0.01, 300)); await tester.pump(); // Move (almost) across the screen, to make the animation as close to finish // as possible. await gesture.moveTo(const Offset(800, 200)); await tester.pump(); // image1 should snap to the top left corner of the Row widget. expect( tester.getRect(find.byKey(imageKey1, skipOffstage: false)), rectMoreOrLessEquals(tester.getTopLeft(find.widgetWithText(Row, '1')) & const Size(100, 100), epsilon: 0.01), ); // Text should respect the correct final size of image1. expect( tester.getTopRight(find.byKey(imageKey1, skipOffstage: false)).dx, moreOrLessEquals(tester.getTopLeft(find.text('1')).dx, epsilon: 0.01), ); }, ); // Regression test for https://github.com/flutter/flutter/issues/38183. testWidgets('Remove user gesture driven flights when the gesture is invalid', (WidgetTester tester) async { transitionFromUserGestures = true; await tester.pumpWidget(MaterialApp( routes: routes, )); await tester.tap(find.text('simple')); await tester.pump(); await tester.pumpAndSettle(); expect(find.byKey(simpleKey), findsOneWidget); // Tap once to trigger a flight. await tester.tapAt(const Offset(10, 200)); await tester.pumpAndSettle(); // Wait till the previous gesture is accepted. await tester.pump(const Duration(milliseconds: 500)); // Tap again to trigger another flight, see if it throws. await tester.tapAt(const Offset(10, 200)); await tester.pumpAndSettle(); // The simple route should still be on top. expect(find.byKey(simpleKey), findsOneWidget); expect(tester.takeException(), isNull); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); // Regression test for https://github.com/flutter/flutter/issues/40239. testWidgets( 'In a pop transition, when fromHero is null, the to hero should eventually become visible', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey(); late StateSetter setState; bool shouldDisplayHero = true; await tester.pumpWidget( CupertinoApp( navigatorKey: navigatorKey, home: Hero( tag: navigatorKey, child: const Placeholder(), ), ), ); final CupertinoPageRoute<void> route2 = CupertinoPageRoute<void>( builder: (BuildContext context) { return CupertinoPageScaffold( child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return shouldDisplayHero ? Hero(tag: navigatorKey, child: const Text('text')) : const SizedBox(); }, ), ); }, ); navigatorKey.currentState!.push(route2); await tester.pumpAndSettle(); expect(find.text('text'), findsOneWidget); expect(find.byType(Placeholder), findsNothing); setState(() { shouldDisplayHero = false; }); await tester.pumpAndSettle(); expect(find.text('text'), findsNothing); navigatorKey.currentState!.pop(); await tester.pumpAndSettle(); expect(find.byType(Placeholder), findsOneWidget); }, ); testWidgets('popped hero uses fastOutSlowIn curve', (WidgetTester tester) async { final Key container1 = UniqueKey(); final Key container2 = UniqueKey(); final GlobalKey<NavigatorState> navigator = GlobalKey<NavigatorState>(); final Animatable<Size?> tween = SizeTween( begin: const Size(200, 200), end: const Size(100, 100), ).chain(CurveTween(curve: Curves.fastOutSlowIn)); await tester.pumpWidget( MaterialApp( navigatorKey: navigator, home: Scaffold( body: Center( child: Hero( tag: 'test', createRectTween: (Rect? begin, Rect? end) { return RectTween(begin: begin, end: end); }, child: SizedBox( key: container1, height: 100, width: 100, ), ), ), ), ), ); final Size originalSize = tester.getSize(find.byKey(container1)); expect(originalSize, const Size(100, 100)); navigator.currentState!.push(MaterialPageRoute<void>(builder: (BuildContext context) { return Scaffold( body: Center( child: Hero( tag: 'test', createRectTween: (Rect? begin, Rect? end) { return RectTween(begin: begin, end: end); }, child: SizedBox( key: container2, height: 200, width: 200, ), ), ), ); })); await tester.pumpAndSettle(); final Size newSize = tester.getSize(find.byKey(container2)); expect(newSize, const Size(200, 200)); navigator.currentState!.pop(); await tester.pump(); // Jump 25% into the transition (total length = 300ms) await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms Size heroSize = tester.getSize(find.byKey(container1)); expect(heroSize, tween.transform(0.25)); // Jump to 50% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byKey(container1)); expect(heroSize, tween.transform(0.50)); // Jump to 75% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byKey(container1)); expect(heroSize, tween.transform(0.75)); // Jump to 100% into the transition. await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms heroSize = tester.getSize(find.byKey(container1)); expect(heroSize, tween.transform(1.0)); }); testWidgets('Heroes in enabled HeroMode do transition', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: Column( children: <Widget>[ HeroMode( child: Card( child: Hero( tag: 'a', child: SizedBox( height: 100.0, width: 100.0, key: firstKey, ), ), ), ), Builder( builder: (BuildContext context) { return TextButton( child: const Text('push'), onPressed: () { Navigator.push(context, PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) { return Card( child: Hero( tag: 'a', child: SizedBox( height: 150.0, width: 150.0, key: secondKey, ), ), ); }, )); }, ); }, ), ], ), ), )); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), findsNothing); await tester.tap(find.text('push')); await tester.pump(); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey, skipOffstage: false), isOffstage); expect(find.byKey(secondKey, skipOffstage: false), isInCard); await tester.pump(); expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), findsOneWidget); expect(find.byKey(secondKey), isNotInCard); expect(find.byKey(secondKey), isOnstage); await tester.pump(const Duration(seconds: 1)); expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), isOnstage); expect(find.byKey(secondKey), isInCard); }); testWidgets('Heroes in disabled HeroMode do not transition', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Material( child: Column( children: <Widget>[ HeroMode( enabled: false, child: Card( child: Hero( tag: 'a', child: SizedBox( height: 100.0, width: 100.0, key: firstKey, ), ), ), ), Builder( builder: (BuildContext context) { return TextButton( child: const Text('push'), onPressed: () { Navigator.push(context, PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> _, Animation<double> __) { return Card( child: Hero( tag: 'a', child: SizedBox( height: 150.0, width: 150.0, key: secondKey, ), ), ); }, )); }, ); }, ), ], ), ), )); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey), findsNothing); await tester.tap(find.text('push')); await tester.pump(); expect(find.byKey(firstKey), isOnstage); expect(find.byKey(firstKey), isInCard); expect(find.byKey(secondKey, skipOffstage: false), isOffstage); expect(find.byKey(secondKey, skipOffstage: false), isInCard); await tester.pump(); // When HeroMode is disabled, heroes will not move. // So the original page contains the hero. expect(find.byKey(firstKey), findsOneWidget); // The hero should be in the new page, onstage, soon. expect(find.byKey(secondKey), findsOneWidget); expect(find.byKey(secondKey), isInCard); expect(find.byKey(secondKey), isOnstage); await tester.pump(const Duration(seconds: 1)); expect(find.byKey(firstKey), findsNothing); expect(find.byKey(secondKey), findsOneWidget); expect(find.byKey(secondKey), isInCard); expect(find.byKey(secondKey), isOnstage); }); testWidgets('kept alive Hero does not throw when the transition begins', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget( MaterialApp( navigatorKey: navigatorKey, home: Scaffold( body: ListView( addAutomaticKeepAlives: false, addRepaintBoundaries: false, addSemanticIndexes: false, children: <Widget>[ const KeepAlive( keepAlive: true, child: Hero( tag: 'a', child: Placeholder(), ), ), Container(height: 1000.0), ], ), ), ), ); // Scroll to make the Hero invisible. await tester.drag(find.byType(ListView), const Offset(0.0, -1000.0)); await tester.pump(); expect(find.byType(TextField), findsNothing); navigatorKey.currentState?.push( MaterialPageRoute<void>( builder: (BuildContext context) { return const Scaffold( body: Center( child: Hero( tag: 'a', child: Placeholder(), ), ), ); }, ), ); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); // The Hero on the new route should be visible . expect(find.byType(Placeholder), findsOneWidget); }); testWidgets('toHero becomes unpaintable after the transition begins', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); RenderAnimatedOpacity? findRenderAnimatedOpacity() { RenderObject? parent = tester.renderObject(find.byType(Placeholder)); while (parent is RenderObject && parent is! RenderAnimatedOpacity) { parent = parent.parent; } return parent is RenderAnimatedOpacity ? parent : null; } await tester.pumpWidget( MaterialApp( navigatorKey: navigatorKey, home: Scaffold( body: ListView( controller: controller, addAutomaticKeepAlives: false, addRepaintBoundaries: false, addSemanticIndexes: false, children: <Widget>[ const KeepAlive( keepAlive: true, child: Hero( tag: 'a', child: Placeholder(), ), ), Container(height: 1000.0), ], ), ), ), ); navigatorKey.currentState?.push( MaterialPageRoute<void>( builder: (BuildContext context) { return const Scaffold( body: Center( child: Hero( tag: 'a', child: Placeholder(), ), ), ); }, ), ); await tester.pump(); await tester.pumpAndSettle(); // Pop the new route, and before the animation finishes we scroll the toHero // to make it unpaintable. navigatorKey.currentState?.pop(); await tester.pump(); controller.jumpTo(1000); // Starts Hero animation and scroll animation almost simultaneously. // Scroll to make the Hero invisible. await tester.pump(); expect(findRenderAnimatedOpacity()?.opacity.value, anyOf(isNull, 1.0)); // In this frame the Hero animation finds out the toHero is not paintable, // and starts fading. await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(findRenderAnimatedOpacity()?.opacity.value, lessThan(1.0)); await tester.pumpAndSettle(); // The Hero on the new route should be invisible. expect(find.byType(Placeholder), findsNothing); }); testWidgets('diverting to a keepalive but unpaintable hero', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget( CupertinoApp( navigatorKey: navigatorKey, home: CupertinoPageScaffold( child: ListView( addAutomaticKeepAlives: false, addRepaintBoundaries: false, addSemanticIndexes: false, children: <Widget>[ const KeepAlive( keepAlive: true, child: Hero( tag: 'a', child: Placeholder(), ), ), Container(height: 1000.0), ], ), ), ), ); // Scroll to make the Hero invisible. await tester.drag(find.byType(ListView), const Offset(0.0, -1000.0)); await tester.pump(); expect(find.byType(Placeholder), findsNothing); expect(find.byType(Placeholder, skipOffstage: false), findsOneWidget); navigatorKey.currentState?.push( MaterialPageRoute<void>( builder: (BuildContext context) { return const Scaffold( body: Center( child: Hero( tag: 'a', child: Placeholder(), ), ), ); }, ), ); await tester.pumpAndSettle(); // Yet another route that contains Hero 'a'. navigatorKey.currentState?.push( MaterialPageRoute<void>( builder: (BuildContext context) { return const Scaffold( body: Center( child: Hero( tag: 'a', child: Placeholder(), ), ), ); }, ), ); await tester.pumpAndSettle(); // Pop both routes. navigatorKey.currentState?.pop(); await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); navigatorKey.currentState?.pop(); await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); expect(find.byType(Placeholder), findsOneWidget); await tester.pumpAndSettle(); expect(tester.takeException(), isNull); }); testWidgets('smooth transition between different incoming data', (WidgetTester tester) async { addTearDown(tester.view.reset); final GlobalKey<NavigatorState> navigatorKey = GlobalKey(); const Key imageKey1 = Key('image1'); const Key imageKey2 = Key('image2'); final TestImageProvider imageProvider = TestImageProvider(testImage); tester.view.padding = const FakeViewPadding(top: 50); await tester.pumpWidget( MaterialApp( navigatorKey: navigatorKey, home: Scaffold( appBar: AppBar(title: const Text('test')), body: Hero( tag: 'imageHero', child: GridView.count( crossAxisCount: 3, shrinkWrap: true, children: <Widget>[ Image(image: imageProvider, key: imageKey1), ], ), ), ), ), ); final MaterialPageRoute<void> route2 = MaterialPageRoute<void>( builder: (BuildContext context) { return Scaffold( body: Hero( tag: 'imageHero', child: GridView.count( crossAxisCount: 3, shrinkWrap: true, children: <Widget>[ Image(image: imageProvider, key: imageKey2), ], ), ), ); }, ); // Load images. imageProvider.complete(); await tester.pump(); final double forwardRest = tester.getTopLeft(find.byType(Image)).dy; navigatorKey.currentState!.push(route2); await tester.pump(); await tester.pump(const Duration(milliseconds: 1)); expect(tester.getTopLeft(find.byType(Image)).dy, moreOrLessEquals(forwardRest, epsilon: 0.1)); await tester.pumpAndSettle(); navigatorKey.currentState!.pop(route2); await tester.pump(); await tester.pump(const Duration(milliseconds: 300)); expect(tester.getTopLeft(find.byType(Image)).dy, moreOrLessEquals(forwardRest, epsilon: 0.1)); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.byType(Image)).dy, moreOrLessEquals(forwardRest, epsilon: 0.1)); }); test('HeroController dispatches memory events', () async { await expectLater( await memoryEvents(() => HeroController().dispose(), HeroController), areCreateAndDispose, ); }); } class TestDependencies extends StatelessWidget { const TestDependencies({required this.child, super.key}); final Widget child; @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: MediaQueryData.fromView(View.of(context)), child: child, ), ); } }
flutter/packages/flutter/test/widgets/heroes_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/heroes_test.dart", "repo_id": "flutter", "token_count": 46900 }
744
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { testWidgets('Implicit Semantics merge behavior', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Semantics( container: true, child: const Column( children: <Widget>[ Text('Michael Goderbauer'), Text('[email protected]'), ], ), ), ), ); // SemanticsNode#0() // └SemanticsNode#1(label: "Michael Goderbauer\[email protected]", textDirection: ltr) expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, label: 'Michael Goderbauer\[email protected]', ), ], ), ignoreRect: true, ignoreTransform: true, ), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Semantics( container: true, explicitChildNodes: true, child: const Column( children: <Widget>[ Text('Michael Goderbauer'), Text('[email protected]'), ], ), ), ), ); // SemanticsNode#0() // └SemanticsNode#1() // ├SemanticsNode#2(label: "Michael Goderbauer", textDirection: ltr) // └SemanticsNode#3(label: "[email protected]", textDirection: ltr) expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, children: <TestSemantics>[ TestSemantics( id: 2, label: 'Michael Goderbauer', ), TestSemantics( id: 3, label: '[email protected]', ), ], ), ], ), ignoreRect: true, ignoreTransform: true, ), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Semantics( container: true, explicitChildNodes: true, child: Semantics( label: 'Signed in as', child: const Column( children: <Widget>[ Text('Michael Goderbauer'), Text('[email protected]'), ], ), ), ), ), ); // SemanticsNode#0() // └SemanticsNode#1() // └SemanticsNode#4(label: "Signed in as\nMichael Goderbauer\[email protected]", textDirection: ltr) expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, children: <TestSemantics>[ TestSemantics( id: 4, label: 'Signed in as\nMichael Goderbauer\[email protected]', ), ], ), ], ), ignoreRect: true, ignoreTransform: true, ), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Semantics( container: true, child: Semantics( label: 'Signed in as', child: const Column( children: <Widget>[ Text('Michael Goderbauer'), Text('[email protected]'), ], ), ), ), ), ); // SemanticsNode#0() // └SemanticsNode#1(label: "Signed in as\nMichael Goderbauer\[email protected]", textDirection: ltr) expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, label: 'Signed in as\nMichael Goderbauer\[email protected]', ), ], ), ignoreRect: true, ignoreTransform: true, ), ); semantics.dispose(); }); testWidgets('Do not merge with conflicts', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Semantics( container: true, child: Column( children: <Widget>[ Semantics( label: 'node 1', selected: true, child: const SizedBox( width: 10.0, height: 10.0, ), ), Semantics( label: 'node 2', selected: true, child: const SizedBox( width: 10.0, height: 10.0, ), ), Semantics( label: 'node 3', selected: true, child: const SizedBox( width: 10.0, height: 10.0, ), ), ], ), ), ), ); // SemanticsNode#0() // └SemanticsNode#1() // ├SemanticsNode#2(selected, label: "node 1", textDirection: ltr) // ├SemanticsNode#3(selected, label: "node 2", textDirection: ltr) // └SemanticsNode#4(selected, label: "node 3", textDirection: ltr) expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, children: <TestSemantics>[ TestSemantics( id: 2, flags: SemanticsFlag.isSelected.index, label: 'node 1', ), TestSemantics( id: 3, flags: SemanticsFlag.isSelected.index, label: 'node 2', ), TestSemantics( id: 4, flags: SemanticsFlag.isSelected.index, label: 'node 3', ), ], ), ], ), ignoreRect: true, ignoreTransform: true, ), ); semantics.dispose(); }); }
flutter/packages/flutter/test/widgets/implicit_semantics_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/implicit_semantics_test.dart", "repo_id": "flutter", "token_count": 3736 }
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:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'test_widgets.dart'; class StatefulWrapper extends StatefulWidget { const StatefulWrapper({ super.key, required this.child, }); final Widget child; @override StatefulWrapperState createState() => StatefulWrapperState(); } class StatefulWrapperState extends State<StatefulWrapper> { void trigger() { setState(() { /* no-op setState */ }); } bool built = false; @override Widget build(BuildContext context) { built = true; return widget.child; } } class Wrapper extends StatelessWidget { const Wrapper({ super.key, required this.child, }); final Widget child; @override Widget build(BuildContext context) { return child; } } void main() { testWidgets('Calling setState on a widget that moves into a LayoutBuilder in the same frame', (WidgetTester tester) async { StatefulWrapperState statefulWrapper; final Widget inner = Wrapper( child: StatefulWrapper( key: GlobalKey(), child: Container(), ), ); await tester.pumpWidget(FlipWidget( left: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { return inner; }), right: inner, )); statefulWrapper = tester.state(find.byType(StatefulWrapper)); expect(statefulWrapper.built, true); statefulWrapper.built = false; statefulWrapper.trigger(); flipStatefulWidget(tester); await tester.pump(); expect(statefulWrapper.built, true); statefulWrapper.built = false; statefulWrapper.trigger(); flipStatefulWidget(tester); await tester.pump(); expect(statefulWrapper.built, true); statefulWrapper.built = false; statefulWrapper.trigger(); flipStatefulWidget(tester); await tester.pump(); expect(statefulWrapper.built, true); statefulWrapper.built = false; }); }
flutter/packages/flutter/test/widgets/layout_builder_and_state_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/layout_builder_and_state_test.dart", "repo_id": "flutter", "token_count": 749 }
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. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import '../rendering/rendering_tester.dart' show TestCallbackPainter, TestClipPaintingContext; void main() { testWidgets('ListWheelScrollView respects clipBehavior', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 2000.0, // huge extent to trigger clip children: <Widget>[Container()], ), ), ); // 1st, check that the render object has received the default clip behavior. final RenderListWheelViewport renderObject = tester.allRenderObjects.whereType<RenderListWheelViewport>().first; expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // 2nd, check that the painting context has received the default clip behavior. final TestClipPaintingContext context = TestClipPaintingContext(); renderObject.paint(context, Offset.zero); expect(context.clipBehavior, equals(Clip.hardEdge)); // 3rd, pump a new widget to check that the render object can update its clip behavior. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 2000.0, // huge extent to trigger clip clipBehavior: Clip.antiAlias, children: <Widget>[Container()], ), ), ); expect(renderObject.clipBehavior, equals(Clip.antiAlias)); // 4th, check that a non-default clip behavior can be sent to the painting context. renderObject.paint(context, Offset.zero); expect(context.clipBehavior, equals(Clip.antiAlias)); }); group('construction check', () { testWidgets('ListWheelScrollView needs positive diameter ratio', (WidgetTester tester) async { expect( () => ListWheelScrollView( diameterRatio: nonconst(-2.0), itemExtent: 20.0, children: const <Widget>[], ), throwsA(isAssertionError.having( (AssertionError error) => error.message, 'message', contains("You can't set a diameterRatio of 0"), )), ); }); testWidgets('ListWheelScrollView can have zero child', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 50.0, children: const <Widget>[], ), ), ); expect(tester.getSize(find.byType(ListWheelScrollView)), const Size(800.0, 600.0)); }); testWidgets('FixedExtentScrollController onAttach, onDetach', (WidgetTester tester) async { int attach = 0; int detach = 0; final FixedExtentScrollController controller = FixedExtentScrollController( onAttach: (_) { attach++; }, onDetach: (_) { detach++; }, ); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 50.0, children: const <Widget>[], ), ), ); await tester.pumpAndSettle(); expect(attach, 1); expect(detach, 0); await tester.pumpWidget(Container()); await tester.pumpAndSettle(); expect(attach, 1); expect(detach, 1); }); testWidgets('ListWheelScrollView needs positive magnification', (WidgetTester tester) async { expect( () { ListWheelScrollView( useMagnifier: true, magnification: -1.0, itemExtent: 20.0, children: <Widget>[Container()], ); }, throwsAssertionError, ); }); testWidgets('ListWheelScrollView needs valid overAndUnderCenterOpacity', (WidgetTester tester) async { expect( () { ListWheelScrollView( overAndUnderCenterOpacity: -1, itemExtent: 20.0, children: <Widget>[Container()], ); }, throwsAssertionError, ); expect( () { ListWheelScrollView( overAndUnderCenterOpacity: 2, itemExtent: 20.0, children: <Widget>[Container()], ); }, throwsAssertionError, ); expect( () { ListWheelScrollView( itemExtent: 20.0, children: <Widget>[Container()], ); }, isNot(throwsAssertionError), ); expect( () { ListWheelScrollView( overAndUnderCenterOpacity: 0, itemExtent: 20.0, children: <Widget>[Container()], ); }, isNot(throwsAssertionError), ); }); }); group('infinite scrolling', () { testWidgets('infinite looping list', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, onSelectedItemChanged: (_) { }, childDelegate: ListWheelChildLoopingListDelegate( children: List<Widget>.generate(10, (int index) { return SizedBox( width: 400.0, height: 100.0, child: Text(index.toString()), ); }), ), ), ), ); // The first item is at the center of the viewport. expect( tester.getTopLeft(find.widgetWithText(SizedBox, '0')), offsetMoreOrLessEquals(const Offset(200.0, 250.0)), ); // The last item is just before the first item. expect( tester.getTopLeft(find.widgetWithText(SizedBox, '9')), offsetMoreOrLessEquals(const Offset(200.0, 150.0), epsilon: 15.0), ); controller.jumpTo(1000.0); await tester.pump(); // We have passed the end of the list, the list should have looped back. expect( tester.getTopLeft(find.widgetWithText(SizedBox, '0')), offsetMoreOrLessEquals(const Offset(200.0, 250.0)), ); }); testWidgets('infinite child builder', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, onSelectedItemChanged: (_) { }, childDelegate: ListWheelChildBuilderDelegate( builder: (BuildContext context, int index) { return SizedBox( width: 400.0, height: 100.0, child: Text(index.toString()), ); }, ), ), ), ); // Can be scrolled infinitely for negative indexes. controller.jumpTo(-100000.0); await tester.pump(); expect( tester.getTopLeft(find.widgetWithText(SizedBox, '-1000')), offsetMoreOrLessEquals(const Offset(200.0, 250.0)), ); // Can be scrolled infinitely for positive indexes. controller.jumpTo(100000.0); await tester.pump(); expect( tester.getTopLeft(find.widgetWithText(SizedBox, '1000')), offsetMoreOrLessEquals(const Offset(200.0, 250.0)), ); }); testWidgets('child builder with lower and upper limits', (WidgetTester tester) async { // Adjust the content dimensions at the end of `RenderListWheelViewport.performLayout()` final List<int> paintedChildren = <int>[]; final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: -10); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, onSelectedItemChanged: (_) { }, childDelegate: ListWheelChildBuilderDelegate( builder: (BuildContext context, int index) { if (index < -15 || index > -5) { return null; } return SizedBox( width: 400.0, height: 100.0, child: CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ), ); }, ), ), ), ); expect(paintedChildren, <int>[-13, -12, -11, -10, -9, -8, -7]); // Flings with high velocity and stop at the lower limit. paintedChildren.clear(); await tester.fling( find.byType(ListWheelScrollView), const Offset(0.0, 1000.0), 1000.0, ); await tester.pumpAndSettle(); expect(controller.selectedItem, -15); // Flings with high velocity and stop at the upper limit. await tester.fling( find.byType(ListWheelScrollView), const Offset(0.0, -1000.0), 1000.0, ); await tester.pumpAndSettle(); expect(controller.selectedItem, -5); }); }); group('layout', () { testWidgets('Flings with high velocity should not break the children lower and upper limits', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/112526 final FixedExtentScrollController controller = FixedExtentScrollController(); addTearDown(controller.dispose); Widget buildFrame() { return Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView.useDelegate( physics: const FixedExtentScrollPhysics(), controller: controller, itemExtent: 400.0, onSelectedItemChanged: (_) { }, childDelegate: ListWheelChildBuilderDelegate( builder: (BuildContext context, int index) { if (index < 0 || index > 5) { return null; } return SizedBox( width: 400.0, height: 400.0, child: Text(index.toString()), ); }, ), ), ); } await tester.pumpWidget(buildFrame()); expect(tester.renderObject(find.text('0')).attached, true); expect(tester.renderObject(find.text('1')).attached, true); expect(find.text('2'), findsNothing); expect(controller.selectedItem, 0); // Flings with high velocity and stop at the child boundary. await tester.fling(find.byType(ListWheelScrollView), const Offset(0.0, 40000.0), 8000.0); expect(controller.selectedItem, 0); }, variant: TargetPlatformVariant(TargetPlatform.values.toSet())); // Regression test for https://github.com/flutter/flutter/issues/90953 testWidgets('ListWheelScrollView childDelegate update test 2', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 2); addTearDown(controller.dispose); Widget buildFrame(int childCount) { return Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 400.0, onSelectedItemChanged: (_) { }, childDelegate: ListWheelChildBuilderDelegate( childCount: childCount, builder: (BuildContext context, int index) { return SizedBox( width: 400.0, height: 400.0, child: Text(index.toString()), ); }, ), ), ); } await tester.pumpWidget(buildFrame(5)); expect(find.text('0'), findsNothing); expect(tester.renderObject(find.text('1')).attached, true); expect(tester.renderObject(find.text('2')).attached, true); expect(tester.renderObject(find.text('3')).attached, true); expect(find.text('4'), findsNothing); // Remove the last 3 items. await tester.pumpWidget(buildFrame(2)); expect(tester.renderObject(find.text('0')).attached, true); expect(tester.renderObject(find.text('1')).attached, true); expect(find.text('3'), findsNothing); // Add 3 items at the end. await tester.pumpWidget(buildFrame(5)); expect(tester.renderObject(find.text('0')).attached, true); expect(tester.renderObject(find.text('1')).attached, true); expect(tester.renderObject(find.text('2')).attached, true); expect(find.text('3'), findsNothing); expect(find.text('4'), findsNothing); // Scroll to the last item. final TestGesture scrollGesture = await tester.startGesture(const Offset(10.0, 10.0)); await scrollGesture.moveBy(const Offset(0.0, -1200.0)); await tester.pump(); expect(find.text('0'), findsNothing); expect(find.text('1'), findsNothing); expect(find.text('2'), findsNothing); expect(tester.renderObject(find.text('3')).attached, true); expect(tester.renderObject(find.text('4')).attached, true); // Remove the last 3 items. await tester.pumpWidget(buildFrame(2)); expect(tester.renderObject(find.text('0')).attached, true); expect(tester.renderObject(find.text('1')).attached, true); expect(find.text('3'), findsNothing); }); // Regression test for https://github.com/flutter/flutter/issues/58144 testWidgets('ListWheelScrollView childDelegate update test', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(); addTearDown(controller.dispose); Widget buildFrame(int childCount) { return Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, onSelectedItemChanged: (_) { }, childDelegate: ListWheelChildBuilderDelegate( childCount: childCount, builder: (BuildContext context, int index) { return SizedBox( width: 400.0, height: 100.0, child: Text(index.toString()), ); }, ), ), ); } await tester.pumpWidget(buildFrame(1)); expect(tester.renderObject(find.text('0')).attached, true); await tester.pumpWidget(buildFrame(2)); expect(tester.renderObject(find.text('0')).attached, true); expect(tester.renderObject(find.text('1')).attached, true); }); testWidgets("ListWheelScrollView takes parent's size with small children", (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( // Inner children smaller than the outer window. itemExtent: 50.0, children: <Widget>[ Container( height: 50.0, color: const Color(0xFFFFFFFF), ), ], ), ), ); expect(tester.getTopLeft(find.byType(ListWheelScrollView)), Offset.zero); // Standard test screen size. expect(tester.getBottomRight(find.byType(ListWheelScrollView)), const Offset(800.0, 600.0)); }); testWidgets("ListWheelScrollView takes parent's size with large children", (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( // Inner children 5000.0px. itemExtent: 50.0, children: List<Widget>.generate(100, (int index) { return Container( height: 50.0, color: const Color(0xFFFFFFFF), ); }), ), ), ); expect(tester.getTopLeft(find.byType(ListWheelScrollView)), Offset.zero); // Still fills standard test screen size. expect(tester.getBottomRight(find.byType(ListWheelScrollView)), const Offset(800.0, 600.0)); }); testWidgets("ListWheelScrollView children can't be bigger than itemExtent", (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 50.0, children: const <Widget>[ SizedBox( height: 200.0, width: 200.0, child: Center( child: Text('blah'), ), ), ], ), ), ); expect(tester.getSize(find.byType(SizedBox)), const Size(200.0, 50.0)); expect(find.text('blah'), findsOneWidget); }); testWidgets('builder is never called twice for same index', (WidgetTester tester) async { final Set<int> builtChildren = <int>{}; final FixedExtentScrollController controller = FixedExtentScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView.useDelegate( controller: controller, itemExtent: 100.0, onSelectedItemChanged: (_) { }, childDelegate: ListWheelChildBuilderDelegate( builder: (BuildContext context, int index) { expect(builtChildren.contains(index), false); builtChildren.add(index); return SizedBox( width: 400.0, height: 100.0, child: Text(index.toString()), ); }, ), ), ), ); // Scrolls up and down to check if builder is called twice. controller.jumpTo(-10000.0); await tester.pump(); controller.jumpTo(10000.0); await tester.pump(); controller.jumpTo(-10000.0); await tester.pump(); }); testWidgets('only visible children are maintained as children of the rendered viewport', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, onSelectedItemChanged: (_) { }, children: List<Widget>.generate(16, (int index) { return Text(index.toString()); }), ), ), ); final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; // Item 0 is in the middle. There are 3 children visible after it, so the // value of childCount should be 4. expect(viewport.childCount, 4); controller.jumpToItem(8); await tester.pump(); // Item 8 is in the middle. There are 3 children visible before it and 3 // after it, so the value of childCount should be 7. expect(viewport.childCount, 7); controller.jumpToItem(15); await tester.pump(); // Item 15 is in the middle. There are 3 children visible before it, so the // value of childCount should be 4. expect(viewport.childCount, 4); }); testWidgets('a tighter squeeze lays out more children', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 10); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, onSelectedItemChanged: (_) { }, children: List<Widget>.generate(20, (int index) { return Text(index.toString()); }), ), ), ); final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; // The screen is vertically 600px. Since the middle item is centered, // half of the first and last items are visible, making 7 children visible. expect(viewport.childCount, 7); // Pump the same widget again but with double the squeeze. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, squeeze: 2, onSelectedItemChanged: (_) { }, children: List<Widget>.generate(20, (int index) { return Text(index.toString()); }), ), ), ); // 12 instead of 6 children are laid out + 1 because the middle item is // centered. expect(viewport.childCount, 13); }); testWidgets('Active children are laid out with correct offset', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/123497 Future<void> buildWidget(double width) async { return tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, children: <Widget>[ SizedBox( width: width, child: const Center(child: Text('blah')), ), ], ), ), ); } double getSizedBoxWidth() => tester.getSize(find.byType(SizedBox)).width; double getSizedBoxCenterX() => tester.getCenter(find.byType(SizedBox)).dx; await buildWidget(200.0); expect(getSizedBoxWidth(), 200.0); expect(getSizedBoxCenterX(), 400.0); await buildWidget(100.0); expect(getSizedBoxWidth(), 100.0); expect(getSizedBoxCenterX(), 400.0); await buildWidget(300.0); expect(getSizedBoxWidth(), 300.0); expect(getSizedBoxCenterX(), 400.0); }); }); group('pre-transform viewport', () { testWidgets('ListWheelScrollView starts and ends from the middle', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); final List<int> paintedChildren = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ); }), ), ), ); // Screen is 600px tall and the first item starts at 250px. The first 4 // children are visible. expect(paintedChildren, <int>[0, 1, 2, 3]); controller.jumpTo(1000.0); paintedChildren.clear(); await tester.pump(); // Item number 10 is now in the middle of the screen at 250px. 9, 8, 7 are // visible before it and 11, 12, 13 are visible after it. expect(paintedChildren, <int>[7, 8, 9, 10, 11, 12, 13]); // Move to the last item. controller.jumpTo(9900.0); paintedChildren.clear(); await tester.pump(); // Item 99 is in the middle at 250px. expect(paintedChildren, <int>[96, 97, 98, 99]); }); testWidgets('A child gets painted as soon as its first pixel is in the viewport', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 50.0); addTearDown(controller.dispose); final List<int> paintedChildren = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: List<Widget>.generate(10, (int index) { return CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ); }), ), ), ); // Screen is 600px tall and the first item starts at 200px. The first 4 // children are visible. expect(paintedChildren, <int>[0, 1, 2, 3]); paintedChildren.clear(); // Move down by 1px. await tester.drag(find.byType(ListWheelScrollView), const Offset(0.0, -1.0)); await tester.pump(); // Now the first pixel of item 5 enters the viewport. expect(paintedChildren, <int>[0, 1, 2, 3, 4]); }); testWidgets('A child is no longer painted after its last pixel leaves the viewport', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 250.0); addTearDown(controller.dispose); final List<int> paintedChildren = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: List<Widget>.generate(10, (int index) { return CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ); }), ), ), ); // The first item is at 0px and the 600px screen is full in the // **untransformed plane's viewport painting coordinates** expect(paintedChildren, <int>[0, 1, 2, 3, 4, 5]); paintedChildren.clear(); // Go down another 99px. controller.jumpTo(349.0); await tester.pump(); // One more item now visible with the last pixel of 0 showing. expect(paintedChildren, <int>[0, 1, 2, 3, 4, 5, 6]); paintedChildren.clear(); // Go down one more pixel. controller.jumpTo(350.0); await tester.pump(); // Item 0 no longer visible. expect(paintedChildren, <int>[1, 2, 3, 4, 5, 6]); }); }); group('viewport transformation', () { testWidgets('Center child is magnified', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RepaintBoundary( key: const Key('list_wheel_scroll_view'), child: ListWheelScrollView( useMagnifier: true, magnification: 2.0, itemExtent: 50.0, children: List<Widget>.generate(10, (int index) { return const Placeholder(); }), ), ), ), ); await expectLater( find.byKey(const Key('list_wheel_scroll_view')), matchesGoldenFile('list_wheel_scroll_view.center_child.magnified.png'), ); }); testWidgets('Default middle transform', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, children: const <Widget>[ SizedBox( width: 200.0, child: Center( child: Text('blah'), ), ), ], ), ), ); final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; expect(viewport, paints..transform( matrix4: equals(<dynamic>[ 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.2 /* origin centering multiplied */, -0.9/* origin centering multiplied*/, 1.0, -0.003 /* inverse of perspective */, moreOrLessEquals(0.0), moreOrLessEquals(0.0), 0.0, moreOrLessEquals(1.0), ]), )); }); testWidgets('Curve the wheel to the left', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 300.0); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RepaintBoundary( key: const Key('list_wheel_scroll_view'), child: ListWheelScrollView( controller: controller, offAxisFraction: 0.5, itemExtent: 50.0, children: List<Widget>.generate(32, (int index) { return const Placeholder(); }), ), ), ), ); await expectLater( find.byKey(const Key('list_wheel_scroll_view')), matchesGoldenFile('list_wheel_scroll_view.curved_wheel.left.png'), ); }); testWidgets('Scrolling, diameterRatio, perspective all changes matrix', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 200.0); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: const <Widget>[ SizedBox( width: 200.0, child: Center( child: Text('blah'), ), ), ], ), ), ); final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; expect(viewport, paints..transform( matrix4: equals(<dynamic>[ 1.0, 0.0, 0.0, 0.0, moreOrLessEquals(-0.41042417199080244), moreOrLessEquals(0.6318744917928065), moreOrLessEquals(0.3420201433256687), moreOrLessEquals(-0.0010260604299770061), moreOrLessEquals(-1.12763114494309), moreOrLessEquals(-1.1877435020329863), moreOrLessEquals(0.9396926207859084), moreOrLessEquals(-0.0028190778623577253), moreOrLessEquals(166.54856463138663), moreOrLessEquals(-62.20844875763376), moreOrLessEquals(-138.79047052615562), moreOrLessEquals(1.4163714115784667), ]), )); // Increase diameter. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, diameterRatio: 3.0, itemExtent: 100.0, children: const <Widget>[ SizedBox( width: 200.0, child: Center( child: Text('blah'), ), ), ], ), ), ); expect(viewport, paints..transform( matrix4: equals(<dynamic>[ 1.0, 0.0, 0.0, 0.0, moreOrLessEquals(-0.26954971336161726), moreOrLessEquals(0.7722830529455648), moreOrLessEquals(0.22462476113468105), moreOrLessEquals(-0.0006738742834040432), moreOrLessEquals(-1.1693344055601331), moreOrLessEquals(-1.101625565304781), moreOrLessEquals(0.9744453379667777), moreOrLessEquals(-0.002923336013900333), moreOrLessEquals(108.46394900436536), moreOrLessEquals(-113.14792465797223), moreOrLessEquals(-90.38662417030434), moreOrLessEquals(1.2711598725109134), ]), )); // Decrease perspective. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, perspective: 0.0001, itemExtent: 100.0, children: const <Widget>[ SizedBox( width: 200.0, child: Center( child: Text('blah'), ), ), ], ), ), ); expect(viewport, paints..transform( matrix4: equals(<dynamic>[ 1.0, 0.0, 0.0, 0.0, moreOrLessEquals(-0.01368080573302675), moreOrLessEquals(0.9294320164861384), moreOrLessEquals(0.3420201433256687), moreOrLessEquals(-0.000034202014332566874), moreOrLessEquals(-0.03758770483143634), moreOrLessEquals(-0.370210921949246), moreOrLessEquals(0.9396926207859084), moreOrLessEquals(-0.00009396926207859085), moreOrLessEquals(5.551618821046304), moreOrLessEquals(-182.95615811538906), moreOrLessEquals(-138.79047052615562), moreOrLessEquals(1.0138790470526158), ]), )); // Scroll a bit. controller.jumpTo(300.0); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: const <Widget>[ SizedBox( width: 200.0, child: Center( child: Text('blah'), ), ), ], ), ), ); expect(viewport, paints..transform( matrix4: equals(<dynamic>[ 1.0, 0.0, 0.0, 0.0, -0.6, moreOrLessEquals(0.41602540378443875), moreOrLessEquals(0.5), moreOrLessEquals(-0.0015), moreOrLessEquals(-1.0392304845413265), moreOrLessEquals(-1.2794228634059948), moreOrLessEquals(0.8660254037844387), moreOrLessEquals(-0.0025980762113533163), moreOrLessEquals(276.46170927520404), moreOrLessEquals(-52.46133917892857), moreOrLessEquals(-230.38475772933677), moreOrLessEquals(1.69115427318801), ]), )); }); testWidgets('offAxisFraction, magnification changes matrix', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 200.0); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, offAxisFraction: 0.5, children: const <Widget>[ SizedBox( width: 200.0, child: Center( child: Text('blah'), ), ), ], ), ), ); final RenderListWheelViewport viewport = tester.renderObject(find.byType(ListWheelViewport)) as RenderListWheelViewport; expect( viewport, paints ..transform( matrix4: equals(<dynamic>[ 1.0, 0.0, 0.0, 0.0, 0.0, moreOrLessEquals(0.6318744917928063), moreOrLessEquals(0.3420201433256688), moreOrLessEquals(-0.0010260604299770066), 0.0, moreOrLessEquals(-1.1877435020329863), moreOrLessEquals(0.9396926207859083), moreOrLessEquals(-0.002819077862357725), 0.0, moreOrLessEquals(-62.20844875763376), moreOrLessEquals(-138.79047052615562), moreOrLessEquals(1.4163714115784667), ]), ), ); controller.jumpTo(0.0); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, offAxisFraction: 0.5, useMagnifier: true, magnification: 1.5, children: const <Widget>[ SizedBox( width: 200.0, child: Center( child: Text('blah'), ), ), ], ), ), ); expect( viewport, paints ..transform( matrix4: equals(<dynamic>[ 1.5, 0.0, 0.0, 0.0, 0.0, 1.5, 0.0, 0.0, 0.0, 0.0, 1.5, 0.0, 0.0, -150.0, 0.0, 1.0, ]), ), ); }); }); group('scroll notifications', () { testWidgets('no onSelectedItemChanged callback on first build', (WidgetTester tester) async { bool itemChangeCalled = false; void onItemChange(int _) { itemChangeCalled = true; } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, onSelectedItemChanged: onItemChange, children: const <Widget>[ SizedBox( width: 200.0, child: Center( child: Text('blah'), ), ), ], ), ), ); expect(itemChangeCalled, false); }); testWidgets('onSelectedItemChanged when a new item is closest to center', (WidgetTester tester) async { final List<int> selectedItems = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, onSelectedItemChanged: (int index) { selectedItems.add(index); }, children: List<Widget>.generate(10, (int index) { return const Placeholder(); }), ), ), ); final TestGesture scrollGesture = await tester.startGesture(const Offset(10.0, 10.0)); // Item 0 is still closest to the center. No updates. await scrollGesture.moveBy(const Offset(0.0, -49.0)); expect(selectedItems.isEmpty, true); // Now item 1 is closest to the center. await scrollGesture.moveBy(const Offset(0.0, -1.0)); expect(selectedItems, <int>[1]); // Now item 1 is still closest to the center for another full itemExtent (100px). await scrollGesture.moveBy(const Offset(0.0, -99.0)); expect(selectedItems, <int>[1]); await scrollGesture.moveBy(const Offset(0.0, -1.0)); expect(selectedItems, <int>[1, 2]); // Going back triggers previous item indices. await scrollGesture.moveBy(const Offset(0.0, 50.0)); expect(selectedItems, <int>[1, 2, 1]); }); testWidgets('onSelectedItemChanged reports only in valid range', (WidgetTester tester) async { final List<int> selectedItems = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, onSelectedItemChanged: (int index) { selectedItems.add(index); }, // So item 0 is at 0 and item 9 is at 900 in the scrollable range. children: List<Widget>.generate(10, (int index) { return const Placeholder(); }), ), ), ); final TestGesture scrollGesture = await tester.startGesture(const Offset(10.0, 10.0)); // First move back past the beginning. await scrollGesture.moveBy(const Offset(0.0, 70.0)); for (double verticalOffset = 0.0; verticalOffset > -2000.0; verticalOffset -= 10.0) { // Then gradually move down by a total vertical extent much higher than // the scrollable extent. await scrollGesture.moveTo(Offset(0.0, verticalOffset)); } // The list should only cover the list of valid items. Item 0 would not // be included because the current item never left the 0 index until it // went to 1. expect(selectedItems, <int>[1, 2, 3, 4, 5, 6, 7, 8, 9]); }); }); group('scroll controller', () { testWidgets('initialItem', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 10); addTearDown(controller.dispose); final List<int> paintedChildren = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ); }), ), ), ); // Screen is 600px tall. Item 10 is in the center and each item is 100px tall. expect(paintedChildren, <int>[7, 8, 9, 10, 11, 12, 13]); expect(controller.selectedItem, 10); }); testWidgets('controller jump', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 10); addTearDown(controller.dispose); final List<int> paintedChildren = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ); }), ), ), ); // Screen is 600px tall. Item 10 is in the center and each item is 100px tall. expect(paintedChildren, <int>[7, 8, 9, 10, 11, 12, 13]); paintedChildren.clear(); controller.jumpToItem(0); await tester.pump(); expect(paintedChildren, <int>[0, 1, 2, 3]); expect(controller.selectedItem, 0); }); testWidgets('controller animateToItem', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 10); addTearDown(controller.dispose); final List<int> paintedChildren = <int>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ); }), ), ), ); // Screen is 600px tall. Item 10 is in the center and each item is 100px tall. expect(paintedChildren, <int>[7, 8, 9, 10, 11, 12, 13]); paintedChildren.clear(); controller.animateToItem( 0, duration: const Duration(seconds: 1), curve: Curves.linear, ); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(paintedChildren, <int>[0, 1, 2, 3]); expect(controller.selectedItem, 0); }); testWidgets('onSelectedItemChanged and controller are in sync', (WidgetTester tester) async { final List<int> selectedItems = <int>[]; final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 10); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, onSelectedItemChanged: (int index) { selectedItems.add(index); }, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), ), ), ); final TestGesture scrollGesture = await tester.startGesture(const Offset(10.0, 10.0)); await scrollGesture.moveBy(const Offset(0.0, -49.0)); await tester.pump(); expect(selectedItems.isEmpty, true); expect(controller.selectedItem, 10); await scrollGesture.moveBy(const Offset(0.0, -1.0)); await tester.pump(); expect(selectedItems, <int>[11]); expect(controller.selectedItem, 11); await scrollGesture.moveBy(const Offset(0.0, 70.0)); await tester.pump(); expect(selectedItems, <int>[11, 10]); expect(controller.selectedItem, 10); }); testWidgets('controller hot swappable', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), ), ), ); // Item 5 is now selected. await tester.drag(find.byType(ListWheelScrollView), const Offset(0.0, -500.0)); await tester.pump(); final FixedExtentScrollController controller1 = FixedExtentScrollController(initialItem: 30); addTearDown(controller1.dispose); // Attaching first controller. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller1, itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), ), ), ); // initialItem doesn't do anything since the scroll position was already // created. expect(controller1.selectedItem, 5); controller1.jumpToItem(50); expect(controller1.selectedItem, 50); expect(controller1.position.pixels, 5000.0); final FixedExtentScrollController controller2 = FixedExtentScrollController(initialItem: 33); addTearDown(controller2.dispose); // Attaching the second controller. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller2, itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), ), ), ); // First controller is now detached. expect(controller1.hasClients, isFalse); // initialItem doesn't do anything since the scroll position was already // created. expect(controller2.selectedItem, 50); controller2.jumpToItem(40); expect(controller2.selectedItem, 40); expect(controller2.position.pixels, 4000.0); // Now, use the internal controller. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), ), ), ); // Both controllers are now detached. expect(controller1.hasClients, isFalse); expect(controller2.hasClients, isFalse); }); testWidgets('controller can be reused', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 3); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), ), ), ); // selectedItem is equal to the initialItem. expect(controller.selectedItem, 3); expect(controller.position.pixels, 300.0); controller.jumpToItem(10); expect(controller.selectedItem, 10); expect(controller.position.pixels, 1000.0); await tester.pumpWidget(const Center()); // Controller is now detached. expect(controller.hasClients, isFalse); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), ), ), ); // Controller is now attached again. expect(controller.hasClients, isTrue); expect(controller.selectedItem, 3); expect(controller.position.pixels, 300.0); }); }); group('physics', () { testWidgets('fling velocities too low snaps back to the same item', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 40); addTearDown(controller.dispose); final List<double> scrolledPositions = <double>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<ScrollNotification>( onNotification: (ScrollNotification notification) { if (notification is ScrollUpdateNotification) { scrolledPositions.add(notification.metrics.pixels); } return false; }, child: ListWheelScrollView( controller: controller, physics: const FixedExtentScrollPhysics(), itemExtent: 1000.0, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), ), ), ), ); await tester.fling( find.byType(ListWheelScrollView), const Offset(0.0, -50.0), 800.0, ); // At this moment, the ballistics is started but 50px is still inside the // initial item. expect(controller.selectedItem, 40); // A tester.fling creates and pumps 50 pointer events. expect(scrolledPositions.length, 50); expect(scrolledPositions.last, moreOrLessEquals(40 * 1000.0 + 50.0, epsilon: 0.2)); // Let the spring back simulation finish. await tester.pump(); await tester.pump(const Duration(seconds: 1)); // The simulation actually did stuff after start ballistics. expect(scrolledPositions.length, greaterThan(50)); // Though it still lands back to the same item with the same scroll offset. expect(controller.selectedItem, 40); expect(scrolledPositions.last, moreOrLessEquals(40 * 1000.0, epsilon: 0.2)); }); testWidgets('high fling velocities lands exactly on items', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 40); addTearDown(controller.dispose); final List<double> scrolledPositions = <double>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<ScrollNotification>( onNotification: (ScrollNotification notification) { if (notification is ScrollUpdateNotification) { scrolledPositions.add(notification.metrics.pixels); } return false; }, child: ListWheelScrollView( controller: controller, physics: const FixedExtentScrollPhysics(), itemExtent: 100.0, children: List<Widget>.generate(100, (int index) { return const Placeholder(); }), ), ), ), ); await tester.fling( find.byType(ListWheelScrollView), // High and random numbers that's unlikely to land on exact multiples of 100. const Offset(0.0, -567.0), // macOS has reduced ballistic distance, need to increase speed to compensate. debugDefaultTargetPlatformOverride == TargetPlatform.macOS ? 1678.0 : 678.0, ); // After the drag, 40 + 567px should be on the 46th item. expect(controller.selectedItem, 46); // A tester.fling creates and pumps 50 pointer events. expect(scrolledPositions.length, 50); // iOS flings ease-in initially. expect(scrolledPositions.last, moreOrLessEquals(40 * 100.0 + 556.826666666673, epsilon: 0.2)); // Let the spring back simulation finish. await tester.pumpAndSettle(); // The simulation actually did stuff after start ballistics. expect(scrolledPositions.length, greaterThan(50)); // Lands on 49. expect(controller.selectedItem, 49); // More importantly, lands tightly on 49. expect(scrolledPositions.last, moreOrLessEquals(49 * 100.0, epsilon: 0.3)); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); }); testWidgets('ListWheelScrollView getOffsetToReveal', (WidgetTester tester) async { List<Widget> outerChildren; final List<Widget> innerChildren = List<Widget>.generate(10, (int index) => Container()); final ScrollController controller = ScrollController(initialScrollOffset: 300.0); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: 500.0, width: 300.0, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: outerChildren = List<Widget>.generate(10, (int i) { return Center( child: innerChildren[i] = SizedBox( height: 50.0, width: 50.0, child: Text('Item $i'), ), ); }), ), ), ), ), ); final RenderListWheelViewport viewport = tester.allRenderObjects.whereType<RenderListWheelViewport>().first; // direct child of viewport RenderObject target = tester.renderObject(find.byWidget(outerChildren[5])); RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(0.0, 200.0, 300.0, 100.0)); revealed = viewport.getOffsetToReveal(target, 1.0); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(0.0, 200.0, 300.0, 100.0)); revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(40.0, 240.0, 10.0, 10.0)); revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(40.0, 240.0, 10.0, 10.0)); // descendant of viewport, not direct child target = tester.renderObject(find.byWidget(innerChildren[5])); revealed = viewport.getOffsetToReveal(target, 0.0); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(125.0, 225.0, 50.0, 50.0)); revealed = viewport.getOffsetToReveal(target, 1.0); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(125.0, 225.0, 50.0, 50.0)); revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(165.0, 265.0, 10.0, 10.0)); revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0)); expect(revealed.offset, 500.0); expect(revealed.rect, const Rect.fromLTWH(165.0, 265.0, 10.0, 10.0)); }); testWidgets('will not assert on getOffsetToReveal Axis', (WidgetTester tester) async { final ScrollController controller = ScrollController(initialScrollOffset: 300.0); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: 500.0, width: 300.0, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: List<Widget>.generate(10, (int i) { return Center( child: SizedBox( height: 50.0, width: 50.0, child: Text('Item $i'), ), ); }), ), ), ), ), ); final RenderListWheelViewport viewport = tester.allRenderObjects.whereType<RenderListWheelViewport>().first; final RenderObject target = tester.renderObject(find.text('Item 5')); viewport.getOffsetToReveal(target, 0.0, axis: Axis.horizontal); }); testWidgets('ListWheelScrollView showOnScreen', (WidgetTester tester) async { List<Widget> outerChildren; final List<Widget> innerChildren = List<Widget>.generate(10, (int index) => Container()); final ScrollController controller = ScrollController(initialScrollOffset: 300.0); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: 500.0, width: 300.0, child: ListWheelScrollView( controller: controller, itemExtent: 100.0, children: outerChildren = List<Widget>.generate(10, (int i) { return Center( child: innerChildren[i] = SizedBox( height: 50.0, width: 50.0, child: Text('Item $i'), ), ); }), ), ), ), ), ); expect(controller.offset, 300.0); tester.renderObject(find.byWidget(outerChildren[5])).showOnScreen(); await tester.pumpAndSettle(); expect(controller.offset, 500.0); tester.renderObject(find.byWidget(outerChildren[7])).showOnScreen(); await tester.pumpAndSettle(); expect(controller.offset, 700.0); tester.renderObject(find.byWidget(innerChildren[9])).showOnScreen(); await tester.pumpAndSettle(); expect(controller.offset, 900.0); tester.renderObject(find.byWidget(outerChildren[7])).showOnScreen(duration: const Duration(seconds: 2)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(tester.hasRunningAnimations, isTrue); expect(controller.offset, lessThan(900.0)); expect(controller.offset, greaterThan(700.0)); await tester.pumpAndSettle(); expect(controller.offset, 700.0); }); group('gestures', () { testWidgets('ListWheelScrollView allows taps for on its children', (WidgetTester tester) async { final FixedExtentScrollController controller = FixedExtentScrollController(initialItem: 10); addTearDown(controller.dispose); final List<int> children = List<int>.generate(100, (int index) => index); final List<int> paintedChildren = <int>[]; final Set<int> tappedChildren = <int>{}; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( controller: controller, itemExtent: 100, children: children .map((int index) => GestureDetector( key: ValueKey<int>(index), onTap: () { tappedChildren.add(index); }, child: SizedBox( width: 100, height: 100, child: CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ), ), )) .toList(), ), ), ); // Screen is 600px tall. Item 10 is in the center and each item is 100px tall. expect(paintedChildren, <int>[7, 8, 9, 10, 11, 12, 13]); for (final int child in paintedChildren) { await tester.tap(find.byKey(ValueKey<int>(child))); } expect(tappedChildren, paintedChildren); }); testWidgets('ListWheelScrollView allows for horizontal drags on its children', (WidgetTester tester) async { final PageController pageController = PageController(); addTearDown(pageController.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListWheelScrollView( itemExtent: 100, children: <Widget>[ PageView( controller: pageController, children: List<int>.generate(100, (int index) => index) .map((int index) => Text(index.toString())) .toList(), ), ], ), ), ); expect(pageController.page, 0.0); await tester.drag(find.byType(PageView), const Offset(-800, 0)); expect(pageController.page, 1.0); }); testWidgets('ListWheelScrollView does not crash and does not allow taps on children that were laid out, but not painted', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/126491 final FixedExtentScrollController controller = FixedExtentScrollController(); addTearDown(controller.dispose); final List<int> children = List<int>.generate(100, (int index) => index); final List<int> paintedChildren = <int>[]; final Set<int> tappedChildren = <int>{}; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: 120, child: ListWheelScrollView.useDelegate( controller: controller, physics: const FixedExtentScrollPhysics(), diameterRatio: 0.9, itemExtent: 55, squeeze: 1.45, childDelegate: ListWheelChildListDelegate( children: children .map((int index) => GestureDetector( key: ValueKey<int>(index), onTap: () { tappedChildren.add(index); }, child: SizedBox( width: 55, height: 55, child: CustomPaint( painter: TestCallbackPainter(onPaint: () { paintedChildren.add(index); }), ), ), )) .toList(), ), ), ), ), ), ); expect(paintedChildren, <int>[0, 1]); // Expect hitting 0 and 1, which are painted await tester.tap(find.byKey(const ValueKey<int>(0))); expect(tappedChildren, const <int>[0]); await tester.tap(find.byKey(const ValueKey<int>(1))); expect(tappedChildren, const <int>[0, 1]); // The third child is not painted, so is not hit await tester.tap(find.byKey(const ValueKey<int>(2)), warnIfMissed: false); expect(tappedChildren, const <int>[0, 1]); }); }); testWidgets('ListWheelScrollView creates only one opacity layer for all children', (WidgetTester tester) async { await tester.pumpWidget( ListWheelScrollView( overAndUnderCenterOpacity: 0.5, itemExtent: 20.0, children: <Widget>[ for (int i = 0; i < 20; i++) Container(), ], ), ); expect(tester.layers.whereType<OpacityLayer>(), hasLength(1)); }); // This is a regression test for https://github.com/flutter/flutter/issues/140780. testWidgets('ListWheelScrollView in an AnimatedContainer with zero height does not throw an error', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: AnimatedContainer( height: 0, duration: Duration.zero, child: ListWheelScrollView( itemExtent: 20.0, children: <Widget>[ for (int i = 0; i < 20; i++) Container(), ], ), ), ), ), ); expect(tester.takeException(), isNull); }); }
flutter/packages/flutter/test/widgets/list_wheel_scroll_view_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/list_wheel_scroll_view_test.dart", "repo_id": "flutter", "token_count": 30508 }
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 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'test_widgets.dart'; void checkTree(WidgetTester tester, List<BoxDecoration> expectedDecorations) { final MultiChildRenderObjectElement element = tester.element(find.byElementPredicate( (Element element) => element is MultiChildRenderObjectElement, )); expect(element, isNotNull); expect(element.renderObject, isA<RenderStack>()); final RenderStack renderObject = element.renderObject as RenderStack; try { RenderObject? child = renderObject.firstChild; for (final BoxDecoration decoration in expectedDecorations) { expect(child, isA<RenderDecoratedBox>()); final RenderDecoratedBox decoratedBox = child! as RenderDecoratedBox; expect(decoratedBox.decoration, equals(decoration)); final StackParentData decoratedBoxParentData = decoratedBox.parentData! as StackParentData; child = decoratedBoxParentData.nextSibling; } expect(child, isNull); } catch (e) { debugPrint(renderObject.toStringDeep()); rethrow; } } void main() { testWidgets('MultiChildRenderObjectElement control test', (WidgetTester tester) async { await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), DecoratedBox(decoration: kBoxDecorationB), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationC]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), DecoratedBox(key: Key('b'), decoration: kBoxDecorationB), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(key: Key('b'), decoration: kBoxDecorationB), DecoratedBox(decoration: kBoxDecorationC), DecoratedBox(key: Key('a'), decoration: kBoxDecorationA), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationB, kBoxDecorationC, kBoxDecorationA]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(key: Key('a'), decoration: kBoxDecorationA), DecoratedBox(decoration: kBoxDecorationC), DecoratedBox(key: Key('b'), decoration: kBoxDecorationB), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationC, kBoxDecorationB]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationC]); await tester.pumpWidget( const Stack(textDirection: TextDirection.ltr), ); checkTree(tester, <BoxDecoration>[]); }); testWidgets('MultiChildRenderObjectElement with stateless widgets', (WidgetTester tester) async { await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), DecoratedBox(decoration: kBoxDecorationB), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), DummyWidget( child: DecoratedBox(decoration: kBoxDecorationB), ), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), DummyWidget( child: DummyWidget( child: DecoratedBox(decoration: kBoxDecorationB), ), ), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationB, kBoxDecorationC]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DummyWidget( child: DummyWidget( child: DecoratedBox(decoration: kBoxDecorationB), ), ), DummyWidget( child: DecoratedBox(decoration: kBoxDecorationA), ), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationB, kBoxDecorationA, kBoxDecorationC]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DummyWidget( child: DecoratedBox(decoration: kBoxDecorationB), ), DummyWidget( child: DecoratedBox(decoration: kBoxDecorationA), ), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationB, kBoxDecorationA, kBoxDecorationC]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DummyWidget( key: Key('b'), child: DecoratedBox(decoration: kBoxDecorationB), ), DummyWidget( key: Key('a'), child: DecoratedBox(decoration: kBoxDecorationA), ), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationB, kBoxDecorationA]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DummyWidget( key: Key('a'), child: DecoratedBox(decoration: kBoxDecorationA), ), DummyWidget( key: Key('b'), child: DecoratedBox(decoration: kBoxDecorationB), ), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationB]); await tester.pumpWidget( const Stack(textDirection: TextDirection.ltr), ); checkTree(tester, <BoxDecoration>[]); }); testWidgets('MultiChildRenderObjectElement with stateful widgets', (WidgetTester tester) async { await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(decoration: kBoxDecorationA), DecoratedBox(decoration: kBoxDecorationB), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationB]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ FlipWidget( left: DecoratedBox(decoration: kBoxDecorationA), right: DecoratedBox(decoration: kBoxDecorationB), ), DecoratedBox(decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationA, kBoxDecorationC]); flipStatefulWidget(tester); await tester.pump(); checkTree(tester, <BoxDecoration>[kBoxDecorationB, kBoxDecorationC]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ FlipWidget( left: DecoratedBox(decoration: kBoxDecorationA), right: DecoratedBox(decoration: kBoxDecorationB), ), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationB]); flipStatefulWidget(tester); await tester.pump(); checkTree(tester, <BoxDecoration>[kBoxDecorationA]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ FlipWidget( key: Key('flip'), left: DecoratedBox(decoration: kBoxDecorationA), right: DecoratedBox(decoration: kBoxDecorationB), ), ], ), ); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ DecoratedBox(key: Key('c'), decoration: kBoxDecorationC), FlipWidget( key: Key('flip'), left: DecoratedBox(decoration: kBoxDecorationA), right: DecoratedBox(decoration: kBoxDecorationB), ), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationC, kBoxDecorationA]); flipStatefulWidget(tester); await tester.pump(); checkTree(tester, <BoxDecoration>[kBoxDecorationC, kBoxDecorationB]); await tester.pumpWidget( const Stack( textDirection: TextDirection.ltr, children: <Widget>[ FlipWidget( key: Key('flip'), left: DecoratedBox(decoration: kBoxDecorationA), right: DecoratedBox(decoration: kBoxDecorationB), ), DecoratedBox(key: Key('c'), decoration: kBoxDecorationC), ], ), ); checkTree(tester, <BoxDecoration>[kBoxDecorationB, kBoxDecorationC]); }); } class DummyWidget extends StatelessWidget { const DummyWidget({ super.key, required this.child }); final Widget child; @override Widget build(BuildContext context) => child; }
flutter/packages/flutter/test/widgets/multichild_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/multichild_test.dart", "repo_id": "flutter", "token_count": 4592 }
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:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'semantics_tester.dart'; void main() { test('OverlayEntry dispatches memory events', () async { await expectLater( await memoryEvents( () => OverlayEntry( builder: (BuildContext context) => Container(), ).dispose(), OverlayEntry, ), areCreateAndDispose, ); }); testWidgets('OverflowEntries context contains Overlay', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); bool didBuild = false; late final OverlayEntry overlayEntry1; addTearDown(() => overlayEntry1..remove()..dispose()); late final OverlayEntry overlayEntry2; addTearDown(() => overlayEntry2..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ overlayEntry1 = OverlayEntry( builder: (BuildContext context) { didBuild = true; final Overlay overlay = context.findAncestorWidgetOfExactType<Overlay>()!; expect(overlay.key, equals(overlayKey)); return Container(); }, ), overlayEntry2 = OverlayEntry( builder: (BuildContext context) => Container(), ), ], ), ), ); expect(didBuild, isTrue); final RenderObject theater = overlayKey.currentContext!.findRenderObject()!; expect(theater, hasAGoodToStringDeep); expect( theater.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( '_RenderTheater#744c9\n' ' │ parentData: <none>\n' ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' │ size: Size(800.0, 600.0)\n' ' │ skipCount: 0\n' ' │ textDirection: ltr\n' ' │\n' ' ├─onstage 1: RenderLimitedBox#bb803\n' ' │ │ parentData: not positioned; offset=Offset(0.0, 0.0) (can use\n' ' │ │ size)\n' ' │ │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' │ │ size: Size(800.0, 600.0)\n' ' │ │ maxWidth: 0.0\n' ' │ │ maxHeight: 0.0\n' ' │ │\n' ' │ └─child: RenderConstrainedBox#62707\n' ' │ parentData: <none> (can use size)\n' ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' │ size: Size(800.0, 600.0)\n' ' │ additionalConstraints: BoxConstraints(biggest)\n' ' │\n' ' ├─onstage 2: RenderLimitedBox#af5f1\n' ' ╎ │ parentData: not positioned; offset=Offset(0.0, 0.0) (can use\n' ' ╎ │ size)\n' ' ╎ │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' ╎ │ size: Size(800.0, 600.0)\n' ' ╎ │ maxWidth: 0.0\n' ' ╎ │ maxHeight: 0.0\n' ' ╎ │\n' ' ╎ └─child: RenderConstrainedBox#69c48\n' ' ╎ parentData: <none> (can use size)\n' ' ╎ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' ╎ size: Size(800.0, 600.0)\n' ' ╎ additionalConstraints: BoxConstraints(biggest)\n' ' ╎\n' ' └╌no offstage children\n', ), ); }); testWidgets('Offstage overlay', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); late final OverlayEntry overlayEntry1; addTearDown(() => overlayEntry1..remove()..dispose()); late final OverlayEntry overlayEntry2; addTearDown(() => overlayEntry2..remove()..dispose()); late final OverlayEntry overlayEntry3; addTearDown(() => overlayEntry3..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ overlayEntry1 = OverlayEntry( opaque: true, maintainState: true, builder: (BuildContext context) => Container(), ), overlayEntry2 = OverlayEntry( opaque: true, maintainState: true, builder: (BuildContext context) => Container(), ), overlayEntry3 = OverlayEntry( opaque: true, maintainState: true, builder: (BuildContext context) => Container(), ), ], ), ), ); final RenderObject theater = overlayKey.currentContext!.findRenderObject()!; expect(theater, hasAGoodToStringDeep); expect( theater.toStringDeep(minLevel: DiagnosticLevel.info), equalsIgnoringHashCodes( '_RenderTheater#385b3\n' ' │ parentData: <none>\n' ' │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' │ size: Size(800.0, 600.0)\n' ' │ skipCount: 2\n' ' │ textDirection: ltr\n' ' │\n' ' ├─onstage 1: RenderLimitedBox#0a77a\n' ' ╎ │ parentData: not positioned; offset=Offset(0.0, 0.0) (can use\n' ' ╎ │ size)\n' ' ╎ │ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' ╎ │ size: Size(800.0, 600.0)\n' ' ╎ │ maxWidth: 0.0\n' ' ╎ │ maxHeight: 0.0\n' ' ╎ │\n' ' ╎ └─child: RenderConstrainedBox#21f3a\n' ' ╎ parentData: <none> (can use size)\n' ' ╎ constraints: BoxConstraints(w=800.0, h=600.0)\n' ' ╎ size: Size(800.0, 600.0)\n' ' ╎ additionalConstraints: BoxConstraints(biggest)\n' ' ╎\n' ' ╎╌offstage 1: RenderLimitedBox#62c8c NEEDS-LAYOUT NEEDS-PAINT\n' ' ╎ │ parentData: not positioned; offset=Offset(0.0, 0.0)\n' ' ╎ │ constraints: MISSING\n' ' ╎ │ size: MISSING\n' ' ╎ │ maxWidth: 0.0\n' ' ╎ │ maxHeight: 0.0\n' ' ╎ │\n' ' ╎ └─child: RenderConstrainedBox#425fa NEEDS-LAYOUT NEEDS-PAINT\n' ' ╎ parentData: <none>\n' ' ╎ constraints: MISSING\n' ' ╎ size: MISSING\n' ' ╎ additionalConstraints: BoxConstraints(biggest)\n' ' ╎\n' ' └╌offstage 2: RenderLimitedBox#03ae2 NEEDS-LAYOUT NEEDS-PAINT\n' ' │ parentData: not positioned; offset=Offset(0.0, 0.0)\n' ' │ constraints: MISSING\n' ' │ size: MISSING\n' ' │ maxWidth: 0.0\n' ' │ maxHeight: 0.0\n' ' │\n' ' └─child: RenderConstrainedBox#b4d48 NEEDS-LAYOUT NEEDS-PAINT\n' ' parentData: <none>\n' ' constraints: MISSING\n' ' size: MISSING\n' ' additionalConstraints: BoxConstraints(biggest)\n', ), ); }); testWidgets('insert top', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); final List<String> buildOrder = <String>[]; late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('Base'); return Container(); }, ), ], ), ), ); expect(buildOrder, <String>['Base']); buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; late final OverlayEntry newEntry; addTearDown(() => newEntry..remove()..dispose()); overlay.insert( newEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('New'); return Container(); }, ), ); await tester.pump(); expect(buildOrder, <String>['Base', 'New']); }); testWidgets('insert below', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); final List<String> buildOrder = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('Base'); return Container(); }, ), ], ), ), ); expect(buildOrder, <String>['Base']); buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; late final OverlayEntry newEntry; addTearDown(() => newEntry..remove()..dispose()); overlay.insert( newEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('New'); return Container(); }, ), below: baseEntry, ); await tester.pump(); expect(buildOrder, <String>['New', 'Base']); }); testWidgets('insert above', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); late final OverlayEntry topEntry; addTearDown(() => topEntry..remove()..dispose()); final List<String> buildOrder = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('Base'); return Container(); }, ), topEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('Top'); return Container(); }, ), ], ), ), ); expect(buildOrder, <String>['Base', 'Top']); buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; late final OverlayEntry newEntry; addTearDown(() => newEntry..remove()..dispose()); overlay.insert( newEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('New'); return Container(); }, ), above: baseEntry, ); await tester.pump(); expect(buildOrder, <String>['Base', 'New', 'Top']); }); testWidgets('insertAll top', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); final List<String> buildOrder = <String>[]; late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('Base'); return Container(); }, ), ], ), ), ); expect(buildOrder, <String>['Base']); final List<OverlayEntry> entries = <OverlayEntry>[ OverlayEntry( builder: (BuildContext context) { buildOrder.add('New1'); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add('New2'); return Container(); }, ), ]; addTearDown(() { for (final OverlayEntry entry in entries) { entry..remove()..dispose(); } }); buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; overlay.insertAll(entries); await tester.pump(); expect(buildOrder, <String>['Base', 'New1', 'New2']); }); testWidgets('insertAll below', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); final List<String> buildOrder = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('Base'); return Container(); }, ), ], ), ), ); expect(buildOrder, <String>['Base']); final List<OverlayEntry> entries = <OverlayEntry>[ OverlayEntry( builder: (BuildContext context) { buildOrder.add('New1'); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add('New2'); return Container(); }, ), ]; addTearDown(() { for (final OverlayEntry entry in entries) { entry..remove()..dispose(); } }); buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; overlay.insertAll(entries, below: baseEntry); await tester.pump(); expect(buildOrder, <String>['New1', 'New2','Base']); }); testWidgets('insertAll above', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); final List<String> buildOrder = <String>[]; late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); late final OverlayEntry topEntry; addTearDown(() => topEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('Base'); return Container(); }, ), topEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add('Top'); return Container(); }, ), ], ), ), ); expect(buildOrder, <String>['Base', 'Top']); final List<OverlayEntry> entries = <OverlayEntry>[ OverlayEntry( builder: (BuildContext context) { buildOrder.add('New1'); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add('New2'); return Container(); }, ), ]; addTearDown(() { for (final OverlayEntry entry in entries) { entry..remove()..dispose(); } }); buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; overlay.insertAll(entries, above: baseEntry); await tester.pump(); expect(buildOrder, <String>['Base', 'New1', 'New2', 'Top']); }); testWidgets('rearrange', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); final List<int> buildOrder = <int>[]; final List<OverlayEntry> initialEntries = <OverlayEntry>[ OverlayEntry( builder: (BuildContext context) { buildOrder.add(0); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add(1); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add(2); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add(3); return Container(); }, ), ]; addTearDown(() { for (final OverlayEntry entry in initialEntries) { entry..remove()..dispose(); } }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: initialEntries, ), ), ); expect(buildOrder, <int>[0, 1, 2, 3]); late final OverlayEntry newEntry; addTearDown(() => newEntry..remove()..dispose()); final List<OverlayEntry> rearranged = <OverlayEntry>[ initialEntries[3], newEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add(4); return Container(); }, ), initialEntries[2], // 1 intentionally missing, will end up on top initialEntries[0], ]; buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; overlay.rearrange(rearranged); await tester.pump(); expect(buildOrder, <int>[3, 4, 2, 0, 1]); }); testWidgets('rearrange above', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); final List<int> buildOrder = <int>[]; final List<OverlayEntry> initialEntries = <OverlayEntry>[ OverlayEntry( builder: (BuildContext context) { buildOrder.add(0); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add(1); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add(2); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add(3); return Container(); }, ), ]; addTearDown(() { for (final OverlayEntry entry in initialEntries) { entry..remove()..dispose(); } }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: initialEntries, ), ), ); expect(buildOrder, <int>[0, 1, 2, 3]); late final OverlayEntry newEntry; addTearDown(() => newEntry..remove()..dispose()); final List<OverlayEntry> rearranged = <OverlayEntry>[ initialEntries[3], newEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add(4); return Container(); }, ), initialEntries[2], // 1 intentionally missing initialEntries[0], ]; buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; overlay.rearrange(rearranged, above: initialEntries[2]); await tester.pump(); expect(buildOrder, <int>[3, 4, 2, 1, 0]); }); testWidgets('rearrange below', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); final List<int> buildOrder = <int>[]; final List<OverlayEntry> initialEntries = <OverlayEntry>[ OverlayEntry( builder: (BuildContext context) { buildOrder.add(0); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add(1); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add(2); return Container(); }, ), OverlayEntry( builder: (BuildContext context) { buildOrder.add(3); return Container(); }, ), ]; addTearDown(() { for (final OverlayEntry entry in initialEntries) { entry..remove()..dispose(); } }); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: initialEntries, ), ), ); expect(buildOrder, <int>[0, 1, 2, 3]); late final OverlayEntry newEntry; addTearDown(() => newEntry..remove()..dispose()); final List<OverlayEntry> rearranged = <OverlayEntry>[ initialEntries[3], newEntry = OverlayEntry( builder: (BuildContext context) { buildOrder.add(4); return Container(); }, ), initialEntries[2], // 1 intentionally missing initialEntries[0], ]; buildOrder.clear(); final OverlayState overlay = overlayKey.currentState! as OverlayState; overlay.rearrange(rearranged, below: initialEntries[2]); await tester.pump(); expect(buildOrder, <int>[3, 4, 1, 2, 0]); }); testWidgets('debugVerifyInsertPosition', (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); late OverlayEntry base; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ base = _buildOverlayEntry((BuildContext context) { return Container(); }, ), ], ), ), ); final OverlayState overlay = overlayKey.currentState! as OverlayState; try { overlay.insert( _buildOverlayEntry((BuildContext context) { return Container(); }), above: _buildOverlayEntry((BuildContext context) { return Container(); }, ), below: _buildOverlayEntry((BuildContext context) { return Container(); }, ), ); } on AssertionError catch (e) { expect(e.message, 'Only one of `above` and `below` may be specified.'); } expect(() => overlay.insert( _buildOverlayEntry((BuildContext context) { return Container(); }), above: base, ), isNot(throwsAssertionError)); try { overlay.insert( _buildOverlayEntry((BuildContext context) { return Container(); }), above: _buildOverlayEntry((BuildContext context) { return Container(); }, ), ); } on AssertionError catch (e) { expect(e.message, 'The provided entry used for `above` must be present in the Overlay.'); } try { overlay.rearrange(<OverlayEntry>[base], above: _buildOverlayEntry((BuildContext context) { return Container(); }, )); } on AssertionError catch (e) { expect(e.message, 'The provided entry used for `above` must be present in the Overlay and in the `newEntriesList`.'); } await tester.pump(); }); testWidgets('OverlayState.of() throws when called if an Overlay does not exist', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Builder( builder: (BuildContext context) { late FlutterError error; final Widget debugRequiredFor = Container(); try { Overlay.of(context, debugRequiredFor: debugRequiredFor); } on FlutterError catch (e) { error = e; } finally { expect(error, isNotNull); expect(error.diagnostics.length, 5); expect(error.diagnostics[2].level, DiagnosticLevel.hint); expect(error.diagnostics[2].toStringDeep(), equalsIgnoringHashCodes( 'The most common way to add an Overlay to an application is to\n' 'include a MaterialApp, CupertinoApp or Navigator widget in the\n' 'runApp() call.\n' )); expect(error.diagnostics[3], isA<DiagnosticsProperty<Widget>>()); expect(error.diagnostics[3].value, debugRequiredFor); expect(error.diagnostics[4], isA<DiagnosticsProperty<Element>>()); expect(error.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' No Overlay widget found.\n' ' Container widgets require an Overlay widget ancestor for correct\n' ' operation.\n' ' The most common way to add an Overlay to an application is to\n' ' include a MaterialApp, CupertinoApp or Navigator widget in the\n' ' runApp() call.\n' ' The specific widget that failed to find an overlay was:\n' ' Container\n' ' The context from which that widget was searching for an overlay\n' ' was:\n' ' Builder\n' )); } return Container(); }, ), ), ); }); testWidgets("OverlayState.maybeOf() works when an Overlay does and doesn't exist", (WidgetTester tester) async { final GlobalKey overlayKey = GlobalKey(); OverlayState? foundState; late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { foundState = Overlay.maybeOf(context); return Container(); }, ), ], ), ), ); expect(tester.takeException(), isNull); expect(foundState, isNotNull); foundState = null; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Builder( builder: (BuildContext context) { foundState = Overlay.maybeOf(context); return const SizedBox(); }, ), ), ); expect(tester.takeException(), isNull); expect(foundState, isNull); }); testWidgets('OverlayEntry.opaque can be changed when OverlayEntry is not part of an Overlay (yet)', (WidgetTester tester) async { final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); final Key root = UniqueKey(); final Key top = UniqueKey(); final OverlayEntry rootEntry = OverlayEntry( builder: (BuildContext context) { return Container(key: root); }, ); addTearDown(() => rootEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ rootEntry, ], ), ), ); expect(find.byKey(root), findsOneWidget); final OverlayEntry newEntry = OverlayEntry( builder: (BuildContext context) { return Container(key: top); }, ); addTearDown(() => newEntry..remove()..dispose()); expect(newEntry.opaque, isFalse); newEntry.opaque = true; // Does neither trigger an assert nor throw. expect(newEntry.opaque, isTrue); // The new opaqueness is honored when inserted into an overlay. overlayKey.currentState!.insert(newEntry); await tester.pumpAndSettle(); expect(find.byKey(root), findsNothing); expect(find.byKey(top), findsOneWidget); }); testWidgets('OverlayEntries do not rebuild when opaqueness changes', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/45797. final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); final Key bottom = UniqueKey(); final Key middle = UniqueKey(); final Key top = UniqueKey(); final Widget bottomWidget = StatefulTestWidget(key: bottom); final Widget middleWidget = StatefulTestWidget(key: middle); final Widget topWidget = StatefulTestWidget(key: top); final OverlayEntry bottomEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return bottomWidget; }, ); addTearDown(() => bottomEntry..remove()..dispose()); final OverlayEntry middleEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return middleWidget; }, ); addTearDown(() => middleEntry..remove()..dispose()); final OverlayEntry topEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return topWidget; }, ); addTearDown(() => topEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ bottomEntry, middleEntry, topEntry, ], ), ), ); // All widgets are onstage. expect(tester.state<StatefulTestState>(find.byKey(bottom)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(middle)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(top)).rebuildCount, 1); middleEntry.opaque = true; await tester.pump(); // Bottom widget is offstage and did not rebuild. expect(find.byKey(bottom), findsNothing); expect(tester.state<StatefulTestState>(find.byKey(bottom, skipOffstage: false)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(middle)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(top)).rebuildCount, 1); }); testWidgets('OverlayEntries do not rebuild when opaque entry is added', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/45797. final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); final Key bottom = UniqueKey(); final Key middle = UniqueKey(); final Key top = UniqueKey(); final Widget bottomWidget = StatefulTestWidget(key: bottom); final Widget middleWidget = StatefulTestWidget(key: middle); final Widget topWidget = StatefulTestWidget(key: top); final OverlayEntry bottomEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return bottomWidget; }, ); addTearDown(() => bottomEntry..remove()..dispose()); final OverlayEntry middleEntry = OverlayEntry( opaque: true, maintainState: true, builder: (BuildContext context) { return middleWidget; }, ); addTearDown(() => middleEntry..remove()..dispose()); final OverlayEntry topEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return topWidget; }, ); addTearDown(() => topEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ bottomEntry, topEntry, ], ), ), ); // Both widgets are onstage. expect(tester.state<StatefulTestState>(find.byKey(bottom)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(top)).rebuildCount, 1); overlayKey.currentState!.rearrange(<OverlayEntry>[ bottomEntry, middleEntry, topEntry, ]); await tester.pump(); // Bottom widget is offstage and did not rebuild. expect(find.byKey(bottom), findsNothing); expect(tester.state<StatefulTestState>(find.byKey(bottom, skipOffstage: false)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(middle)).rebuildCount, 1); expect(tester.state<StatefulTestState>(find.byKey(top)).rebuildCount, 1); }); testWidgets('entries below opaque entries are ignored for hit testing', (WidgetTester tester) async { final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); int bottomTapCount = 0; late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return GestureDetector( onTap: () { bottomTapCount++; }, ); }, ), ], ), ), ); expect(bottomTapCount, 0); await tester.tap(find.byKey(overlayKey), warnIfMissed: false); // gesture detector is translucent; no hit is registered between it and the render view expect(bottomTapCount, 1); late final OverlayEntry newEntry1; addTearDown(() => newEntry1..remove()..dispose()); overlayKey.currentState!.insert( newEntry1 = OverlayEntry( maintainState: true, opaque: true, builder: (BuildContext context) { return Container(); }, ), ); await tester.pump(); // Bottom is offstage and does not receive tap events. expect(find.byType(GestureDetector), findsNothing); expect(find.byType(GestureDetector, skipOffstage: false), findsOneWidget); await tester.tap(find.byKey(overlayKey), warnIfMissed: false); // gesture detector is translucent; no hit is registered between it and the render view expect(bottomTapCount, 1); int topTapCount = 0; late final OverlayEntry newEntry2; addTearDown(() => newEntry2..remove()..dispose()); overlayKey.currentState!.insert( newEntry2 = OverlayEntry( maintainState: true, opaque: true, builder: (BuildContext context) { return GestureDetector( onTap: () { topTapCount++; }, ); }, ), ); await tester.pump(); expect(topTapCount, 0); await tester.tap(find.byKey(overlayKey), warnIfMissed: false); // gesture detector is translucent; no hit is registered between it and the render view expect(topTapCount, 1); expect(bottomTapCount, 1); }); testWidgets('Semantics of entries below opaque entries are ignored', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final GlobalKey<OverlayState> overlayKey = GlobalKey<OverlayState>(); late final OverlayEntry bottomEntry; addTearDown(() => bottomEntry..remove()..dispose()); late final OverlayEntry topEntry; addTearDown(() => topEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( key: overlayKey, initialEntries: <OverlayEntry>[ bottomEntry = OverlayEntry( maintainState: true, builder: (BuildContext context) { return const Text('bottom'); }, ), topEntry = OverlayEntry( maintainState: true, opaque: true, builder: (BuildContext context) { return const Text('top'); }, ), ], ), ), ); expect(find.text('bottom'), findsNothing); expect(find.text('bottom', skipOffstage: false), findsOneWidget); expect(find.text('top'), findsOneWidget); expect(semantics, includesNodeWith(label: 'top')); expect(semantics, isNot(includesNodeWith(label: 'bottom'))); semantics.dispose(); }); testWidgets('Can use Positioned within OverlayEntry', (WidgetTester tester) async { late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { return const Positioned( left: 145, top: 123, child: Text('positioned child'), ); }, ), ], ), ), ); expect(tester.getTopLeft(find.text('positioned child')), const Offset(145, 123)); }); testWidgets('Overlay can set and update clipBehavior', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ _buildOverlayEntry((BuildContext context) => Positioned(left: 2000, right: 2500, child: Container())), ], ), ), ); // By default, clipBehavior should be Clip.hardEdge final RenderObject renderObject = tester.renderObject(find.byType(Overlay)); expect((renderObject as dynamic).clipBehavior, equals(Clip.hardEdge)); for (final Clip clip in Clip.values) { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ _buildOverlayEntry((BuildContext context) => Container()), ], clipBehavior: clip, ), ), ); expect((renderObject as dynamic).clipBehavior, clip); bool visited = false; renderObject.visitChildren((RenderObject child) { visited = true; switch (clip) { case Clip.none: expect(renderObject.describeApproximatePaintClip(child), null); case Clip.hardEdge: case Clip.antiAlias: case Clip.antiAliasWithSaveLayer: expect( renderObject.describeApproximatePaintClip(child), const Rect.fromLTRB(0, 0, 800, 600), ); } }); expect(visited, true); } }); testWidgets('Overlay always applies clip', (WidgetTester tester) async { late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) => Positioned(left: 10, right: 10, child: Container()), ), ], ), ), ); final RenderObject renderObject = tester.renderObject(find.byType(Overlay)); expect((renderObject as dynamic).paint, paints ..save() ..clipRect(rect: const Rect.fromLTWH(0.0, 0.0, 800.0, 600.0)) ..restore(), ); }); testWidgets('OverlayEntry throws if inserted to an invalid Overlay', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Overlay(), ), ); final OverlayState overlay = tester.state(find.byType(Overlay)); final OverlayEntry entry = OverlayEntry(builder: (BuildContext context) => const SizedBox()); addTearDown(() => entry..remove()..dispose()); expect( () => overlay.insert(entry), returnsNormally, ); // Throws when inserted to the same Overlay. expect( () => overlay.insert(entry), throwsA(isA<FlutterError>().having( (FlutterError error) => error.toString(), 'toString()', allOf( contains('The specified entry is already present in the target Overlay.'), contains('The OverlayEntry was'), contains('The Overlay the OverlayEntry was trying to insert to was'), ), )), ); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: SizedBox(child: Overlay()), ), ); // Throws if inserted to an already disposed Overlay. expect( () => overlay.insert(entry), throwsA(isA<FlutterError>().having( (FlutterError error) => error.toString(), 'toString()', allOf( contains('Attempted to insert an OverlayEntry to an already disposed Overlay.'), contains('The OverlayEntry was'), contains('The Overlay the OverlayEntry was trying to insert to was'), ), )), ); final OverlayState newOverlay = tester.state(find.byType(Overlay)); // Throws when inserted to a different Overlay without calling remove. expect( () => newOverlay.insert(entry), throwsA(isA<FlutterError>().having( (FlutterError error) => error.toString(), 'toString()', allOf( contains('The specified entry is already present in a different Overlay.'), contains('The OverlayEntry was'), contains('The Overlay the OverlayEntry was trying to insert to was'), contains("The OverlayEntry's current Overlay was"), ), )), ); }); group('OverlayEntry listenable', () { final GlobalKey overlayKey = GlobalKey(); final Widget emptyOverlay = Directionality( textDirection: TextDirection.ltr, child: Overlay(key: overlayKey), ); testWidgets('mounted state can be listened', (WidgetTester tester) async { await tester.pumpWidget(emptyOverlay); final OverlayState overlay = overlayKey.currentState! as OverlayState; final List<bool> mountedLog = <bool>[]; final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) => Container(), ); addTearDown(entry.dispose); entry.addListener(() { mountedLog.add(entry.mounted); }); overlay.insert(entry); expect(mountedLog, isEmpty); // Pump a frame. The Overlay entry will be mounted. await tester.pump(); expect(mountedLog, <bool>[true]); entry.remove(); expect(mountedLog, <bool>[true]); await tester.pump(); expect(mountedLog, <bool>[true, false]); // Insert & remove again. overlay.insert(entry); await tester.pump(); entry.remove(); await tester.pump(); expect(mountedLog, <bool>[true, false, true, false]); }); testWidgets('throw if disposed before removal', (WidgetTester tester) async { await tester.pumpWidget(emptyOverlay); final OverlayState overlay = overlayKey.currentState! as OverlayState; final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) => Container(), ); addTearDown(() => entry..remove()..dispose()); overlay.insert(entry); Object? error; try { entry.dispose(); } catch (e) { error = e; } expect(error, isAssertionError); }); test('dispose works', () { final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) => Container(), ); entry.dispose(); Object? error; try { entry.addListener(() { }); } catch (e) { error = e; } expect(error, isAssertionError); }); testWidgets('delayed dispose', (WidgetTester tester) async { await tester.pumpWidget(emptyOverlay); final OverlayState overlay = overlayKey.currentState! as OverlayState; final List<bool> mountedLog = <bool>[]; final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) => Container(), ); entry.addListener(() { mountedLog.add(entry.mounted); }); overlay.insert(entry); await tester.pump(); expect(mountedLog, <bool>[true]); entry.remove(); // Call dispose on the entry. The listeners should be notified for one // last time after this. entry.dispose(); expect(mountedLog, <bool>[true]); await tester.pump(); expect(mountedLog, <bool>[true, false]); expect(tester.takeException(), isNull); // The entry is no longer usable. Object? error; try { entry.addListener(() { }); } catch (e) { error = e; } expect(error, isAssertionError); }); }); group('LookupBoundary', () { testWidgets('hides Overlay from Overlay.maybeOf', (WidgetTester tester) async { OverlayState? overlay; late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { return LookupBoundary( child: Builder( builder: (BuildContext context) { overlay = Overlay.maybeOf(context); return Container(); }, ), ); }, ), ], ), ), ); expect(overlay, isNull); }); testWidgets('hides Overlay from Overlay.of', (WidgetTester tester) async { late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { return LookupBoundary( child: Builder( builder: (BuildContext context) { Overlay.of(context); return Container(); }, ), ); }, ), ], ), ), ); final Object? exception = tester.takeException(); expect(exception, isFlutterError); final FlutterError error = exception! as FlutterError; expect( error.toStringDeep(), 'FlutterError\n' ' No Overlay widget found within the closest LookupBoundary.\n' ' There is an ancestor Overlay widget, but it is hidden by a\n' ' LookupBoundary.\n' ' Some widgets require an Overlay widget ancestor for correct\n' ' operation.\n' ' The most common way to add an Overlay to an application is to\n' ' include a MaterialApp, CupertinoApp or Navigator widget in the\n' ' runApp() call.\n' ' The context from which that widget was searching for an overlay\n' ' was:\n' ' Builder\n' ); }); testWidgets('hides Overlay from debugCheckHasOverlay', (WidgetTester tester) async { late final OverlayEntry baseEntry; addTearDown(() => baseEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ baseEntry = OverlayEntry( builder: (BuildContext context) { return LookupBoundary( child: Builder( builder: (BuildContext context) { debugCheckHasOverlay(context); return Container(); }, ), ); }, ), ], ), ), ); final Object? exception = tester.takeException(); expect(exception, isFlutterError); final FlutterError error = exception! as FlutterError; expect( error.toStringDeep(), startsWith( 'FlutterError\n' ' No Overlay widget found within the closest LookupBoundary.\n' ' There is an ancestor Overlay widget, but it is hidden by a\n' ' LookupBoundary.\n' ' Builder widgets require an Overlay widget ancestor within the\n' ' closest LookupBoundary.\n' ' An overlay lets widgets float on top of other widget children.\n' ' To introduce an Overlay widget, you can either directly include\n' ' one, or use a widget that contains an Overlay itself, such as a\n' ' Navigator, WidgetApp, MaterialApp, or CupertinoApp.\n' ' The specific widget that could not find a Overlay ancestor was:\n' ' Builder\n' ' The ancestors of this widget were:\n' ' LookupBoundary\n' ), ); }); }); testWidgets('Overlay.wrap', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay.wrap( child: const Center( child: Text('Hello World'), ), ), ), ); final State overlayState = tester.state(find.byType(Overlay)); expect(find.text('Hello World'), findsOneWidget); expect(find.text('Bye, bye'), findsNothing); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay.wrap( child: const Center( child: Text('Bye, bye'), ), ), ), ); expect(find.text('Hello World'), findsNothing); expect(find.text('Bye, bye'), findsOneWidget); expect(tester.state(find.byType(Overlay)), same(overlayState)); }); testWidgets('Overlay.wrap is sized by child in an unconstrained environment', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: UnconstrainedBox( child: Overlay.wrap( child: const Center( child: SizedBox( width: 123, height: 456, ) ), ), ), ), ); expect(tester.getSize(find.byType(Overlay)), const Size(123, 456)); }); testWidgets('Overlay is sized by child in an unconstrained environment', (WidgetTester tester) async { final OverlayEntry initialEntry = OverlayEntry( opaque: true, canSizeOverlay: true, builder: (BuildContext context) { return const SizedBox(width: 123, height: 456); } ); addTearDown(() => initialEntry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: UnconstrainedBox( child: Overlay( initialEntries: <OverlayEntry>[initialEntry] ), ), ), ); expect(tester.getSize(find.byType(Overlay)), const Size(123, 456)); final OverlayState overlay = tester.state<OverlayState>(find.byType(Overlay)); final OverlayEntry nonSizingEntry = OverlayEntry( builder: (BuildContext context) { return const SizedBox( width: 600, height: 600, child: Center(child: Text('Hello')), ); }, ); addTearDown(nonSizingEntry.dispose); overlay.insert(nonSizingEntry); await tester.pump(); expect(tester.getSize(find.byType(Overlay)), const Size(123, 456)); expect(find.text('Hello'), findsOneWidget); final OverlayEntry sizingEntry = OverlayEntry( canSizeOverlay: true, builder: (BuildContext context) { return const SizedBox( width: 222, height: 111, child: Center(child: Text('World')), ); }, ); addTearDown(sizingEntry.dispose); overlay.insert(sizingEntry); await tester.pump(); expect(tester.getSize(find.byType(Overlay)), const Size(222, 111)); expect(find.text('Hello'), findsOneWidget); expect(find.text('World'), findsOneWidget); nonSizingEntry.remove(); await tester.pump(); expect(tester.getSize(find.byType(Overlay)), const Size(222, 111)); expect(find.text('Hello'), findsNothing); expect(find.text('World'), findsOneWidget); sizingEntry.remove(); await tester.pump(); expect(tester.getSize(find.byType(Overlay)), const Size(123, 456)); expect(find.text('Hello'), findsNothing); expect(find.text('World'), findsNothing); }); testWidgets('Overlay throws if unconstrained and has no child', (WidgetTester tester) async { final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = errors.add; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: UnconstrainedBox( child: Overlay(), ), ), ); FlutterError.onError = oldHandler; expect( errors.first.toString().replaceAll('\n', ' '), contains('Overlay was given infinite constraints and cannot be sized by a suitable child.'), ); }); testWidgets('Overlay throws if unconstrained and only positioned child', (WidgetTester tester) async { final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = errors.add; final OverlayEntry entry = OverlayEntry( canSizeOverlay: true, builder: (BuildContext context) { return const Positioned( top: 100, child: SizedBox(width: 600, height: 600), ); }, ); addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: UnconstrainedBox( child: Overlay( initialEntries: <OverlayEntry>[entry], ), ), ), ); FlutterError.onError = oldHandler; expect( errors.first.toString().replaceAll('\n', ' '), contains('Overlay was given infinite constraints and cannot be sized by a suitable child.'), ); }); testWidgets('Overlay throws if unconstrained and no canSizeOverlay child', (WidgetTester tester) async { final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[]; final FlutterExceptionHandler? oldHandler = FlutterError.onError; FlutterError.onError = errors.add; final OverlayEntry entry = OverlayEntry( builder: (BuildContext context) { return const SizedBox(width: 600, height: 600); }, ); addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: UnconstrainedBox( child: Overlay( initialEntries: <OverlayEntry>[entry], ), ), ), ); FlutterError.onError = oldHandler; expect( errors.first.toString().replaceAll('\n', ' '), contains('Overlay was given infinite constraints and cannot be sized by a suitable child.'), ); }); } 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(); } } /// This helper makes leak tracker forgiving the entry is not disposed. OverlayEntry _buildOverlayEntry(WidgetBuilder builder) => OverlayEntry(builder: builder);
flutter/packages/flutter/test/widgets/overlay_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/overlay_test.dart", "repo_id": "flutter", "token_count": 24460 }
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 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Positioned constructors', (WidgetTester tester) async { final Widget child = Container(); final Positioned a = Positioned( left: 101.0, right: 201.0, top: 301.0, bottom: 401.0, child: child, ); expect(a.left, 101.0); expect(a.right, 201.0); expect(a.top, 301.0); expect(a.bottom, 401.0); expect(a.width, null); expect(a.height, null); final Positioned b = Positioned.fromRect( rect: const Rect.fromLTRB( 102.0, 302.0, 202.0, 502.0, ), child: child, ); expect(b.left, 102.0); expect(b.right, null); expect(b.top, 302.0); expect(b.bottom, null); expect(b.width, 100.0); expect(b.height, 200.0); final Positioned c = Positioned.fromRelativeRect( rect: const RelativeRect.fromLTRB( 103.0, 303.0, 203.0, 403.0, ), child: child, ); expect(c.left, 103.0); expect(c.right, 203.0); expect(c.top, 303.0); expect(c.bottom, 403.0); expect(c.width, null); expect(c.height, null); }); testWidgets('Can animate position data', (WidgetTester tester) async { final RelativeRectTween rect = RelativeRectTween( begin: RelativeRect.fromRect( const Rect.fromLTRB(10.0, 20.0, 20.0, 30.0), const Rect.fromLTRB(0.0, 10.0, 100.0, 110.0), ), end: RelativeRect.fromRect( const Rect.fromLTRB(80.0, 90.0, 90.0, 100.0), const Rect.fromLTRB(0.0, 10.0, 100.0, 110.0), ), ); final AnimationController controller = AnimationController( duration: const Duration(seconds: 10), vsync: tester, ); addTearDown(controller.dispose); final List<Size> sizes = <Size>[]; final List<Offset> positions = <Offset>[]; final GlobalKey key = GlobalKey(); void recordMetrics() { final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox; final BoxParentData boxParentData = box.parentData! as BoxParentData; sizes.add(box.size); positions.add(boxParentData.offset); } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: 100.0, width: 100.0, child: Stack( children: <Widget>[ PositionedTransition( rect: rect.animate(controller), child: Container( key: key, ), ), ], ), ), ), ), ); // t=0 recordMetrics(); final Completer<void> completer = Completer<void>(); controller.forward().whenComplete(completer.complete); expect(completer.isCompleted, isFalse); await tester.pump(); // t=0 again expect(completer.isCompleted, isFalse); recordMetrics(); await tester.pump(const Duration(seconds: 1)); // t=1 expect(completer.isCompleted, isFalse); recordMetrics(); await tester.pump(const Duration(seconds: 1)); // t=2 expect(completer.isCompleted, isFalse); recordMetrics(); await tester.pump(const Duration(seconds: 3)); // t=5 expect(completer.isCompleted, isFalse); recordMetrics(); await tester.pump(const Duration(seconds: 5)); // t=10 expect(completer.isCompleted, isFalse); recordMetrics(); expect(sizes, equals(<Size>[const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0), const Size(10.0, 10.0)])); expect(positions, equals(<Offset>[const Offset(10.0, 10.0), const Offset(10.0, 10.0), const Offset(17.0, 17.0), const Offset(24.0, 24.0), const Offset(45.0, 45.0), const Offset(80.0, 80.0)])); controller.stop(canceled: false); await tester.pump(); expect(completer.isCompleted, isTrue); }); }
flutter/packages/flutter/test/widgets/positioned_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/positioned_test.dart", "repo_id": "flutter", "token_count": 1899 }
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 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('RichText with recognizers without handlers does not throw', (WidgetTester tester) async { final TapGestureRecognizer recognizer1 = TapGestureRecognizer(); addTearDown(recognizer1.dispose); final LongPressGestureRecognizer recognizer2 = LongPressGestureRecognizer(); addTearDown(recognizer2.dispose); final DoubleTapGestureRecognizer recognizer3 = DoubleTapGestureRecognizer(); addTearDown(recognizer3.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RichText( text: TextSpan(text: 'root', children: <InlineSpan>[ TextSpan(text: 'one', recognizer: recognizer1), TextSpan(text: 'two', recognizer: recognizer2), TextSpan(text: 'three', recognizer: recognizer3), ]), ), ), ); expect(tester.getSemantics(find.byType(RichText)), matchesSemantics( children: <Matcher>[ matchesSemantics( label: 'root', ), matchesSemantics( label: 'one', ), matchesSemantics( label: 'two', ), matchesSemantics( label: 'three', ), ], )); }); testWidgets('TextSpan Locale works', (WidgetTester tester) async { final TapGestureRecognizer recognizer1 = TapGestureRecognizer(); addTearDown(recognizer1.dispose); final DoubleTapGestureRecognizer recognizer2 = DoubleTapGestureRecognizer(); addTearDown(recognizer2.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RichText( text: TextSpan( text: 'root', locale: const Locale('es', 'MX'), children: <InlineSpan>[ TextSpan(text: 'one', recognizer: recognizer1), const WidgetSpan( child: SizedBox(), ), TextSpan(text: 'three', recognizer: recognizer2), ] ), ), ), ); expect(tester.getSemantics(find.byType(RichText)), matchesSemantics( children: <Matcher>[ matchesSemantics( attributedLabel: AttributedString( 'root', attributes: <StringAttribute>[ LocaleStringAttribute(range: const TextRange(start: 0, end: 4), locale: const Locale('es', 'MX')), ] ), ), matchesSemantics( attributedLabel: AttributedString( 'one', attributes: <StringAttribute>[ LocaleStringAttribute(range: const TextRange(start: 0, end: 3), locale: const Locale('es', 'MX')), ] ), ), matchesSemantics( attributedLabel: AttributedString( 'three', attributes: <StringAttribute>[ LocaleStringAttribute(range: const TextRange(start: 0, end: 5), locale: const Locale('es', 'MX')), ] ), ), ], )); }); testWidgets('TextSpan spellOut works', (WidgetTester tester) async { final TapGestureRecognizer recognizer1 = TapGestureRecognizer(); addTearDown(recognizer1.dispose); final DoubleTapGestureRecognizer recognizer2 = DoubleTapGestureRecognizer(); addTearDown(recognizer2.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RichText( text: TextSpan( text: 'root', spellOut: true, children: <InlineSpan>[ TextSpan(text: 'one', recognizer: recognizer1), const WidgetSpan( child: SizedBox(), ), TextSpan(text: 'three', recognizer: recognizer2), ] ), ), ), ); expect(tester.getSemantics(find.byType(RichText)), matchesSemantics( children: <Matcher>[ matchesSemantics( attributedLabel: AttributedString( 'root', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 4)), ] ), ), matchesSemantics( attributedLabel: AttributedString( 'one', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 3)), ] ), ), matchesSemantics( attributedLabel: AttributedString( 'three', attributes: <StringAttribute>[ SpellOutStringAttribute(range: const TextRange(start: 0, end: 5)), ] ), ), ], )); }); testWidgets('WidgetSpan calculate correct intrinsic heights', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: ColoredBox( color: Colors.green, child: IntrinsicHeight( child: RichText( text: const TextSpan( children: <InlineSpan>[ TextSpan(text: 'Start\n', style: TextStyle(height: 1.0, fontSize: 16)), WidgetSpan( child: Row( children: <Widget>[ SizedBox(height: 16, width: 16), ], ), ), TextSpan(text: 'End', style: TextStyle(height: 1.0, fontSize: 16)), ], ), ), ), ), ), ), ); expect(tester.getSize(find.byType(IntrinsicHeight)).height, 3 * 16); }); testWidgets('RichText implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); RichText( text: const TextSpan(text: 'rich text'), textAlign: TextAlign.center, textDirection: TextDirection.rtl, softWrap: false, overflow: TextOverflow.ellipsis, textScaleFactor: 1.3, maxLines: 1, locale: const Locale('zh', 'HK'), strutStyle: const StrutStyle( fontSize: 16, ), textWidthBasis: TextWidthBasis.longestLine, textHeightBehavior: const TextHeightBehavior(applyHeightToFirstAscent: false), ).debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, unorderedMatches(<Matcher>[ contains('textAlign: center'), contains('textDirection: rtl'), contains('softWrap: no wrapping except at line break characters'), contains('overflow: ellipsis'), contains('textScaler: linear (1.3x)'), contains('maxLines: 1'), contains('textWidthBasis: longestLine'), contains('text: "rich text"'), contains('locale: zh_HK'), allOf(startsWith('strutStyle: StrutStyle('), contains('size: 16.0')), allOf( startsWith('textHeightBehavior: TextHeightBehavior('), contains('applyHeightToFirstAscent: false'), contains('applyHeightToLastDescent: true'), ), ])); }); }
flutter/packages/flutter/test/widgets/rich_text_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/rich_text_test.dart", "repo_id": "flutter", "token_count": 3613 }
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 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; Widget _buildScroller({ required List<String> log }) { return NotificationListener<ScrollNotification>( onNotification: (ScrollNotification notification) { if (notification is ScrollStartNotification) { log.add('scroll-start'); } else if (notification is ScrollUpdateNotification) { log.add('scroll-update'); } else if (notification is ScrollEndNotification) { log.add('scroll-end'); } return false; }, child: const SingleChildScrollView( child: SizedBox(width: 1000.0, height: 1000.0), ), ); } void main() { Completer<void> animateTo(WidgetTester tester, double newScrollOffset, { required Duration duration }) { final Completer<void> completer = Completer<void>(); final ScrollableState scrollable = tester.state(find.byType(Scrollable)); scrollable.position.animateTo(newScrollOffset, duration: duration, curve: Curves.linear).whenComplete(completer.complete); return completer; } void jumpTo(WidgetTester tester, double newScrollOffset) { final ScrollableState scrollable = tester.state(find.byType(Scrollable)); scrollable.position.jumpTo(newScrollOffset); } testWidgets('Scroll event drag', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(_buildScroller(log: log)); expect(log, equals(<String>[])); final TestGesture gesture = await tester.startGesture(const Offset(100.0, 100.0)); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(seconds: 1)); expect(log, equals(<String>['scroll-start'])); await gesture.moveBy(const Offset(-10.0, -10.0)); expect(log, equals(<String>['scroll-start', 'scroll-update'])); await tester.pump(const Duration(seconds: 1)); expect(log, equals(<String>['scroll-start', 'scroll-update'])); await gesture.up(); expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end'])); await tester.pump(const Duration(seconds: 1)); expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end'])); }); testWidgets('Scroll animateTo', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(_buildScroller(log: log)); expect(log, equals(<String>[])); final Completer<void> completer = animateTo(tester, 100.0, duration: const Duration(seconds: 1)); expect(completer.isCompleted, isFalse); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(milliseconds: 100)); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(milliseconds: 100)); expect(log, equals(<String>['scroll-start', 'scroll-update'])); await tester.pump(const Duration(milliseconds: 1500)); expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-update', 'scroll-end'])); expect(completer.isCompleted, isTrue); }); testWidgets('Scroll jumpTo', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(_buildScroller(log: log)); expect(log, equals(<String>[])); jumpTo(tester, 100.0); expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end'])); await tester.pump(); expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end'])); }); testWidgets('Scroll jumpTo during animation', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(_buildScroller(log: log)); expect(log, equals(<String>[])); final Completer<void> completer = animateTo(tester, 100.0, duration: const Duration(seconds: 1)); expect(completer.isCompleted, isFalse); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(milliseconds: 100)); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(milliseconds: 100)); expect(log, equals(<String>['scroll-start', 'scroll-update'])); expect(completer.isCompleted, isFalse); jumpTo(tester, 100.0); expect(completer.isCompleted, isFalse); expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end', 'scroll-start', 'scroll-update', 'scroll-end'])); await tester.pump(const Duration(milliseconds: 100)); expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end', 'scroll-start', 'scroll-update', 'scroll-end'])); expect(completer.isCompleted, isTrue); await tester.pump(const Duration(milliseconds: 1500)); expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-end', 'scroll-start', 'scroll-update', 'scroll-end'])); expect(completer.isCompleted, isTrue); }); testWidgets('Scroll scrollTo during animation', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(_buildScroller(log: log)); expect(log, equals(<String>[])); Completer<void> completer = animateTo(tester, 100.0, duration: const Duration(seconds: 1)); expect(completer.isCompleted, isFalse); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(milliseconds: 100)); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(milliseconds: 100)); expect(log, equals(<String>['scroll-start', 'scroll-update'])); expect(completer.isCompleted, isFalse); completer = animateTo(tester, 100.0, duration: const Duration(seconds: 1)); expect(completer.isCompleted, isFalse); expect(log, equals(<String>['scroll-start', 'scroll-update'])); await tester.pump(const Duration(milliseconds: 100)); expect(log, equals(<String>['scroll-start', 'scroll-update'])); await tester.pump(const Duration(milliseconds: 1500)); expect(log, equals(<String>['scroll-start', 'scroll-update', 'scroll-update', 'scroll-end'])); expect(completer.isCompleted, isTrue); }); testWidgets('fling, fling generates two start/end pairs', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(_buildScroller(log: log)); // The ideal behavior here would be a single start/end pair, but for // simplicity of implementation we compromise here and accept two. Should // you find a way to make this work with just one without complicating the // API, feel free to change the expectation here. expect(log, equals(<String>[])); await tester.flingFrom(const Offset(100.0, 100.0), const Offset(-50.0, -50.0), 500.0); await tester.pump(const Duration(seconds: 1)); log.removeWhere((String value) => value == 'scroll-update'); expect(log, equals(<String>['scroll-start'])); await tester.flingFrom(const Offset(100.0, 100.0), const Offset(-50.0, -50.0), 500.0); log.removeWhere((String value) => value == 'scroll-update'); expect(log, equals(<String>['scroll-start', 'scroll-end', 'scroll-start'])); await tester.pump(const Duration(seconds: 1)); await tester.pump(const Duration(seconds: 1)); log.removeWhere((String value) => value == 'scroll-update'); expect(log, equals(<String>['scroll-start', 'scroll-end', 'scroll-start', 'scroll-end'])); }); testWidgets('fling, pause, fling generates two start/end pairs', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(_buildScroller(log: log)); expect(log, equals(<String>[])); await tester.flingFrom(const Offset(100.0, 100.0), const Offset(-50.0, -50.0), 500.0); await tester.pump(const Duration(seconds: 1)); log.removeWhere((String value) => value == 'scroll-update'); expect(log, equals(<String>['scroll-start'])); await tester.pump(const Duration(minutes: 1)); await tester.flingFrom(const Offset(100.0, 100.0), const Offset(-50.0, -50.0), 500.0); log.removeWhere((String value) => value == 'scroll-update'); expect(log, equals(<String>['scroll-start', 'scroll-end', 'scroll-start'])); await tester.pump(const Duration(seconds: 1)); await tester.pump(const Duration(seconds: 1)); log.removeWhere((String value) => value == 'scroll-update'); expect(log, equals(<String>['scroll-start', 'scroll-end', 'scroll-start', 'scroll-end'])); }); testWidgets('fling up ends', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget(_buildScroller(log: log)); expect(log, equals(<String>[])); await tester.flingFrom(const Offset(100.0, 100.0), const Offset(50.0, 50.0), 500.0); await tester.pump(const Duration(seconds: 1)); await tester.pump(const Duration(seconds: 1)); await tester.pump(const Duration(seconds: 1)); expect(log.first, equals('scroll-start')); expect(log.last, equals('scroll-end')); log.removeWhere((String value) => value == 'scroll-update'); expect(log.length, equals(2)); expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, equals(0.0)); }); }
flutter/packages/flutter/test/widgets/scroll_events_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/scroll_events_test.dart", "repo_id": "flutter", "token_count": 3276 }
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 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'clipboard_utils.dart'; import 'keyboard_utils.dart'; Offset textOffsetToPosition(RenderParagraph paragraph, int offset) { const Rect caret = Rect.fromLTWH(0.0, 0.0, 2.0, 20.0); final Offset localOffset = paragraph.getOffsetForCaret(TextPosition(offset: offset), caret); return paragraph.localToGlobal(localOffset); } Offset globalize(Offset point, RenderBox box) { return box.localToGlobal(point); } 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); }); testWidgets('mouse can select multiple widgets', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph3, 3)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 3)); await gesture.up(); }); testWidgets('mouse can select multiple widgets - horizontal', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5) + const Offset(0, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); await gesture.up(); }); testWidgets('mouse can select multiple widgets on double-click drag', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph1, 2)); await tester.pumpAndSettle(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4)); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 4)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph3, 3)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4)); await gesture.up(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('mouse can select multiple widgets on double-click drag - horizontal', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.up(); await tester.pump(); await gesture.down(textOffsetToPosition(paragraph1, 2)); await tester.pumpAndSettle(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4)); await gesture.moveTo(textOffsetToPosition(paragraph1, 4)); await tester.pump(); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 5)); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph2, 5) + const Offset(0, 5)); // Should select the rest of paragraph 1. expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); await gesture.up(); }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/125582. testWidgets('select to scroll forward', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 0.0); double previousOffset = controller.offset; // Scrollable only auto scroll if the drag passes the boundary. await gesture.moveTo(tester.getBottomRight(find.byType(ListView)) + const Offset(0, 20)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); previousOffset = controller.offset; await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); // Scroll to the end. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 4200.0); final RenderParagraph paragraph99 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 99'), matching: find.byType(RichText))); final RenderParagraph paragraph98 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 98'), matching: find.byType(RichText))); final RenderParagraph paragraph97 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 97'), matching: find.byType(RichText))); final RenderParagraph paragraph96 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 96'), matching: find.byType(RichText))); expect(paragraph99.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph98.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph97.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph96.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); await gesture.up(); }); testWidgets('select to scroll works for small scrollable', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: false), home: SelectionArea( selectionControls: materialTextSelectionControls, child: Scaffold( body: SizedBox( height: 10, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 0.0); double previousOffset = controller.offset; // Scrollable only auto scroll if the drag passes the boundary await gesture.moveTo(tester.getBottomRight(find.byType(ListView)) + const Offset(0, 20)); await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(controller.offset > previousOffset, isTrue); previousOffset = controller.offset; await tester.pump(); await tester.pump(const Duration(milliseconds: 100)); expect(controller.offset > previousOffset, isTrue); await gesture.up(); // Shouldn't be stuck if gesture is up. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(tester.takeException(), isNull); }); testWidgets('select to scroll backward', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); controller.jumpTo(4000); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(ListView)), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 4000); double previousOffset = controller.offset; await gesture.moveTo(tester.getTopLeft(find.byType(ListView)) + const Offset(0, -20)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset < previousOffset, isTrue); previousOffset = controller.offset; await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset < previousOffset, isTrue); // Scroll to the beginning. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 0.0); final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 2'), matching: find.byType(RichText))); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); expect(paragraph0.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); expect(paragraph3.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); }); testWidgets('select to scroll forward - horizontal', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( scrollDirection: Axis.horizontal, controller: controller, itemCount: 10, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 0.0); double previousOffset = controller.offset; // Scrollable only auto scroll if the drag passes the boundary await gesture.moveTo(tester.getBottomRight(find.byType(ListView)) + const Offset(20, 0)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); previousOffset = controller.offset; await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); // Scroll to the end. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 2080.0); final RenderParagraph paragraph9 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 9'), matching: find.byType(RichText))); final RenderParagraph paragraph8 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 8'), matching: find.byType(RichText))); final RenderParagraph paragraph7 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 7'), matching: find.byType(RichText))); expect(paragraph9.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph8.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); expect(paragraph7.selections[0], const TextSelection(baseOffset: 0, extentOffset: 6)); await gesture.up(); }); testWidgets('select to scroll backward - horizontal', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( scrollDirection: Axis.horizontal, controller: controller, itemCount: 10, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); controller.jumpTo(2080); await tester.pumpAndSettle(); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(ListView)), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); expect(controller.offset, 2080); double previousOffset = controller.offset; await gesture.moveTo(tester.getTopLeft(find.byType(ListView)) + const Offset(-10, 0)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset < previousOffset, isTrue); previousOffset = controller.offset; await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset < previousOffset, isTrue); // Scroll to the beginning. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 0.0); final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 2'), matching: find.byType(RichText))); expect(paragraph0.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); expect(paragraph2.selections[0], const TextSelection(baseOffset: 6, extentOffset: 0)); await gesture.up(); }); testWidgets('preserve selection when out of view.', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); controller.jumpTo(2000); await tester.pumpAndSettle(); expect(find.text('Item 50'), findsOneWidget); RenderParagraph paragraph50 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 50'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph50, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph50, 4)); await gesture.up(); expect(paragraph50.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); controller.jumpTo(0); await tester.pumpAndSettle(); expect(find.text('Item 50'), findsNothing); controller.jumpTo(2000); await tester.pumpAndSettle(); expect(find.text('Item 50'), findsOneWidget); paragraph50 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 50'), matching: find.byType(RichText))); expect(paragraph50.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); controller.jumpTo(4000); await tester.pumpAndSettle(); expect(find.text('Item 50'), findsNothing); controller.jumpTo(2000); await tester.pumpAndSettle(); expect(find.text('Item 50'), findsOneWidget); paragraph50 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 50'), matching: find.byType(RichText))); expect(paragraph50.selections[0], const TextSelection(baseOffset: 2, extentOffset: 4)); }); testWidgets('can select all non-Apple', (WidgetTester tester) async { final FocusNode node = FocusNode(); addTearDown(node.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( focusNode: node, selectionControls: materialTextSelectionControls, child: ListView.builder( itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); node.requestFocus(); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, control: true)); await tester.pump(); for (int i = 0; i < 13; i += 1) { final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item $i'), matching: find.byType(RichText))); expect(paragraph.selections[0], TextSelection(baseOffset: 0, extentOffset: 'Item $i'.length)); } expect(find.text('Item 13'), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); testWidgets('can select all - Apple', (WidgetTester tester) async { final FocusNode node = FocusNode(); addTearDown(node.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( focusNode: node, selectionControls: materialTextSelectionControls, child: ListView.builder( itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); node.requestFocus(); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyA, meta: true)); await tester.pump(); for (int i = 0; i < 13; i += 1) { final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item $i'), matching: find.byType(RichText))); expect(paragraph.selections[0], TextSelection(baseOffset: 0, extentOffset: 'Item $i'.length)); } expect(find.text('Item 13'), findsNothing); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('select to scroll by dragging selection handles forward', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); // Long press to bring up the selection handles. final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph0.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4)); final List<TextBox> boxes = paragraph0.getBoxesForSelection(paragraph0.selections[0]); expect(boxes.length, 1); // Find end handle. final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph0); await gesture.down(handlePos); expect(controller.offset, 0.0); double previousOffset = controller.offset; // Scrollable only auto scroll if the drag passes the boundary await gesture.moveTo(tester.getBottomRight(find.byType(ListView)) + const Offset(0, 40)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); previousOffset = controller.offset; await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); // Scroll to the end. await tester.pumpAndSettle(const Duration(seconds: 1)); expect(controller.offset, 4200.0); final RenderParagraph paragraph99 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 99'), matching: find.byType(RichText))); final RenderParagraph paragraph98 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 98'), matching: find.byType(RichText))); final RenderParagraph paragraph97 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 97'), matching: find.byType(RichText))); final RenderParagraph paragraph96 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 96'), matching: find.byType(RichText))); expect(paragraph99.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph98.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph97.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); expect(paragraph96.selections[0], const TextSelection(baseOffset: 0, extentOffset: 7)); await gesture.up(); }); testWidgets('select to scroll by dragging start selection handle stops scroll when released', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); // Long press to bring up the selection handles. final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph0.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4)); final List<TextBox> boxes = paragraph0.getBoxesForSelection(paragraph0.selections[0]); expect(boxes.length, 1); // Find start handle. final Offset handlePos = globalize(boxes[0].toRect().bottomLeft, paragraph0); await gesture.down(handlePos); expect(controller.offset, 0.0); double previousOffset = controller.offset; // Scrollable only auto scroll if the drag passes the boundary. await gesture.moveTo(tester.getBottomRight(find.byType(ListView)) + const Offset(0, 40)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); previousOffset = controller.offset; await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); previousOffset = controller.offset; // Release handle should stop scrolling. await gesture.up(); // Last scheduled scroll. await tester.pump(); await tester.pump(const Duration(seconds: 1)); previousOffset = controller.offset; await tester.pumpAndSettle(); expect(controller.offset, previousOffset); }); testWidgets('select to scroll by dragging end selection handle stops scroll when released', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); // Long press to bring up the selection handles. final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2)); addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph0.selections[0], const TextSelection(baseOffset: 0, extentOffset: 4)); final List<TextBox> boxes = paragraph0.getBoxesForSelection(paragraph0.selections[0]); expect(boxes.length, 1); final Offset handlePos = globalize(boxes[0].toRect().bottomRight, paragraph0); await gesture.down(handlePos); expect(controller.offset, 0.0); double previousOffset = controller.offset; // Scrollable only auto scroll if the drag passes the boundary await gesture.moveTo(tester.getBottomRight(find.byType(ListView)) + const Offset(0, 40)); await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); previousOffset = controller.offset; await tester.pump(); await tester.pump(const Duration(seconds: 1)); expect(controller.offset > previousOffset, isTrue); previousOffset = controller.offset; // Release handle should stop scrolling. await gesture.up(); // Last scheduled scroll. await tester.pump(); await tester.pump(const Duration(seconds: 1)); previousOffset = controller.offset; await tester.pumpAndSettle(); expect(controller.offset, previousOffset); }); testWidgets('keyboard selection should auto scroll - vertical', (WidgetTester tester) async { final FocusNode node = FocusNode(); addTearDown(node.dispose); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( focusNode: node, selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph9 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 9'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph9, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await gesture.moveTo(textOffsetToPosition(paragraph9, 4) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); await tester.pump(); expect(paragraph9.selections.length, 1); expect(paragraph9.selections[0].start, 2); expect(paragraph9.selections[0].end, 4); expect(controller.offset, 0.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); final RenderParagraph paragraph10 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 10'), matching: find.byType(RichText))); expect(paragraph10.selections.length, 1); expect(paragraph10.selections[0].start, 0); expect(paragraph10.selections[0].end, 4); expect(controller.offset, 0.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); final RenderParagraph paragraph11 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 11'), matching: find.byType(RichText))); expect(paragraph11.selections.length, 1); expect(paragraph11.selections[0].start, 0); expect(paragraph11.selections[0].end, 4); expect(controller.offset, 0.0); // Should start scrolling. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); final RenderParagraph paragraph12 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 12'), matching: find.byType(RichText))); expect(paragraph12.selections.length, 1); expect(paragraph12.selections[0].start, 0); expect(paragraph12.selections[0].end, 4); expect(controller.offset, 24.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); final RenderParagraph paragraph13 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 13'), matching: find.byType(RichText))); expect(paragraph13.selections.length, 1); expect(paragraph13.selections[0].start, 0); expect(paragraph13.selections[0].end, 4); expect(controller.offset, 72.0); }, variant: TargetPlatformVariant.all()); testWidgets('keyboard selection should auto scroll - vertical reversed', (WidgetTester tester) async { final FocusNode node = FocusNode(); addTearDown(node.dispose); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( focusNode: node, selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, reverse: true, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph9 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 9'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph9, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await gesture.moveTo(textOffsetToPosition(paragraph9, 4) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); await tester.pump(); expect(paragraph9.selections.length, 1); expect(paragraph9.selections[0].start, 2); expect(paragraph9.selections[0].end, 4); expect(controller.offset, 0.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); final RenderParagraph paragraph10 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 10'), matching: find.byType(RichText))); expect(paragraph10.selections.length, 1); expect(paragraph10.selections[0].start, 2); expect(paragraph10.selections[0].end, 7); expect(controller.offset, 0.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); final RenderParagraph paragraph11 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 11'), matching: find.byType(RichText))); expect(paragraph11.selections.length, 1); expect(paragraph11.selections[0].start, 2); expect(paragraph11.selections[0].end, 7); expect(controller.offset, 0.0); // Should start scrolling. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); final RenderParagraph paragraph12 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 12'), matching: find.byType(RichText))); expect(paragraph12.selections.length, 1); expect(paragraph12.selections[0].start, 2); expect(paragraph12.selections[0].end, 7); expect(controller.offset, 24.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); final RenderParagraph paragraph13 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 13'), matching: find.byType(RichText))); expect(paragraph13.selections.length, 1); expect(paragraph13.selections[0].start, 2); expect(paragraph13.selections[0].end, 7); expect(controller.offset, 72.0); }, variant: TargetPlatformVariant.all()); testWidgets('keyboard selection should auto scroll - horizontal', (WidgetTester tester) async { final FocusNode node = FocusNode(); addTearDown(node.dispose); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( focusNode: node, selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, scrollDirection: Axis.horizontal, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 2'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 0), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await gesture.moveTo(textOffsetToPosition(paragraph2, 1) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); await tester.pump(); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 1); expect(controller.offset, 0.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 6); expect(controller.offset, 64.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true)); await tester.pump(); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 6); expect(controller.offset, 352.0); }, variant: TargetPlatformVariant.all()); testWidgets('keyboard selection should auto scroll - horizontal reversed', (WidgetTester tester) async { final FocusNode node = FocusNode(); addTearDown(node.dispose); final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( focusNode: node, selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, scrollDirection: Axis.horizontal, reverse: true, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 5) + const Offset(0, 5), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); await gesture.moveTo(textOffsetToPosition(paragraph1, 4) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 4); expect(paragraph1.selections[0].end, 5); expect(controller.offset, 0.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); expect(paragraph1.selections.length, 1); expect(paragraph1.selections[0].start, 0); expect(paragraph1.selections[0].end, 5); expect(controller.offset, 0.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 2'), matching: find.byType(RichText))); expect(paragraph2.selections.length, 1); expect(paragraph2.selections[0].start, 0); expect(paragraph2.selections[0].end, 6); expect(controller.offset, 64.0); await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true)); await tester.pump(); final RenderParagraph paragraph3 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 3'), matching: find.byType(RichText))); expect(paragraph3.selections.length, 1); expect(paragraph3.selections[0].start, 0); expect(paragraph3.selections[0].end, 6); expect(controller.offset, 352.0); }, variant: TargetPlatformVariant.all()); group('Complex cases', () { testWidgets('selection starts outside of the scrollable', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: Column( children: <Widget>[ const Text('Item 0'), SizedBox( height: 400, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Inner item $index'); }, ), ), const Text('Item 1'), ], ), ), )); await tester.pumpAndSettle(); controller.jumpTo(1000); await tester.pumpAndSettle(); final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph1, 2) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); // The entire scrollable should be selected. expect(paragraph0.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); final RenderParagraph innerParagraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Inner item 20'), matching: find.byType(RichText))); expect(innerParagraph.selections[0], const TextSelection(baseOffset: 0, extentOffset: 13)); // Should not scroll the inner scrollable. expect(controller.offset, 1000.0); }); testWidgets('nested scrollables keep selection alive', (WidgetTester tester) async { final ScrollController outerController = ScrollController(); addTearDown(outerController.dispose); final ScrollController innerController = ScrollController(); addTearDown(innerController.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( selectionControls: materialTextSelectionControls, child: ListView.builder( controller: outerController, itemCount: 100, itemBuilder: (BuildContext context, int index) { if (index == 2) { return SizedBox( height: 700, child: ListView.builder( controller: innerController, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Iteminner $index'); }, ), ); } return Text('Item $index'); }, ), ), )); await tester.pumpAndSettle(); innerController.jumpTo(1000); await tester.pumpAndSettle(); RenderParagraph innerParagraph23 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(innerParagraph23, 2) + const Offset(0, 5), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); RenderParagraph innerParagraph24 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Iteminner 24'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(innerParagraph24, 2) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); expect(innerParagraph23.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(innerParagraph24.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); innerController.jumpTo(2000); await tester.pumpAndSettle(); expect(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText)), findsNothing); outerController.jumpTo(2000); await tester.pumpAndSettle(); expect(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText)), findsNothing); // Selected item is still kept alive. expect(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText), skipOffstage: false), findsNothing); // Selection stays the same after scrolling back. outerController.jumpTo(0); await tester.pumpAndSettle(); expect(innerController.offset, 2000.0); innerController.jumpTo(1000); await tester.pumpAndSettle(); innerParagraph23 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Iteminner 23'), matching: find.byType(RichText))); innerParagraph24 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Iteminner 24'), matching: find.byType(RichText))); expect(innerParagraph23.selections[0], const TextSelection(baseOffset: 2, extentOffset: 12)); expect(innerParagraph24.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); }); testWidgets('can copy off screen selection - Apple', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); focusNode.requestFocus(); await tester.pumpAndSettle(); final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2) + const Offset(0, 5), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph1, 2) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); expect(paragraph0.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); // Scroll the selected text out off the screen. controller.jumpTo(1000); await tester.pumpAndSettle(); expect(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), findsNothing); expect(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), findsNothing); // Start copying. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, meta: true)); final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'em 0It'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS })); testWidgets('can copy off screen selection - non-Apple', (WidgetTester tester) async { final ScrollController controller = ScrollController(); addTearDown(controller.dispose); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget(MaterialApp( home: SelectionArea( focusNode: focusNode, selectionControls: materialTextSelectionControls, child: ListView.builder( controller: controller, itemCount: 100, itemBuilder: (BuildContext context, int index) { return Text('Item $index'); }, ), ), )); focusNode.requestFocus(); await tester.pumpAndSettle(); final RenderParagraph paragraph0 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph0, 2) + const Offset(0, 5), kind: ui.PointerDeviceKind.mouse); addTearDown(gesture.removePointer); final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText))); await gesture.moveTo(textOffsetToPosition(paragraph1, 2) + const Offset(0, 5)); await tester.pumpAndSettle(); await gesture.up(); expect(paragraph0.selections[0], const TextSelection(baseOffset: 2, extentOffset: 6)); expect(paragraph1.selections[0], const TextSelection(baseOffset: 0, extentOffset: 2)); // Scroll the selected text out off the screen. controller.jumpTo(1000); await tester.pumpAndSettle(); expect(find.descendant(of: find.text('Item 0'), matching: find.byType(RichText)), findsNothing); expect(find.descendant(of: find.text('Item 1'), matching: find.byType(RichText)), findsNothing); // Start copying. await sendKeyCombination(tester, const SingleActivator(LogicalKeyboardKey.keyC, control: true)); final Map<String, dynamic> clipboardData = mockClipboard.clipboardData as Map<String, dynamic>; expect(clipboardData['text'], 'em 0It'); }, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.android, TargetPlatform.windows, TargetPlatform.linux, TargetPlatform.fuchsia })); }); }
flutter/packages/flutter/test/widgets/scrollable_selection_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/scrollable_selection_test.dart", "repo_id": "flutter", "token_count": 19240 }
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 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { testWidgets('can change semantics in a branch blocked by BlockSemantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, label: 'hello', textDirection: TextDirection.ltr, rect: TestSemantics.fullScreen, ), ], ); await tester.pumpWidget(buildWidget( blockedText: 'one', )); expect(semantics, hasSemantics(expectedSemantics)); // The purpose of the test is to ensure that this change does not throw. await tester.pumpWidget(buildWidget( blockedText: 'two', )); expect(semantics, hasSemantics(expectedSemantics)); // Ensure that the previously blocked semantics end up in the tree correctly when unblocked. await tester.pumpWidget(buildWidget( blockedText: 'two', blocking: false, )); expect(semantics, includesNodeWith(label: 'two', textDirection: TextDirection.ltr)); semantics.dispose(); }); } Widget buildWidget({ required String blockedText, bool blocking = true }) { return Directionality( textDirection: TextDirection.ltr, child: Stack( fit: StackFit.expand, children: <Widget>[ Semantics( container: true, child: ListView( children: <Widget>[ Text(blockedText), ], ), ), BlockSemantics( blocking: blocking, child: Semantics( label: 'hello', container: true, ), ), ], ), ); }
flutter/packages/flutter/test/widgets/semantics_6_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/semantics_6_test.dart", "repo_id": "flutter", "token_count": 844 }
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:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class Inside extends StatefulWidget { const Inside({ super.key }); @override InsideState createState() => InsideState(); } class InsideState extends State<Inside> { @override Widget build(BuildContext context) { return Listener( onPointerDown: _handlePointerDown, child: const Text('INSIDE', textDirection: TextDirection.ltr), ); } void _handlePointerDown(PointerDownEvent event) { setState(() { }); } } class Middle extends StatefulWidget { const Middle({ super.key, this.child, }); final Inside? child; @override MiddleState createState() => MiddleState(); } class MiddleState extends State<Middle> { @override Widget build(BuildContext context) { return Listener( onPointerDown: _handlePointerDown, child: widget.child, ); } void _handlePointerDown(PointerDownEvent event) { setState(() { }); } } class Outside extends StatefulWidget { const Outside({ super.key }); @override OutsideState createState() => OutsideState(); } class OutsideState extends State<Outside> { @override Widget build(BuildContext context) { return const Middle(child: Inside()); } } void main() { testWidgets('setState() smoke test', (WidgetTester tester) async { await tester.pumpWidget(const Outside()); final Offset location = tester.getCenter(find.text('INSIDE')); final TestGesture gesture = await tester.startGesture(location); await tester.pump(); await gesture.up(); await tester.pump(); }); }
flutter/packages/flutter/test/widgets/set_state_1_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/set_state_1_test.dart", "repo_id": "flutter", "token_count": 591 }
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:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; const double VIEWPORT_HEIGHT = 500; const double VIEWPORT_WIDTH = 300; void main() { testWidgets('SliverConstrainedCrossAxis basic test', (WidgetTester tester) async { await tester.pumpWidget(_buildSliverConstrainedCrossAxis(maxExtent: 50)); final RenderBox box = tester.renderObject(find.byType(Container)); expect(box.size.height, 100); expect(box.size.width, 50); final RenderSliver sliver = tester.renderObject(find.byType(SliverToBoxAdapter)); expect(sliver.geometry!.paintExtent, equals(100)); }); testWidgets('SliverConstrainedCrossAxis updates correctly', (WidgetTester tester) async { await tester.pumpWidget(_buildSliverConstrainedCrossAxis(maxExtent: 50)); final RenderBox box1 = tester.renderObject(find.byType(Container)); expect(box1.size.height, 100); expect(box1.size.width, 50); await tester.pumpWidget(_buildSliverConstrainedCrossAxis(maxExtent: 80)); final RenderBox box2 = tester.renderObject(find.byType(Container)); expect(box2.size.height, 100); expect(box2.size.width, 80); }); testWidgets('SliverConstrainedCrossAxis uses parent extent if maxExtent is greater', (WidgetTester tester) async { await tester.pumpWidget(_buildSliverConstrainedCrossAxis(maxExtent: 400)); final RenderBox box = tester.renderObject(find.byType(Container)); expect(box.size.height, 100); expect(box.size.width, VIEWPORT_WIDTH); }); testWidgets('SliverConstrainedCrossAxis constrains the height when direction is horizontal', (WidgetTester tester) async { await tester.pumpWidget(_buildSliverConstrainedCrossAxis( maxExtent: 50, scrollDirection: Axis.horizontal, )); final RenderBox box = tester.renderObject(find.byType(Container)); expect(box.size.height, 50); }); testWidgets('SliverConstrainedCrossAxis sets its own flex to 0', (WidgetTester tester) async { await tester.pumpWidget(_buildSliverConstrainedCrossAxis( maxExtent: 50, )); final RenderSliver sliver = tester.renderObject(find.byType(SliverConstrainedCrossAxis)); expect((sliver.parentData! as SliverPhysicalParentData).crossAxisFlex, equals(0)); }); } Widget _buildSliverConstrainedCrossAxis({ required double maxExtent, Axis scrollDirection = Axis.vertical, }) { return Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: VIEWPORT_WIDTH, height: VIEWPORT_HEIGHT, child: CustomScrollView( scrollDirection: scrollDirection, slivers: <Widget>[ SliverConstrainedCrossAxis( maxExtent: maxExtent, sliver: SliverToBoxAdapter( child: scrollDirection == Axis.vertical ? Container(height: 100) : Container(width: 100), ), ), ], ), ), ), ); }
flutter/packages/flutter/test/widgets/sliver_constrained_cross_axis_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/sliver_constrained_cross_axis_test.dart", "repo_id": "flutter", "token_count": 1214 }
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 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; int globalGeneration = 0; class GenerationText extends StatefulWidget { const GenerationText(this.value, { super.key }); final int value; @override State<GenerationText> createState() => _GenerationTextState(); } class _GenerationTextState extends State<GenerationText> { _GenerationTextState() : generation = globalGeneration; final int generation; @override Widget build(BuildContext context) => Text('${widget.value}:$generation ', textDirection: TextDirection.ltr); } // Creates a SliverList with `keys.length` children and each child having a key from `keys` and a text of `key:generation`. // The generation is increased with every call to this method. Future<void> test(WidgetTester tester, double offset, List<int> keys) { final ViewportOffset viewportOffset = ViewportOffset.fixed(offset); addTearDown(viewportOffset.dispose); globalGeneration += 1; return tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( cacheExtent: 0.0, offset: viewportOffset, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(keys.map<Widget>((int key) { return SizedBox(key: GlobalObjectKey(key), height: 100.0, child: GenerationText(key)); }).toList()), ), ], ), ), ); } // `answerKey`: Expected offsets of visible SliverList children in global coordinate system. // `text`: A space-separated list of expected `key:generation` pairs for the visible SliverList children. void verify(WidgetTester tester, List<Offset> answerKey, String text) { final List<Offset> testAnswers = tester.renderObjectList<RenderBox>(find.byType(SizedBox)).map<Offset>( (RenderBox target) => target.localToGlobal(Offset.zero), ).toList(); expect(testAnswers, equals(answerKey)); final String foundText = tester.widgetList<Text>(find.byType(Text)) .map<String>((Text widget) => widget.data!) .reduce((String value, String element) => value + element); expect(foundText, equals(text)); } void main() { testWidgets('Viewport+SliverBlock with GlobalKey reparenting', (WidgetTester tester) async { await test(tester, 0.0, <int>[1,2,3,4,5,6,7,8,9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), const Offset(0.0, 200.0), const Offset(0.0, 300.0), const Offset(0.0, 400.0), const Offset(0.0, 500.0), ], '1:1 2:1 3:1 4:1 5:1 6:1 '); // gen 2 - flipping the order: await test(tester, 0.0, <int>[9,8,7,6,5,4,3,2,1]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), const Offset(0.0, 200.0), const Offset(0.0, 300.0), const Offset(0.0, 400.0), const Offset(0.0, 500.0), ], '9:2 8:2 7:2 6:1 5:1 4:1 '); // gen 3 - flipping the order back: await test(tester, 0.0, <int>[1,2,3,4,5,6,7,8,9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), const Offset(0.0, 200.0), const Offset(0.0, 300.0), const Offset(0.0, 400.0), const Offset(0.0, 500.0), ], '1:3 2:3 3:3 4:1 5:1 6:1 '); // gen 4 - removal: await test(tester, 0.0, <int>[1,2,3,5,6,7,8,9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), const Offset(0.0, 200.0), const Offset(0.0, 300.0), const Offset(0.0, 400.0), const Offset(0.0, 500.0), ], '1:3 2:3 3:3 5:1 6:1 7:4 '); // gen 5 - insertion: await test(tester, 0.0, <int>[1,2,3,4,5,6,7,8,9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), const Offset(0.0, 200.0), const Offset(0.0, 300.0), const Offset(0.0, 400.0), const Offset(0.0, 500.0), ], '1:3 2:3 3:3 4:5 5:1 6:1 '); // gen 6 - adjacent reordering: await test(tester, 0.0, <int>[1,2,3,5,4,6,7,8,9]); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 100.0), const Offset(0.0, 200.0), const Offset(0.0, 300.0), const Offset(0.0, 400.0), const Offset(0.0, 500.0), ], '1:3 2:3 3:3 5:1 4:5 6:1 '); // gen 7 - scrolling: await test(tester, 120.0, <int>[1,2,3,5,4,6,7,8,9]); verify(tester, <Offset>[ const Offset(0.0, -20.0), const Offset(0.0, 80.0), const Offset(0.0, 180.0), const Offset(0.0, 280.0), const Offset(0.0, 380.0), const Offset(0.0, 480.0), const Offset(0.0, 580.0), ], '2:3 3:3 5:1 4:5 6:1 7:7 8:7 '); }); }
flutter/packages/flutter/test/widgets/slivers_block_global_key_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/slivers_block_global_key_test.dart", "repo_id": "flutter", "token_count": 2150 }
757
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; class TestStatusTransitionWidget extends StatusTransitionWidget { const TestStatusTransitionWidget({ super.key, required this.builder, required super.animation, }); final WidgetBuilder builder; @override Widget build(BuildContext context) => builder(context); } void main() { testWidgets('Status transition control test', (WidgetTester tester) async { bool didBuild = false; final AnimationController controller = AnimationController( duration: const Duration(seconds: 1), vsync: const TestVSync(), ); addTearDown(controller.dispose); await tester.pumpWidget(TestStatusTransitionWidget( animation: controller, builder: (BuildContext context) { expect(didBuild, isFalse); didBuild = true; return Container(); }, )); expect(didBuild, isTrue); didBuild = false; controller.forward(); expect(didBuild, isFalse); await tester.pump(); expect(didBuild, isTrue); didBuild = false; await tester.pump(const Duration(milliseconds: 100)); expect(didBuild, isFalse); await tester.pump(const Duration(milliseconds: 850)); expect(didBuild, isFalse); await tester.pump(const Duration(milliseconds: 100)); expect(didBuild, isTrue); didBuild = false; controller.forward(); await tester.pump(const Duration(milliseconds: 100)); expect(didBuild, isFalse); controller.stop(); await tester.pump(const Duration(milliseconds: 100)); expect(didBuild, isFalse); final AnimationController anotherController = AnimationController( duration: const Duration(seconds: 1), vsync: const TestVSync(), ); addTearDown(anotherController.dispose); await tester.pumpWidget(TestStatusTransitionWidget( animation: anotherController, builder: (BuildContext context) { expect(didBuild, isFalse); didBuild = true; return Container(); }, )); expect(didBuild, isTrue); didBuild = false; controller.reverse(); await tester.pump(const Duration(milliseconds: 100)); expect(didBuild, isFalse); anotherController.forward(); await tester.pump(const Duration(milliseconds: 100)); expect(didBuild, isTrue); didBuild = false; controller.stop(); anotherController.stop(); }); }
flutter/packages/flutter/test/widgets/status_transitions_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/status_transitions_test.dart", "repo_id": "flutter", "token_count": 896 }
758
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('toString control test', (WidgetTester tester) async { final Widget widget = Title( color: const Color(0xFF00FF00), title: 'Awesome app', child: Container(), ); expect(widget.toString, isNot(throwsException)); }); testWidgets('should handle having no title', (WidgetTester tester) async { final Title widget = Title( color: const Color(0xFF00FF00), child: Container(), ); expect(widget.toString, isNot(throwsException)); expect(widget.title, equals('')); expect(widget.color, equals(const Color(0xFF00FF00))); }); testWidgets('should not allow non-opaque color', (WidgetTester tester) async { expect(() => Title( color: const Color(0x00000000), child: Container(), ), throwsAssertionError); }); testWidgets('should not pass "null" to setApplicationSwitcherDescription', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { log.add(methodCall); return null; }); await tester.pumpWidget(Title( color: const Color(0xFF00FF00), child: Container(), )); expect(log, hasLength(1)); expect(log.single, isMethodCall( 'SystemChrome.setApplicationSwitcherDescription', arguments: <String, dynamic>{'label': '', 'primaryColor': 4278255360}, )); }); }
flutter/packages/flutter/test/widgets/title_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/title_test.dart", "repo_id": "flutter", "token_count": 627 }
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. // reduced-test-set: // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) @TestOn('!chrome') library; import 'dart:convert'; import 'dart:math'; import 'dart:ui' as ui; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker/leak_tracker.dart'; import '../impeller_test_helpers.dart'; import 'widget_inspector_test_utils.dart'; // Start of block of code where widget creation location line numbers and // columns will impact whether tests pass. class ClockDemo extends StatelessWidget { const ClockDemo({ super.key }); @override Widget build(BuildContext context) { return Directionality( textDirection: TextDirection.ltr, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text('World Clock'), makeClock('Local', DateTime.now().timeZoneOffset.inHours), makeClock('UTC', 0), makeClock('New York, NY', -4), makeClock('Chicago, IL', -5), makeClock('Denver, CO', -6), makeClock('Los Angeles, CA', -7), ], ), ); } Widget makeClock(String label, int utcOffset) { return Stack( children: <Widget>[ const Icon(Icons.watch), Text(label), ClockText(utcOffset: utcOffset), ], ); } } class ClockText extends StatefulWidget { const ClockText({ super.key, this.utcOffset = 0, }); final int utcOffset; @override State<ClockText> createState() => _ClockTextState(); } class _ClockTextState extends State<ClockText> { DateTime? currentTime = DateTime.now(); void updateTime() { setState(() { currentTime = DateTime.now(); }); } void stopClock() { setState(() { currentTime = null; }); } @override Widget build(BuildContext context) { if (currentTime == null) { return const Text('stopped'); } return Text( currentTime! .toUtc() .add(Duration(hours: widget.utcOffset)) .toIso8601String(), ); } } // End of block of code where widget creation location line numbers and // columns will impact whether tests pass. // Class to enable building trees of nodes with cycles between properties of // nodes and the properties of those properties. // This exposed a bug in code serializing DiagnosticsNode objects that did not // handle these sorts of cycles robustly. class CyclicDiagnostic extends DiagnosticableTree { CyclicDiagnostic(this.name); // Field used to create cyclic relationships. CyclicDiagnostic? related; final List<DiagnosticsNode> children = <DiagnosticsNode>[]; final String name; @override String toStringShort() => '${objectRuntimeType(this, 'CyclicDiagnostic')}-$name'; // We have to override toString to avoid the toString call itself triggering a // stack overflow. @override String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) { return toStringShort(); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<CyclicDiagnostic>('related', related)); } @override List<DiagnosticsNode> debugDescribeChildren() => children; } class _CreationLocation { _CreationLocation({ required this.id, required this.file, required this.line, required this.column, required this.name, }); final int id; final String file; final int line; final int column; String? name; } class RenderRepaintBoundaryWithDebugPaint extends RenderRepaintBoundary { @override void debugPaintSize(PaintingContext context, Offset offset) { super.debugPaintSize(context, offset); assert(() { // Draw some debug paint UI interleaving creating layers and drawing // directly to the context's canvas. final Paint paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = 1.0 ..color = Colors.red; { final PictureLayer pictureLayer = PictureLayer(Offset.zero & size); final ui.PictureRecorder recorder = ui.PictureRecorder(); final Canvas pictureCanvas = Canvas(recorder); pictureCanvas.drawCircle(Offset.zero, 20.0, paint); pictureLayer.picture = recorder.endRecording(); context.addLayer( OffsetLayer() ..offset = offset ..append(pictureLayer), ); } context.canvas.drawLine( offset, offset.translate(size.width, size.height), paint, ); { final PictureLayer pictureLayer = PictureLayer(Offset.zero & size); final ui.PictureRecorder recorder = ui.PictureRecorder(); final Canvas pictureCanvas = Canvas(recorder); pictureCanvas.drawCircle(const Offset(20.0, 20.0), 20.0, paint); pictureLayer.picture = recorder.endRecording(); context.addLayer( OffsetLayer() ..offset = offset ..append(pictureLayer), ); } paint.color = Colors.blue; context.canvas.drawLine( offset, offset.translate(size.width * 0.5, size.height * 0.5), paint, ); return true; }()); } } class RepaintBoundaryWithDebugPaint extends RepaintBoundary { /// Creates a widget that isolates repaints. const RepaintBoundaryWithDebugPaint({ super.key, super.child, }); @override RenderRepaintBoundary createRenderObject(BuildContext context) { return RenderRepaintBoundaryWithDebugPaint(); } } Widget _applyConstructor(Widget Function() constructor) => constructor(); class _TrivialWidget extends StatelessWidget { const _TrivialWidget() : super(key: const Key('singleton')); @override Widget build(BuildContext context) => const Text('Hello, world!'); } int getChildLayerCount(OffsetLayer layer) { Layer? child = layer.firstChild; int count = 0; while (child != null) { count++; child = child.nextSibling; } return count; } extension TextFromString on String { @widgetFactory Widget text() { return Text(this); } } final List<Object> _weakValueTests = <Object>[1, 1.0, 'hello', true, false, Object(), <int>[3, 4], DateTime(2023)]; void main() { group('$InspectorReferenceData', (){ for (final Object item in _weakValueTests) { test('can be created for any type but $Record, $item', () async { final InspectorReferenceData weakValue = InspectorReferenceData(item, 'id'); expect(weakValue.value, item); }); } test('throws for $Record', () async { expect(()=> InspectorReferenceData((1, 2), 'id'), throwsA(isA<ArgumentError>())); }); }); group('$WeakMap', (){ for (final Object item in _weakValueTests) { test('assigns and removes value, $item', () async { final WeakMap<Object, Object> weakMap = WeakMap<Object, Object>(); weakMap[item] = 1; expect(weakMap[item], 1); expect(weakMap.remove(item), 1); expect(weakMap[item], null); }); } for (final Object item in _weakValueTests) { test('returns null for absent value, $item', () async { final WeakMap<Object, Object> weakMap = WeakMap<Object, Object>(); expect(weakMap[item], null); }); } }); _TestWidgetInspectorService.runTests(); } class _TestWidgetInspectorService extends TestWidgetInspectorService { // These tests need access to protected members of WidgetInspectorService. static void runTests() { final TestWidgetInspectorService service = TestWidgetInspectorService(); WidgetInspectorService.instance = service; setUp(() { WidgetInspectorService.instance.isSelectMode.value = true; }); tearDown(() async { service.resetAllState(); if (WidgetInspectorService.instance.isWidgetCreationTracked()) { await service.testBoolExtension( WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, <String, String>{'enabled': 'false'}, ); } }); test ('objectToDiagnosticsNode returns null for non-diagnosticable', () { expect(WidgetInspectorService.objectToDiagnosticsNode(Alignment.bottomCenter), isNull); }); test('WidgetInspector does not hold objects from GC', () async { List<DateTime>? someObject = <DateTime>[DateTime.now(), DateTime.now()]; final String? id = service.toId(someObject, 'group_name'); expect(id, isNotNull); final WeakReference<Object> ref = WeakReference<Object>(someObject); someObject = null; // 1 should be enough for [fullGcCycles], but it is 3 to make sure tests are not flaky. await forceGC(fullGcCycles: 3); expect(ref.target, null); }); testWidgets('WidgetInspector smoke test', (WidgetTester tester) async { // This is a smoke test to verify that adding the inspector doesn't crash. await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( selectButtonBuilder: null, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ), ); expect(true, isTrue); // Expect that we reach here without crashing. }); testWidgets('WidgetInspector interaction test', (WidgetTester tester) async { final List<String> log = <String>[]; final GlobalKey selectButtonKey = GlobalKey(); final GlobalKey inspectorKey = GlobalKey(); final GlobalKey topButtonKey = GlobalKey(); Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) { return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null)); } String paragraphText(RenderParagraph paragraph) { final TextSpan textSpan = paragraph.text as TextSpan; return textSpan.text!; } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, selectButtonBuilder: selectButtonBuilder, child: Material( child: ListView( children: <Widget>[ ElevatedButton( key: topButtonKey, onPressed: () { log.add('top'); }, child: const Text('TOP'), ), ElevatedButton( onPressed: () { log.add('bottom'); }, child: const Text('BOTTOM'), ), ], ), ), ), ), ); expect(WidgetInspectorService.instance.selection.current, isNull); await tester.tap(find.text('TOP'), warnIfMissed: false); await tester.pump(); // Tap intercepted by the inspector expect(log, equals(<String>[])); expect( paragraphText( WidgetInspectorService.instance.selection.current! as RenderParagraph, ), equals('TOP'), ); final RenderObject topButton = find.byKey(topButtonKey).evaluate().first.renderObject!; expect( WidgetInspectorService.instance.selection.candidates, contains(topButton), ); await tester.tap(find.text('TOP')); expect(log, equals(<String>['top'])); log.clear(); await tester.tap(find.text('BOTTOM')); expect(log, equals(<String>['bottom'])); log.clear(); // Ensure the inspector selection has not changed to bottom. expect( paragraphText( WidgetInspectorService.instance.selection.current! as RenderParagraph, ), equals('TOP'), ); await tester.tap(find.byKey(selectButtonKey)); await tester.pump(); // We are now back in select mode so tapping the bottom button will have // not trigger a click but will cause it to be selected. await tester.tap(find.text('BOTTOM'), warnIfMissed: false); expect(log, equals(<String>[])); log.clear(); expect( paragraphText( WidgetInspectorService.instance.selection.current! as RenderParagraph, ), equals('BOTTOM'), ); }); testWidgets('WidgetInspector non-invertible transform regression test', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( selectButtonBuilder: null, child: Transform( transform: Matrix4.identity()..scale(0.0), child: const Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ), ), ); await tester.tap(find.byType(Transform), warnIfMissed: false); expect(true, isTrue); // Expect that we reach here without crashing. }); testWidgets('WidgetInspector scroll test', (WidgetTester tester) async { final Key childKey = UniqueKey(); final GlobalKey selectButtonKey = GlobalKey(); final GlobalKey inspectorKey = GlobalKey(); Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) { return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null)); } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, selectButtonBuilder: selectButtonBuilder, child: ListView( dragStartBehavior: DragStartBehavior.down, children: <Widget>[ Container( key: childKey, height: 5000.0, ), ], ), ), ), ); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0, warnIfMissed: false); await tester.pump(); // Fling does nothing as are in inspect mode. expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); await tester.fling(find.byType(ListView), const Offset(200.0, 0.0), 200.0, warnIfMissed: false); await tester.pump(); // Fling still does nothing as are in inspect mode. expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); await tester.tap(find.byType(ListView), warnIfMissed: false); await tester.pump(); expect(WidgetInspectorService.instance.selection.current, isNotNull); // Now out of inspect mode due to the click. await tester.fling(find.byType(ListView), const Offset(0.0, -200.0), 200.0); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(-200.0)); await tester.fling(find.byType(ListView), const Offset(0.0, 200.0), 200.0); await tester.pump(); expect(tester.getTopLeft(find.byKey(childKey)).dy, equals(0.0)); }); testWidgets('WidgetInspector long press', (WidgetTester tester) async { bool didLongPress = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( selectButtonBuilder: null, child: GestureDetector( onLongPress: () { expect(didLongPress, isFalse); didLongPress = true; }, child: const Text('target', textDirection: TextDirection.ltr), ), ), ), ); await tester.longPress(find.text('target'), warnIfMissed: false); // The inspector will swallow the long press. expect(didLongPress, isFalse); }); testWidgets('WidgetInspector offstage', (WidgetTester tester) async { final GlobalKey inspectorKey = GlobalKey(); final GlobalKey clickTarget = GlobalKey(); Widget createSubtree({ double? width, Key? key }) { return Stack( children: <Widget>[ Positioned( key: key, left: 0.0, top: 0.0, width: width, height: 100.0, child: Text(width.toString(), textDirection: TextDirection.ltr), ), ], ); } late final OverlayEntry entry1; addTearDown(() => entry1..remove()..dispose()); late final OverlayEntry entry2; addTearDown(() => entry2..remove()..dispose()); late final OverlayEntry entry3; addTearDown(() => entry3..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, selectButtonBuilder: null, child: Overlay( initialEntries: <OverlayEntry>[ entry1 = OverlayEntry( maintainState: true, builder: (BuildContext _) => createSubtree(width: 94.0), ), entry2 = OverlayEntry( opaque: true, maintainState: true, builder: (BuildContext _) => createSubtree(width: 95.0), ), entry3 = OverlayEntry( maintainState: true, builder: (BuildContext _) => createSubtree(width: 96.0, key: clickTarget), ), ], ), ), ), ); await tester.longPress(find.byKey(clickTarget), warnIfMissed: false); // The object with width 95.0 wins over the object with width 94.0 because // the subtree with width 94.0 is offstage. expect( WidgetInspectorService.instance.selection.current?.semanticBounds.width, equals(95.0), ); // Exactly 2 out of the 3 text elements should be in the candidate list of // objects to select as only 2 are onstage. expect( WidgetInspectorService.instance.selection.candidates .whereType<RenderParagraph>() .length, equals(2), ); }); testWidgets('WidgetInspector with Transform above', (WidgetTester tester) async { final GlobalKey childKey = GlobalKey(); final GlobalKey repaintBoundaryKey = GlobalKey(); final Matrix4 mainTransform = Matrix4.identity() ..translate(50.0, 30.0) ..scale(0.8, 0.8) ..translate(100.0, 50.0); await tester.pumpWidget( RepaintBoundary( key: repaintBoundaryKey, child: ColoredBox( color: Colors.grey, child: Transform( transform: mainTransform, child: Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( selectButtonBuilder: null, child: ColoredBox( color: Colors.white, child: Center( child: Container( key: childKey, height: 100.0, width: 50.0, color: Colors.red, ), ), ), ), ), ), ), ), ); await tester.tap(find.byKey(childKey), warnIfMissed: false); await tester.pump(); await expectLater( find.byKey(repaintBoundaryKey), matchesGoldenFile('inspector.overlay_positioning_with_transform.png'), ); }); testWidgets('Multiple widget inspectors', (WidgetTester tester) async { // This test verifies that interacting with different inspectors // works correctly. This use case may be an app that displays multiple // apps inside (i.e. a storyboard). final GlobalKey selectButton1Key = GlobalKey(); final GlobalKey selectButton2Key = GlobalKey(); final GlobalKey inspector1Key = GlobalKey(); final GlobalKey inspector2Key = GlobalKey(); final GlobalKey child1Key = GlobalKey(); final GlobalKey child2Key = GlobalKey(); InspectorSelectButtonBuilder selectButtonBuilder(Key key) { return (BuildContext context, VoidCallback onPressed) { return Material(child: ElevatedButton(onPressed: onPressed, key: key, child: null)); }; } String paragraphText(RenderParagraph paragraph) { final TextSpan textSpan = paragraph.text as TextSpan; return textSpan.text!; } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Row( children: <Widget>[ Flexible( child: WidgetInspector( key: inspector1Key, selectButtonBuilder: selectButtonBuilder(selectButton1Key), child: Container( key: child1Key, child: const Text('Child 1'), ), ), ), Flexible( child: WidgetInspector( key: inspector2Key, selectButtonBuilder: selectButtonBuilder(selectButton2Key), child: Container( key: child2Key, child: const Text('Child 2'), ), ), ), ], ), ), ); await tester.tap(find.text('Child 1'), warnIfMissed: false); await tester.pump(); expect( paragraphText( WidgetInspectorService.instance.selection.current! as RenderParagraph, ), equals('Child 1'), ); // Re-enable select mode since it's state is shared between the // WidgetInspectors WidgetInspectorService.instance.isSelectMode.value = true; await tester.tap(find.text('Child 2'), warnIfMissed: false); await tester.pump(); expect( paragraphText( WidgetInspectorService.instance.selection.current! as RenderParagraph, ), equals('Child 2'), ); }); test('WidgetInspectorService null id', () { service.disposeAllGroups(); expect(service.toObject(null), isNull); expect(service.toId(null, 'test-group'), isNull); }); test('WidgetInspectorService dispose group', () { service.disposeAllGroups(); final Object a = Object(); const String group1 = 'group-1'; const String group2 = 'group-2'; const String group3 = 'group-3'; final String? aId = service.toId(a, group1); expect(service.toId(a, group2), equals(aId)); expect(service.toId(a, group3), equals(aId)); service.disposeGroup(group1); service.disposeGroup(group2); expect(service.toObject(aId), equals(a)); service.disposeGroup(group3); expect(() => service.toObject(aId), throwsFlutterError); }); test('WidgetInspectorService dispose id', () { service.disposeAllGroups(); final Object a = Object(); final Object b = Object(); const String group1 = 'group-1'; const String group2 = 'group-2'; final String? aId = service.toId(a, group1); final String? bId = service.toId(b, group1); expect(service.toId(a, group2), equals(aId)); service.disposeId(bId, group1); expect(() => service.toObject(bId), throwsFlutterError); service.disposeId(aId, group1); expect(service.toObject(aId), equals(a)); service.disposeId(aId, group2); expect(() => service.toObject(aId), throwsFlutterError); }); test('WidgetInspectorService toObjectForSourceLocation', () { const String group = 'test-group'; const Text widget = Text('a', textDirection: TextDirection.ltr); service.disposeAllGroups(); final String id = service.toId(widget, group)!; expect(service.toObjectForSourceLocation(id), equals(widget)); final Element element = widget.createElement(); final String elementId = service.toId(element, group)!; expect(service.toObjectForSourceLocation(elementId), equals(widget)); expect(element, isNot(equals(widget))); service.disposeGroup(group); expect(() => service.toObjectForSourceLocation(elementId), throwsFlutterError); }); test('WidgetInspectorService object id test', () { const Text a = Text('a', textDirection: TextDirection.ltr); const Text b = Text('b', textDirection: TextDirection.ltr); const Text c = Text('c', textDirection: TextDirection.ltr); const Text d = Text('d', textDirection: TextDirection.ltr); const String group1 = 'group-1'; const String group2 = 'group-2'; const String group3 = 'group-3'; service.disposeAllGroups(); final String? aId = service.toId(a, group1); final String? bId = service.toId(b, group2); final String? cId = service.toId(c, group3); final String? dId = service.toId(d, group1); // Make sure we get a consistent id if we add the object to a group multiple // times. expect(aId, equals(service.toId(a, group1))); expect(service.toObject(aId), equals(a)); expect(service.toObject(aId), isNot(equals(b))); expect(service.toObject(bId), equals(b)); expect(service.toObject(cId), equals(c)); expect(service.toObject(dId), equals(d)); // Make sure we get a consistent id even if we add the object to a different // group. expect(aId, equals(service.toId(a, group3))); expect(aId, isNot(equals(bId))); expect(aId, isNot(equals(cId))); service.disposeGroup(group3); }); testWidgets('WidgetInspectorService maybeSetSelection', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; final Element elementB = find.text('b').evaluate().first; service.disposeAllGroups(); service.selection.clear(); int selectionChangedCount = 0; service.selectionChangedCallback = () => selectionChangedCount++; service.setSelection('invalid selection'); expect(selectionChangedCount, equals(0)); expect(service.selection.currentElement, isNull); service.setSelection(elementA); expect(selectionChangedCount, equals(1)); expect(service.selection.currentElement, equals(elementA)); expect(service.selection.current, equals(elementA.renderObject)); service.setSelection(elementB.renderObject); expect(selectionChangedCount, equals(2)); expect(service.selection.current, equals(elementB.renderObject)); expect(service.selection.currentElement, equals((elementB.renderObject!.debugCreator! as DebugCreator).element)); service.setSelection('invalid selection'); expect(selectionChangedCount, equals(2)); expect(service.selection.current, equals(elementB.renderObject)); service.setSelectionById(service.toId(elementA, 'my-group')); expect(selectionChangedCount, equals(3)); expect(service.selection.currentElement, equals(elementA)); expect(service.selection.current, equals(elementA.renderObject)); service.setSelectionById(service.toId(elementA, 'my-group')); expect(selectionChangedCount, equals(3)); expect(service.selection.currentElement, equals(elementA)); }); testWidgets('WidgetInspectorService defunct selection regression test', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA); expect(service.selection.currentElement, equals(elementA)); expect(service.selection.current, equals(elementA.renderObject)); await tester.pumpWidget( const SizedBox( child: Text('b', textDirection: TextDirection.ltr), ), ); // Selection is now empty as the element is defunct. expect(service.selection.currentElement, equals(null)); expect(service.selection.current, equals(null)); // Verify that getting the debug creation location of the defunct element // does not crash. expect(debugIsLocalCreationLocation(elementA), isFalse); // Verify that generating json for a defunct element does not crash. expect( elementA.toDiagnosticsNode().toJsonMap( InspectorSerializationDelegate( service: service, includeProperties: true, ), ), isNotNull, ); final Element elementB = find.text('b').evaluate().first; service.setSelection(elementB); expect(service.selection.currentElement, equals(elementB)); expect(service.selection.current, equals(elementB.renderObject)); // Set selection back to a defunct element. service.setSelection(elementA); expect(service.selection.currentElement, equals(null)); expect(service.selection.current, equals(null)); }); testWidgets('WidgetInspectorService getParentChain', (WidgetTester tester) async { const String group = 'test-group'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); service.disposeAllGroups(); final Element elementB = find.text('b').evaluate().first; final String bId = service.toId(elementB, group)!; final Object? jsonList = json.decode(service.getParentChain(bId, group)); expect(jsonList, isList); final List<Object?> chainElements = jsonList! as List<Object?>; final List<Element> expectedChain = elementB.debugGetDiagnosticChain().reversed.toList(); // Sanity check that the chain goes back to the root. expect(expectedChain.first, tester.binding.rootElement); expect(chainElements.length, equals(expectedChain.length)); for (int i = 0; i < expectedChain.length; i += 1) { expect(chainElements[i], isMap); final Map<String, Object?> chainNode = chainElements[i]! as Map<String, Object?>; final Element element = expectedChain[i]; expect(chainNode['node'], isMap); final Map<String, Object?> jsonNode = chainNode['node']! as Map<String, Object?>; expect(service.toObject(jsonNode['valueId']! as String), equals(element)); expect(chainNode['children'], isList); final List<Object?> jsonChildren = chainNode['children']! as List<Object?>; final List<Element> childrenElements = <Element>[]; element.visitChildren(childrenElements.add); expect(jsonChildren.length, equals(childrenElements.length)); if (i + 1 == expectedChain.length) { expect(chainNode['childIndex'], isNull); } else { expect(chainNode['childIndex'], equals(childrenElements.indexOf(expectedChain[i+1]))); } for (int j = 0; j < childrenElements.length; j += 1) { expect(jsonChildren[j], isMap); final Map<String, Object?> childJson = jsonChildren[j]! as Map<String, Object?>; expect(service.toObject(childJson['valueId']! as String), equals(childrenElements[j])); } } }); test('WidgetInspectorService getProperties', () { const Diagnosticable diagnosticable = Text('a', textDirection: TextDirection.ltr); const String group = 'group'; service.disposeAllGroups(); final String id = service.toId(diagnosticable, group)!; final List<Object?> propertiesJson = json.decode(service.getProperties(id, group)) as List<Object?>; final List<DiagnosticsNode> properties = diagnosticable.toDiagnosticsNode().getProperties(); expect(properties, isNotEmpty); expect(propertiesJson.length, equals(properties.length)); for (int i = 0; i < propertiesJson.length; ++i) { final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>; expect(service.toObject(propertyJson['valueId'] as String?), equals(properties[i].value)); } }); testWidgets('WidgetInspectorService getChildren', (WidgetTester tester) async { const String group = 'test-group'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode(); service.disposeAllGroups(); final String id = service.toId(diagnostic, group)!; final List<Object?> propertiesJson = json.decode(service.getChildren(id, group)) as List<Object?>; final List<DiagnosticsNode> children = diagnostic.getChildren(); expect(children.length, equals(3)); expect(propertiesJson.length, equals(children.length)); for (int i = 0; i < propertiesJson.length; ++i) { final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>; expect(service.toObject(propertyJson['valueId']! as String), equals(children[i].value)); } }); testWidgets('WidgetInspectorService creationLocation', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ const Text('a'), const Text('b', textDirection: TextDirection.ltr), 'c'.text(), ], ), ), ); final Element elementA = find.text('a').evaluate().first; final Element elementB = find.text('b').evaluate().first; final Element elementC = find.text('c').evaluate().first; service.disposeAllGroups(); service.resetPubRootDirectories(); service.setSelection(elementA, 'my-group'); final Map<String, Object?> jsonA = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; final Map<String, Object?> creationLocationA = jsonA['creationLocation']! as Map<String, Object?>; expect(creationLocationA, isNotNull); final String fileA = creationLocationA['file']! as String; final int lineA = creationLocationA['line']! as int; final int columnA = creationLocationA['column']! as int; final String nameA = creationLocationA['name']! as String; expect(nameA, equals('Text')); service.setSelection(elementB, 'my-group'); final Map<String, Object?> jsonB = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; final Map<String, Object?> creationLocationB = jsonB['creationLocation']! as Map<String, Object?>; expect(creationLocationB, isNotNull); final String fileB = creationLocationB['file']! as String; final int lineB = creationLocationB['line']! as int; final int columnB = creationLocationB['column']! as int; final String? nameB = creationLocationB['name'] as String?; expect(nameB, equals('Text')); service.setSelection(elementC, 'my-group'); final Map<String, Object?> jsonC = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; final Map<String, Object?> creationLocationC = jsonC['creationLocation']! as Map<String, Object?>; expect(creationLocationC, isNotNull); final String fileC = creationLocationC['file']! as String; final int lineC = creationLocationC['line']! as int; final int columnC = creationLocationC['column']! as int; final String? nameC = creationLocationC['name'] as String?; expect(nameC, equals('TextFromString|text')); expect(fileA, endsWith('widget_inspector_test.dart')); expect(fileA, equals(fileB)); expect(fileA, equals(fileC)); // We don't hardcode the actual lines the widgets are created on as that // would make this test fragile. expect(lineA + 1, equals(lineB)); expect(lineB + 1, equals(lineC)); // Column numbers are more stable than line numbers. expect(columnA, equals(21)); expect(columnA, equals(columnB)); expect(columnC, equals(19)); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('WidgetInspectorService setSelection notifiers for an Element', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.disposeAllGroups(); setupDefaultPubRootDirectory(service); // Select the widget service.setSelection(elementA, 'my-group'); // ensure that developer.inspect was called on the widget final List<Object?> objectsInspected = service.inspectedObjects(); expect(objectsInspected, equals(<Element>[elementA])); // ensure that a navigate event was sent for the element final List<Map<Object, Object?>> navigateEventsPosted = service.dispatchedEvents('navigate', stream: 'ToolEvent',); expect(navigateEventsPosted.length, equals(1)); final Map<Object,Object?> event = navigateEventsPosted[0]; final String file = event['fileUri']! as String; final int line = event['line']! as int; final int column = event['column']! as int; expect(file, endsWith('widget_inspector_test.dart')); // We don't hardcode the actual lines the widgets are created on as that // would make this test fragile. expect(line, isNotNull); // Column numbers are more stable than line numbers. expect(column, equals(15)); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. ); testWidgets( 'WidgetInspectorService setSelection notifiers for a RenderObject', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.disposeAllGroups(); setupDefaultPubRootDirectory(service); // Select the render object for the widget. service.setSelection(elementA.renderObject, 'my-group'); // ensure that developer.inspect was called on the widget final List<Object?> objectsInspected = service.inspectedObjects(); expect(objectsInspected, equals(<RenderObject?>[elementA.renderObject])); // ensure that a navigate event was sent for the renderObject final List<Map<Object, Object?>> navigateEventsPosted = service.dispatchedEvents('navigate', stream: 'ToolEvent',); expect(navigateEventsPosted.length, equals(1)); final Map<Object,Object?> event = navigateEventsPosted[0]; final String file = event['fileUri']! as String; final int line = event['line']! as int; final int column = event['column']! as int; expect(file, endsWith('widget_inspector_test.dart')); // We don't hardcode the actual lines the widgets are created on as that // would make this test fragile. expect(line, isNotNull); // Column numbers are more stable than line numbers. expect(column, equals(17)); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. ); testWidgets( 'WidgetInspector selectButton inspection for tap', (WidgetTester tester) async { final GlobalKey selectButtonKey = GlobalKey(); final GlobalKey inspectorKey = GlobalKey(); setupDefaultPubRootDirectory(service); Widget selectButtonBuilder(BuildContext context, VoidCallback onPressed) { return Material(child: ElevatedButton(onPressed: onPressed, key: selectButtonKey, child: null)); } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( key: inspectorKey, selectButtonBuilder: selectButtonBuilder, child: const Text('Child 1'), ), ), ); final Finder child = find.text('Child 1'); final Element childElement = child.evaluate().first; await tester.tap(child, warnIfMissed: false); await tester.pump(); // ensure that developer.inspect was called on the widget final List<Object?> objectsInspected = service.inspectedObjects(); expect(objectsInspected, equals(<RenderObject?>[childElement.renderObject])); // ensure that a navigate event was sent for the renderObject final List<Map<Object, Object?>> navigateEventsPosted = service.dispatchedEvents('navigate', stream: 'ToolEvent',); expect(navigateEventsPosted.length, equals(1)); final Map<Object,Object?> event = navigateEventsPosted[0]; final String file = event['fileUri']! as String; final int line = event['line']! as int; final int column = event['column']! as int; expect(file, endsWith('widget_inspector_test.dart')); // We don't hardcode the actual lines the widgets are created on as that // would make this test fragile. expect(line, isNotNull); // Column numbers are more stable than line numbers. expect(column, equals(28)); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked() // [intended] Test requires --track-widget-creation flag. ); testWidgets('test transformDebugCreator will re-order if after stack trace', (WidgetTester tester) async { final bool widgetTracked = WidgetInspectorService.instance.isWidgetCreationTracked(); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); late String pubRootTest; if (widgetTracked) { final Map<String, Object?> jsonObject = json.decode( service.getSelectedWidget(null, 'my-group'), ) as Map<String, Object?>; final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String fileA = creationLocation['file']! as String; expect(fileA, endsWith('widget_inspector_test.dart')); expect(jsonObject, isNot(contains('createdByLocalProject'))); final List<String> segments = Uri .parse(fileA) .pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; service.resetPubRootDirectories(); service.addPubRootDirectories(<String>[pubRootTest]); } final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); builder.add(StringProperty('dummy1', 'value')); builder.add(StringProperty('dummy2', 'value')); builder.add(DiagnosticsStackTrace('When the exception was thrown, this was the stack', null)); builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); expect(nodes.length, 5); expect(nodes[0].runtimeType, StringProperty); expect(nodes[0].name, 'dummy1'); expect(nodes[1].runtimeType, StringProperty); expect(nodes[1].name, 'dummy2'); // transformed node should come in front of stack trace. if (widgetTracked) { expect(nodes[2].runtimeType, DiagnosticsBlock); final DiagnosticsBlock node = nodes[2] as DiagnosticsBlock; final List<DiagnosticsNode> children = node.getChildren(); expect(children.length, 1); final ErrorDescription child = children[0] as ErrorDescription; expect(child.valueToString(), contains(Uri.parse(pubRootTest).path)); } else { expect(nodes[2].runtimeType, ErrorDescription); final ErrorDescription node = nodes[2] as ErrorDescription; expect(node.valueToString().startsWith('Widget creation tracking is currently disabled.'), true); } expect(nodes[3].runtimeType, ErrorSpacer); expect(nodes[4].runtimeType, DiagnosticsStackTrace); }); testWidgets('test transformDebugCreator will not re-order if before stack trace', (WidgetTester tester) async { final bool widgetTracked = WidgetInspectorService.instance.isWidgetCreationTracked(); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; late String pubRootTest; if (widgetTracked) { final Map<String, Object?> jsonObject = json.decode( service.getSelectedWidget(null, 'my-group'), ) as Map<String, Object?>; final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String fileA = creationLocation['file']! as String; expect(fileA, endsWith('widget_inspector_test.dart')); expect(jsonObject, isNot(contains('createdByLocalProject'))); final List<String> segments = Uri .parse(fileA) .pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; service.resetPubRootDirectories(); service.addPubRootDirectories(<String>[pubRootTest]); } final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); builder.add(StringProperty('dummy1', 'value')); builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); builder.add(StringProperty('dummy2', 'value')); builder.add(DiagnosticsStackTrace('When the exception was thrown, this was the stack', null)); final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); expect(nodes.length, 5); expect(nodes[0].runtimeType, StringProperty); expect(nodes[0].name, 'dummy1'); // transformed node stays at original place. if (widgetTracked) { expect(nodes[1].runtimeType, DiagnosticsBlock); final DiagnosticsBlock node = nodes[1] as DiagnosticsBlock; final List<DiagnosticsNode> children = node.getChildren(); expect(children.length, 1); final ErrorDescription child = children[0] as ErrorDescription; expect(child.valueToString(), contains(Uri.parse(pubRootTest).path)); } else { expect(nodes[1].runtimeType, ErrorDescription); final ErrorDescription node = nodes[1] as ErrorDescription; expect(node.valueToString().startsWith('Widget creation tracking is currently disabled.'), true); } expect(nodes[2].runtimeType, ErrorSpacer); expect(nodes[3].runtimeType, StringProperty); expect(nodes[3].name, 'dummy2'); expect(nodes[4].runtimeType, DiagnosticsStackTrace); }, skip: WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --no-track-widget-creation flag. testWidgets('test transformDebugCreator will add DevToolsDeepLinkProperty for overflow errors', (WidgetTester tester) async { activeDevToolsServerAddress = 'http://127.0.0.1:9100'; connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; setupDefaultPubRootDirectory(service); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); builder.add(ErrorSummary('A RenderFlex overflowed by 273 pixels on the bottom')); builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); builder.add(StringProperty('dummy2', 'value')); final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); expect(nodes.length, 6); expect(nodes[0].runtimeType, ErrorSummary); expect(nodes[1].runtimeType, DiagnosticsBlock); expect(nodes[2].runtimeType, ErrorSpacer); expect(nodes[3].runtimeType, DevToolsDeepLinkProperty); expect(nodes[4].runtimeType, ErrorSpacer); expect(nodes[5].runtimeType, StringProperty); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('test transformDebugCreator will not add DevToolsDeepLinkProperty for non-overflow errors', (WidgetTester tester) async { activeDevToolsServerAddress = 'http://127.0.0.1:9100'; connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; setupDefaultPubRootDirectory(service); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); builder.add(ErrorSummary('some other error')); builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); builder.add(StringProperty('dummy2', 'value')); final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); expect(nodes.length, 4); expect(nodes[0].runtimeType, ErrorSummary); expect(nodes[1].runtimeType, DiagnosticsBlock); expect(nodes[2].runtimeType, ErrorSpacer); expect(nodes[3].runtimeType, StringProperty); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('test transformDebugCreator will not add DevToolsDeepLinkProperty if devtoolsServerAddress is unavailable', (WidgetTester tester) async { activeDevToolsServerAddress = null; connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; setupDefaultPubRootDirectory(service); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); builder.add(ErrorSummary('A RenderFlex overflowed by 273 pixels on the bottom')); builder.add(DiagnosticsDebugCreator(DebugCreator(elementA))); builder.add(StringProperty('dummy2', 'value')); final List<DiagnosticsNode> nodes = List<DiagnosticsNode>.from(debugTransformDebugCreator(builder.properties)); expect(nodes.length, 4); expect(nodes[0].runtimeType, ErrorSummary); expect(nodes[1].runtimeType, DiagnosticsBlock); expect(nodes[2].runtimeType, ErrorSpacer); expect(nodes[3].runtimeType, StringProperty); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. // TODO(CoderDake): Clean up pubRootDirectory tests https://github.com/flutter/flutter/issues/107186 group('pubRootDirectory', () { const String directoryA = '/a/b/c'; const String directoryB = '/d/e/f'; const String directoryC = '/g/h/i'; setUp(() { service.resetPubRootDirectories(); }); group('addPubRootDirectories', () { test('can add multiple directories', () async { const List<String> directories = <String>[directoryA, directoryB]; service.addPubRootDirectories(directories); final List<String> pubRoots = await service.currentPubRootDirectories; expect(pubRoots, unorderedEquals(directories)); }); test('can add multiple directories separately', () async { service.addPubRootDirectories(<String>[directoryA]); service.addPubRootDirectories(<String>[directoryB]); service.addPubRootDirectories(<String>[]); final List<String> pubRoots = await service.currentPubRootDirectories; expect(pubRoots, unorderedEquals(<String>[ directoryA, directoryB, ])); }); test('handles duplicates', () async { const List<String> directories = <String>[ directoryA, 'file://$directoryA', directoryB, directoryB ]; service.addPubRootDirectories(directories); final List<String> pubRoots = await service.currentPubRootDirectories; expect(pubRoots, unorderedEquals(<String>[ directoryA, directoryB, ])); }); }); group('removePubRootDirectories', () { setUp(() { service.resetPubRootDirectories(); service.addPubRootDirectories(<String>[directoryA, directoryB, directoryC]); }); test('removes multiple directories', () async { service.removePubRootDirectories(<String>[directoryA, directoryB,]); final List<String> pubRoots = await service.currentPubRootDirectories; expect(pubRoots, equals(<String>[directoryC])); }); test('removes multiple directories separately', () async { service.removePubRootDirectories(<String>[directoryA]); service.removePubRootDirectories(<String>[directoryB]); service.removePubRootDirectories(<String>[]); final List<String> pubRoots = await service.currentPubRootDirectories; expect(pubRoots, equals(<String>[directoryC])); }); test('handles duplicates', () async { service.removePubRootDirectories(<String>[ 'file://$directoryA', directoryA, directoryB, directoryB, ]); final List<String> pubRoots = await service.currentPubRootDirectories; expect(pubRoots, equals(<String>[directoryC])); }); test("does nothing if the directories doesn't exist ", () async { service.removePubRootDirectories(<String>['/x/y/z']); final List<String> pubRoots = await service.currentPubRootDirectories; expect(pubRoots, unorderedEquals(<String>[ directoryA, directoryB, directoryC, ])); }); }); }); group( 'WidgetInspectorService', () { late final String pubRootTest; setUpAll(() { pubRootTest = generateTestPubRootDirectory(service); }); setUp(() { service.disposeAllGroups(); service.resetPubRootDirectories(); }); group('addPubRootDirectories', () { testWidgets( 'does not have createdByLocalProject when there are no pubRootDirectories', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); final Map<String, Object?> jsonObject = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String fileA = creationLocation['file']! as String; expect(fileA, endsWith('widget_inspector_test.dart')); expect(jsonObject, isNot(contains('createdByLocalProject'))); }, ); testWidgets( 'has createdByLocalProject when the element is part of the pubRootDirectory', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.addPubRootDirectories(<String>[pubRootTest]); service.setSelection(elementA, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); }, ); testWidgets( 'does not have createdByLocalProject when widget package directory is a suffix of a pubRootDirectory', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.addPubRootDirectories(<String>['/invalid/$pubRootTest']); expect( json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.addPubRootDirectories(<String>['file://$pubRootTest']); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); }, ); testWidgets( 'does not have createdByLocalProject when thePubRootDirectory has a different suffix', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.addPubRootDirectories(<String>['$pubRootTest/different']); expect( json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'has createdByLocalProject even if another pubRootDirectory does not match', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.addPubRootDirectories(<String>[ '/invalid/$pubRootTest', pubRootTest, ]); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); }, ); testWidgets( 'widget is part of core framework and is the child of a widget in the package pubRootDirectories', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; final Element richText = find .descendant( of: find.text('a'), matching: find.byType(RichText), ) .evaluate() .first; service.setSelection(richText, 'my-group'); service.addPubRootDirectories(<String>[pubRootTest]); final Map<String, Object?> jsonObject = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; expect(jsonObject, isNot(contains('createdByLocalProject'))); final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); // This RichText widget is created by the build method of the Text widget // thus the creation location is in text.dart not basic.dart final List<String> pathSegmentsFramework = Uri.parse(creationLocation['file']! as String).pathSegments; expect( pathSegmentsFramework.join('/'), endsWith('/flutter/lib/src/widgets/text.dart'), ); // Strip off /src/widgets/text.dart. final String pubRootFramework = '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}'; service.resetPubRootDirectories(); service.addPubRootDirectories(<String>[pubRootFramework]); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); service.setSelection(elementA, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')), ); service .setPubRootDirectories(<String>[pubRootFramework, pubRootTest]); service.setSelection(elementA, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); service.setSelection(richText, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); }, ); }); group('createdByLocalProject', () { setUp(() { service.resetPubRootDirectories(); }); testWidgets( 'reacts to add and removing pubRootDirectories', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.addPubRootDirectories(<String>[ pubRootTest, 'file://$pubRootTest', '/unrelated/$pubRootTest', ]); service.setSelection(elementA, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); service.removePubRootDirectories(<String>[pubRootTest]); service.setSelection(elementA, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'does not match when the package directory does not match', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.addPubRootDirectories(<String>[ '$pubRootTest/different', '/unrelated/$pubRootTest', ]); expect( json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.addPubRootDirectories(<String>['file://$pubRootTest']); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); }, ); testWidgets( 'can handle consecutive calls to add', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.addPubRootDirectories(<String>[ pubRootTest, ]); service.addPubRootDirectories(<String>[ '/invalid/$pubRootTest', ]); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); }, ); testWidgets( 'can handle removing an unrelated pubRootDirectory', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.addPubRootDirectories(<String>[ pubRootTest, '/invalid/$pubRootTest', ]); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); service.removePubRootDirectories(<String>[ '/invalid/$pubRootTest', ]); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); }, ); testWidgets( 'can handle parent widget being part of a separate package', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; final Element richText = find .descendant( of: find.text('a'), matching: find.byType(RichText), ) .evaluate() .first; service.setSelection(richText, 'my-group'); service.addPubRootDirectories(<String>[pubRootTest]); final Map<String, Object?> jsonObject = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; expect(jsonObject, isNot(contains('createdByLocalProject'))); final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); // This RichText widget is created by the build method of the Text widget // thus the creation location is in text.dart not basic.dart final List<String> pathSegmentsFramework = Uri.parse(creationLocation['file']! as String).pathSegments; expect( pathSegmentsFramework.join('/'), endsWith('/flutter/lib/src/widgets/text.dart'), ); // Strip off /src/widgets/text.dart. final String pubRootFramework = '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}'; service.resetPubRootDirectories(); service.addPubRootDirectories(<String>[pubRootFramework]); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); service.setSelection(elementA, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), isNot(contains('createdByLocalProject')), ); service.resetPubRootDirectories(); service .addPubRootDirectories(<String>[pubRootFramework, pubRootTest]); service.setSelection(elementA, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); service.setSelection(richText, 'my-group'); expect( json.decode(service.getSelectedWidget(null, 'my-group')), contains('createdByLocalProject'), ); }, ); }); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. ); group('InspectorSelection', () { testWidgets('receives notifications when selection changes', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b'), ], ), ), ); final InspectorSelection selection = InspectorSelection(); addTearDown(selection.dispose); int count = 0; selection.addListener(() { count++; }); final RenderParagraph renderObjectA = tester.renderObject<RenderParagraph>(find.text('a')); final RenderParagraph renderObjectB = tester.renderObject<RenderParagraph>(find.text('b')); final Element elementA = find.text('a').evaluate().first; selection.candidates = <RenderObject>[renderObjectA, renderObjectB]; await tester.pump(); expect(count, equals(1)); selection.index = 1; await tester.pump(); expect(count, equals(2)); selection.clear(); await tester.pump(); expect(count, equals(3)); selection.current = renderObjectA; await tester.pump(); expect(count, equals(4)); selection.currentElement = elementA; expect(count, equals(5)); }); }); test('ext.flutter.inspector.disposeGroup', () async { final Object a = Object(); const String group1 = 'group-1'; const String group2 = 'group-2'; const String group3 = 'group-3'; final String? aId = service.toId(a, group1); expect(service.toId(a, group2), equals(aId)); expect(service.toId(a, group3), equals(aId)); await service.testExtension( WidgetInspectorServiceExtensions.disposeGroup.name, <String, String>{'objectGroup': group1}, ); await service.testExtension( WidgetInspectorServiceExtensions.disposeGroup.name, <String, String>{'objectGroup': group2}, ); expect(service.toObject(aId), equals(a)); await service.testExtension( WidgetInspectorServiceExtensions.disposeGroup.name, <String, String>{'objectGroup': group3}, ); expect(() => service.toObject(aId), throwsFlutterError); }); test('ext.flutter.inspector.disposeId', () async { final Object a = Object(); final Object b = Object(); const String group1 = 'group-1'; const String group2 = 'group-2'; final String aId = service.toId(a, group1)!; final String bId = service.toId(b, group1)!; expect(service.toId(a, group2), equals(aId)); await service.testExtension( WidgetInspectorServiceExtensions.disposeId.name, <String, String>{'arg': bId, 'objectGroup': group1}, ); expect(() => service.toObject(bId), throwsFlutterError); await service.testExtension( WidgetInspectorServiceExtensions.disposeId.name, <String, String>{'arg': aId, 'objectGroup': group1}, ); expect(service.toObject(aId), equals(a)); await service.testExtension( WidgetInspectorServiceExtensions.disposeId.name, <String, String>{'arg': aId, 'objectGroup': group2}, ); expect(() => service.toObject(aId), throwsFlutterError); }); testWidgets('ext.flutter.inspector.setSelection', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; final Element elementB = find.text('b').evaluate().first; service.disposeAllGroups(); service.selection.clear(); int selectionChangedCount = 0; service.selectionChangedCallback = () => selectionChangedCount++; service.setSelection('invalid selection'); expect(selectionChangedCount, equals(0)); expect(service.selection.currentElement, isNull); service.setSelection(elementA); expect(selectionChangedCount, equals(1)); expect(service.selection.currentElement, equals(elementA)); expect(service.selection.current, equals(elementA.renderObject)); service.setSelection(elementB.renderObject); expect(selectionChangedCount, equals(2)); expect(service.selection.current, equals(elementB.renderObject)); expect(service.selection.currentElement, equals((elementB.renderObject!.debugCreator! as DebugCreator).element)); service.setSelection('invalid selection'); expect(selectionChangedCount, equals(2)); expect(service.selection.current, equals(elementB.renderObject)); await service.testExtension( WidgetInspectorServiceExtensions.setSelectionById.name, <String, String>{'arg': service.toId(elementA, 'my-group')!, 'objectGroup': 'my-group'}, ); expect(selectionChangedCount, equals(3)); expect(service.selection.currentElement, equals(elementA)); expect(service.selection.current, equals(elementA.renderObject)); service.setSelectionById(service.toId(elementA, 'my-group')); expect(selectionChangedCount, equals(3)); expect(service.selection.currentElement, equals(elementA)); }); testWidgets('ext.flutter.inspector.getParentChain', (WidgetTester tester) async { const String group = 'test-group'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementB = find.text('b').evaluate().first; final String bId = service.toId(elementB, group)!; final Object? jsonList = await service.testExtension( WidgetInspectorServiceExtensions.getParentChain.name, <String, String>{'arg': bId, 'objectGroup': group}, ); expect(jsonList, isList); final List<Object?> chainElements = jsonList! as List<Object?>; final List<Element> expectedChain = elementB.debugGetDiagnosticChain().reversed.toList(); // Sanity check that the chain goes back to the root. expect(expectedChain.first, tester.binding.rootElement); expect(chainElements.length, equals(expectedChain.length)); for (int i = 0; i < expectedChain.length; i += 1) { expect(chainElements[i], isMap); final Map<String, Object?> chainNode = chainElements[i]! as Map<String, Object?>; final Element element = expectedChain[i]; expect(chainNode['node'], isMap); final Map<String, Object?> jsonNode = chainNode['node']! as Map<String, Object?>; expect(service.toObject(jsonNode['valueId']! as String), equals(element)); expect(chainNode['children'], isList); final List<Object?> jsonChildren = chainNode['children']! as List<Object?>; final List<Element> childrenElements = <Element>[]; element.visitChildren(childrenElements.add); expect(jsonChildren.length, equals(childrenElements.length)); if (i + 1 == expectedChain.length) { expect(chainNode['childIndex'], isNull); } else { expect(chainNode['childIndex'], equals(childrenElements.indexOf(expectedChain[i+1]))); } for (int j = 0; j < childrenElements.length; j += 1) { expect(jsonChildren[j], isMap); final Map<String, Object?> childJson = jsonChildren[j]! as Map<String, Object?>; expect(service.toObject(childJson['valueId']! as String), equals(childrenElements[j])); } } }); test('ext.flutter.inspector.getProperties', () async { const Diagnosticable diagnosticable = Text('a', textDirection: TextDirection.ltr); const String group = 'group'; final String id = service.toId(diagnosticable, group)!; final List<Object?> propertiesJson = (await service.testExtension( WidgetInspectorServiceExtensions.getProperties.name, <String, String>{'arg': id, 'objectGroup': group}, ))! as List<Object?>; final List<DiagnosticsNode> properties = diagnosticable.toDiagnosticsNode().getProperties(); expect(properties, isNotEmpty); expect(propertiesJson.length, equals(properties.length)); for (int i = 0; i < propertiesJson.length; ++i) { final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>; expect(service.toObject(propertyJson['valueId'] as String?), equals(properties[i].value)); } }); testWidgets('ext.flutter.inspector.getChildren', (WidgetTester tester) async { const String group = 'test-group'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final DiagnosticsNode diagnostic = find.byType(Stack).evaluate().first.toDiagnosticsNode(); final String id = service.toId(diagnostic, group)!; final List<Object?> propertiesJson = (await service.testExtension( WidgetInspectorServiceExtensions.getChildren.name, <String, String>{'arg': id, 'objectGroup': group}, ))! as List<Object?>; final List<DiagnosticsNode> children = diagnostic.getChildren(); expect(children.length, equals(3)); expect(propertiesJson.length, equals(children.length)); for (int i = 0; i < propertiesJson.length; ++i) { final Map<String, Object?> propertyJson = propertiesJson[i]! as Map<String, Object?>; expect(service.toObject(propertyJson['valueId']! as String), equals(children[i].value)); } }); testWidgets('ext.flutter.inspector.getChildrenDetailsSubtree', (WidgetTester tester) async { const String group = 'test-group'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Diagnosticable diagnosticable = find.byType(Stack).evaluate().first; final String id = service.toId(diagnosticable, group)!; final List<Object?> childrenJson = (await service.testExtension( WidgetInspectorServiceExtensions.getChildrenDetailsSubtree.name, <String, String>{'arg': id, 'objectGroup': group}, ))! as List<Object?>; final List<DiagnosticsNode> children = diagnosticable.toDiagnosticsNode().getChildren(); expect(children.length, equals(3)); expect(childrenJson.length, equals(children.length)); for (int i = 0; i < childrenJson.length; ++i) { final Map<String, Object?> childJson = childrenJson[i]! as Map<String, Object?>; expect(service.toObject(childJson['valueId']! as String), equals(children[i].value)); final List<Object?> propertiesJson = childJson['properties']! as List<Object?>; final Element element = service.toObject(childJson['valueId']! as String)! as Element; final List<DiagnosticsNode> expectedProperties = element.toDiagnosticsNode().getProperties(); final Iterable<Object?> propertyValues = expectedProperties.map((DiagnosticsNode e) => e.value.toString()); for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) { final String id = propertyJson['valueId']! as String; final String property = service.toObject(id)!.toString(); expect(propertyValues, contains(property)); } } }); testWidgets('WidgetInspectorService getDetailsSubtree', (WidgetTester tester) async { const String group = 'test-group'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Diagnosticable diagnosticable = find.byType(Stack).evaluate().first; final String id = service.toId(diagnosticable, group)!; final Map<String, Object?> subtreeJson = (await service.testExtension( WidgetInspectorServiceExtensions.getDetailsSubtree.name, <String, String>{'arg': id, 'objectGroup': group}, ))! as Map<String, Object?>; expect(subtreeJson['valueId'], equals(id)); final List<Object?> childrenJson = subtreeJson['children']! as List<Object?>; final List<DiagnosticsNode> children = diagnosticable.toDiagnosticsNode().getChildren(); expect(children.length, equals(3)); expect(childrenJson.length, equals(children.length)); for (int i = 0; i < childrenJson.length; ++i) { final Map<String, Object?> childJson = childrenJson[i]! as Map<String, Object?>; expect(service.toObject(childJson['valueId']! as String), equals(children[i].value)); final List<Object?> propertiesJson = childJson['properties']! as List<Object?>; for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) { expect(propertyJson, isNot(contains('children'))); } final Element element = service.toObject(childJson['valueId']! as String)! as Element; final List<DiagnosticsNode> expectedProperties = element.toDiagnosticsNode().getProperties(); final Iterable<Object?> propertyValues = expectedProperties.map((DiagnosticsNode e) => e.value.toString()); for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) { final String id = propertyJson['valueId']! as String; final String property = service.toObject(id)!.toString(); expect(propertyValues, contains(property)); } } final Map<String, Object?> deepSubtreeJson = (await service.testExtension( WidgetInspectorServiceExtensions.getDetailsSubtree.name, <String, String>{'arg': id, 'objectGroup': group, 'subtreeDepth': '3'}, ))! as Map<String, Object?>; final List<Object?> deepChildrenJson = deepSubtreeJson['children']! as List<Object?>; for (final Map<String, Object?> childJson in deepChildrenJson.cast<Map<String, Object?>>()) { final List<Object?> propertiesJson = childJson['properties']! as List<Object?>; for (final Map<String, Object?> propertyJson in propertiesJson.cast<Map<String, Object?>>()) { expect(propertyJson, contains('children')); } } }); testWidgets('cyclic diagnostics regression test', (WidgetTester tester) async { const String group = 'test-group'; final CyclicDiagnostic a = CyclicDiagnostic('a'); final CyclicDiagnostic b = CyclicDiagnostic('b'); a.related = b; a.children.add(b.toDiagnosticsNode()); b.related = a; final String id = service.toId(a, group)!; final Map<String, Object?> subtreeJson = (await service.testExtension( WidgetInspectorServiceExtensions.getDetailsSubtree.name, <String, String>{'arg': id, 'objectGroup': group}, ))! as Map<String, Object?>; expect(subtreeJson['valueId'], equals(id)); expect(subtreeJson, contains('children')); final List<Object?> propertiesJson = subtreeJson['properties']! as List<Object?>; expect(propertiesJson.length, equals(1)); final Map<String, Object?> relatedProperty = propertiesJson.first! as Map<String, Object?>; expect(relatedProperty['name'], equals('related')); expect(relatedProperty['description'], equals('CyclicDiagnostic-b')); expect(relatedProperty, contains('isDiagnosticableValue')); expect(relatedProperty, isNot(contains('children'))); expect(relatedProperty, contains('properties')); final List<Object?> relatedWidgetProperties = relatedProperty['properties']! as List<Object?>; expect(relatedWidgetProperties.length, equals(1)); final Map<String, Object?> nestedRelatedProperty = relatedWidgetProperties.first! as Map<String, Object?>; expect(nestedRelatedProperty['name'], equals('related')); // Make sure we do not include properties or children for diagnostic a // which we already included as the root node as that would indicate a // cycle. expect(nestedRelatedProperty['description'], equals('CyclicDiagnostic-a')); expect(nestedRelatedProperty, contains('isDiagnosticableValue')); expect(nestedRelatedProperty, isNot(contains('properties'))); expect(nestedRelatedProperty, isNot(contains('children'))); }); testWidgets('ext.flutter.inspector.getRootWidgetSummaryTree', (WidgetTester tester) async { const String group = 'test-group'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.disposeAllGroups(); service.resetPubRootDirectories(); service.setSelection(elementA, 'my-group'); final Map<String, dynamic> jsonA = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, dynamic>; service.resetPubRootDirectories(); Map<String, Object?> rootJson = (await service.testExtension( WidgetInspectorServiceExtensions.getRootWidgetSummaryTree.name, <String, String>{'objectGroup': group}, ))! as Map<String, Object?>; // We haven't yet properly specified which directories are summary tree // directories so we get an empty tree other than the root that is always // included. final Object? rootWidget = service.toObject(rootJson['valueId']! as String); expect(rootWidget, equals(WidgetsBinding.instance.rootElement)); List<Object?> childrenJson = rootJson['children']! as List<Object?>; // There are no summary tree children. expect(childrenJson.length, equals(0)); final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String testFile = creationLocation['file']! as String; expect(testFile, endsWith('widget_inspector_test.dart')); final List<String> segments = Uri.parse(testFile).pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; service.resetPubRootDirectories(); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootTest}, ); rootJson = (await service.testExtension( WidgetInspectorServiceExtensions.getRootWidgetSummaryTree.name, <String, String>{'objectGroup': group}, ))! as Map<String, Object?>; childrenJson = rootJson['children']! as List<Object?>; // The tree of nodes returned contains all widgets created directly by the // test. childrenJson = rootJson['children']! as List<Object?>; expect(childrenJson.length, equals(1)); List<Object?> alternateChildrenJson = (await service.testExtension( WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, <String, String>{'arg': rootJson['valueId']! as String, 'objectGroup': group}, ))! as List<Object?>; expect(alternateChildrenJson.length, equals(1)); Map<String, Object?> childJson = childrenJson[0]! as Map<String, Object?>; Map<String, Object?> alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>; expect(childJson['description'], startsWith('Directionality')); expect(alternateChildJson['description'], startsWith('Directionality')); expect(alternateChildJson['valueId'], equals(childJson['valueId'])); childrenJson = childJson['children']! as List<Object?>; alternateChildrenJson = (await service.testExtension( WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, ))! as List<Object?>; expect(alternateChildrenJson.length, equals(1)); expect(childrenJson.length, equals(1)); alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>; childJson = childrenJson[0]! as Map<String, Object?>; expect(childJson['description'], startsWith('Stack')); expect(alternateChildJson['description'], startsWith('Stack')); expect(alternateChildJson['valueId'], equals(childJson['valueId'])); childrenJson = childJson['children']! as List<Object?>; childrenJson = childJson['children']! as List<Object?>; alternateChildrenJson = (await service.testExtension( WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, ))! as List<Object?>; expect(alternateChildrenJson.length, equals(3)); expect(childrenJson.length, equals(3)); alternateChildJson = alternateChildrenJson[2]! as Map<String, Object?>; childJson = childrenJson[2]! as Map<String, Object?>; expect(childJson['description'], startsWith('Text')); expect(alternateChildJson['description'], startsWith('Text')); expect(alternateChildJson['valueId'], equals(childJson['valueId'])); alternateChildrenJson = (await service.testExtension( WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, ))! as List<Object?>; expect(alternateChildrenJson.length , equals(0)); // Tests are failing when this typo is fixed. expect(childJson['chidlren'], isNull); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('ext.flutter.inspector.getRootWidgetSummaryTreeWithPreviews', (WidgetTester tester) async { const String group = 'test-group'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service ..disposeAllGroups() ..resetPubRootDirectories() ..setSelection(elementA, 'my-group'); final Map<String, dynamic> jsonA = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, dynamic>; final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String testFile = creationLocation['file']! as String; expect(testFile, endsWith('widget_inspector_test.dart')); final List<String> segments = Uri.parse(testFile).pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; service ..resetPubRootDirectories() ..addPubRootDirectories(<String>[pubRootTest]); final Map<String, Object?> rootJson = (await service.testExtension( WidgetInspectorServiceExtensions.getRootWidgetSummaryTreeWithPreviews.name, <String, String>{'groupName': group}, ))! as Map<String, Object?>; List<Object?> childrenJson = rootJson['children']! as List<Object?>; // The tree of nodes returned contains all widgets created directly by the // test. childrenJson = rootJson['children']! as List<Object?>; expect(childrenJson.length, equals(1)); List<Object?> alternateChildrenJson = (await service.testExtension( WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, <String, String>{'arg': rootJson['valueId']! as String, 'objectGroup': group}, ))! as List<Object?>; expect(alternateChildrenJson.length, equals(1)); Map<String, Object?> childJson = childrenJson[0]! as Map<String, Object?>; Map<String, Object?> alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>; expect(childJson['description'], startsWith('Directionality')); expect(alternateChildJson['description'], startsWith('Directionality')); expect(alternateChildJson['valueId'], equals(childJson['valueId'])); childrenJson = childJson['children']! as List<Object?>; alternateChildrenJson = (await service.testExtension( WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, ))! as List<Object?>; expect(alternateChildrenJson.length, equals(1)); expect(childrenJson.length, equals(1)); alternateChildJson = alternateChildrenJson[0]! as Map<String, Object?>; childJson = childrenJson[0]! as Map<String, Object?>; expect(childJson['description'], startsWith('Stack')); expect(alternateChildJson['description'], startsWith('Stack')); expect(alternateChildJson['valueId'], equals(childJson['valueId'])); childrenJson = childJson['children']! as List<Object?>; childrenJson = childJson['children']! as List<Object?>; alternateChildrenJson = (await service.testExtension( WidgetInspectorServiceExtensions.getChildrenSummaryTree.name, <String, String>{'arg': childJson['valueId']! as String, 'objectGroup': group}, ))! as List<Object?>; expect(alternateChildrenJson.length, equals(3)); expect(childrenJson.length, equals(3)); alternateChildJson = alternateChildrenJson[2]! as Map<String, Object?>; childJson = childrenJson[2]! as Map<String, Object?>; expect(childJson['description'], startsWith('Text')); // [childJson] contains the 'textPreview' key since the tree was requested // with previews [getRootWidgetSummaryTreeWithPreviews]. expect(childJson['textPreview'], equals('c')); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('ext.flutter.inspector.getSelectedSummaryWidget', (WidgetTester tester) async { const String group = 'test-group'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a', textDirection: TextDirection.ltr), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; final List<DiagnosticsNode> children = elementA.debugDescribeChildren(); expect(children.length, equals(1)); final DiagnosticsNode richTextDiagnostic = children.first; service.disposeAllGroups(); service.resetPubRootDirectories(); service.setSelection(elementA, 'my-group'); final Map<String, Object?> jsonA = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, Object?>; service.setSelection(richTextDiagnostic.value, 'my-group'); service.resetPubRootDirectories(); Map<String, Object?>? summarySelection = await service.testExtension( WidgetInspectorServiceExtensions.getSelectedSummaryWidget.name, <String, String>{'objectGroup': group}, ) as Map<String, Object?>?; // No summary selection because we haven't set the pub root directories // yet to indicate what directories are in the summary tree. expect(summarySelection, isNull); final Map<String, Object?> creationLocation = jsonA['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String testFile = creationLocation['file']! as String; expect(testFile, endsWith('widget_inspector_test.dart')); final List<String> segments = Uri.parse(testFile).pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; service.resetPubRootDirectories(); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootTest}, ); summarySelection = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedSummaryWidget.name, <String, String>{'objectGroup': group}, ))! as Map<String, Object?>; expect(summarySelection['valueId'], isNotNull); // We got the Text element instead of the selected RichText element // because only the RichText element is part of the summary tree. expect(service.toObject(summarySelection['valueId']! as String), elementA); // Verify tha the regular getSelectedWidget method still returns // the RichText object not the Text element. final Map<String, Object?> regularSelection = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, Object?>; expect(service.toObject(regularSelection['valueId']! as String), richTextDiagnostic.value); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('ext.flutter.inspector creationLocation', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; final Element elementB = find.text('b').evaluate().first; service.disposeAllGroups(); service.resetPubRootDirectories(); service.setSelection(elementA, 'my-group'); final Map<String, Object?> jsonA = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, Object?>; final Map<String, Object?> creationLocationA = jsonA['creationLocation']! as Map<String, Object?>; expect(creationLocationA, isNotNull); final String fileA = creationLocationA['file']! as String; final int lineA = creationLocationA['line']! as int; final int columnA = creationLocationA['column']! as int; service.setSelection(elementB, 'my-group'); final Map<String, Object?> jsonB = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, Object?>; final Map<String, Object?> creationLocationB = jsonB['creationLocation']! as Map<String, Object?>; expect(creationLocationB, isNotNull); final String fileB = creationLocationB['file']! as String; final int lineB = creationLocationB['line']! as int; final int columnB = creationLocationB['column']! as int; expect(fileA, endsWith('widget_inspector_test.dart')); expect(fileA, equals(fileB)); // We don't hardcode the actual lines the widgets are created on as that // would make this test fragile. expect(lineA + 1, equals(lineB)); // Column numbers are more stable than line numbers. expect(columnA, equals(15)); expect(columnA, equals(columnB)); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. group( 'ext.flutter.inspector.addPubRootDirectories group', () { late final String pubRootTest; setUpAll(() async { pubRootTest = generateTestPubRootDirectory(service); }); setUp(() { service.resetPubRootDirectories(); }); testWidgets( 'has createdByLocalProject when the widget is in the pubRootDirectory', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootTest}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'does not have createdByLocalProject if the prefix of the pubRootDirectory is different', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': '/invalid/$pubRootTest'}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'has createdByLocalProject if the pubRootDirectory is prefixed with file://', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': 'file://$pubRootTest'}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'does not have createdByLocalProject if the pubRootDirectory has a different suffix', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': '$pubRootTest/different'}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'has createdByLocalProject if at least one of the pubRootDirectories matches', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': '/unrelated/$pubRootTest', 'arg1': 'file://$pubRootTest', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'widget is part of core framework and is the child of a widget in the package pubRootDirectories', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; // The RichText child of the Text widget is created by the core framework // not the current package. final Element richText = find .descendant( of: find.text('a'), matching: find.byType(RichText), ) .evaluate() .first; service.setSelection(richText, 'my-group'); service.setPubRootDirectories(<String>[pubRootTest]); final Map<String, Object?> jsonObject = json.decode(service.getSelectedWidget(null, 'my-group')) as Map<String, Object?>; expect(jsonObject, isNot(contains('createdByLocalProject'))); final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); // This RichText widget is created by the build method of the Text widget // thus the creation location is in text.dart not basic.dart final List<String> pathSegmentsFramework = Uri.parse(creationLocation['file']! as String).pathSegments; expect( pathSegmentsFramework.join('/'), endsWith('/flutter/lib/src/widgets/text.dart'), ); // Strip off /src/widgets/text.dart. final String pubRootFramework = '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}'; service.resetPubRootDirectories(); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootFramework}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); service.setSelection(elementA, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), isNot(contains('createdByLocalProject')), ); service.resetPubRootDirectories(); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootFramework, 'arg1': pubRootTest}, ); service.setSelection(elementA, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); service.setSelection(richText, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. ); group( 'ext.flutter.inspector.setPubRootDirectories extra args regression test', () { // Ensure that passing the isolate id as an argument won't break // setPubRootDirectories command. late final String pubRootTest; setUpAll(() { pubRootTest = generateTestPubRootDirectory(service); }); setUp(() { service.resetPubRootDirectories(); }); testWidgets( 'has createdByLocalProject when the widget is in the pubRootDirectory', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootTest, 'isolateId': '34'}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'does not have createdByLocalProject if the prefix of the pubRootDirectory is different', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': '/invalid/$pubRootTest', 'isolateId': '34' }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'has createdByLocalProject if the pubRootDirectory is prefixed with file://', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': 'file://$pubRootTest', 'isolateId': '34'}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'does not have createdByLocalProject if the pubRootDirectory has a different suffix', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': '$pubRootTest/different', 'isolateId': '34' }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'has createdByLocalProject if at least one of the pubRootDirectories matches', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ), ); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': '/unrelated/$pubRootTest', 'isolateId': '34', 'arg1': 'file://$pubRootTest', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. ); Map<Object, Object?> removeLastEvent(List<Map<Object, Object?>> events) { final Map<Object, Object?> event = events.removeLast(); // Verify that the event is json encodable. json.encode(event); return event; } group('ext.flutter.inspector createdByLocalProject', () { late final String pubRootTest; setUpAll(() { pubRootTest = generateTestPubRootDirectory(service); }); setUp(() { service.resetPubRootDirectories(); }); testWidgets( 'reacts to add and removing pubRootDirectories', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': pubRootTest, 'arg1': 'file://$pubRootTest', 'arg2': '/unrelated/$pubRootTest', }, ); service.setSelection(elementA, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); await service.testExtension( WidgetInspectorServiceExtensions.removePubRootDirectories.name, <String, String>{ 'arg0': pubRootTest, }, ); service.setSelection(elementA, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'does not match when the package directory does not match', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': '$pubRootTest/different', 'arg1': '/unrelated/$pubRootTest', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0':'file://$pubRootTest'}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'can handle consecutive calls to add', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootTest}, ); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': '/invalid/$pubRootTest'}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'can handle removing an unrelated pubRootDirectory', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': pubRootTest, 'arg1': '/invalid/$pubRootTest', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); service.testExtension( WidgetInspectorServiceExtensions.removePubRootDirectories.name, <String, String>{'arg0': '/invalid/$pubRootTest'}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'can handle parent widget being part of a separate package', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; final Element richText = find .descendant( of: find.text('a'), matching: find.byType(RichText), ) .evaluate() .first; service.setSelection(richText, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': pubRootTest }, ); final Map<String, Object?> jsonObject = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, Object?>; expect(jsonObject, isNot(contains('createdByLocalProject'))); final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); // This RichText widget is created by the build method of the Text widget // thus the creation location is in text.dart not basic.dart final List<String> pathSegmentsFramework = Uri.parse(creationLocation['file']! as String).pathSegments; expect( pathSegmentsFramework.join('/'), endsWith('/flutter/lib/src/widgets/text.dart'), ); // Strip off /src/widgets/text.dart. final String pubRootFramework = '/${pathSegmentsFramework.take(pathSegmentsFramework.length - 3).join('/')}'; service.resetPubRootDirectories(); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootFramework}, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); service.setSelection(elementA, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), isNot(contains('createdByLocalProject')), ); service.resetPubRootDirectories(); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': pubRootFramework, 'arg1': pubRootTest, }, ); service.setSelection(elementA, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); service.setSelection(richText, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ), contains('createdByLocalProject'), ); }, ); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. ); group('ext.flutter.inspector createdByLocalProject extra args regression test', () { late final String pubRootTest; setUpAll(() { pubRootTest = generateTestPubRootDirectory(service); }); setUp(() { service.resetPubRootDirectories(); }); testWidgets( 'reacts to add and removing pubRootDirectories', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': pubRootTest, 'arg1': 'file://$pubRootTest', 'arg2': '/unrelated/$pubRootTest', 'isolateId': '34', }, ); service.setSelection(elementA, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, ), contains('createdByLocalProject'), ); await service.testExtension( WidgetInspectorServiceExtensions.removePubRootDirectories.name, <String, String>{ 'arg0': pubRootTest, 'isolateId': '34', }, ); service.setSelection(elementA, 'my-group'); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, ), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'does not match when the package directory does not match', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': '$pubRootTest/different', 'arg1': '/unrelated/$pubRootTest', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, ), isNot(contains('createdByLocalProject')), ); }, ); testWidgets( 'has createdByLocalProject when the pubRootDirectory is prefixed with file://', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0':'file://$pubRootTest', 'isolateId': '34', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'can handle consecutive calls to add', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': pubRootTest, 'isolateId': '34', }, ); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': '/invalid/$pubRootTest', 'isolateId': '34', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group', 'isolateId': '34',}, ), contains('createdByLocalProject'), ); }, ); testWidgets( 'can handle removing an unrelated pubRootDirectory', (WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ Text('a'), Text('b', textDirection: TextDirection.ltr), Text('c', textDirection: TextDirection.ltr), ], ), ); await tester.pumpWidget(widget); final Element elementA = find.text('a').evaluate().first; service.setSelection(elementA, 'my-group'); service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{ 'arg0': pubRootTest, 'arg1': '/invalid/$pubRootTest', 'isolateId': '34', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{ 'objectGroup': 'my-group', 'isolateId': '34', }, ), contains('createdByLocalProject'), ); service.testExtension( WidgetInspectorServiceExtensions.removePubRootDirectories.name, <String, String>{ 'arg0': '/invalid/$pubRootTest', 'isolateId': '34', }, ); expect( await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{ 'objectGroup': 'my-group', 'isolateId': '34', }, ), contains('createdByLocalProject'), ); }, ); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. ); testWidgets('ext.flutter.inspector.trackRebuildDirtyWidgets with tear-offs', (WidgetTester tester) async { final Widget widget = Directionality( textDirection: TextDirection.ltr, child: WidgetInspector( selectButtonBuilder: null, child: _applyConstructor(_TrivialWidget.new), ), ); expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, <String, String>{'enabled': 'true'}, ), equals('true'), ); await tester.pumpWidget(widget); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked(), // [intended] Test requires --track-widget-creation flag. ); testWidgets('ext.flutter.inspector.trackRebuildDirtyWidgets', (WidgetTester tester) async { service.rebuildCount = 0; await tester.pumpWidget(const ClockDemo()); final Element clockDemoElement = find.byType(ClockDemo).evaluate().first; service.setSelection(clockDemoElement, 'my-group'); final Map<String, Object?> jsonObject = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, Object?>; final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String file = creationLocation['file']! as String; expect(file, endsWith('widget_inspector_test.dart')); final List<String> segments = Uri.parse(file).pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; service.resetPubRootDirectories(); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootTest}, ); final List<Map<Object, Object?>> rebuildEvents = service.dispatchedEvents('Flutter.RebuiltWidgets'); expect(rebuildEvents, isEmpty); expect(service.rebuildCount, equals(0)); expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, <String, String>{'enabled': 'true'}, ), equals('true'), ); expect(service.rebuildCount, equals(1)); await tester.pump(); expect(rebuildEvents.length, equals(1)); Map<Object, Object?> event = removeLastEvent(rebuildEvents); expect(event['startTime'], isA<int>()); List<int> data = event['events']! as List<int>; expect(data.length, equals(14)); final int numDataEntries = data.length ~/ 2; Map<String, List<int>> newLocations = event['newLocations']! as Map<String, List<int>>; expect(newLocations, isNotNull); expect(newLocations.length, equals(1)); expect(newLocations.keys.first, equals(file)); Map<String, Map<String, List<Object?>>> fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>; expect(fileLocationsMap, isNotNull); expect(fileLocationsMap.length, equals(1)); expect(fileLocationsMap.keys.first, equals(file)); final List<int> locationsForFile = newLocations[file]!; expect(locationsForFile.length, equals(21)); final int numLocationEntries = locationsForFile.length ~/ 3; expect(numLocationEntries, equals(numDataEntries)); final Map<String, List<Object?>> locations = fileLocationsMap[file]!; expect(locations.length, equals(4)); expect(locations['ids']!.length, equals(7)); final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{}; _addToKnownLocationsMap( knownLocations: knownLocations, newLocations: fileLocationsMap, ); int totalCount = 0; int maxCount = 0; for (int i = 0; i < data.length; i += 2) { final int id = data[i]; final int count = data[i + 1]; totalCount += count; maxCount = max(maxCount, count); expect(knownLocations, contains(id)); } expect(totalCount, equals(27)); // The creation locations that were rebuilt the most were rebuilt 6 times // as there are 6 instances of the ClockText widget. expect(maxCount, equals(6)); final List<Element> clocks = find.byType(ClockText).evaluate().toList(); expect(clocks.length, equals(6)); // Update a single clock. StatefulElement clockElement = clocks.first as StatefulElement; _ClockTextState state = clockElement.state as _ClockTextState; state.updateTime(); // Triggers a rebuild. await tester.pump(); expect(rebuildEvents.length, equals(1)); event = removeLastEvent(rebuildEvents); expect(event['startTime'], isA<int>()); data = event['events']! as List<int>; // No new locations were rebuilt. expect(event, isNot(contains('newLocations'))); expect(event, isNot(contains('locations'))); // There were two rebuilds: one for the ClockText element itself and one // for its child. expect(data.length, equals(4)); int id = data[0]; int count = data[1]; _CreationLocation location = knownLocations[id]!; expect(location.file, equals(file)); // ClockText widget. expect(location.line, equals(57)); expect(location.column, equals(9)); expect(location.name, equals('ClockText')); expect(count, equals(1)); id = data[2]; count = data[3]; location = knownLocations[id]!; expect(location.file, equals(file)); // Text widget in _ClockTextState build method. expect(location.line, equals(95)); expect(location.column, equals(12)); expect(location.name, equals('Text')); expect(count, equals(1)); // Update 3 of the clocks; for (int i = 0; i < 3; i++) { clockElement = clocks[i] as StatefulElement; state = clockElement.state as _ClockTextState; state.updateTime(); // Triggers a rebuild. } await tester.pump(); expect(rebuildEvents.length, equals(1)); event = removeLastEvent(rebuildEvents); expect(event['startTime'], isA<int>()); data = event['events']! as List<int>; // No new locations were rebuilt. expect(event, isNot(contains('newLocations'))); expect(event, isNot(contains('locations'))); expect(data.length, equals(4)); id = data[0]; count = data[1]; location = knownLocations[id]!; expect(location.file, equals(file)); // ClockText widget. expect(location.line, equals(57)); expect(location.column, equals(9)); expect(location.name, equals('ClockText')); expect(count, equals(3)); // 3 clock widget instances rebuilt. id = data[2]; count = data[3]; location = knownLocations[id]!; expect(location.file, equals(file)); // Text widget in _ClockTextState build method. expect(location.line, equals(95)); expect(location.column, equals(12)); expect(location.name, equals('Text')); expect(count, equals(3)); // 3 clock widget instances rebuilt. // Update one clock 3 times. clockElement = clocks.first as StatefulElement; state = clockElement.state as _ClockTextState; state.updateTime(); // Triggers a rebuild. state.updateTime(); // Triggers a rebuild. state.updateTime(); // Triggers a rebuild. await tester.pump(); expect(rebuildEvents.length, equals(1)); event = removeLastEvent(rebuildEvents); expect(event['startTime'], isA<int>()); data = event['events']! as List<int>; // No new locations were rebuilt. expect(event, isNot(contains('newLocations'))); expect(event, isNot(contains('locations'))); expect(data.length, equals(4)); id = data[0]; count = data[1]; // Even though a rebuild was triggered 3 times, only one rebuild actually // occurred. expect(count, equals(1)); // Trigger a widget creation location that wasn't previously triggered. state.stopClock(); await tester.pump(); expect(rebuildEvents.length, equals(1)); event = removeLastEvent(rebuildEvents); expect(event['startTime'], isA<int>()); data = event['events']! as List<int>; newLocations = event['newLocations']! as Map<String, List<int>>; fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>; expect(data.length, equals(4)); // The second pair in data is the previously unseen rebuild location. id = data[2]; count = data[3]; expect(count, equals(1)); // Verify the rebuild location is new. expect(knownLocations, isNot(contains(id))); _addToKnownLocationsMap( knownLocations: knownLocations, newLocations: fileLocationsMap, ); // Verify the rebuild location was included in the newLocations data. expect(knownLocations, contains(id)); // Turn off rebuild counts. expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.trackRebuildDirtyWidgets.name, <String, String>{'enabled': 'false'}, ), equals('false'), ); state.updateTime(); // Triggers a rebuild. await tester.pump(); // Verify that rebuild events are not fired once the extension is disabled. expect(rebuildEvents, isEmpty); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('ext.flutter.inspector.trackRepaintWidgets', (WidgetTester tester) async { service.rebuildCount = 0; await tester.pumpWidget(const ClockDemo()); final Element clockDemoElement = find.byType(ClockDemo).evaluate().first; service.setSelection(clockDemoElement, 'my-group'); final Map<String, Object?> jsonObject = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, Object?>; final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String file = creationLocation['file']! as String; expect(file, endsWith('widget_inspector_test.dart')); final List<String> segments = Uri.parse(file).pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; service.resetPubRootDirectories(); await service.testExtension( WidgetInspectorServiceExtensions.addPubRootDirectories.name, <String, String>{'arg0': pubRootTest}, ); final List<Map<Object, Object?>> repaintEvents = service.dispatchedEvents('Flutter.RepaintWidgets'); expect(repaintEvents, isEmpty); expect(service.rebuildCount, equals(0)); expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.trackRepaintWidgets.name, <String, String>{'enabled': 'true'}, ), equals('true'), ); // Unlike trackRebuildDirtyWidgets, trackRepaintWidgets doesn't force a full // rebuild. expect(service.rebuildCount, equals(0)); await tester.pump(); expect(repaintEvents.length, equals(1)); Map<Object, Object?> event = removeLastEvent(repaintEvents); expect(event['startTime'], isA<int>()); List<int> data = event['events']! as List<int>; expect(data.length, equals(18)); final int numDataEntries = data.length ~/ 2; final Map<String, List<int>> newLocations = event['newLocations']! as Map<String, List<int>>; expect(newLocations, isNotNull); expect(newLocations.length, equals(1)); expect(newLocations.keys.first, equals(file)); final Map<String, Map<String, List<Object?>>> fileLocationsMap = event['locations']! as Map<String, Map<String, List<Object?>>>; expect(fileLocationsMap, isNotNull); expect(fileLocationsMap.length, equals(1)); expect(fileLocationsMap.keys.first, equals(file)); final List<int> locationsForFile = newLocations[file]!; expect(locationsForFile.length, equals(27)); final int numLocationEntries = locationsForFile.length ~/ 3; expect(numLocationEntries, equals(numDataEntries)); final Map<String, List<Object?>> locations = fileLocationsMap[file]!; expect(locations.length, equals(4)); expect(locations['ids']!.length, equals(9)); final Map<int, _CreationLocation> knownLocations = <int, _CreationLocation>{}; _addToKnownLocationsMap( knownLocations: knownLocations, newLocations: fileLocationsMap, ); int totalCount = 0; int maxCount = 0; for (int i = 0; i < data.length; i += 2) { final int id = data[i]; final int count = data[i + 1]; totalCount += count; maxCount = max(maxCount, count); expect(knownLocations, contains(id)); } expect(totalCount, equals(34)); // The creation locations that were rebuilt the most were rebuilt 6 times // as there are 6 instances of the ClockText widget. expect(maxCount, equals(6)); final List<Element> clocks = find.byType(ClockText).evaluate().toList(); expect(clocks.length, equals(6)); // Update a single clock. final StatefulElement clockElement = clocks.first as StatefulElement; final _ClockTextState state = clockElement.state as _ClockTextState; state.updateTime(); // Triggers a rebuild. await tester.pump(); expect(repaintEvents.length, equals(1)); event = removeLastEvent(repaintEvents); expect(event['startTime'], isA<int>()); data = event['events']! as List<int>; // No new locations were rebuilt. expect(event, isNot(contains('newLocations'))); expect(event, isNot(contains('locations'))); // Triggering a rebuild of one widget in this app causes the whole app // to repaint. expect(data.length, equals(18)); // TODO(jacobr): add an additional repaint test that uses multiple repaint // boundaries to test more complex repaint conditions. // Turn off rebuild counts. expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.trackRepaintWidgets.name, <String, String>{'enabled': 'false'}, ), equals('false'), ); state.updateTime(); // Triggers a rebuild. await tester.pump(); // Verify that repaint events are not fired once the extension is disabled. expect(repaintEvents, isEmpty); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('ext.flutter.inspector.show', (WidgetTester tester) async { final Iterable<Map<Object, Object?>> extensionChangedEvents = service.getServiceExtensionStateChangedEvents('ext.flutter.inspector.show'); Map<Object, Object?> extensionChangedEvent; int debugShowChangeCounter = 0; final GlobalKey key = GlobalKey(); await tester.pumpWidget( WidgetsApp( key: key, builder: (BuildContext context, Widget? child) { return const Placeholder(); }, color: const Color(0xFF123456), ), ); final ValueListenableBuilder<bool> valueListenableBuilderWidget = tester.widget( find.byType(ValueListenableBuilder<bool>), ); void debugShowWidgetInspectorOverrideCallback() { debugShowChangeCounter++; } WidgetsBinding.instance.debugShowWidgetInspectorOverride = false; valueListenableBuilderWidget.valueListenable.addListener(debugShowWidgetInspectorOverrideCallback); service.rebuildCount = 0; expect(extensionChangedEvents, isEmpty); expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.show.name, <String, String>{'enabled': 'true'}, ), equals('true'), ); expect(extensionChangedEvents.length, equals(1)); extensionChangedEvent = extensionChangedEvents.last; expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show')); expect(extensionChangedEvent['value'], isTrue); expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. expect(debugShowChangeCounter, equals(1)); expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.show.name, <String, String>{}, ), equals('true'), ); expect(WidgetsBinding.instance.debugShowWidgetInspectorOverride, isTrue); expect(extensionChangedEvents.length, equals(1)); expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. expect(debugShowChangeCounter, equals(1)); expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.show.name, <String, String>{'enabled': 'true'}, ), equals('true'), ); expect(extensionChangedEvents.length, equals(2)); extensionChangedEvent = extensionChangedEvents.last; expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show')); expect(extensionChangedEvent['value'], isTrue); expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. expect(debugShowChangeCounter, equals(1)); expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.show.name, <String, String>{'enabled': 'false'}, ), equals('false'), ); expect(extensionChangedEvents.length, equals(3)); extensionChangedEvent = extensionChangedEvents.last; expect(extensionChangedEvent['extension'], equals('ext.flutter.inspector.show')); expect(extensionChangedEvent['value'], isFalse); expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. expect(debugShowChangeCounter, equals(2)); expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.show.name, <String, String>{}, ), equals('false'), ); expect(extensionChangedEvents.length, equals(3)); expect(service.rebuildCount, equals(0)); // Should not be force rebuilt. expect(debugShowChangeCounter, equals(2)); expect(WidgetsBinding.instance.debugShowWidgetInspectorOverride, isFalse); }); testWidgets('ext.flutter.inspector.screenshot', (WidgetTester tester) async { final GlobalKey outerContainerKey = GlobalKey(); final GlobalKey paddingKey = GlobalKey(); final GlobalKey redContainerKey = GlobalKey(); final GlobalKey whiteContainerKey = GlobalKey(); final GlobalKey sizedBoxKey = GlobalKey(); // Complex widget tree intended to exercise features such as children // with rotational transforms and clipping without introducing platform // specific behavior as text rendering would. await tester.pumpWidget( Center( child: RepaintBoundaryWithDebugPaint( child: ColoredBox( key: outerContainerKey, color: Colors.white, child: Padding( key: paddingKey, padding: const EdgeInsets.all(100.0), child: SizedBox( key: sizedBoxKey, height: 100.0, width: 100.0, child: Transform.rotate( angle: 1.0, // radians child: ClipRRect( borderRadius: const BorderRadius.only( topLeft: Radius.elliptical(10.0, 20.0), topRight: Radius.elliptical(5.0, 30.0), bottomLeft: Radius.elliptical(2.5, 12.0), bottomRight: Radius.elliptical(15.0, 6.0), ), child: ColoredBox( key: redContainerKey, color: Colors.red, child: ColoredBox( key: whiteContainerKey, color: Colors.white, child: RepaintBoundary( child: Center( child: Container( color: Colors.black, height: 10.0, width: 10.0, ), ), ), ), ), ), ), ), ), ), ), ), ); final Element repaintBoundary = find.byType(RepaintBoundaryWithDebugPaint).evaluate().single; final RenderRepaintBoundary renderObject = repaintBoundary.renderObject! as RenderRepaintBoundary; final OffsetLayer layer = renderObject.debugLayer! as OffsetLayer; final int expectedChildLayerCount = getChildLayerCount(layer); expect(expectedChildLayerCount, equals(2)); final ui.Image image1 = await layer.toImage( renderObject.semanticBounds.inflate(50.0), ); addTearDown(image1.dispose); await expectLater( image1, matchesGoldenFile('inspector.repaint_boundary_margin.png'), ); // Regression test for how rendering with a pixel scale other than 1.0 // was handled. final ui.Image image2 = await layer.toImage( renderObject.semanticBounds.inflate(50.0), pixelRatio: 0.5, ); addTearDown(image2.dispose); await expectLater( image2, matchesGoldenFile('inspector.repaint_boundary_margin_small.png'), ); final ui.Image image3 = await layer.toImage( renderObject.semanticBounds.inflate(50.0), pixelRatio: 2.0, ); addTearDown(image3.dispose); await expectLater( image3, matchesGoldenFile('inspector.repaint_boundary_margin_large.png'), ); final Layer? layerParent = layer.parent; final Layer? firstChild = layer.firstChild; expect(layerParent, isNotNull); expect(firstChild, isNotNull); final ui.Image? screenshot1 = await service.screenshot( repaintBoundary, width: 300.0, height: 300.0, ); addTearDown(() => screenshot1?.dispose()); await expectLater( screenshot1, matchesGoldenFile('inspector.repaint_boundary.png'), ); // Verify that taking a screenshot didn't change the layers associated with // the renderObject. expect(renderObject.debugLayer, equals(layer)); // Verify that taking a screenshot did not change the number of children // of the layer. expect(getChildLayerCount(layer), equals(expectedChildLayerCount)); final ui.Image? screenshot2 = await service.screenshot( repaintBoundary, width: 500.0, height: 500.0, margin: 50.0, ); addTearDown(() => screenshot2?.dispose()); await expectLater( screenshot2, matchesGoldenFile('inspector.repaint_boundary_margin.png'), ); // Verify that taking a screenshot didn't change the layers associated with // the renderObject. expect(renderObject.debugLayer, equals(layer)); // Verify that taking a screenshot did not change the number of children // of the layer. expect(getChildLayerCount(layer), equals(expectedChildLayerCount)); // Make sure taking a screenshot didn't change the parent of the layer. expect(layer.parent, equals(layerParent)); final ui.Image? screenshot3 = await service.screenshot( repaintBoundary, width: 300.0, height: 300.0, debugPaint: true, ); addTearDown(() => screenshot3?.dispose()); await expectLater( screenshot3, matchesGoldenFile('inspector.repaint_boundary_debugPaint.png'), ); // Verify that taking a screenshot with debug paint on did not change // the number of children the layer has. expect(getChildLayerCount(layer), equals(expectedChildLayerCount)); // Ensure that creating screenshots including ones with debug paint // hasn't changed the regular render of the widget. await expectLater( find.byType(RepaintBoundaryWithDebugPaint), matchesGoldenFile('inspector.repaint_boundary.png'), ); expect(renderObject.debugLayer, equals(layer)); expect(layer.attached, isTrue); // Full size image final ui.Image? screenshot4 = await service.screenshot( find.byKey(outerContainerKey).evaluate().single, width: 100.0, height: 100.0, ); addTearDown(() => screenshot4?.dispose()); await expectLater( screenshot4, matchesGoldenFile('inspector.container.png'), ); final ui.Image? screenshot5 = await service.screenshot( find.byKey(outerContainerKey).evaluate().single, width: 100.0, height: 100.0, debugPaint: true, ); addTearDown(() => screenshot5?.dispose()); await expectLater( screenshot5, matchesGoldenFile('inspector.container_debugPaint.png'), ); { // Verify calling the screenshot method still works if the RenderObject // needs to be laid out again. final RenderObject container = find.byKey(outerContainerKey).evaluate().single.renderObject!; container ..markNeedsLayout() ..markNeedsPaint(); expect(container.debugNeedsLayout, isTrue); final ui.Image? screenshot6 = await service.screenshot( find.byKey(outerContainerKey).evaluate().single, width: 100.0, height: 100.0, debugPaint: true, ); addTearDown(() => screenshot6?.dispose()); await expectLater( screenshot6, matchesGoldenFile('inspector.container_debugPaint.png'), ); expect(container.debugNeedsLayout, isFalse); } // Small image final ui.Image? screenshot7 = await service.screenshot( find.byKey(outerContainerKey).evaluate().single, width: 50.0, height: 100.0, ); addTearDown(() => screenshot7?.dispose()); await expectLater( screenshot7, matchesGoldenFile('inspector.container_small.png'), ); final ui.Image? screenshot8 = await service.screenshot( find.byKey(outerContainerKey).evaluate().single, width: 400.0, height: 400.0, maxPixelRatio: 3.0, ); addTearDown(() => screenshot8?.dispose()); await expectLater( screenshot8, matchesGoldenFile('inspector.container_large.png'), ); // This screenshot will show the clip rect debug paint but no other // debug paint. final ui.Image? screenshot9 = await service.screenshot( find.byType(ClipRRect).evaluate().single, width: 100.0, height: 100.0, debugPaint: true, ); addTearDown(() => screenshot9?.dispose()); await expectLater( screenshot9, matchesGoldenFile('inspector.clipRect_debugPaint.png'), ); final Element clipRect = find.byType(ClipRRect).evaluate().single; final ui.Image? clipRectScreenshot = await service.screenshot( clipRect, width: 100.0, height: 100.0, margin: 20.0, debugPaint: true, ); addTearDown(() => clipRectScreenshot?.dispose()); // Add a margin so that the clip icon shows up in the screenshot. // This golden image is platform dependent due to the clip icon. await expectLater( clipRectScreenshot, matchesGoldenFile('inspector.clipRect_debugPaint_margin.png'), ); // Verify we get the same image if we go through the service extension // instead of invoking the screenshot method directly. final Future<Object?> base64ScreenshotFuture = service.testExtension( WidgetInspectorServiceExtensions.screenshot.name, <String, String>{ 'id': service.toId(clipRect, 'group')!, 'width': '100.0', 'height': '100.0', 'margin': '20.0', 'debugPaint': 'true', }, ); final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); final ui.Image screenshotImage = (await binding.runAsync<ui.Image>(() async { final String base64Screenshot = (await base64ScreenshotFuture)! as String; final ui.Codec codec = await ui.instantiateImageCodec(base64.decode(base64Screenshot)); final ui.FrameInfo frame = await codec.getNextFrame(); return frame.image; }))!; addTearDown(screenshotImage.dispose); await expectLater( screenshotImage, matchesReferenceImage(clipRectScreenshot!), ); // Test with a very visible debug paint final ui.Image? screenshot10 = await service.screenshot( find.byKey(paddingKey).evaluate().single, width: 300.0, height: 300.0, debugPaint: true, ); addTearDown(() => screenshot10?.dispose()); await expectLater( screenshot10, matchesGoldenFile('inspector.padding_debugPaint.png'), ); // The bounds for this box crop its rendered content. final ui.Image? screenshot11 = await service.screenshot( find.byKey(sizedBoxKey).evaluate().single, width: 300.0, height: 300.0, debugPaint: true, ); addTearDown(() => screenshot11?.dispose()); await expectLater( screenshot11, matchesGoldenFile('inspector.sizedBox_debugPaint.png'), ); // Verify that setting a margin includes the previously cropped content. final ui.Image? screenshot12 = await service.screenshot( find.byKey(sizedBoxKey).evaluate().single, width: 300.0, height: 300.0, margin: 50.0, debugPaint: true, ); addTearDown(() => screenshot12?.dispose()); await expectLater( screenshot12, matchesGoldenFile('inspector.sizedBox_debugPaint_margin.png'), ); }, skip: impellerEnabled); // TODO(jonahwilliams): https://github.com/flutter/flutter/issues/143616 group('layout explorer', () { const String group = 'test-group'; tearDown(() { service.disposeAllGroups(); }); Future<void> pumpWidgetForLayoutExplorer(WidgetTester tester) async { const Widget widget = Directionality( textDirection: TextDirection.ltr, child: Center( child: Row( children: <Widget>[ Flexible( child: ColoredBox( color: Colors.green, child: Text('a'), ), ), Text('b'), ], ), ), ); await tester.pumpWidget(widget); } testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderBox with BoxParentData',(WidgetTester tester) async { await pumpWidgetForLayoutExplorer(tester); final Element rowElement = tester.element(find.byType(Row)); service.setSelection(rowElement, group); final String id = service.toId(rowElement, group)!; final Map<String, Object?> result = (await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ))! as Map<String, Object?>; expect(result['description'], equals('Row')); final Map<String, Object?>? renderObject = result['renderObject'] as Map<String, Object?>?; expect(renderObject, isNotNull); expect(renderObject!['description'], startsWith('RenderFlex')); final Map<String, Object?>? parentRenderElement = result['parentRenderElement'] as Map<String, Object?>?; expect(parentRenderElement, isNotNull); expect(parentRenderElement!['description'], equals('Center')); final Map<String, Object?>? constraints = result['constraints'] as Map<String, Object?>?; expect(constraints, isNotNull); expect(constraints!['type'], equals('BoxConstraints')); expect(constraints['minWidth'], equals('0.0')); expect(constraints['minHeight'], equals('0.0')); expect(constraints['maxWidth'], equals('800.0')); expect(constraints['maxHeight'], equals('600.0')); expect(result['isBox'], equals(true)); final Map<String, Object?>? size = result['size'] as Map<String, Object?>?; expect(size, isNotNull); expect(size!['width'], equals('800.0')); expect(size['height'], equals('14.0')); expect(result['flexFactor'], isNull); expect(result['flexFit'], isNull); final Map<String, Object?>? parentData = result['parentData'] as Map<String, Object?>?; expect(parentData, isNotNull); expect(parentData!['offsetX'], equals('0.0')); expect(parentData['offsetY'], equals('293.0')); }); testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderBox with FlexParentData',(WidgetTester tester) async { await pumpWidgetForLayoutExplorer(tester); final Element flexibleElement = tester.element(find.byType(Flexible).first); service.setSelection(flexibleElement, group); final String id = service.toId(flexibleElement, group)!; final Map<String, Object?> result = (await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ))! as Map<String, Object?>; expect(result['description'], equals('Flexible')); final Map<String, Object?>? renderObject = result['renderObject'] as Map<String, Object?>?; expect(renderObject, isNotNull); expect(renderObject!['description'], startsWith('_RenderColoredBox')); final Map<String, Object?>? parentRenderElement = result['parentRenderElement'] as Map<String, Object?>?; expect(parentRenderElement, isNotNull); expect(parentRenderElement!['description'], equals('Row')); final Map<String, Object?>? constraints = result['constraints'] as Map<String, Object?>?; expect(constraints, isNotNull); expect(constraints!['type'], equals('BoxConstraints')); expect(constraints['minWidth'], equals('0.0')); expect(constraints['minHeight'], equals('0.0')); expect(constraints['maxWidth'], equals('786.0')); expect(constraints['maxHeight'], equals('600.0')); expect(result['isBox'], equals(true)); final Map<String, Object?>? size = result['size'] as Map<String, Object?>?; expect(size, isNotNull); expect(size!['width'], equals('14.0')); expect(size['height'], equals('14.0')); expect(result['flexFactor'], equals(1)); expect(result['flexFit'], equals('loose')); expect(result['parentData'], isNull); }); testWidgets('ext.flutter.inspector.getLayoutExplorerNode for RenderView',(WidgetTester tester) async { await pumpWidgetForLayoutExplorer(tester); final Element element = tester.element(find.byType(Directionality).first); late Element root; element.visitAncestorElements((Element ancestor) { root = ancestor; return true; }); service.setSelection(root, group); final String id = service.toId(root, group)!; final Map<String, Object?> result = (await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ))! as Map<String, Object?>; expect(result['description'], equals('[root]')); final Map<String, Object?>? renderObject = result['renderObject'] as Map<String, Object?>?; expect(renderObject, isNotNull); expect(renderObject!['description'], contains('RenderView')); expect(result['parentRenderElement'], isNull); final Map<String, Object?>? constraints = result['constraints'] as Map<String, Object?>?; expect(constraints, isNotNull); expect(constraints!['type'], equals('BoxConstraints')); expect(constraints['minWidth'], equals('800.0')); expect(constraints['minHeight'], equals('600.0')); expect(constraints['maxWidth'], equals('800.0')); expect(constraints['maxHeight'], equals('600.0')); expect(result['isBox'], isNull); final Map<String, Object?>? size = result['size'] as Map<String, Object?>?; expect(size, isNotNull); expect(size!['width'], equals('800.0')); expect(size['height'], equals('600.0')); expect(result['flexFactor'], isNull); expect(result['flexFit'], isNull); expect(result['parentData'], isNull); }); testWidgets('ext.flutter.inspector.setFlexFit', (WidgetTester tester) async { await pumpWidgetForLayoutExplorer(tester); final Element childElement = tester.element(find.byType(Flexible).first); service.setSelection(childElement, group); final String id = service.toId(childElement, group)!; Map<String, Object?> result = (await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ))! as Map<String, Object?>; expect(result['description'], equals('Flexible')); expect(result['flexFit'], equals('loose')); final String valueId = result['valueId']! as String; final bool flexFitSuccess = (await service.testExtension( WidgetInspectorServiceExtensions.setFlexFit.name, <String, String>{'id': valueId, 'flexFit': 'FlexFit.tight'}, ))! as bool; expect(flexFitSuccess, isTrue); result = (await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ))! as Map<String, Object?>; expect(result['description'], equals('Flexible')); expect(result['flexFit'], equals('tight')); }); testWidgets('ext.flutter.inspector.setFlexFactor', (WidgetTester tester) async { await pumpWidgetForLayoutExplorer(tester); final Element childElement = tester.element(find.byType(Flexible).first); service.setSelection(childElement, group); final String id = service.toId(childElement, group)!; Map<String, Object?> result = (await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ))! as Map<String, Object?>; expect(result['description'], equals('Flexible')); expect(result['flexFactor'], equals(1)); final String valueId = result['valueId']! as String; final bool flexFactorSuccess = (await service.testExtension( WidgetInspectorServiceExtensions.setFlexFactor.name, <String, String>{'id': valueId, 'flexFactor': '3'}, ))! as bool; expect(flexFactorSuccess, isTrue); result = (await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ))! as Map<String, Object?>; expect(result['description'], equals('Flexible')); expect(result['flexFactor'], equals(3)); }); testWidgets('ext.flutter.inspector.setFlexProperties', (WidgetTester tester) async { await pumpWidgetForLayoutExplorer(tester); final Element rowElement = tester.element(find.byType(Row).first); service.setSelection(rowElement, group); final String id = service.toId(rowElement, group)!; Map<String, Object?> result = (await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ))! as Map<String, Object?>; expect(result['description'], equals('Row')); Map<String, Object?> renderObject = result['renderObject']! as Map<String, Object?>; List<Map<String, Object?>> properties = (renderObject['properties']! as List<dynamic>).cast<Map<String, Object?>>(); Map<String, Object?> mainAxisAlignmentProperties = properties.firstWhere( (Map<String, Object?> p) => p['type'] == 'EnumProperty<MainAxisAlignment>', ); Map<String, Object?> crossAxisAlignmentProperties = properties.firstWhere( (Map<String, Object?> p) => p['type'] == 'EnumProperty<CrossAxisAlignment>', ); String mainAxisAlignment = mainAxisAlignmentProperties['description']! as String; String crossAxisAlignment = crossAxisAlignmentProperties['description']! as String; expect(mainAxisAlignment, equals('start')); expect(crossAxisAlignment, equals('center')); final String valueId = result['valueId']! as String; final bool flexFactorSuccess = (await service.testExtension( WidgetInspectorServiceExtensions.setFlexProperties.name, <String, String>{ 'id': valueId, 'mainAxisAlignment': 'MainAxisAlignment.center', 'crossAxisAlignment': 'CrossAxisAlignment.start', }, ))! as bool; expect(flexFactorSuccess, isTrue); result = (await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ))! as Map<String, Object?>; expect(result['description'], equals('Row')); renderObject = result['renderObject']! as Map<String, Object?>; properties = (renderObject['properties']! as List<dynamic>).cast<Map<String, Object?>>(); mainAxisAlignmentProperties = properties.firstWhere( (Map<String, Object?> p) => p['type'] == 'EnumProperty<MainAxisAlignment>', ); crossAxisAlignmentProperties = properties.firstWhere( (Map<String, Object?> p) => p['type'] == 'EnumProperty<CrossAxisAlignment>', ); mainAxisAlignment = mainAxisAlignmentProperties['description']! as String; crossAxisAlignment = crossAxisAlignmentProperties['description']! as String; expect(mainAxisAlignment, equals('center')); expect(crossAxisAlignment, equals('start')); }); testWidgets('ext.flutter.inspector.getLayoutExplorerNode does not throw StackOverflowError',(WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/115228 const Key leafKey = ValueKey<String>('ColoredBox'); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: Builder( builder: (BuildContext context) => ColoredBox(key: leafKey, color: CupertinoTheme.of(context).primaryColor), ), ), ), ); final Element leaf = tester.element(find.byKey(leafKey)); service.setSelection(leaf, group); final DiagnosticsNode diagnostic = leaf.toDiagnosticsNode(); final String id = service.toId(diagnostic, group)!; Object? error; try { await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ); } catch (e) { error = e; } expect(error, isNull); }); testWidgets( 'ext.flutter.inspector.getLayoutExplorerNode, on a ToolTip, does not throw StackOverflowError', (WidgetTester tester) async { // Regression test for https://github.com/flutter/devtools/issues/5946 const Widget widget = MaterialApp( home: Directionality( textDirection: TextDirection.ltr, child: Center( child: Row( children: <Widget>[ Flexible( child: ColoredBox( color: Colors.green, child: Tooltip( message: 'a', child: ElevatedButton( onPressed: null, child: Text('a'), ), ), ), ), ], ), ), ), ); await tester.pumpWidget(widget); final Element elevatedButton = tester.element(find.byType(ElevatedButton).first); service.setSelection(elevatedButton, group); final String id = service.toId(elevatedButton, group)!; Object? error; try { await service.testExtension( WidgetInspectorServiceExtensions.getLayoutExplorerNode.name, <String, String>{'id': id, 'groupName': group, 'subtreeDepth': '1'}, ); } catch (e) { error = e; } expect(error, isNull); }); }); test('ext.flutter.inspector.structuredErrors', () async { List<Map<Object, Object?>> flutterErrorEvents = service.dispatchedEvents('Flutter.Error'); expect(flutterErrorEvents, isEmpty); final FlutterExceptionHandler oldHandler = FlutterError.presentError; try { // Enable structured errors. expect( await service.testBoolExtension( WidgetInspectorServiceExtensions.structuredErrors.name, <String, String>{'enabled': 'true'}, ), equals('true'), ); // Create an error. FlutterError.reportError(FlutterErrorDetails( library: 'rendering library', context: ErrorDescription('during layout'), exception: StackTrace.current, )); // Validate that we received an error. flutterErrorEvents = service.dispatchedEvents('Flutter.Error'); expect(flutterErrorEvents, hasLength(1)); // Validate the error contents. Map<Object, Object?> error = flutterErrorEvents.first; expect(error['description'], 'Exception caught by rendering library'); expect(error['children'], isEmpty); // Validate that we received an error count. expect(error['errorsSinceReload'], 0); expect( error['renderedErrorText'], startsWith('══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞════════════'), ); // Send a second error. FlutterError.reportError(FlutterErrorDetails( library: 'rendering library', context: ErrorDescription('also during layout'), exception: StackTrace.current, )); // Validate that the error count increased. flutterErrorEvents = service.dispatchedEvents('Flutter.Error'); expect(flutterErrorEvents, hasLength(2)); error = flutterErrorEvents.last; expect(error['errorsSinceReload'], 1); expect(error['renderedErrorText'], startsWith('Another exception was thrown:')); // Reloads the app. final FlutterExceptionHandler? oldHandler = FlutterError.onError; final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); // We need the runTest to setup the fake async in the test binding. await binding.runTest(() async { binding.reassembleApplication(); await binding.pump(); }, () { }); // The run test overrides the flutter error handler, so we should // restore it back for the structure error to continue working. FlutterError.onError = oldHandler; // Cleans up the fake async so it does not bleed into next test. binding.postTest(); // Send another error. FlutterError.reportError(FlutterErrorDetails( library: 'rendering library', context: ErrorDescription('during layout'), exception: StackTrace.current, )); // And, validate that the error count has been reset. flutterErrorEvents = service.dispatchedEvents('Flutter.Error'); expect(flutterErrorEvents, hasLength(3)); error = flutterErrorEvents.last; expect(error['errorsSinceReload'], 0); } finally { FlutterError.presentError = oldHandler; } }); testWidgets('Screenshot of composited transforms - only offsets', (WidgetTester tester) async { // Composited transforms are challenging to take screenshots of as the // LeaderLayer and FollowerLayer classes used by CompositedTransformTarget // and CompositedTransformFollower depend on traversing ancestors of the // layer tree and mutating a [LayerLink] object when attaching layers to // the tree so that the FollowerLayer knows about the LeaderLayer. // 1. Finding the correct position for the follower layers requires // traversing the ancestors of the follow layer to find a common ancestor // with the leader layer. // 2. Creating a LeaderLayer and attaching it to a layer tree has side // effects as the leader layer will attempt to modify the mutable // LeaderLayer object shared by the LeaderLayer and FollowerLayer. // These tests verify that screenshots can still be taken and look correct // when the leader and follower layer are both in the screenshots and when // only the leader or follower layer is in the screenshot. final LayerLink link = LayerLink(); final GlobalKey key = GlobalKey(); final GlobalKey mainStackKey = GlobalKey(); final GlobalKey transformTargetParent = GlobalKey(); final GlobalKey stackWithTransformFollower = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RepaintBoundary( child: Stack( key: mainStackKey, children: <Widget>[ Stack( key: transformTargetParent, children: <Widget>[ Positioned( left: 123.0, top: 456.0, child: CompositedTransformTarget( link: link, child: Container(height: 20.0, width: 20.0, color: const Color.fromARGB(128, 255, 0, 0)), ), ), ], ), Positioned( left: 787.0, top: 343.0, child: Stack( key: stackWithTransformFollower, children: <Widget>[ // Container so we can see how the follower layer was // transformed relative to its initial location. Container(height: 15.0, width: 15.0, color: const Color.fromARGB(128, 0, 0, 255)), CompositedTransformFollower( link: link, child: Container(key: key, height: 10.0, width: 10.0, color: const Color.fromARGB(128, 0, 255, 0)), ), ], ), ), ], ), ), ), ); final RenderBox box = key.currentContext!.findRenderObject()! as RenderBox; expect(box.localToGlobal(Offset.zero), const Offset(123.0, 456.0)); await expectLater( find.byKey(mainStackKey), matchesGoldenFile('inspector.composited_transform.only_offsets.png'), ); final ui.Image? screenshot1 = await WidgetInspectorService.instance.screenshot( find.byKey(stackWithTransformFollower).evaluate().first, width: 5000.0, height: 500.0, ); addTearDown(() => screenshot1?.dispose()); await expectLater( screenshot1, matchesGoldenFile('inspector.composited_transform.only_offsets_follower.png'), ); final ui.Image? screenshot2 = await WidgetInspectorService.instance.screenshot( find.byType(Stack).evaluate().first, width: 300.0, height: 300.0, ); addTearDown(() => screenshot2?.dispose()); await expectLater( screenshot2, matchesGoldenFile('inspector.composited_transform.only_offsets_small.png'), ); final ui.Image? screenshot3 = await WidgetInspectorService.instance.screenshot( find.byKey(transformTargetParent).evaluate().first, width: 500.0, height: 500.0, ); addTearDown(() => screenshot3?.dispose()); await expectLater( screenshot3, matchesGoldenFile('inspector.composited_transform.only_offsets_target.png'), ); }); testWidgets('Screenshot composited transforms - with rotations', (WidgetTester tester) async { final LayerLink link = LayerLink(); final GlobalKey key1 = GlobalKey(); final GlobalKey key2 = GlobalKey(); final GlobalKey rotate1 = GlobalKey(); final GlobalKey rotate2 = GlobalKey(); final GlobalKey mainStackKey = GlobalKey(); final GlobalKey stackWithTransformTarget = GlobalKey(); final GlobalKey stackWithTransformFollower = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Stack( key: mainStackKey, children: <Widget>[ Stack( key: stackWithTransformTarget, children: <Widget>[ Positioned( top: 123.0, left: 456.0, child: Transform.rotate( key: rotate1, angle: 1.0, // radians child: CompositedTransformTarget( link: link, child: Container(key: key1, height: 20.0, width: 20.0, color: const Color.fromARGB(128, 255, 0, 0)), ), ), ), ], ), Positioned( top: 487.0, left: 243.0, child: Stack( key: stackWithTransformFollower, children: <Widget>[ Container(height: 15.0, width: 15.0, color: const Color.fromARGB(128, 0, 0, 255)), Transform.rotate( key: rotate2, angle: -0.3, // radians child: CompositedTransformFollower( link: link, child: Container(key: key2, height: 10.0, width: 10.0, color: const Color.fromARGB(128, 0, 255, 0)), ), ), ], ), ), ], ), ), ); final RenderBox box1 = key1.currentContext!.findRenderObject()! as RenderBox; final RenderBox box2 = key2.currentContext!.findRenderObject()! as RenderBox; // Snapshot the positions of the two relevant boxes to ensure that taking // screenshots doesn't impact their positions. final Offset position1 = box1.localToGlobal(Offset.zero); final Offset position2 = box2.localToGlobal(Offset.zero); expect(position1.dx, moreOrLessEquals(position2.dx)); expect(position1.dy, moreOrLessEquals(position2.dy)); // Image of the full scene to use as reference to help validate that the // screenshots of specific subtrees are reasonable. await expectLater( find.byKey(mainStackKey), matchesGoldenFile('inspector.composited_transform.with_rotations.png'), ); final ui.Image? screenshot1 = await WidgetInspectorService.instance.screenshot( find.byKey(mainStackKey).evaluate().first, width: 500.0, height: 500.0, ); addTearDown(() => screenshot1?.dispose()); await expectLater( screenshot1, matchesGoldenFile('inspector.composited_transform.with_rotations_small.png'), ); final ui.Image? screenshot2 = await WidgetInspectorService.instance.screenshot( find.byKey(stackWithTransformTarget).evaluate().first, width: 500.0, height: 500.0, ); addTearDown(() => screenshot2?.dispose()); await expectLater( screenshot2, matchesGoldenFile('inspector.composited_transform.with_rotations_target.png'), ); final ui.Image? screenshot3 = await WidgetInspectorService.instance.screenshot( find.byKey(stackWithTransformFollower).evaluate().first, width: 500.0, height: 500.0, ); addTearDown(() => screenshot3?.dispose()); await expectLater( screenshot3, matchesGoldenFile('inspector.composited_transform.with_rotations_follower.png'), ); // Make sure taking screenshots hasn't modified the positions of the // TransformTarget or TransformFollower layers. expect(identical(key1.currentContext!.findRenderObject(), box1), isTrue); expect(identical(key2.currentContext!.findRenderObject(), box2), isTrue); expect(box1.localToGlobal(Offset.zero), equals(position1)); expect(box2.localToGlobal(Offset.zero), equals(position2)); }); testWidgets('getChildrenDetailsSubtree', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( title: 'Hello, World', theme: ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( appBar: AppBar( title: const Text('Hello, World'), ), body: const Center( child: Text('Hello, World!'), ), ), ), ); service.setSelection(find.text('Hello, World!').evaluate().first, 'my-group'); // Figure out the pubRootDirectory final Map<String, Object?> jsonObject = (await service.testExtension( WidgetInspectorServiceExtensions.getSelectedWidget.name, <String, String>{'objectGroup': 'my-group'}, ))! as Map<String, Object?>; final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String file = creationLocation['file']! as String; expect(file, endsWith('widget_inspector_test.dart')); final List<String> segments = Uri.parse(file).pathSegments; // Strip a couple subdirectories away to generate a plausible pub rootdirectory. final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; service.resetPubRootDirectories(); service.addPubRootDirectories(<String>[pubRootTest]); final String summary = service.getRootWidgetSummaryTree('foo1'); // ignore: avoid_dynamic_calls final List<Object?> childrenOfRoot = json.decode(summary)['children'] as List<Object?>; final List<Object?> childrenOfMaterialApp = (childrenOfRoot.first! as Map<String, Object?>)['children']! as List<Object?>; final Map<String, Object?> scaffold = childrenOfMaterialApp.first! as Map<String, Object?>; expect(scaffold['description'], 'Scaffold'); final String objectId = scaffold['valueId']! as String; final String details = service.getDetailsSubtree(objectId, 'foo2'); // ignore: avoid_dynamic_calls final List<Object?> detailedChildren = json.decode(details)['children'] as List<Object?>; final List<Map<String, Object?>> appBars = <Map<String, Object?>>[]; void visitChildren(List<Object?> children) { for (final Map<String, Object?> child in children.cast<Map<String, Object?>>()) { if (child['description'] == 'AppBar') { appBars.add(child); } if (child.containsKey('children')) { visitChildren(child['children']! as List<Object?>); } } } visitChildren(detailedChildren); expect(appBars.single, isNot(contains('children'))); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('InspectorSerializationDelegate addAdditionalPropertiesCallback', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( title: 'Hello World!', home: Scaffold( appBar: AppBar( title: const Text('Hello World!'), ), body: const Center( child: Column( children: <Widget>[ Text('Hello World!'), ], ), ), ), ), ); final Finder columnWidgetFinder = find.byType(Column); expect(columnWidgetFinder, findsOneWidget); final Element columnWidgetElement = columnWidgetFinder .evaluate() .first; final DiagnosticsNode node = columnWidgetElement.toDiagnosticsNode(); final InspectorSerializationDelegate delegate = InspectorSerializationDelegate( service: service, includeProperties: true, addAdditionalPropertiesCallback: (DiagnosticsNode node, InspectorSerializationDelegate delegate) { final Map<String, Object> additionalJson = <String, Object>{}; final Object? value = node.value; if (value is Element) { final RenderObject? renderObject = value.renderObject; if (renderObject != null) { additionalJson['renderObject'] = renderObject.toDiagnosticsNode().toJsonMap( delegate.copyWith(subtreeDepth: 0), ); } } additionalJson['callbackExecuted'] = true; return additionalJson; }, ); final Map<String, Object?> json = node.toJsonMap(delegate); expect(json['callbackExecuted'], true); expect(json.containsKey('renderObject'), true); expect(json['renderObject'], isA<Map<String, Object?>>()); final Map<String, Object?> renderObjectJson = json['renderObject']! as Map<String, Object?>; expect(renderObjectJson['description'], startsWith('RenderFlex')); final InspectorSerializationDelegate emptyDelegate = InspectorSerializationDelegate( service: service, includeProperties: true, addAdditionalPropertiesCallback: (DiagnosticsNode node, InspectorSerializationDelegate delegate) { return null; }, ); final InspectorSerializationDelegate defaultDelegate = InspectorSerializationDelegate( service: service, includeProperties: true, ); expect(node.toJsonMap(emptyDelegate), node.toJsonMap(defaultDelegate)); }); testWidgets('debugIsLocalCreationLocation test', (WidgetTester tester) async { setupDefaultPubRootDirectory(service); final GlobalKey key = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Container( padding: const EdgeInsets.all(8), child: Text('target', key: key, textDirection: TextDirection.ltr), ), ), ); final Element element = key.currentContext! as Element; expect(debugIsLocalCreationLocation(element), isTrue); expect(debugIsLocalCreationLocation(element.widget), isTrue); // Padding is inside container final Finder paddingFinder = find.byType(Padding); final Element paddingElement = paddingFinder.evaluate().first; expect(debugIsLocalCreationLocation(paddingElement), isFalse); expect(debugIsLocalCreationLocation(paddingElement.widget), isFalse); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('debugIsWidgetLocalCreation test', (WidgetTester tester) async { setupDefaultPubRootDirectory(service); final GlobalKey key = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Container( padding: const EdgeInsets.all(8), child: Text('target', key: key, textDirection: TextDirection.ltr), ), ), ); final Element element = key.currentContext! as Element; expect(debugIsWidgetLocalCreation(element.widget), isTrue); final Finder paddingFinder = find.byType(Padding); final Element paddingElement = paddingFinder.evaluate().first; expect(debugIsWidgetLocalCreation(paddingElement.widget), isFalse); }, skip: !WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --track-widget-creation flag. testWidgets('debugIsWidgetLocalCreation false test', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Container( padding: const EdgeInsets.all(8), child: Text('target', key: key, textDirection: TextDirection.ltr), ), ), ); final Element element = key.currentContext! as Element; expect(debugIsWidgetLocalCreation(element.widget), isFalse); }, skip: WidgetInspectorService.instance.isWidgetCreationTracked()); // [intended] Test requires --no-track-widget-creation flag. test('devToolsInspectorUri test', () { activeDevToolsServerAddress = 'http://127.0.0.1:9100'; connectedVmServiceUri = 'http://127.0.0.1:55269/798ay5al_FM=/'; expect( WidgetInspectorService.instance.devToolsInspectorUri('inspector-0'), equals('http://127.0.0.1:9100/#/inspector?uri=http%3A%2F%2F127.0.0.1%3A55269%2F798ay5al_FM%3D%2F&inspectorRef=inspector-0'), ); }); test('DevToolsDeepLinkProperty test', () { final DevToolsDeepLinkProperty node = DevToolsDeepLinkProperty( 'description of the deep link', 'http://the-deeplink/', ); expect(node.toString(), equals('description of the deep link')); expect(node.name, isEmpty); expect(node.value, equals('http://the-deeplink/')); expect( node.toJsonMap(const DiagnosticsSerializationDelegate()), equals(<String, dynamic>{ 'description': 'description of the deep link', 'type': 'DevToolsDeepLinkProperty', 'name': '', 'style': 'singleLine', 'allowNameWrap': true, 'missingIfNull': false, 'propertyType': 'String', 'defaultLevel': 'info', 'value': 'http://the-deeplink/', }), ); }); } static String generateTestPubRootDirectory(TestWidgetInspectorService service) { final Map<String, Object?> jsonObject = const SizedBox().toDiagnosticsNode().toJsonMap(InspectorSerializationDelegate(service: service)); final Map<String, Object?> creationLocation = jsonObject['creationLocation']! as Map<String, Object?>; expect(creationLocation, isNotNull); final String file = creationLocation['file']! as String; expect(file, endsWith('widget_inspector_test.dart')); final List<String> segments = Uri .parse(file) .pathSegments; // Strip a couple subdirectories away to generate a plausible pub root // directory. final String pubRootTest = '/${segments.take(segments.length - 2).join('/')}'; return pubRootTest; } static void setupDefaultPubRootDirectory(TestWidgetInspectorService service) { service.resetPubRootDirectories(); service .addPubRootDirectories(<String>[generateTestPubRootDirectory(service)]); } } void _addToKnownLocationsMap({ required Map<int, _CreationLocation> knownLocations, required Map<String, Map<String, List<Object?>>> newLocations, }) { newLocations.forEach((String file, Map<String, List<Object?>> entries) { final List<int> ids = entries['ids']!.cast<int>(); final List<int> lines = entries['lines']!.cast<int>(); final List<int> columns = entries['columns']!.cast<int>(); final List<String> names = entries['names']!.cast<String>(); for (int i = 0; i < ids.length; i++) { final int id = ids[i]; knownLocations[id] = _CreationLocation( id: id, file: file, line: lines[i], column: columns[i], name: names[i], ); } }); } extension WidgetInspectorServiceExtension on WidgetInspectorService { Future<List<String>> get currentPubRootDirectories async { return ((await pubRootDirectories( <String, String>{}, ))['result'] as List<Object?>).cast<String>(); } }
flutter/packages/flutter/test/widgets/widget_inspector_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/widget_inspector_test.dart", "repo_id": "flutter", "token_count": 94913 }
760
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { // Changes made in https://github.com/flutter/flutter/pull/86198 AppBar appBar = AppBar(); appBar = AppBar(systemOverlayStyle: SystemUiOverlayStyle.dark); appBar = AppBar(systemOverlayStyle: SystemUiOverlayStyle.light); appBar = AppBar(error: ''); appBar.systemOverlayStyle; TextTheme myTextTheme = TextTheme(); AppBar appBar = AppBar(); appBar = AppBar(toolbarTextStyle: myTextTheme.bodyMedium, titleTextStyle: myTextTheme.titleLarge); appBar = AppBar(toolbarTextStyle: myTextTheme.bodyMedium, titleTextStyle: myTextTheme.titleLarge); AppBar appBar = AppBar(); appBar = AppBar(); appBar = AppBar()); appBar.backwardsCompatibility; // Removing field reference not supported. }
flutter/packages/flutter/test_fixes/material/app_bar.dart.expect/0
{ "file_path": "flutter/packages/flutter/test_fixes/material/app_bar.dart.expect", "repo_id": "flutter", "token_count": 301 }
761
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; void main() { // Changes made in https://github.com/flutter/flutter/pull/142151 WidgetState selected = WidgetState.selected; WidgetState hovered = WidgetState.hovered; WidgetState focused = WidgetState.focused; WidgetState pressed = WidgetState.pressed; WidgetState dragged = WidgetState.dragged; WidgetState scrolledUnder = WidgetState.scrolledUnder; WidgetState disabled = WidgetState.disabled; WidgetState error = WidgetState.error; final WidgetPropertyResolver<MouseCursor?> resolveCallback; Color getColor(Set<WidgetState> states) { if (states.contains(WidgetState.disabled)) { if (states.contains(WidgetState.selected)) { return Color(0xFF000002); } return Color(0xFF000004); } if (states.contains(WidgetState.selected)) { return Color(0xFF000001); } return Color(0xFF000003); } final WidgetStateProperty<Color> backgroundColor = WidgetStateColor.resolveWith(getColor); class _MouseCursor extends WidgetStateMouseCursor { const _MouseCursor(this.resolveCallback); final WidgetPropertyResolver<MouseCursor?> resolveCallback; @override MouseCursor resolve(Set<WidgetState> states) => resolveCallback(states) ?? MouseCursor.uncontrolled; } WidgetStateBorderSide? get side { return WidgetStateBorderSide.resolveWith((Set<WidgetState> states) { if (states.contains(WidgetState.disabled)) { if (states.contains(WidgetState.selected)) { return const BorderSide(width: 2.0); } return BorderSide(width: 1.0); } if (states.contains(WidgetState.selected)) { return const BorderSide(width: 1.5); } return BorderSide(width: 0.5); }); } class SelectedBorder extends RoundedRectangleBorder implements WidgetStateOutlinedBorder { const SelectedBorder(); @override OutlinedBorder? resolve(Set<WidgetState> states) { if (states.contains(WidgetState.selected)) { return const RoundedRectangleBorder(); } return null; } } TextStyle floatingLabelStyle = WidgetStateTextStyle.resolveWith( (Set<WidgetState> states) { final Color color = states.contains(WidgetState.error) ? Theme.of(context).colorScheme.error : Colors.orange; return TextStyle(color: color, letterSpacing: 1.3); }, ); final WidgetStateProperty<Icon?> thumbIcon = WidgetStateProperty.resolveWith<Icon?>((Set<WidgetState> states) { if (states.contains(WidgetState.selected)) { return const Icon(Icons.check); } return const Icon(Icons.close); }); final Color backgroundColor = WidgetStatePropertyAll<Color>( Colors.blue.withOpacity(0.12), ); final WidgetStatesController statesController = WidgetStatesController(<WidgetState>{if (widget.selected) WidgetState.selected}); class _MyWidget extends StatefulWidget { const _MyWidget({ required this.controller, required this.evaluator, required this.materialState, }); final bool Function(_MyWidgetState state) evaluator; /// Stream passed down to the child [_InnerWidget] to begin the process. /// This plays the role of an actual user interaction in the wild, but allows /// us to engage the system without mocking pointers/hovers etc. final StreamController<bool> controller; /// The value we're watching in the given test. final WidgetState materialState; @override State createState() => _MyWidgetState(); } }
flutter/packages/flutter/test_fixes/material/widget_state.dart.expect/0
{ "file_path": "flutter/packages/flutter/test_fixes/material/widget_state.dart.expect", "repo_id": "flutter", "token_count": 1258 }
762
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'enum_util.dart'; import 'find.dart'; import 'message.dart'; /// [DiagnosticsNode] tree types that can be requested by [GetDiagnosticsTree]. enum DiagnosticsType { /// The [DiagnosticsNode] tree formed by [RenderObject]s. renderObject, /// The [DiagnosticsNode] tree formed by [Widget]s. widget, } EnumIndex<DiagnosticsType> _diagnosticsTypeIndex = EnumIndex<DiagnosticsType>(DiagnosticsType.values); /// A Flutter Driver command to retrieve the JSON-serialized [DiagnosticsNode] /// tree of the object identified by [finder]. /// /// The [DiagnosticsType] of the [DiagnosticsNode] tree returned is specified by /// [diagnosticsType]. class GetDiagnosticsTree extends CommandWithTarget { /// Creates a [GetDiagnosticsTree] Flutter Driver command. GetDiagnosticsTree(super.finder, this.diagnosticsType, { this.subtreeDepth = 0, this.includeProperties = true, super.timeout, }); /// Deserializes this command from the value generated by [serialize]. GetDiagnosticsTree.deserialize(super.json, super.finderFactory) : subtreeDepth = int.parse(json['subtreeDepth']!), includeProperties = json['includeProperties'] == 'true', diagnosticsType = _diagnosticsTypeIndex.lookupBySimpleName(json['diagnosticsType']!), super.deserialize(); /// How many levels of children to include in the JSON result. /// /// Defaults to zero, which will only return the [DiagnosticsNode] information /// of the object identified by [finder]. final int subtreeDepth; /// Whether the properties of a [DiagnosticsNode] should be included. final bool includeProperties; /// The type of [DiagnosticsNode] tree that is requested. final DiagnosticsType diagnosticsType; @override Map<String, String> serialize() => super.serialize()..addAll(<String, String>{ 'subtreeDepth': subtreeDepth.toString(), 'includeProperties': includeProperties.toString(), 'diagnosticsType': _diagnosticsTypeIndex.toSimpleName(diagnosticsType), }); @override String get kind => 'get_diagnostics_tree'; } /// The result of a [GetDiagnosticsTree] command. class DiagnosticsTreeResult extends Result { /// Creates a [DiagnosticsTreeResult]. const DiagnosticsTreeResult(this.json); /// The JSON encoded [DiagnosticsNode] tree requested by the /// [GetDiagnosticsTree] command. final Map<String, dynamic> json; @override Map<String, dynamic> toJson() => json; }
flutter/packages/flutter_driver/lib/src/common/diagnostics_tree.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/common/diagnostics_tree.dart", "repo_id": "flutter", "token_count": 784 }
763
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'enum_util.dart'; import 'message.dart'; EnumIndex<TextInputAction> _textInputActionIndex = EnumIndex<TextInputAction>(TextInputAction.values); /// A Flutter Driver command that send a text input action. class SendTextInputAction extends Command { /// Creates a command that enters text into the currently focused widget. const SendTextInputAction(this.textInputAction, {super.timeout}); /// Deserializes this command from the value generated by [serialize]. SendTextInputAction.deserialize(super.json) : textInputAction = _textInputActionIndex.lookupBySimpleName(json['action']!), super.deserialize(); /// The [TextInputAction] final TextInputAction textInputAction; @override String get kind => 'send_text_input_action'; @override Map<String, String> serialize() => super.serialize() ..addAll(<String, String>{ 'action': _textInputActionIndex.toSimpleName(textInputAction), }); } /// An action the user has requested the text input control to perform. /// // This class is identical to [TextInputAction](https://api.flutter.dev/flutter/services/TextInputAction.html). // This class is cloned from `TextInputAction` and must be kept in sync. The cloning is needed // because importing is not allowed directly. enum TextInputAction { /// Logical meaning: There is no relevant input action for the current input /// source, e.g., [TextField]. /// /// Android: Corresponds to Android's "IME_ACTION_NONE". The keyboard setup /// is decided by the OS. The keyboard will likely show a return key. /// /// iOS: iOS does not have a keyboard return type of "none." It is /// inappropriate to choose this [TextInputAction] when running on iOS. none, /// Logical meaning: Let the OS decide which action is most appropriate. /// /// Android: Corresponds to Android's "IME_ACTION_UNSPECIFIED". The OS chooses /// which keyboard action to display. The decision will likely be a done /// button or a return key. /// /// iOS: Corresponds to iOS's "UIReturnKeyDefault". The title displayed in /// the action button is "return". unspecified, /// Logical meaning: The user is done providing input to a group of inputs /// (like a form). Some kind of finalization behavior should now take place. /// /// Android: Corresponds to Android's "IME_ACTION_DONE". The OS displays a /// button that represents completion, e.g., a checkmark button. /// /// iOS: Corresponds to iOS's "UIReturnKeyDone". The title displayed in the /// action button is "Done". done, /// Logical meaning: The user has entered some text that represents a /// destination, e.g., a restaurant name. The "go" button is intended to take /// the user to a part of the app that corresponds to this destination. /// /// Android: Corresponds to Android's "IME_ACTION_GO". The OS displays a /// button that represents taking "the user to the target of the text they /// typed", e.g., a right-facing arrow button. /// /// iOS: Corresponds to iOS's "UIReturnKeyGo". The title displayed in the /// action button is "Go". go, /// Logical meaning: Execute a search query. /// /// Android: Corresponds to Android's "IME_ACTION_SEARCH". The OS displays a /// button that represents a search, e.g., a magnifying glass button. /// /// iOS: Corresponds to iOS's "UIReturnKeySearch". The title displayed in the /// action button is "Search". search, /// Logical meaning: Sends something that the user has composed, e.g., an /// email or a text message. /// /// Android: Corresponds to Android's "IME_ACTION_SEND". The OS displays a /// button that represents sending something, e.g., a paper plane button. /// /// iOS: Corresponds to iOS's "UIReturnKeySend". The title displayed in the /// action button is "Send". send, /// Logical meaning: The user is done with the current input source and wants /// to move to the next one. /// /// Moves the focus to the next focusable item in the same [FocusScope]. /// /// Android: Corresponds to Android's "IME_ACTION_NEXT". The OS displays a /// button that represents moving forward, e.g., a right-facing arrow button. /// /// iOS: Corresponds to iOS's "UIReturnKeyNext". The title displayed in the /// action button is "Next". next, /// Logical meaning: The user wishes to return to the previous input source /// in the group, e.g., a form with multiple [TextField]s. /// /// Moves the focus to the previous focusable item in the same [FocusScope]. /// /// Android: Corresponds to Android's "IME_ACTION_PREVIOUS". The OS displays a /// button that represents moving backward, e.g., a left-facing arrow button. /// /// iOS: iOS does not have a keyboard return type of "previous." It is /// inappropriate to choose this [TextInputAction] when running on iOS. previous, /// Logical meaning: In iOS apps, it is common for a "Back" button and /// "Continue" button to appear at the top of the screen. However, when the /// keyboard is open, these buttons are often hidden off-screen. Therefore, /// the purpose of the "Continue" return key on iOS is to make the "Continue" /// button available when the user is entering text. /// /// Historical context aside, [TextInputAction.continueAction] can be used any /// time that the term "Continue" seems most appropriate for the given action. /// /// Android: Android does not have an IME input type of "continue." It is /// inappropriate to choose this [TextInputAction] when running on Android. /// /// iOS: Corresponds to iOS's "UIReturnKeyContinue". The title displayed in the /// action button is "Continue". This action is only available on iOS 9.0+. /// /// The reason that this value has "Action" post-fixed to it is because /// "continue" is a reserved word in Dart, as well as many other languages. continueAction, /// Logical meaning: The user wants to join something, e.g., a wireless /// network. /// /// Android: Android does not have an IME input type of "join." It is /// inappropriate to choose this [TextInputAction] when running on Android. /// /// iOS: Corresponds to iOS's "UIReturnKeyJoin". The title displayed in the /// action button is "Join". join, /// Logical meaning: The user wants routing options, e.g., driving directions. /// /// Android: Android does not have an IME input type of "route." It is /// inappropriate to choose this [TextInputAction] when running on Android. /// /// iOS: Corresponds to iOS's "UIReturnKeyRoute". The title displayed in the /// action button is "Route". route, /// Logical meaning: Initiate a call to emergency services. /// /// Android: Android does not have an IME input type of "emergencyCall." It is /// inappropriate to choose this [TextInputAction] when running on Android. /// /// iOS: Corresponds to iOS's "UIReturnKeyEmergencyCall". The title displayed /// in the action button is "Emergency Call". emergencyCall, /// Logical meaning: Insert a newline character in the focused text input, /// e.g., [TextField]. /// /// Android: Corresponds to Android's "IME_ACTION_NONE". The OS displays a /// button that represents a new line, e.g., a carriage return button. /// /// iOS: Corresponds to iOS's "UIReturnKeyDefault". The title displayed in the /// action button is "return". /// /// The term [TextInputAction.newline] exists in Flutter but not in Android /// or iOS. The reason for introducing this term is so that developers can /// achieve the common result of inserting new lines without needing to /// understand the various IME actions on Android and return keys on iOS. /// Thus, [TextInputAction.newline] is a convenience term that alleviates the /// need to understand the underlying platforms to achieve this common behavior. newline, }
flutter/packages/flutter_driver/lib/src/common/text_input_action.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/common/text_input_action.dart", "repo_id": "flutter", "token_count": 2205 }
764
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'percentile_utils.dart'; import 'timeline.dart'; const String _kPlatformVsyncEvent = 'VSYNC'; const String _kUIThreadVsyncProcessEvent = 'VsyncProcessCallback'; /// Event names for frame lag related timeline events. const Set<String> kVsyncTimelineEventNames = <String>{ _kUIThreadVsyncProcessEvent, _kPlatformVsyncEvent, }; /// Summarizes [TimelineEvents]s corresponding to [kVsyncTimelineEventNames] events. /// /// `VsyncFrameLag` is the time between when a platform vsync event is received to /// when the frame starts getting processed by the Flutter Engine. This delay is /// typically seen due to non-frame workload related dart tasks being scheduled /// on the UI thread. class VsyncFrameLagSummarizer { /// Creates a VsyncFrameLagSummarizer given the timeline events. VsyncFrameLagSummarizer(this.vsyncEvents); /// Timeline events with names in [kVsyncTimelineEventNames]. final List<TimelineEvent> vsyncEvents; /// Computes the average `VsyncFrameLag` over the period of the timeline. double computeAverageVsyncFrameLag() { final List<double> vsyncFrameLags = _computePlatformToFlutterVsyncBeginLags(); if (vsyncFrameLags.isEmpty) { return 0; } final double total = vsyncFrameLags.reduce((double a, double b) => a + b); return total / vsyncFrameLags.length; } /// Computes the [percentile]-th percentile `VsyncFrameLag` over the /// period of the timeline. double computePercentileVsyncFrameLag(double percentile) { final List<double> vsyncFrameLags = _computePlatformToFlutterVsyncBeginLags(); if (vsyncFrameLags.isEmpty) { return 0; } return findPercentile(vsyncFrameLags, percentile); } List<double> _computePlatformToFlutterVsyncBeginLags() { int platformIdx = -1; final List<double> result = <double>[]; for (int i = 0; i < vsyncEvents.length; i++) { final TimelineEvent event = vsyncEvents[i]; if (event.phase != 'B') { continue; } if (event.name == _kPlatformVsyncEvent) { // There was a vsync that resulted in a frame not being built. // This needs to be penalized. if (platformIdx != -1) { final int prevTS = vsyncEvents[platformIdx].timestampMicros!; result.add((event.timestampMicros! - prevTS).toDouble()); } platformIdx = i; } else if (platformIdx != -1) { final int platformTS = vsyncEvents[platformIdx].timestampMicros!; result.add((event.timestampMicros! - platformTS).toDouble()); platformIdx = -1; } } return result; } }
flutter/packages/flutter_driver/lib/src/driver/vsync_frame_lag_summarizer.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/driver/vsync_frame_lag_summarizer.dart", "repo_id": "flutter", "token_count": 975 }
765
// Copyright 2014 The Flutter Authors. 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/driver_extension.dart'; import 'package:flutter_driver/flutter_driver.dart'; import 'package:flutter_test/flutter_test.dart'; import 'stub_command.dart'; class StubNestedCommandExtension extends CommandExtension { @override String get commandKind => 'StubNestedCommand'; @override Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async { final StubNestedCommand stubCommand = command as StubNestedCommand; handlerFactory.waitForElement(finderFactory.createFinder(stubCommand.finder)); for (int index = 0; index < stubCommand.times; index++) { await handlerFactory.handleCommand(Tap(stubCommand.finder), prober, finderFactory); } return const StubCommandResult('stub response'); } @override Command deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory, DeserializeCommandFactory commandFactory) { return StubNestedCommand.deserialize(params, finderFactory); } } class StubProberCommandExtension extends CommandExtension { @override String get commandKind => 'StubProberCommand'; @override Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async { final StubProberCommand stubCommand = command as StubProberCommand; final Finder finder = finderFactory.createFinder(stubCommand.finder); handlerFactory.waitForElement(finder); for (int index = 0; index < stubCommand.times; index++) { await prober.tap(finder); } return const StubCommandResult('stub response'); } @override Command deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory, DeserializeCommandFactory commandFactory) { return StubProberCommand.deserialize(params, finderFactory); } }
flutter/packages/flutter_driver/test/src/real_tests/stubs/stub_command_extension.dart/0
{ "file_path": "flutter/packages/flutter_driver/test/src/real_tests/stubs/stub_command_extension.dart", "repo_id": "flutter", "token_count": 604 }
766
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter_driver/flutter_driver.dart'; void main() async { // Changes made in https://github.com/flutter/flutter/pull/82939 final FlutterDriver driver = FlutterDriver(); await driver.enableAccessibility(); // Changes made in https://github.com/flutter/flutter/pull/79310 final Timeline timeline = Timeline.fromJson({}); TimelineSummary.summarize(timeline).writeSummaryToFile('traceName'); TimelineSummary.summarize(timeline).writeSummaryToFile( 'traceName', destinationDirectory: 'destination', pretty: false, ); }
flutter/packages/flutter_driver/test_fixes/flutter_driver/flutter_driver.dart/0
{ "file_path": "flutter/packages/flutter_driver/test_fixes/flutter_driver/flutter_driver.dart", "repo_id": "flutter", "token_count": 215 }
767
{ "datePickerHourSemanticsLabelOne": "$hour বাজিছে", "datePickerHourSemanticsLabelOther": "$hour বাজিছে", "datePickerMinuteSemanticsLabelOne": "১মিনিট", "datePickerMinuteSemanticsLabelOther": "$minuteমিনিট", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "পূৰ্বাহ্ন", "postMeridiemAbbreviation": "অপৰাহ্ন", "todayLabel": "আজি", "alertDialogLabel": "সতৰ্কবাৰ্তা", "timerPickerHourLabelOne": "ঘণ্টা", "timerPickerHourLabelOther": "ঘণ্টা", "timerPickerMinuteLabelOne": "মিনিট।", "timerPickerMinuteLabelOther": "মিনিট।", "timerPickerSecondLabelOne": "ছেকেণ্ড।", "timerPickerSecondLabelOther": "ছেকেণ্ড।", "cutButtonLabel": "কাট কৰক", "copyButtonLabel": "প্ৰতিলিপি কৰক", "pasteButtonLabel": "পে'ষ্ট কৰক", "clearButtonLabel": "Clear", "selectAllButtonLabel": "সকলো বাছনি কৰক", "tabSemanticsLabel": "$tabCount টা টেবৰ $tabIndex নম্বৰটো", "modalBarrierDismissLabel": "অগ্ৰাহ্য কৰক", "searchTextFieldPlaceholderLabel": "সন্ধান কৰক", "noSpellCheckReplacementsLabel": "এইটোৰ সলনি ব্যৱহাৰ কৰিব পৰা শব্দ পোৱা নগ’ল", "menuDismissLabel": "অগ্ৰাহ্য কৰাৰ মেনু", "lookUpButtonLabel": "ওপৰলৈ চাওক", "searchWebButtonLabel": "ৱেবত সন্ধান কৰক", "shareButtonLabel": "শ্বেয়াৰ কৰক…" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_as.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_as.arb", "repo_id": "flutter", "token_count": 939 }
768
{ "timerPickerSecondLabelOne": "s", "datePickerHourSemanticsLabelOne": "$hour heure", "datePickerHourSemanticsLabelOther": "$hour heures", "datePickerMinuteSemanticsLabelOne": "1 minute", "datePickerMinuteSemanticsLabelOther": "$minute minutes", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "aujourd'hui", "alertDialogLabel": "Alerte", "timerPickerHourLabelOne": "heure", "timerPickerHourLabelOther": "heures", "timerPickerMinuteLabelOne": "minute", "timerPickerMinuteLabelOther": "minutes", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Couper", "copyButtonLabel": "Copier", "pasteButtonLabel": "Coller", "selectAllButtonLabel": "Tout sélectionner", "tabSemanticsLabel": "Onglet $tabIndex sur $tabCount", "modalBarrierDismissLabel": "Ignorer", "searchTextFieldPlaceholderLabel": "Rechercher", "noSpellCheckReplacementsLabel": "Aucun remplacement trouvé", "menuDismissLabel": "Fermer le menu", "lookUpButtonLabel": "Recherche visuelle", "searchWebButtonLabel": "Rechercher sur le Web", "shareButtonLabel": "Partager…", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_fr.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_fr.arb", "repo_id": "flutter", "token_count": 438 }
769
{ "datePickerHourSemanticsLabelOne": "ម៉ោង $hour", "datePickerHourSemanticsLabelOther": "ម៉ោង $hour", "datePickerMinuteSemanticsLabelOne": "1 នាទី", "datePickerMinuteSemanticsLabelOther": "$minute នាទី", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "ថ្ងៃនេះ", "alertDialogLabel": "ជូនដំណឹង", "timerPickerHourLabelOne": "ម៉ោង", "timerPickerHourLabelOther": "ម៉ោង", "timerPickerMinuteLabelOne": "នាទី", "timerPickerMinuteLabelOther": "នាទី", "timerPickerSecondLabelOne": "វិនាទី", "timerPickerSecondLabelOther": "វិនាទី", "cutButtonLabel": "កាត់", "copyButtonLabel": "ចម្លង", "pasteButtonLabel": "ដាក់​ចូល", "selectAllButtonLabel": "ជ្រើសរើស​ទាំងអស់", "tabSemanticsLabel": "ផ្ទាំងទី $tabIndex នៃ $tabCount", "modalBarrierDismissLabel": "ច្រាន​ចោល", "searchTextFieldPlaceholderLabel": "ស្វែងរក", "noSpellCheckReplacementsLabel": "រកមិនឃើញ​ការជំនួសទេ", "menuDismissLabel": "ច្រានចោល​ម៉ឺនុយ", "lookUpButtonLabel": "រកមើល", "searchWebButtonLabel": "ស្វែងរក​លើបណ្ដាញ", "shareButtonLabel": "ចែករំលែក...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_km.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_km.arb", "repo_id": "flutter", "token_count": 892 }
770
{ "datePickerHourSemanticsLabelOne": "$hour மணி", "datePickerHourSemanticsLabelOther": "$hour மணி", "datePickerMinuteSemanticsLabelOne": "1 நிமிடம்", "datePickerMinuteSemanticsLabelOther": "$minute நிமிடங்கள்", "datePickerDateOrder": "dmy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "இன்று", "alertDialogLabel": "விழிப்பூட்டல்", "timerPickerHourLabelOne": "மணிநேரம்", "timerPickerHourLabelOther": "மணிநேரம்", "timerPickerMinuteLabelOne": "நிமி.", "timerPickerMinuteLabelOther": "நிமி.", "timerPickerSecondLabelOne": "வி.", "timerPickerSecondLabelOther": "வி.", "cutButtonLabel": "வெட்டு", "copyButtonLabel": "நகலெடு", "pasteButtonLabel": "ஒட்டு", "selectAllButtonLabel": "எல்லாம் தேர்ந்தெடு", "tabSemanticsLabel": "தாவல் $tabIndex / $tabCount", "modalBarrierDismissLabel": "நிராகரிக்கும்", "searchTextFieldPlaceholderLabel": "தேடுக", "noSpellCheckReplacementsLabel": "மாற்று வார்த்தைகள் கிடைக்கவில்லை", "menuDismissLabel": "மெனுவை மூடும்", "lookUpButtonLabel": "தேடு", "searchWebButtonLabel": "இணையத்தில் தேடு", "shareButtonLabel": "பகிர்...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ta.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ta.arb", "repo_id": "flutter", "token_count": 942 }
771
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been automatically generated. Please do not edit it manually. // To regenerate the file, use: // dart dev/tools/localization/bin/gen_localizations.dart --overwrite import 'dart:collection'; import 'dart:ui'; import '../widgets_localizations.dart'; // The classes defined here encode all of the translations found in the // `flutter_localizations/lib/src/l10n/*.arb` files. // // These classes are constructed by the [getWidgetsTranslation] method at the // bottom of this file, and used by the [_WidgetsLocalizationsDelegate.load] // method defined in `flutter_localizations/lib/src/widgets_localizations.dart`. /// The translations for Afrikaans (`af`). class WidgetsLocalizationAf extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Afrikaans. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationAf() : super(TextDirection.ltr); @override String get reorderItemDown => 'Skuif af'; @override String get reorderItemLeft => 'Skuif na links'; @override String get reorderItemRight => 'Skuif na regs'; @override String get reorderItemToEnd => 'Skuif na die einde'; @override String get reorderItemToStart => 'Skuif na die begin'; @override String get reorderItemUp => 'Skuif op'; } /// The translations for Amharic (`am`). class WidgetsLocalizationAm extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Amharic. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationAm() : super(TextDirection.ltr); @override String get reorderItemDown => 'ወደ ታች ውሰድ'; @override String get reorderItemLeft => 'ወደ ግራ ውሰድ'; @override String get reorderItemRight => 'ወደ ቀኝ ውሰድ'; @override String get reorderItemToEnd => 'ወደ መጨረሻ ውሰድ'; @override String get reorderItemToStart => 'ወደ መጀመሪያ ውሰድ'; @override String get reorderItemUp => 'ወደ ላይ ውሰድ'; } /// The translations for Arabic (`ar`). class WidgetsLocalizationAr extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Arabic. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationAr() : super(TextDirection.rtl); @override String get reorderItemDown => 'نقل لأسفل'; @override String get reorderItemLeft => 'نقل لليمين'; @override String get reorderItemRight => 'نقل لليسار'; @override String get reorderItemToEnd => 'نقل إلى نهاية القائمة'; @override String get reorderItemToStart => 'نقل إلى بداية القائمة'; @override String get reorderItemUp => 'نقل لأعلى'; } /// The translations for Assamese (`as`). class WidgetsLocalizationAs extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Assamese. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationAs() : super(TextDirection.ltr); @override String get reorderItemDown => 'তললৈ স্থানান্তৰ কৰক'; @override String get reorderItemLeft => 'বাওঁফাললৈ স্থানান্তৰ কৰক'; @override String get reorderItemRight => 'সোঁফাললৈ স্থানান্তৰ কৰক'; @override String get reorderItemToEnd => 'শেষলৈ স্থানান্তৰ কৰক'; @override String get reorderItemToStart => 'আৰম্ভণিলৈ স্থানান্তৰ কৰক'; @override String get reorderItemUp => 'ওপৰলৈ নিয়ক'; } /// The translations for Azerbaijani (`az`). class WidgetsLocalizationAz extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Azerbaijani. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationAz() : super(TextDirection.ltr); @override String get reorderItemDown => 'Aşağı köçürün'; @override String get reorderItemLeft => 'Sola köçürün'; @override String get reorderItemRight => 'Sağa köçürün'; @override String get reorderItemToEnd => 'Sona köçürün'; @override String get reorderItemToStart => 'Əvvələ köçürün'; @override String get reorderItemUp => 'Yuxarı köçürün'; } /// The translations for Belarusian (`be`). class WidgetsLocalizationBe extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Belarusian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationBe() : super(TextDirection.ltr); @override String get reorderItemDown => 'Перамясціць уніз'; @override String get reorderItemLeft => 'Перамясціць улева'; @override String get reorderItemRight => 'Перамясціць управа'; @override String get reorderItemToEnd => 'Перамясціць у канец'; @override String get reorderItemToStart => 'Перамясціць у пачатак'; @override String get reorderItemUp => 'Перамясціць уверх'; } /// The translations for Bulgarian (`bg`). class WidgetsLocalizationBg extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Bulgarian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationBg() : super(TextDirection.ltr); @override String get reorderItemDown => 'Преместване надолу'; @override String get reorderItemLeft => 'Преместване наляво'; @override String get reorderItemRight => 'Преместване надясно'; @override String get reorderItemToEnd => 'Преместване в края'; @override String get reorderItemToStart => 'Преместване в началото'; @override String get reorderItemUp => 'Преместване нагоре'; } /// The translations for Bengali Bangla (`bn`). class WidgetsLocalizationBn extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Bengali Bangla. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationBn() : super(TextDirection.ltr); @override String get reorderItemDown => 'নিচের দিকে সরান'; @override String get reorderItemLeft => 'বাঁদিকে সরান'; @override String get reorderItemRight => 'ডানদিকে সরান'; @override String get reorderItemToEnd => 'একদম শেষের দিকে যান'; @override String get reorderItemToStart => 'চালু করতে সরান'; @override String get reorderItemUp => 'উপরের দিকে সরান'; } /// The translations for Bosnian (`bs`). class WidgetsLocalizationBs extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Bosnian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationBs() : super(TextDirection.ltr); @override String get reorderItemDown => 'Pomjeri nadolje'; @override String get reorderItemLeft => 'Pomjeri lijevo'; @override String get reorderItemRight => 'Pomjeri desno'; @override String get reorderItemToEnd => 'Pomjerite na kraj'; @override String get reorderItemToStart => 'Pomjerite na početak'; @override String get reorderItemUp => 'Pomjeri nagore'; } /// The translations for Catalan Valencian (`ca`). class WidgetsLocalizationCa extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Catalan Valencian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationCa() : super(TextDirection.ltr); @override String get reorderItemDown => 'Mou avall'; @override String get reorderItemLeft => "Mou cap a l'esquerra"; @override String get reorderItemRight => 'Mou cap a la dreta'; @override String get reorderItemToEnd => 'Mou al final'; @override String get reorderItemToStart => 'Mou al principi'; @override String get reorderItemUp => 'Mou amunt'; } /// The translations for Czech (`cs`). class WidgetsLocalizationCs extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Czech. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationCs() : super(TextDirection.ltr); @override String get reorderItemDown => 'Přesunout dolů'; @override String get reorderItemLeft => 'Přesunout doleva'; @override String get reorderItemRight => 'Přesunout doprava'; @override String get reorderItemToEnd => 'Přesunout na konec'; @override String get reorderItemToStart => 'Přesunout na začátek'; @override String get reorderItemUp => 'Přesunout nahoru'; } /// The translations for Welsh (`cy`). class WidgetsLocalizationCy extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Welsh. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationCy() : super(TextDirection.ltr); @override String get reorderItemDown => 'Symud i lawr'; @override String get reorderItemLeft => "Symud i'r chwith"; @override String get reorderItemRight => "Symud i'r dde"; @override String get reorderItemToEnd => "Symud i'r diwedd"; @override String get reorderItemToStart => "Symud i'r dechrau"; @override String get reorderItemUp => 'Symud i fyny'; } /// The translations for Danish (`da`). class WidgetsLocalizationDa extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Danish. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationDa() : super(TextDirection.ltr); @override String get reorderItemDown => 'Flyt ned'; @override String get reorderItemLeft => 'Flyt til venstre'; @override String get reorderItemRight => 'Flyt til højre'; @override String get reorderItemToEnd => 'Flyt til sidst på listen'; @override String get reorderItemToStart => 'Flyt til først på listen'; @override String get reorderItemUp => 'Flyt op'; } /// The translations for German (`de`). class WidgetsLocalizationDe extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for German. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationDe() : super(TextDirection.ltr); @override String get reorderItemDown => 'Nach unten verschieben'; @override String get reorderItemLeft => 'Nach links verschieben'; @override String get reorderItemRight => 'Nach rechts verschieben'; @override String get reorderItemToEnd => 'An das Ende verschieben'; @override String get reorderItemToStart => 'An den Anfang verschieben'; @override String get reorderItemUp => 'Nach oben verschieben'; } /// The translations for German, as used in Switzerland (`de_CH`). class WidgetsLocalizationDeCh extends WidgetsLocalizationDe { /// Create an instance of the translation bundle for German, as used in Switzerland. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationDeCh(); } /// The translations for Modern Greek (`el`). class WidgetsLocalizationEl extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Modern Greek. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEl() : super(TextDirection.ltr); @override String get reorderItemDown => 'Μετακίνηση προς τα κάτω'; @override String get reorderItemLeft => 'Μετακίνηση αριστερά'; @override String get reorderItemRight => 'Μετακίνηση δεξιά'; @override String get reorderItemToEnd => 'Μετακίνηση στο τέλος'; @override String get reorderItemToStart => 'Μετακίνηση στην αρχή'; @override String get reorderItemUp => 'Μετακίνηση προς τα πάνω'; } /// The translations for English (`en`). class WidgetsLocalizationEn extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for English. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEn() : super(TextDirection.ltr); @override String get reorderItemDown => 'Move down'; @override String get reorderItemLeft => 'Move left'; @override String get reorderItemRight => 'Move right'; @override String get reorderItemToEnd => 'Move to the end'; @override String get reorderItemToStart => 'Move to the start'; @override String get reorderItemUp => 'Move up'; } /// The translations for English, as used in Australia (`en_AU`). class WidgetsLocalizationEnAu extends WidgetsLocalizationEn { /// Create an instance of the translation bundle for English, as used in Australia. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEnAu(); @override String get reorderItemLeft => 'Move to the left'; @override String get reorderItemRight => 'Move to the right'; } /// The translations for English, as used in Canada (`en_CA`). class WidgetsLocalizationEnCa extends WidgetsLocalizationEn { /// Create an instance of the translation bundle for English, as used in Canada. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEnCa(); @override String get reorderItemLeft => 'Move to the left'; @override String get reorderItemRight => 'Move to the right'; } /// The translations for English, as used in the United Kingdom (`en_GB`). class WidgetsLocalizationEnGb extends WidgetsLocalizationEn { /// Create an instance of the translation bundle for English, as used in the United Kingdom. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEnGb(); @override String get reorderItemLeft => 'Move to the left'; @override String get reorderItemRight => 'Move to the right'; } /// The translations for English, as used in Ireland (`en_IE`). class WidgetsLocalizationEnIe extends WidgetsLocalizationEn { /// Create an instance of the translation bundle for English, as used in Ireland. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEnIe(); @override String get reorderItemLeft => 'Move to the left'; @override String get reorderItemRight => 'Move to the right'; } /// The translations for English, as used in India (`en_IN`). class WidgetsLocalizationEnIn extends WidgetsLocalizationEn { /// Create an instance of the translation bundle for English, as used in India. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEnIn(); @override String get reorderItemLeft => 'Move to the left'; @override String get reorderItemRight => 'Move to the right'; } /// The translations for English, as used in New Zealand (`en_NZ`). class WidgetsLocalizationEnNz extends WidgetsLocalizationEn { /// Create an instance of the translation bundle for English, as used in New Zealand. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEnNz(); @override String get reorderItemLeft => 'Move to the left'; @override String get reorderItemRight => 'Move to the right'; } /// The translations for English, as used in Singapore (`en_SG`). class WidgetsLocalizationEnSg extends WidgetsLocalizationEn { /// Create an instance of the translation bundle for English, as used in Singapore. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEnSg(); @override String get reorderItemLeft => 'Move to the left'; @override String get reorderItemRight => 'Move to the right'; } /// The translations for English, as used in South Africa (`en_ZA`). class WidgetsLocalizationEnZa extends WidgetsLocalizationEn { /// Create an instance of the translation bundle for English, as used in South Africa. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEnZa(); @override String get reorderItemLeft => 'Move to the left'; @override String get reorderItemRight => 'Move to the right'; } /// The translations for Spanish Castilian (`es`). class WidgetsLocalizationEs extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Spanish Castilian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEs() : super(TextDirection.ltr); @override String get reorderItemDown => 'Mover hacia abajo'; @override String get reorderItemLeft => 'Mover hacia la izquierda'; @override String get reorderItemRight => 'Mover hacia la derecha'; @override String get reorderItemToEnd => 'Mover al final'; @override String get reorderItemToStart => 'Mover al principio'; @override String get reorderItemUp => 'Mover hacia arriba'; } /// The translations for Spanish Castilian, as used in Latin America and the Caribbean (`es_419`). class WidgetsLocalizationEs419 extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Latin America and the Caribbean. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEs419(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Argentina (`es_AR`). class WidgetsLocalizationEsAr extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Argentina. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsAr(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Bolivia (`es_BO`). class WidgetsLocalizationEsBo extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Bolivia. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsBo(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Chile (`es_CL`). class WidgetsLocalizationEsCl extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Chile. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsCl(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Colombia (`es_CO`). class WidgetsLocalizationEsCo extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Colombia. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsCo(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Costa Rica (`es_CR`). class WidgetsLocalizationEsCr extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Costa Rica. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsCr(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in the Dominican Republic (`es_DO`). class WidgetsLocalizationEsDo extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in the Dominican Republic. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsDo(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Ecuador (`es_EC`). class WidgetsLocalizationEsEc extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Ecuador. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsEc(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Guatemala (`es_GT`). class WidgetsLocalizationEsGt extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Guatemala. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsGt(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Honduras (`es_HN`). class WidgetsLocalizationEsHn extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Honduras. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsHn(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Mexico (`es_MX`). class WidgetsLocalizationEsMx extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Mexico. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsMx(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Nicaragua (`es_NI`). class WidgetsLocalizationEsNi extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Nicaragua. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsNi(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Panama (`es_PA`). class WidgetsLocalizationEsPa extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Panama. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsPa(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Peru (`es_PE`). class WidgetsLocalizationEsPe extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Peru. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsPe(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Puerto Rico (`es_PR`). class WidgetsLocalizationEsPr extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Puerto Rico. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsPr(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Paraguay (`es_PY`). class WidgetsLocalizationEsPy extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Paraguay. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsPy(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in El Salvador (`es_SV`). class WidgetsLocalizationEsSv extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in El Salvador. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsSv(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in the United States (`es_US`). class WidgetsLocalizationEsUs extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in the United States. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsUs(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Uruguay (`es_UY`). class WidgetsLocalizationEsUy extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Uruguay. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsUy(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Spanish Castilian, as used in Venezuela (`es_VE`). class WidgetsLocalizationEsVe extends WidgetsLocalizationEs { /// Create an instance of the translation bundle for Spanish Castilian, as used in Venezuela. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEsVe(); @override String get reorderItemToStart => 'Mover al inicio'; } /// The translations for Estonian (`et`). class WidgetsLocalizationEt extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Estonian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEt() : super(TextDirection.ltr); @override String get reorderItemDown => 'Teisalda alla'; @override String get reorderItemLeft => 'Teisalda vasakule'; @override String get reorderItemRight => 'Teisalda paremale'; @override String get reorderItemToEnd => 'Teisalda lõppu'; @override String get reorderItemToStart => 'Teisalda algusesse'; @override String get reorderItemUp => 'Teisalda üles'; } /// The translations for Basque (`eu`). class WidgetsLocalizationEu extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Basque. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationEu() : super(TextDirection.ltr); @override String get reorderItemDown => 'Eraman behera'; @override String get reorderItemLeft => 'Eraman ezkerrera'; @override String get reorderItemRight => 'Eraman eskuinera'; @override String get reorderItemToEnd => 'Eraman amaierara'; @override String get reorderItemToStart => 'Eraman hasierara'; @override String get reorderItemUp => 'Eraman gora'; } /// The translations for Persian (`fa`). class WidgetsLocalizationFa extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Persian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationFa() : super(TextDirection.rtl); @override String get reorderItemDown => 'انتقال به پایین'; @override String get reorderItemLeft => 'انتقال به راست'; @override String get reorderItemRight => 'انتقال به چپ'; @override String get reorderItemToEnd => 'انتقال به انتها'; @override String get reorderItemToStart => 'انتقال به ابتدا'; @override String get reorderItemUp => 'انتقال به بالا'; } /// The translations for Finnish (`fi`). class WidgetsLocalizationFi extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Finnish. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationFi() : super(TextDirection.ltr); @override String get reorderItemDown => 'Siirrä alas'; @override String get reorderItemLeft => 'Siirrä vasemmalle'; @override String get reorderItemRight => 'Siirrä oikealle'; @override String get reorderItemToEnd => 'Siirrä loppuun'; @override String get reorderItemToStart => 'Siirrä alkuun'; @override String get reorderItemUp => 'Siirrä ylös'; } /// The translations for Filipino Pilipino (`fil`). class WidgetsLocalizationFil extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Filipino Pilipino. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationFil() : super(TextDirection.ltr); @override String get reorderItemDown => 'Ilipat pababa'; @override String get reorderItemLeft => 'Ilipat pakaliwa'; @override String get reorderItemRight => 'Ilipat pakanan'; @override String get reorderItemToEnd => 'Ilipat sa dulo'; @override String get reorderItemToStart => 'Ilipat sa simula'; @override String get reorderItemUp => 'Ilipat pataas'; } /// The translations for French (`fr`). class WidgetsLocalizationFr extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for French. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationFr() : super(TextDirection.ltr); @override String get reorderItemDown => 'Déplacer vers le bas'; @override String get reorderItemLeft => 'Déplacer vers la gauche'; @override String get reorderItemRight => 'Déplacer vers la droite'; @override String get reorderItemToEnd => 'Déplacer vers la fin'; @override String get reorderItemToStart => 'Déplacer vers le début'; @override String get reorderItemUp => 'Déplacer vers le haut'; } /// The translations for French, as used in Canada (`fr_CA`). class WidgetsLocalizationFrCa extends WidgetsLocalizationFr { /// Create an instance of the translation bundle for French, as used in Canada. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationFrCa(); @override String get reorderItemToStart => 'Déplacer au début'; @override String get reorderItemToEnd => 'Déplacer à la fin'; } /// The translations for Galician (`gl`). class WidgetsLocalizationGl extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Galician. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationGl() : super(TextDirection.ltr); @override String get reorderItemDown => 'Mover cara abaixo'; @override String get reorderItemLeft => 'Mover cara á esquerda'; @override String get reorderItemRight => 'Mover cara á dereita'; @override String get reorderItemToEnd => 'Mover ao final'; @override String get reorderItemToStart => 'Mover ao inicio'; @override String get reorderItemUp => 'Mover cara arriba'; } /// The translations for Swiss German Alemannic Alsatian (`gsw`). class WidgetsLocalizationGsw extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Swiss German Alemannic Alsatian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationGsw() : super(TextDirection.ltr); @override String get reorderItemDown => 'Nach unten verschieben'; @override String get reorderItemLeft => 'Nach links verschieben'; @override String get reorderItemRight => 'Nach rechts verschieben'; @override String get reorderItemToEnd => 'An das Ende verschieben'; @override String get reorderItemToStart => 'An den Anfang verschieben'; @override String get reorderItemUp => 'Nach oben verschieben'; } /// The translations for Gujarati (`gu`). class WidgetsLocalizationGu extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Gujarati. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationGu() : super(TextDirection.ltr); @override String get reorderItemDown => 'નીચે ખસેડો'; @override String get reorderItemLeft => 'ડાબે ખસેડો'; @override String get reorderItemRight => 'જમણે ખસેડો'; @override String get reorderItemToEnd => 'અંતમાં ખસેડો'; @override String get reorderItemToStart => 'પ્રારંભમાં ખસેડો'; @override String get reorderItemUp => 'ઉપર ખસેડો'; } /// The translations for Hebrew (`he`). class WidgetsLocalizationHe extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Hebrew. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationHe() : super(TextDirection.rtl); @override String get reorderItemDown => 'העברה למטה'; @override String get reorderItemLeft => 'העברה שמאלה'; @override String get reorderItemRight => 'העברה ימינה'; @override String get reorderItemToEnd => 'העברה לסוף'; @override String get reorderItemToStart => 'העברה להתחלה'; @override String get reorderItemUp => 'העברה למעלה'; } /// The translations for Hindi (`hi`). class WidgetsLocalizationHi extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Hindi. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationHi() : super(TextDirection.ltr); @override String get reorderItemDown => 'नीचे ले जाएं'; @override String get reorderItemLeft => 'बाएं ले जाएं'; @override String get reorderItemRight => 'दाएं ले जाएं'; @override String get reorderItemToEnd => 'आखिर में ले जाएं'; @override String get reorderItemToStart => 'शुरुआत पर ले जाएं'; @override String get reorderItemUp => 'ऊपर ले जाएं'; } /// The translations for Croatian (`hr`). class WidgetsLocalizationHr extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Croatian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationHr() : super(TextDirection.ltr); @override String get reorderItemDown => 'Pomakni prema dolje'; @override String get reorderItemLeft => 'Pomakni ulijevo'; @override String get reorderItemRight => 'Pomakni udesno'; @override String get reorderItemToEnd => 'Premjesti na kraj'; @override String get reorderItemToStart => 'Premjesti na početak'; @override String get reorderItemUp => 'Pomakni prema gore'; } /// The translations for Hungarian (`hu`). class WidgetsLocalizationHu extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Hungarian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationHu() : super(TextDirection.ltr); @override String get reorderItemDown => 'Áthelyezés lefelé'; @override String get reorderItemLeft => 'Áthelyezés balra'; @override String get reorderItemRight => 'Áthelyezés jobbra'; @override String get reorderItemToEnd => 'Áthelyezés a végére'; @override String get reorderItemToStart => 'Áthelyezés az elejére'; @override String get reorderItemUp => 'Áthelyezés felfelé'; } /// The translations for Armenian (`hy`). class WidgetsLocalizationHy extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Armenian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationHy() : super(TextDirection.ltr); @override String get reorderItemDown => 'Տեղափոխել ներքև'; @override String get reorderItemLeft => 'Տեղափոխել ձախ'; @override String get reorderItemRight => 'Տեղափոխել աջ'; @override String get reorderItemToEnd => 'Տեղափոխել վերջ'; @override String get reorderItemToStart => 'Տեղափոխել սկիզբ'; @override String get reorderItemUp => 'Տեղափոխել վերև'; } /// The translations for Indonesian (`id`). class WidgetsLocalizationId extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Indonesian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationId() : super(TextDirection.ltr); @override String get reorderItemDown => 'Turunkan'; @override String get reorderItemLeft => 'Pindahkan ke kiri'; @override String get reorderItemRight => 'Pindahkan ke kanan'; @override String get reorderItemToEnd => 'Pindahkan ke akhir'; @override String get reorderItemToStart => 'Pindahkan ke awal'; @override String get reorderItemUp => 'Naikkan'; } /// The translations for Icelandic (`is`). class WidgetsLocalizationIs extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Icelandic. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationIs() : super(TextDirection.ltr); @override String get reorderItemDown => 'Færa niður'; @override String get reorderItemLeft => 'Færa til vinstri'; @override String get reorderItemRight => 'Færa til hægri'; @override String get reorderItemToEnd => 'Færa aftast'; @override String get reorderItemToStart => 'Færa fremst'; @override String get reorderItemUp => 'Færa upp'; } /// The translations for Italian (`it`). class WidgetsLocalizationIt extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Italian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationIt() : super(TextDirection.ltr); @override String get reorderItemDown => 'Sposta giù'; @override String get reorderItemLeft => 'Sposta a sinistra'; @override String get reorderItemRight => 'Sposta a destra'; @override String get reorderItemToEnd => 'Sposta alla fine'; @override String get reorderItemToStart => "Sposta all'inizio"; @override String get reorderItemUp => 'Sposta su'; } /// The translations for Japanese (`ja`). class WidgetsLocalizationJa extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Japanese. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationJa() : super(TextDirection.ltr); @override String get reorderItemDown => '下に移動'; @override String get reorderItemLeft => '左に移動'; @override String get reorderItemRight => '右に移動'; @override String get reorderItemToEnd => '最後に移動'; @override String get reorderItemToStart => '先頭に移動'; @override String get reorderItemUp => '上に移動'; } /// The translations for Georgian (`ka`). class WidgetsLocalizationKa extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Georgian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationKa() : super(TextDirection.ltr); @override String get reorderItemDown => 'ქვემოთ გადატანა'; @override String get reorderItemLeft => 'მარცხნივ გადატანა'; @override String get reorderItemRight => 'მარჯვნივ გადატანა'; @override String get reorderItemToEnd => 'ბოლოში გადატანა'; @override String get reorderItemToStart => 'დასაწყისში გადატანა'; @override String get reorderItemUp => 'ზემოთ გადატანა'; } /// The translations for Kazakh (`kk`). class WidgetsLocalizationKk extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Kazakh. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationKk() : super(TextDirection.ltr); @override String get reorderItemDown => 'Төменге жылжыту'; @override String get reorderItemLeft => 'Солға жылжыту'; @override String get reorderItemRight => 'Оңға жылжыту'; @override String get reorderItemToEnd => 'Соңына өту'; @override String get reorderItemToStart => 'Басына өту'; @override String get reorderItemUp => 'Жоғарыға жылжыту'; } /// The translations for Khmer Central Khmer (`km`). class WidgetsLocalizationKm extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Khmer Central Khmer. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationKm() : super(TextDirection.ltr); @override String get reorderItemDown => 'ផ្លាស់ទី​ចុះ​ក្រោម'; @override String get reorderItemLeft => 'ផ្លាស់ទី​ទៅ​ឆ្វេង'; @override String get reorderItemRight => 'ផ្លាស់ទីទៅ​ស្តាំ'; @override String get reorderItemToEnd => 'ផ្លាស់ទីទៅ​ចំណុចបញ្ចប់'; @override String get reorderItemToStart => 'ផ្លាស់ទីទៅ​ចំណុច​ចាប់ផ្ដើម'; @override String get reorderItemUp => 'ផ្លាស់ទី​ឡើង​លើ'; } /// The translations for Kannada (`kn`). class WidgetsLocalizationKn extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Kannada. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationKn() : super(TextDirection.ltr); @override String get reorderItemDown => '\u{c95}\u{cc6}\u{cb3}\u{c97}\u{cc6}\u{20}\u{cb8}\u{cb0}\u{cbf}\u{cb8}\u{cbf}'; @override String get reorderItemLeft => '\u{c8e}\u{ca1}\u{c95}\u{ccd}\u{c95}\u{cc6}\u{20}\u{cb8}\u{cb0}\u{cbf}\u{cb8}\u{cbf}'; @override String get reorderItemRight => '\u{cac}\u{cb2}\u{c95}\u{ccd}\u{c95}\u{cc6}\u{20}\u{cb8}\u{cb0}\u{cbf}\u{cb8}\u{cbf}'; @override String get reorderItemToEnd => '\u{c95}\u{cca}\u{ca8}\u{cc6}\u{c97}\u{cc6}\u{20}\u{cb8}\u{cb0}\u{cbf}\u{cb8}\u{cbf}'; @override String get reorderItemToStart => '\u{caa}\u{ccd}\u{cb0}\u{cbe}\u{cb0}\u{c82}\u{cad}\u{c95}\u{ccd}\u{c95}\u{cc6}\u{20}\u{cb8}\u{cb0}\u{cbf}\u{cb8}\u{cbf}'; @override String get reorderItemUp => '\u{cae}\u{cc7}\u{cb2}\u{cc6}\u{20}\u{cb8}\u{cb0}\u{cbf}\u{cb8}\u{cbf}'; } /// The translations for Korean (`ko`). class WidgetsLocalizationKo extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Korean. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationKo() : super(TextDirection.ltr); @override String get reorderItemDown => '아래로 이동'; @override String get reorderItemLeft => '왼쪽으로 이동'; @override String get reorderItemRight => '오른쪽으로 이동'; @override String get reorderItemToEnd => '끝으로 이동'; @override String get reorderItemToStart => '시작으로 이동'; @override String get reorderItemUp => '위로 이동'; } /// The translations for Kirghiz Kyrgyz (`ky`). class WidgetsLocalizationKy extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Kirghiz Kyrgyz. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationKy() : super(TextDirection.ltr); @override String get reorderItemDown => 'Төмөн жылдыруу'; @override String get reorderItemLeft => 'Солго жылдыруу'; @override String get reorderItemRight => 'Оңго жылдыруу'; @override String get reorderItemToEnd => 'Аягына жылдыруу'; @override String get reorderItemToStart => 'Башына жылдыруу'; @override String get reorderItemUp => 'Жогору жылдыруу'; } /// The translations for Lao (`lo`). class WidgetsLocalizationLo extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Lao. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationLo() : super(TextDirection.ltr); @override String get reorderItemDown => 'ຍ້າຍລົງ'; @override String get reorderItemLeft => 'ຍ້າຍໄປຊ້າຍ'; @override String get reorderItemRight => 'ຍ້າຍໄປຂວາ'; @override String get reorderItemToEnd => 'ຍ້າຍໄປສິ້ນສຸດ'; @override String get reorderItemToStart => 'ຍ້າຍໄປເລີ່ມຕົ້ນ'; @override String get reorderItemUp => 'ຍ້າຍຂຶ້ນ'; } /// The translations for Lithuanian (`lt`). class WidgetsLocalizationLt extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Lithuanian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationLt() : super(TextDirection.ltr); @override String get reorderItemDown => 'Perkelti žemyn'; @override String get reorderItemLeft => 'Perkelti kairėn'; @override String get reorderItemRight => 'Perkelti dešinėn'; @override String get reorderItemToEnd => 'Perkelti į pabaigą'; @override String get reorderItemToStart => 'Perkelti į pradžią'; @override String get reorderItemUp => 'Perkelti aukštyn'; } /// The translations for Latvian (`lv`). class WidgetsLocalizationLv extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Latvian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationLv() : super(TextDirection.ltr); @override String get reorderItemDown => 'Pārvietot uz leju'; @override String get reorderItemLeft => 'Pārvietot pa kreisi'; @override String get reorderItemRight => 'Pārvietot pa labi'; @override String get reorderItemToEnd => 'Pārvietot uz beigām'; @override String get reorderItemToStart => 'Pārvietot uz sākumu'; @override String get reorderItemUp => 'Pārvietot uz augšu'; } /// The translations for Macedonian (`mk`). class WidgetsLocalizationMk extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Macedonian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationMk() : super(TextDirection.ltr); @override String get reorderItemDown => 'Преместете надолу'; @override String get reorderItemLeft => 'Преместете налево'; @override String get reorderItemRight => 'Преместете надесно'; @override String get reorderItemToEnd => 'Преместете на крајот'; @override String get reorderItemToStart => 'Преместете на почеток'; @override String get reorderItemUp => 'Преместете нагоре'; } /// The translations for Malayalam (`ml`). class WidgetsLocalizationMl extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Malayalam. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationMl() : super(TextDirection.ltr); @override String get reorderItemDown => 'താഴോട്ട് നീക്കുക'; @override String get reorderItemLeft => 'ഇടത്തോട്ട് നീക്കുക'; @override String get reorderItemRight => 'വലത്തോട്ട് നീക്കുക'; @override String get reorderItemToEnd => 'അവസാന ഭാഗത്തേക്ക് പോവുക'; @override String get reorderItemToStart => 'തുടക്കത്തിലേക്ക് പോവുക'; @override String get reorderItemUp => 'മുകളിലോട്ട് നീക്കുക'; } /// The translations for Mongolian (`mn`). class WidgetsLocalizationMn extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Mongolian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationMn() : super(TextDirection.ltr); @override String get reorderItemDown => 'Доош зөөх'; @override String get reorderItemLeft => 'Зүүн тийш зөөх'; @override String get reorderItemRight => 'Баруун тийш зөөх'; @override String get reorderItemToEnd => 'Төгсгөл рүү зөөх'; @override String get reorderItemToStart => 'Эхлэл рүү зөөх'; @override String get reorderItemUp => 'Дээш зөөх'; } /// The translations for Marathi (`mr`). class WidgetsLocalizationMr extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Marathi. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationMr() : super(TextDirection.ltr); @override String get reorderItemDown => 'खाली हलवा'; @override String get reorderItemLeft => 'डावीकडे हलवा'; @override String get reorderItemRight => 'उजवीकडे हलवा'; @override String get reorderItemToEnd => 'शेवटाकडे हलवा'; @override String get reorderItemToStart => 'सुरुवातीला हलवा'; @override String get reorderItemUp => 'वर हलवा'; } /// The translations for Malay (`ms`). class WidgetsLocalizationMs extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Malay. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationMs() : super(TextDirection.ltr); @override String get reorderItemDown => 'Alih ke bawah'; @override String get reorderItemLeft => 'Alih ke kiri'; @override String get reorderItemRight => 'Alih ke kanan'; @override String get reorderItemToEnd => 'Alih ke penghujung'; @override String get reorderItemToStart => 'Alih ke permulaan'; @override String get reorderItemUp => 'Alih ke atas'; } /// The translations for Burmese (`my`). class WidgetsLocalizationMy extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Burmese. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationMy() : super(TextDirection.ltr); @override String get reorderItemDown => 'အောက်သို့ရွှေ့ရန်'; @override String get reorderItemLeft => 'ဘယ်ဘက်သို့ရွှေ့ရန်'; @override String get reorderItemRight => 'ညာဘက်သို့ရွှေ့ရန်'; @override String get reorderItemToEnd => 'အဆုံးသို့ ‌ရွှေ့ရန်'; @override String get reorderItemToStart => 'အစသို့ ရွှေ့ရန်'; @override String get reorderItemUp => 'အပေါ်သို့ ရွှေ့ရန်'; } /// The translations for Norwegian Bokmål (`nb`). class WidgetsLocalizationNb extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Norwegian Bokmål. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationNb() : super(TextDirection.ltr); @override String get reorderItemDown => 'Flytt ned'; @override String get reorderItemLeft => 'Flytt til venstre'; @override String get reorderItemRight => 'Flytt til høyre'; @override String get reorderItemToEnd => 'Flytt til slutten'; @override String get reorderItemToStart => 'Flytt til starten'; @override String get reorderItemUp => 'Flytt opp'; } /// The translations for Nepali (`ne`). class WidgetsLocalizationNe extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Nepali. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationNe() : super(TextDirection.ltr); @override String get reorderItemDown => 'तल सार्नुहोस्'; @override String get reorderItemLeft => 'बायाँ सार्नुहोस्'; @override String get reorderItemRight => 'दायाँ सार्नुहोस्'; @override String get reorderItemToEnd => 'अन्त्यमा जानुहोस्'; @override String get reorderItemToStart => 'सुरुमा सार्नुहोस्'; @override String get reorderItemUp => 'माथि सार्नुहोस्'; } /// The translations for Dutch Flemish (`nl`). class WidgetsLocalizationNl extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Dutch Flemish. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationNl() : super(TextDirection.ltr); @override String get reorderItemDown => 'Omlaag verplaatsen'; @override String get reorderItemLeft => 'Naar links verplaatsen'; @override String get reorderItemRight => 'Naar rechts verplaatsen'; @override String get reorderItemToEnd => 'Naar het einde verplaatsen'; @override String get reorderItemToStart => 'Naar het begin verplaatsen'; @override String get reorderItemUp => 'Omhoog verplaatsen'; } /// The translations for Norwegian (`no`). class WidgetsLocalizationNo extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Norwegian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationNo() : super(TextDirection.ltr); @override String get reorderItemDown => 'Flytt ned'; @override String get reorderItemLeft => 'Flytt til venstre'; @override String get reorderItemRight => 'Flytt til høyre'; @override String get reorderItemToEnd => 'Flytt til slutten'; @override String get reorderItemToStart => 'Flytt til starten'; @override String get reorderItemUp => 'Flytt opp'; } /// The translations for Oriya (`or`). class WidgetsLocalizationOr extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Oriya. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationOr() : super(TextDirection.ltr); @override String get reorderItemDown => 'ତଳକୁ ଯାଆନ୍ତୁ'; @override String get reorderItemLeft => 'ବାମକୁ ଯାଆନ୍ତୁ'; @override String get reorderItemRight => 'ଡାହାଣକୁ ଯାଆନ୍ତୁ'; @override String get reorderItemToEnd => 'ଶେଷକୁ ଯାଆନ୍ତୁ'; @override String get reorderItemToStart => 'ଆରମ୍ଭକୁ ଯାଆନ୍ତୁ'; @override String get reorderItemUp => 'ଉପରକୁ ନିଅନ୍ତୁ'; } /// The translations for Panjabi Punjabi (`pa`). class WidgetsLocalizationPa extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Panjabi Punjabi. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationPa() : super(TextDirection.ltr); @override String get reorderItemDown => 'ਹੇਠਾਂ ਲਿਜਾਓ'; @override String get reorderItemLeft => 'ਖੱਬੇ ਲਿਜਾਓ'; @override String get reorderItemRight => 'ਸੱਜੇ ਲਿਜਾਓ'; @override String get reorderItemToEnd => 'ਅੰਤ ਵਿੱਚ ਲਿਜਾਓ'; @override String get reorderItemToStart => 'ਸ਼ੁਰੂ ਵਿੱਚ ਲਿਜਾਓ'; @override String get reorderItemUp => 'ਉੱਪਰ ਲਿਜਾਓ'; } /// The translations for Polish (`pl`). class WidgetsLocalizationPl extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Polish. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationPl() : super(TextDirection.ltr); @override String get reorderItemDown => 'Przenieś w dół'; @override String get reorderItemLeft => 'Przenieś w lewo'; @override String get reorderItemRight => 'Przenieś w prawo'; @override String get reorderItemToEnd => 'Przenieś na koniec'; @override String get reorderItemToStart => 'Przenieś na początek'; @override String get reorderItemUp => 'Przenieś w górę'; } /// The translations for Pushto Pashto (`ps`). class WidgetsLocalizationPs extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Pushto Pashto. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationPs() : super(TextDirection.rtl); @override String get reorderItemDown => 'Move down'; @override String get reorderItemLeft => 'Move left'; @override String get reorderItemRight => 'Move right'; @override String get reorderItemToEnd => 'Move to the end'; @override String get reorderItemToStart => 'Move to the start'; @override String get reorderItemUp => 'Move up'; } /// The translations for Portuguese (`pt`). class WidgetsLocalizationPt extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Portuguese. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationPt() : super(TextDirection.ltr); @override String get reorderItemDown => 'Mover para baixo'; @override String get reorderItemLeft => 'Mover para a esquerda'; @override String get reorderItemRight => 'Mover para a direita'; @override String get reorderItemToEnd => 'Mover para o final'; @override String get reorderItemToStart => 'Mover para o início'; @override String get reorderItemUp => 'Mover para cima'; } /// The translations for Portuguese, as used in Portugal (`pt_PT`). class WidgetsLocalizationPtPt extends WidgetsLocalizationPt { /// Create an instance of the translation bundle for Portuguese, as used in Portugal. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationPtPt(); @override String get reorderItemToEnd => 'Mover para o fim'; } /// The translations for Romanian Moldavian Moldovan (`ro`). class WidgetsLocalizationRo extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Romanian Moldavian Moldovan. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationRo() : super(TextDirection.ltr); @override String get reorderItemDown => 'Mutați în jos'; @override String get reorderItemLeft => 'Mutați la stânga'; @override String get reorderItemRight => 'Mutați la dreapta'; @override String get reorderItemToEnd => 'Mutați la sfârșit'; @override String get reorderItemToStart => 'Mutați la început'; @override String get reorderItemUp => 'Mutați în sus'; } /// The translations for Russian (`ru`). class WidgetsLocalizationRu extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Russian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationRu() : super(TextDirection.ltr); @override String get reorderItemDown => 'Переместить вниз'; @override String get reorderItemLeft => 'Переместить влево'; @override String get reorderItemRight => 'Переместить вправо'; @override String get reorderItemToEnd => 'Переместить в конец'; @override String get reorderItemToStart => 'Переместить в начало'; @override String get reorderItemUp => 'Переместить вверх'; } /// The translations for Sinhala Sinhalese (`si`). class WidgetsLocalizationSi extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Sinhala Sinhalese. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationSi() : super(TextDirection.ltr); @override String get reorderItemDown => 'පහළට ගෙන යන්න'; @override String get reorderItemLeft => 'වමට ගෙන යන්න'; @override String get reorderItemRight => 'දකුණට ගෙන යන්න'; @override String get reorderItemToEnd => 'අවසානයට යන්න'; @override String get reorderItemToStart => 'ආරම්භය වෙත යන්න'; @override String get reorderItemUp => 'ඉහළට ගෙන යන්න'; } /// The translations for Slovak (`sk`). class WidgetsLocalizationSk extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Slovak. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationSk() : super(TextDirection.ltr); @override String get reorderItemDown => 'Presunúť nadol'; @override String get reorderItemLeft => 'Presunúť doľava'; @override String get reorderItemRight => 'Presunúť doprava'; @override String get reorderItemToEnd => 'Presunúť na koniec'; @override String get reorderItemToStart => 'Presunúť na začiatok'; @override String get reorderItemUp => 'Presunúť nahor'; } /// The translations for Slovenian (`sl`). class WidgetsLocalizationSl extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Slovenian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationSl() : super(TextDirection.ltr); @override String get reorderItemDown => 'Premakni navzdol'; @override String get reorderItemLeft => 'Premakni levo'; @override String get reorderItemRight => 'Premakni desno'; @override String get reorderItemToEnd => 'Premakni na konec'; @override String get reorderItemToStart => 'Premakni na začetek'; @override String get reorderItemUp => 'Premakni navzgor'; } /// The translations for Albanian (`sq`). class WidgetsLocalizationSq extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Albanian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationSq() : super(TextDirection.ltr); @override String get reorderItemDown => 'Lëvize poshtë'; @override String get reorderItemLeft => 'Lëvize majtas'; @override String get reorderItemRight => 'Lëvize djathtas'; @override String get reorderItemToEnd => 'Lëvize në fund'; @override String get reorderItemToStart => 'Lëvize në fillim'; @override String get reorderItemUp => 'Lëvize lart'; } /// The translations for Serbian (`sr`). class WidgetsLocalizationSr extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Serbian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationSr() : super(TextDirection.ltr); @override String get reorderItemDown => 'Померите надоле'; @override String get reorderItemLeft => 'Померите улево'; @override String get reorderItemRight => 'Померите удесно'; @override String get reorderItemToEnd => 'Померите на крај'; @override String get reorderItemToStart => 'Померите на почетак'; @override String get reorderItemUp => 'Померите нагоре'; } /// The translations for Serbian, using the Cyrillic script (`sr_Cyrl`). class WidgetsLocalizationSrCyrl extends WidgetsLocalizationSr { /// Create an instance of the translation bundle for Serbian, using the Cyrillic script. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationSrCyrl(); } /// The translations for Serbian, using the Latin script (`sr_Latn`). class WidgetsLocalizationSrLatn extends WidgetsLocalizationSr { /// Create an instance of the translation bundle for Serbian, using the Latin script. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationSrLatn(); @override String get reorderItemDown => 'Pomerite nadole'; @override String get reorderItemLeft => 'Pomerite ulevo'; @override String get reorderItemRight => 'Pomerite udesno'; @override String get reorderItemToEnd => 'Pomerite na kraj'; @override String get reorderItemToStart => 'Pomerite na početak'; @override String get reorderItemUp => 'Pomerite nagore'; } /// The translations for Swedish (`sv`). class WidgetsLocalizationSv extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Swedish. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationSv() : super(TextDirection.ltr); @override String get reorderItemDown => 'Flytta nedåt'; @override String get reorderItemLeft => 'Flytta åt vänster'; @override String get reorderItemRight => 'Flytta åt höger'; @override String get reorderItemToEnd => 'Flytta till slutet'; @override String get reorderItemToStart => 'Flytta till början'; @override String get reorderItemUp => 'Flytta uppåt'; } /// The translations for Swahili (`sw`). class WidgetsLocalizationSw extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Swahili. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationSw() : super(TextDirection.ltr); @override String get reorderItemDown => 'Sogeza chini'; @override String get reorderItemLeft => 'Sogeza kushoto'; @override String get reorderItemRight => 'Sogeza kulia'; @override String get reorderItemToEnd => 'Sogeza hadi mwisho'; @override String get reorderItemToStart => 'Sogeza hadi mwanzo'; @override String get reorderItemUp => 'Sogeza juu'; } /// The translations for Tamil (`ta`). class WidgetsLocalizationTa extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Tamil. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationTa() : super(TextDirection.ltr); @override String get reorderItemDown => 'கீழே நகர்த்தவும்'; @override String get reorderItemLeft => 'இடப்புறம் நகர்த்தவும்'; @override String get reorderItemRight => 'வலப்புறம் நகர்த்தவும்'; @override String get reorderItemToEnd => 'இறுதிக்கு நகர்த்தவும்'; @override String get reorderItemToStart => 'தொடக்கத்திற்கு நகர்த்தவும்'; @override String get reorderItemUp => 'மேலே நகர்த்தவும்'; } /// The translations for Telugu (`te`). class WidgetsLocalizationTe extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Telugu. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationTe() : super(TextDirection.ltr); @override String get reorderItemDown => 'కిందికు జరుపు'; @override String get reorderItemLeft => 'ఎడమవైపుగా జరపండి'; @override String get reorderItemRight => 'కుడివైపుగా జరపండి'; @override String get reorderItemToEnd => 'చివరకు తరలించండి'; @override String get reorderItemToStart => 'ప్రారంభానికి తరలించండి'; @override String get reorderItemUp => 'పైకి జరపండి'; } /// The translations for Thai (`th`). class WidgetsLocalizationTh extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Thai. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationTh() : super(TextDirection.ltr); @override String get reorderItemDown => 'ย้ายลง'; @override String get reorderItemLeft => 'ย้ายไปทางซ้าย'; @override String get reorderItemRight => 'ย้ายไปทางขวา'; @override String get reorderItemToEnd => 'ย้ายไปท้ายรายการ'; @override String get reorderItemToStart => 'ย้ายไปต้นรายการ'; @override String get reorderItemUp => 'ย้ายขึ้น'; } /// The translations for Tagalog (`tl`). class WidgetsLocalizationTl extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Tagalog. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationTl() : super(TextDirection.ltr); @override String get reorderItemDown => 'Ilipat pababa'; @override String get reorderItemLeft => 'Ilipat pakaliwa'; @override String get reorderItemRight => 'Ilipat pakanan'; @override String get reorderItemToEnd => 'Ilipat sa dulo'; @override String get reorderItemToStart => 'Ilipat sa simula'; @override String get reorderItemUp => 'Ilipat pataas'; } /// The translations for Turkish (`tr`). class WidgetsLocalizationTr extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Turkish. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationTr() : super(TextDirection.ltr); @override String get reorderItemDown => 'Aşağı taşı'; @override String get reorderItemLeft => 'Sola taşı'; @override String get reorderItemRight => 'Sağa taşı'; @override String get reorderItemToEnd => 'Sona taşı'; @override String get reorderItemToStart => 'Başa taşı'; @override String get reorderItemUp => 'Yukarı taşı'; } /// The translations for Ukrainian (`uk`). class WidgetsLocalizationUk extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Ukrainian. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationUk() : super(TextDirection.ltr); @override String get reorderItemDown => 'Перемістити вниз'; @override String get reorderItemLeft => 'Перемістити ліворуч'; @override String get reorderItemRight => 'Перемістити праворуч'; @override String get reorderItemToEnd => 'Перемістити в кінець'; @override String get reorderItemToStart => 'Перемістити на початок'; @override String get reorderItemUp => 'Перемістити вгору'; } /// The translations for Urdu (`ur`). class WidgetsLocalizationUr extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Urdu. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationUr() : super(TextDirection.rtl); @override String get reorderItemDown => 'نیچے منتقل کریں'; @override String get reorderItemLeft => 'بائیں منتقل کریں'; @override String get reorderItemRight => 'دائیں منتقل کریں'; @override String get reorderItemToEnd => 'آخر میں منتقل کریں'; @override String get reorderItemToStart => 'شروع میں منتقل کریں'; @override String get reorderItemUp => 'اوپر منتقل کریں'; } /// The translations for Uzbek (`uz`). class WidgetsLocalizationUz extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Uzbek. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationUz() : super(TextDirection.ltr); @override String get reorderItemDown => 'Pastga siljitish'; @override String get reorderItemLeft => 'Chapga siljitish'; @override String get reorderItemRight => 'Oʻngga siljitish'; @override String get reorderItemToEnd => 'Oxiriga siljitish'; @override String get reorderItemToStart => 'Boshiga siljitish'; @override String get reorderItemUp => 'Tepaga siljitish'; } /// The translations for Vietnamese (`vi`). class WidgetsLocalizationVi extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Vietnamese. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationVi() : super(TextDirection.ltr); @override String get reorderItemDown => 'Di chuyển xuống'; @override String get reorderItemLeft => 'Di chuyển sang trái'; @override String get reorderItemRight => 'Di chuyển sang phải'; @override String get reorderItemToEnd => 'Di chuyển xuống cuối danh sách'; @override String get reorderItemToStart => 'Di chuyển lên đầu danh sách'; @override String get reorderItemUp => 'Di chuyển lên'; } /// The translations for Chinese (`zh`). class WidgetsLocalizationZh extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Chinese. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationZh() : super(TextDirection.ltr); @override String get reorderItemDown => '下移'; @override String get reorderItemLeft => '左移'; @override String get reorderItemRight => '右移'; @override String get reorderItemToEnd => '移到末尾'; @override String get reorderItemToStart => '移到开头'; @override String get reorderItemUp => '上移'; } /// The translations for Chinese, using the Han script (`zh_Hans`). class WidgetsLocalizationZhHans extends WidgetsLocalizationZh { /// Create an instance of the translation bundle for Chinese, using the Han script. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationZhHans(); } /// The translations for Chinese, using the Han script (`zh_Hant`). class WidgetsLocalizationZhHant extends WidgetsLocalizationZh { /// Create an instance of the translation bundle for Chinese, using the Han script. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationZhHant(); @override String get reorderItemDown => '向下移'; @override String get reorderItemLeft => '向左移'; @override String get reorderItemRight => '向右移'; @override String get reorderItemToEnd => '移到最後'; @override String get reorderItemToStart => '移到開頭'; @override String get reorderItemUp => '向上移'; } /// The translations for Chinese, as used in Hong Kong, using the Han script (`zh_Hant_HK`). class WidgetsLocalizationZhHantHk extends WidgetsLocalizationZhHant { /// Create an instance of the translation bundle for Chinese, as used in Hong Kong, using the Han script. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationZhHantHk(); } /// The translations for Chinese, as used in Taiwan, using the Han script (`zh_Hant_TW`). class WidgetsLocalizationZhHantTw extends WidgetsLocalizationZhHant { /// Create an instance of the translation bundle for Chinese, as used in Taiwan, using the Han script. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationZhHantTw(); @override String get reorderItemToStart => '移至開頭'; @override String get reorderItemToEnd => '移至結尾'; } /// The translations for Zulu (`zu`). class WidgetsLocalizationZu extends GlobalWidgetsLocalizations { /// Create an instance of the translation bundle for Zulu. /// /// For details on the meaning of the arguments, see [GlobalWidgetsLocalizations]. const WidgetsLocalizationZu() : super(TextDirection.ltr); @override String get reorderItemDown => 'Iya phansi'; @override String get reorderItemLeft => 'Hambisa kwesokunxele'; @override String get reorderItemRight => 'Yisa kwesokudla'; @override String get reorderItemToEnd => 'Yisa ekugcineni'; @override String get reorderItemToStart => 'Yisa ekuqaleni'; @override String get reorderItemUp => 'Iya phezulu'; } /// The set of supported languages, as language code strings. /// /// The [GlobalWidgetsLocalizations.delegate] can generate localizations for /// any [Locale] with a language code from this set, regardless of the region. /// Some regions have specific support (e.g. `de` covers all forms of German, /// but there is support for `de-CH` specifically to override some of the /// translations for Switzerland). /// /// See also: /// /// * [getWidgetsTranslation], whose documentation describes these values. final Set<String> kWidgetsSupportedLanguages = HashSet<String>.from(const <String>[ 'af', // Afrikaans 'am', // Amharic 'ar', // Arabic 'as', // Assamese 'az', // Azerbaijani 'be', // Belarusian 'bg', // Bulgarian 'bn', // Bengali Bangla 'bs', // Bosnian 'ca', // Catalan Valencian 'cs', // Czech 'cy', // Welsh 'da', // Danish 'de', // German 'el', // Modern Greek 'en', // English 'es', // Spanish Castilian 'et', // Estonian 'eu', // Basque 'fa', // Persian 'fi', // Finnish 'fil', // Filipino Pilipino 'fr', // French 'gl', // Galician 'gsw', // Swiss German Alemannic Alsatian 'gu', // Gujarati 'he', // Hebrew 'hi', // Hindi 'hr', // Croatian 'hu', // Hungarian 'hy', // Armenian 'id', // Indonesian 'is', // Icelandic 'it', // Italian 'ja', // Japanese 'ka', // Georgian 'kk', // Kazakh 'km', // Khmer Central Khmer 'kn', // Kannada 'ko', // Korean 'ky', // Kirghiz Kyrgyz 'lo', // Lao 'lt', // Lithuanian 'lv', // Latvian 'mk', // Macedonian 'ml', // Malayalam 'mn', // Mongolian 'mr', // Marathi 'ms', // Malay 'my', // Burmese 'nb', // Norwegian Bokmål 'ne', // Nepali 'nl', // Dutch Flemish 'no', // Norwegian 'or', // Oriya 'pa', // Panjabi Punjabi 'pl', // Polish 'ps', // Pushto Pashto 'pt', // Portuguese 'ro', // Romanian Moldavian Moldovan 'ru', // Russian 'si', // Sinhala Sinhalese 'sk', // Slovak 'sl', // Slovenian 'sq', // Albanian 'sr', // Serbian 'sv', // Swedish 'sw', // Swahili 'ta', // Tamil 'te', // Telugu 'th', // Thai 'tl', // Tagalog 'tr', // Turkish 'uk', // Ukrainian 'ur', // Urdu 'uz', // Uzbek 'vi', // Vietnamese 'zh', // Chinese 'zu', // Zulu ]); /// Creates a [GlobalWidgetsLocalizations] instance for the given `locale`. /// /// All of the function's arguments except `locale` will be passed to the [ /// GlobalWidgetsLocalizations] constructor. (The `localeName` argument of that /// constructor is specified by the actual subclass constructor by this /// function.) /// /// The following locales are supported by this package: /// /// {@template flutter.localizations.widgets.languages} /// * `af` - Afrikaans /// * `am` - Amharic /// * `ar` - Arabic /// * `as` - Assamese /// * `az` - Azerbaijani /// * `be` - Belarusian /// * `bg` - Bulgarian /// * `bn` - Bengali Bangla /// * `bs` - Bosnian /// * `ca` - Catalan Valencian /// * `cs` - Czech /// * `cy` - Welsh /// * `da` - Danish /// * `de` - German (plus one country variation) /// * `el` - Modern Greek /// * `en` - English (plus 8 country variations) /// * `es` - Spanish Castilian (plus 20 country variations) /// * `et` - Estonian /// * `eu` - Basque /// * `fa` - Persian /// * `fi` - Finnish /// * `fil` - Filipino Pilipino /// * `fr` - French (plus one country variation) /// * `gl` - Galician /// * `gsw` - Swiss German Alemannic Alsatian /// * `gu` - Gujarati /// * `he` - Hebrew /// * `hi` - Hindi /// * `hr` - Croatian /// * `hu` - Hungarian /// * `hy` - Armenian /// * `id` - Indonesian /// * `is` - Icelandic /// * `it` - Italian /// * `ja` - Japanese /// * `ka` - Georgian /// * `kk` - Kazakh /// * `km` - Khmer Central Khmer /// * `kn` - Kannada /// * `ko` - Korean /// * `ky` - Kirghiz Kyrgyz /// * `lo` - Lao /// * `lt` - Lithuanian /// * `lv` - Latvian /// * `mk` - Macedonian /// * `ml` - Malayalam /// * `mn` - Mongolian /// * `mr` - Marathi /// * `ms` - Malay /// * `my` - Burmese /// * `nb` - Norwegian Bokmål /// * `ne` - Nepali /// * `nl` - Dutch Flemish /// * `no` - Norwegian /// * `or` - Oriya /// * `pa` - Panjabi Punjabi /// * `pl` - Polish /// * `ps` - Pushto Pashto /// * `pt` - Portuguese (plus one country variation) /// * `ro` - Romanian Moldavian Moldovan /// * `ru` - Russian /// * `si` - Sinhala Sinhalese /// * `sk` - Slovak /// * `sl` - Slovenian /// * `sq` - Albanian /// * `sr` - Serbian (plus 2 scripts) /// * `sv` - Swedish /// * `sw` - Swahili /// * `ta` - Tamil /// * `te` - Telugu /// * `th` - Thai /// * `tl` - Tagalog /// * `tr` - Turkish /// * `uk` - Ukrainian /// * `ur` - Urdu /// * `uz` - Uzbek /// * `vi` - Vietnamese /// * `zh` - Chinese (plus 2 country variations and 2 scripts) /// * `zu` - Zulu /// {@endtemplate} /// /// Generally speaking, this method is only intended to be used by /// [GlobalWidgetsLocalizations.delegate]. GlobalWidgetsLocalizations? getWidgetsTranslation( Locale locale, ) { switch (locale.languageCode) { case 'af': return const WidgetsLocalizationAf(); case 'am': return const WidgetsLocalizationAm(); case 'ar': return const WidgetsLocalizationAr(); case 'as': return const WidgetsLocalizationAs(); case 'az': return const WidgetsLocalizationAz(); case 'be': return const WidgetsLocalizationBe(); case 'bg': return const WidgetsLocalizationBg(); case 'bn': return const WidgetsLocalizationBn(); case 'bs': return const WidgetsLocalizationBs(); case 'ca': return const WidgetsLocalizationCa(); case 'cs': return const WidgetsLocalizationCs(); case 'cy': return const WidgetsLocalizationCy(); case 'da': return const WidgetsLocalizationDa(); case 'de': { switch (locale.countryCode) { case 'CH': return const WidgetsLocalizationDeCh(); } return const WidgetsLocalizationDe(); } case 'el': return const WidgetsLocalizationEl(); case 'en': { switch (locale.countryCode) { case 'AU': return const WidgetsLocalizationEnAu(); case 'CA': return const WidgetsLocalizationEnCa(); case 'GB': return const WidgetsLocalizationEnGb(); case 'IE': return const WidgetsLocalizationEnIe(); case 'IN': return const WidgetsLocalizationEnIn(); case 'NZ': return const WidgetsLocalizationEnNz(); case 'SG': return const WidgetsLocalizationEnSg(); case 'ZA': return const WidgetsLocalizationEnZa(); } return const WidgetsLocalizationEn(); } case 'es': { switch (locale.countryCode) { case '419': return const WidgetsLocalizationEs419(); case 'AR': return const WidgetsLocalizationEsAr(); case 'BO': return const WidgetsLocalizationEsBo(); case 'CL': return const WidgetsLocalizationEsCl(); case 'CO': return const WidgetsLocalizationEsCo(); case 'CR': return const WidgetsLocalizationEsCr(); case 'DO': return const WidgetsLocalizationEsDo(); case 'EC': return const WidgetsLocalizationEsEc(); case 'GT': return const WidgetsLocalizationEsGt(); case 'HN': return const WidgetsLocalizationEsHn(); case 'MX': return const WidgetsLocalizationEsMx(); case 'NI': return const WidgetsLocalizationEsNi(); case 'PA': return const WidgetsLocalizationEsPa(); case 'PE': return const WidgetsLocalizationEsPe(); case 'PR': return const WidgetsLocalizationEsPr(); case 'PY': return const WidgetsLocalizationEsPy(); case 'SV': return const WidgetsLocalizationEsSv(); case 'US': return const WidgetsLocalizationEsUs(); case 'UY': return const WidgetsLocalizationEsUy(); case 'VE': return const WidgetsLocalizationEsVe(); } return const WidgetsLocalizationEs(); } case 'et': return const WidgetsLocalizationEt(); case 'eu': return const WidgetsLocalizationEu(); case 'fa': return const WidgetsLocalizationFa(); case 'fi': return const WidgetsLocalizationFi(); case 'fil': return const WidgetsLocalizationFil(); case 'fr': { switch (locale.countryCode) { case 'CA': return const WidgetsLocalizationFrCa(); } return const WidgetsLocalizationFr(); } case 'gl': return const WidgetsLocalizationGl(); case 'gsw': return const WidgetsLocalizationGsw(); case 'gu': return const WidgetsLocalizationGu(); case 'he': return const WidgetsLocalizationHe(); case 'hi': return const WidgetsLocalizationHi(); case 'hr': return const WidgetsLocalizationHr(); case 'hu': return const WidgetsLocalizationHu(); case 'hy': return const WidgetsLocalizationHy(); case 'id': return const WidgetsLocalizationId(); case 'is': return const WidgetsLocalizationIs(); case 'it': return const WidgetsLocalizationIt(); case 'ja': return const WidgetsLocalizationJa(); case 'ka': return const WidgetsLocalizationKa(); case 'kk': return const WidgetsLocalizationKk(); case 'km': return const WidgetsLocalizationKm(); case 'kn': return const WidgetsLocalizationKn(); case 'ko': return const WidgetsLocalizationKo(); case 'ky': return const WidgetsLocalizationKy(); case 'lo': return const WidgetsLocalizationLo(); case 'lt': return const WidgetsLocalizationLt(); case 'lv': return const WidgetsLocalizationLv(); case 'mk': return const WidgetsLocalizationMk(); case 'ml': return const WidgetsLocalizationMl(); case 'mn': return const WidgetsLocalizationMn(); case 'mr': return const WidgetsLocalizationMr(); case 'ms': return const WidgetsLocalizationMs(); case 'my': return const WidgetsLocalizationMy(); case 'nb': return const WidgetsLocalizationNb(); case 'ne': return const WidgetsLocalizationNe(); case 'nl': return const WidgetsLocalizationNl(); case 'no': return const WidgetsLocalizationNo(); case 'or': return const WidgetsLocalizationOr(); case 'pa': return const WidgetsLocalizationPa(); case 'pl': return const WidgetsLocalizationPl(); case 'ps': return const WidgetsLocalizationPs(); case 'pt': { switch (locale.countryCode) { case 'PT': return const WidgetsLocalizationPtPt(); } return const WidgetsLocalizationPt(); } case 'ro': return const WidgetsLocalizationRo(); case 'ru': return const WidgetsLocalizationRu(); case 'si': return const WidgetsLocalizationSi(); case 'sk': return const WidgetsLocalizationSk(); case 'sl': return const WidgetsLocalizationSl(); case 'sq': return const WidgetsLocalizationSq(); case 'sr': { switch (locale.scriptCode) { case 'Cyrl': { return const WidgetsLocalizationSrCyrl(); } case 'Latn': { return const WidgetsLocalizationSrLatn(); } } return const WidgetsLocalizationSr(); } case 'sv': return const WidgetsLocalizationSv(); case 'sw': return const WidgetsLocalizationSw(); case 'ta': return const WidgetsLocalizationTa(); case 'te': return const WidgetsLocalizationTe(); case 'th': return const WidgetsLocalizationTh(); case 'tl': return const WidgetsLocalizationTl(); case 'tr': return const WidgetsLocalizationTr(); case 'uk': return const WidgetsLocalizationUk(); case 'ur': return const WidgetsLocalizationUr(); case 'uz': return const WidgetsLocalizationUz(); case 'vi': return const WidgetsLocalizationVi(); case 'zh': { switch (locale.scriptCode) { case 'Hans': { return const WidgetsLocalizationZhHans(); } case 'Hant': { switch (locale.countryCode) { case 'HK': return const WidgetsLocalizationZhHantHk(); case 'TW': return const WidgetsLocalizationZhHantTw(); } return const WidgetsLocalizationZhHant(); } } switch (locale.countryCode) { case 'HK': return const WidgetsLocalizationZhHantHk(); case 'TW': return const WidgetsLocalizationZhHantTw(); } return const WidgetsLocalizationZh(); } case 'zu': return const WidgetsLocalizationZu(); } assert(false, 'getWidgetsTranslation() called for unsupported locale "$locale"'); return null; }
flutter/packages/flutter_localizations/lib/src/l10n/generated_widgets_localizations.dart/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/generated_widgets_localizations.dart", "repo_id": "flutter", "token_count": 32777 }
772
{ "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "openAppDrawerTooltip": "Άνοιγμα μενού πλοήγησης", "backButtonTooltip": "Πίσω", "closeButtonTooltip": "Κλείσιμο", "deleteButtonTooltip": "Διαγραφή", "nextMonthTooltip": "Επόμενος μήνας", "previousMonthTooltip": "Προηγούμενος μήνας", "nextPageTooltip": "Επόμενη σελίδα", "previousPageTooltip": "Προηγούμενη σελίδα", "firstPageTooltip": "Πρώτη σελίδα", "lastPageTooltip": "Τελευταία σελίδα", "showMenuTooltip": "Εμφάνιση μενού", "aboutListTileTitle": "Σχετικά με την εφαρμογή $applicationName", "licensesPageTitle": "Άδειες", "pageRowsInfoTitle": "$firstRow-$lastRow από $rowCount", "pageRowsInfoTitleApproximate": "$firstRow-$lastRow από περίπου $rowCount", "rowsPerPageTitle": "Σειρές ανά σελίδα:", "tabLabel": "Καρτέλα $tabIndex από $tabCount", "selectedRowCountTitleOne": "Επιλέχθηκε 1 στοιχείο", "selectedRowCountTitleOther": "Επιλέχθηκαν $selectedRowCount στοιχεία", "cancelButtonLabel": "Ακύρωση", "closeButtonLabel": "Κλείσιμο", "continueButtonLabel": "Συνέχεια", "copyButtonLabel": "Αντιγραφή", "cutButtonLabel": "Αποκοπή", "scanTextButtonLabel": "Σάρωση κειμένου", "okButtonLabel": "ΟΚ", "pasteButtonLabel": "Επικόλληση", "selectAllButtonLabel": "Επιλογή όλων", "viewLicensesButtonLabel": "Προβολή αδειών", "anteMeridiemAbbreviation": "π.μ.", "postMeridiemAbbreviation": "μ.μ.", "timePickerHourModeAnnouncement": "Επιλογή ωρών", "timePickerMinuteModeAnnouncement": "Επιλογή λεπτών", "modalBarrierDismissLabel": "Παράβλεψη", "signedInLabel": "Σε σύνδεση", "hideAccountsLabel": "Απόκρυψη λογαριασμών", "showAccountsLabel": "Εμφάνιση λογαριασμών", "drawerLabel": "Μενού πλοήγησης", "popupMenuLabel": "Αναδυόμενο μενού", "dialogLabel": "Παράθυρο διαλόγου", "alertDialogLabel": "Ειδοποίηση", "searchFieldLabel": "Αναζήτηση", "reorderItemToStart": "Μετακίνηση στην αρχή", "reorderItemToEnd": "Μετακίνηση στο τέλος", "reorderItemUp": "Μετακίνηση προς τα πάνω", "reorderItemDown": "Μετακίνηση προς τα κάτω", "reorderItemLeft": "Μετακίνηση αριστερά", "reorderItemRight": "Μετακίνηση δεξιά", "expandedIconTapHint": "Σύμπτυξη", "collapsedIconTapHint": "Ανάπτυξη", "remainingTextFieldCharacterCountOne": "απομένει 1 χαρακτήρας", "remainingTextFieldCharacterCountOther": "απομένουν $remainingCount χαρακτήρες", "refreshIndicatorSemanticLabel": "Ανανέωση", "moreButtonTooltip": "Περισσότερα", "dateSeparator": "/", "dateHelpText": "μμ/ηη/εεεε", "selectYearSemanticsLabel": "Επιλογή έτους", "unspecifiedDate": "Ημερομηνία", "unspecifiedDateRange": "Εύρος ημερομηνιών", "dateInputLabel": "Εισαγωγή ημερομηνίας", "dateRangeStartLabel": "Ημερομηνία έναρξης", "dateRangeEndLabel": "Ημερομηνία λήξης", "dateRangeStartDateSemanticLabel": "Ημερομηνία έναρξης $fullDate", "dateRangeEndDateSemanticLabel": "Ημερομηνία λήξης $fullDate", "invalidDateFormatLabel": "Μη έγκυρη μορφή.", "invalidDateRangeLabel": "Μη έγκυρο εύρος.", "dateOutOfRangeLabel": "Εκτός εύρους τιμών.", "saveButtonLabel": "Αποθήκευση", "datePickerHelpText": "Επιλογή ημερομηνίας", "dateRangePickerHelpText": "Επιλογή εύρους", "calendarModeButtonLabel": "Εναλλαγή σε ημερολόγιο", "inputDateModeButtonLabel": "Εναλλαγή σε καταχώριση", "timePickerDialHelpText": "Επιλογή ώρας", "timePickerInputHelpText": "Εισαγωγή ώρας", "timePickerHourLabel": "Ώρα", "timePickerMinuteLabel": "Λεπτό", "invalidTimeLabel": "Εισαγάγετε μια έγκυρη ώρα", "dialModeButtonLabel": "Εναλλαγή στη λειτουργία επιλογέα κλήσης", "inputTimeModeButtonLabel": "Εναλλαγή στη λειτουργία εισαγωγής κειμένου", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 άδεια", "licensesPackageDetailTextOther": "$licenseCount άδειες", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Επόμενο κανάλι", "keyboardKeyChannelUp": "Προηγούμενο κανάλι", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Εξαγωγή", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Ενεργοποίηση", "keyboardKeyPowerOff": "Απενεργοποίηση", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Επιλογή", "keyboardKeySpace": "Διάστημα", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Μενού γραμμής μενού", "currentDateLabel": "Σήμερα", "scrimLabel": "Επικάλυψη", "bottomSheetLabel": "Φύλλο κάτω μέρους", "scrimOnTapHint": "Κλείσιμο $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "πατήστε δύο φορές για σύμπτυξη", "expansionTileCollapsedHint": "πατήστε δύο φορές για ανάπτυξη", "expansionTileExpandedTapHint": "Σύμπτυξη", "expansionTileCollapsedTapHint": "Ανάπτυξη για περισσότερες λεπτομέρειες", "expandedHint": "Συμπτύχθηκε", "collapsedHint": "Αναπτύχθηκε", "menuDismissLabel": "Παράβλεψη μενού", "lookUpButtonLabel": "Look Up", "searchWebButtonLabel": "Αναζήτηση στον ιστό", "shareButtonLabel": "Κοινοποίηση…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_el.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_el.arb", "repo_id": "flutter", "token_count": 3611 }
773
{ "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "Ireki nabigazio-menua", "backButtonTooltip": "Atzera", "closeButtonTooltip": "Itxi", "deleteButtonTooltip": "Ezabatu", "nextMonthTooltip": "Hurrengo hilabetea", "previousMonthTooltip": "Aurreko hilabetea", "nextPageTooltip": "Hurrengo orria", "previousPageTooltip": "Aurreko orria", "firstPageTooltip": "Lehenengo orria", "lastPageTooltip": "Azken orria", "showMenuTooltip": "Erakutsi menua", "aboutListTileTitle": "$applicationName aplikazioari buruz", "licensesPageTitle": "Lizentziak", "pageRowsInfoTitle": "$firstRow - $lastRow / $rowCount", "pageRowsInfoTitleApproximate": "$firstRow - $lastRow / $rowCount", "rowsPerPageTitle": "Errenkadak orriko:", "tabLabel": "$tabIndex/$tabCount fitxa", "selectedRowCountTitleOne": "1 elementu hautatu da", "selectedRowCountTitleOther": "$selectedRowCount elementu hautatu dira", "cancelButtonLabel": "Utzi", "closeButtonLabel": "Itxi", "continueButtonLabel": "Egin aurrera", "copyButtonLabel": "Kopiatu", "cutButtonLabel": "Ebaki", "scanTextButtonLabel": "Eskaneatu testua", "okButtonLabel": "Ados", "pasteButtonLabel": "Itsatsi", "selectAllButtonLabel": "Hautatu guztiak", "viewLicensesButtonLabel": "Ikusi lizentziak", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Hautatu orduak", "timePickerMinuteModeAnnouncement": "Hautatu minutuak", "modalBarrierDismissLabel": "Baztertu", "signedInLabel": "Hasi da saioa", "hideAccountsLabel": "Ezkutatu kontuak", "showAccountsLabel": "Erakutsi kontuak", "drawerLabel": "Nabigazio-menua", "popupMenuLabel": "Menu gainerakorra", "dialogLabel": "Leihoa", "alertDialogLabel": "Alerta", "searchFieldLabel": "Bilatu", "reorderItemToStart": "Eraman hasierara", "reorderItemToEnd": "Eraman amaierara", "reorderItemUp": "Eraman gora", "reorderItemDown": "Eraman behera", "reorderItemLeft": "Eraman ezkerrera", "reorderItemRight": "Eraman eskuinera", "expandedIconTapHint": "Tolestu", "collapsedIconTapHint": "Zabaldu", "remainingTextFieldCharacterCountOne": "1 karaktere geratzen da", "remainingTextFieldCharacterCountOther": "$remainingCount karaktere geratzen dira", "refreshIndicatorSemanticLabel": "Freskatu", "moreButtonTooltip": "Gehiago", "dateSeparator": "/", "dateHelpText": "uuuu/hh/ee", "selectYearSemanticsLabel": "Hautatu urtea", "unspecifiedDate": "Data", "unspecifiedDateRange": "Data tartea", "dateInputLabel": "Idatzi data", "dateRangeStartLabel": "Hasiera-data", "dateRangeEndLabel": "Amaiera-data", "dateRangeStartDateSemanticLabel": "Hasiera-data: $fullDate", "dateRangeEndDateSemanticLabel": "Amaiera-data: $fullDate", "invalidDateFormatLabel": "Formatuak ez du balio.", "invalidDateRangeLabel": "Tarteak ez du balio.", "dateOutOfRangeLabel": "Barrutitik kanpo.", "saveButtonLabel": "Gorde", "datePickerHelpText": "Hautatu data", "dateRangePickerHelpText": "Hautatu barrutia", "calendarModeButtonLabel": "Aldatu egutegiaren modura", "inputDateModeButtonLabel": "Aldatu datak aukeratzeko modura", "timePickerDialHelpText": "Hautatu ordua", "timePickerInputHelpText": "Idatzi ordua", "timePickerHourLabel": "Ordua", "timePickerMinuteLabel": "Minutua", "invalidTimeLabel": "Idatzi balio duen ordu bat", "dialModeButtonLabel": "Aldatu esfera hautatzeko modura", "inputTimeModeButtonLabel": "Aldatu testua idazteko modura", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 lizentzia", "licensesPackageDetailTextOther": "$licenseCount lizentzia", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "Alt Gr", "keyboardKeyBackspace": "Atzera tekla", "keyboardKeyCapsLock": "Blok Maius", "keyboardKeyChannelDown": "Jaitsi kanal bat", "keyboardKeyChannelUp": "Igo kanal bat", "keyboardKeyControl": "Ktrl", "keyboardKeyDelete": "Ezab", "keyboardKeyEject": "Kanporatu", "keyboardKeyEnd": "Amaiera", "keyboardKeyEscape": "Ihes", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Hasi", "keyboardKeyInsert": "Txertatu", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Blok Zenb", "keyboardKeyNumpad1": "Zenbakizko teklatuko 1", "keyboardKeyNumpad2": "Zenbakizko teklatuko 2", "keyboardKeyNumpad3": "Zenbakizko teklatuko 3", "keyboardKeyNumpad4": "Zenbakizko teklatuko 4", "keyboardKeyNumpad5": "Zenbakizko teklatuko 5", "keyboardKeyNumpad6": "Zenbakizko teklatuko 6", "keyboardKeyNumpad7": "Zenbakizko teklatuko 7", "keyboardKeyNumpad8": "Zenbakizko teklatuko 8", "keyboardKeyNumpad9": "Zenbakizko teklatuko 9", "keyboardKeyNumpad0": "Zenbakizko teklatuko 0", "keyboardKeyNumpadAdd": "Zenbakizko teklatuko +", "keyboardKeyNumpadComma": "Zenbakizko teklatuko ,", "keyboardKeyNumpadDecimal": "Zenbakizko teklatuko .", "keyboardKeyNumpadDivide": "Zenbakizko teklatuko /", "keyboardKeyNumpadEnter": "Zenbakizko teklatuko Sartu", "keyboardKeyNumpadEqual": "Zenbakizko teklatuko =", "keyboardKeyNumpadMultiply": "Zenbakizko teklatuko *", "keyboardKeyNumpadParenLeft": "Zenbakizko teklatuko (", "keyboardKeyNumpadParenRight": "Zenbakizko teklatuko )", "keyboardKeyNumpadSubtract": "Zenbakizko teklatuko -", "keyboardKeyPageDown": "OrBeh", "keyboardKeyPageUp": "OrGo", "keyboardKeyPower": "Piztu/Itzali", "keyboardKeyPowerOff": "Itzali", "keyboardKeyPrintScreen": "Inp pant", "keyboardKeyScrollLock": "Blok Korr", "keyboardKeySelect": "Hautatu", "keyboardKeySpace": "Zuriune-barra", "keyboardKeyMetaMacOs": "Komandoa", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Menu-barraren menua", "currentDateLabel": "Gaur", "scrimLabel": "Barrera", "bottomSheetLabel": "Behealdeko orria", "scrimOnTapHint": "Itxi $modalRouteContentName", "keyboardKeyShift": "Maius", "expansionTileExpandedHint": "tolesteko, sakatu birritan", "expansionTileCollapsedHint": "zabaltzeko, sakatu birritan", "expansionTileExpandedTapHint": "Tolestu", "expansionTileCollapsedTapHint": "Zabaldu hau xehetasun gehiago lortzeko", "expandedHint": "Tolestuta", "collapsedHint": "Zabalduta", "menuDismissLabel": "Baztertu menua", "lookUpButtonLabel": "Bilatu", "searchWebButtonLabel": "Bilatu sarean", "shareButtonLabel": "Partekatu...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_eu.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_eu.arb", "repo_id": "flutter", "token_count": 2523 }
774
{ "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "selectedRowCountTitleOne": "1 elemento selezionato", "openAppDrawerTooltip": "Apri il menu di navigazione", "backButtonTooltip": "Indietro", "closeButtonTooltip": "Chiudi", "deleteButtonTooltip": "Elimina", "nextMonthTooltip": "Mese successivo", "previousMonthTooltip": "Mese precedente", "nextPageTooltip": "Pagina successiva", "previousPageTooltip": "Pagina precedente", "firstPageTooltip": "Prima pagina", "lastPageTooltip": "Ultima pagina", "showMenuTooltip": "Mostra il menu", "aboutListTileTitle": "Informazioni su $applicationName", "licensesPageTitle": "Licenze", "pageRowsInfoTitle": "$firstRow-$lastRow di $rowCount", "pageRowsInfoTitleApproximate": "$firstRow-$lastRow di circa $rowCount", "rowsPerPageTitle": "Righe per pagina:", "tabLabel": "Scheda $tabIndex di $tabCount", "selectedRowCountTitleOther": "$selectedRowCount elementi selezionati", "cancelButtonLabel": "Annulla", "closeButtonLabel": "Chiudi", "continueButtonLabel": "Continua", "copyButtonLabel": "Copia", "cutButtonLabel": "Taglia", "scanTextButtonLabel": "Scansiona testo", "okButtonLabel": "OK", "pasteButtonLabel": "Incolla", "selectAllButtonLabel": "Seleziona tutto", "viewLicensesButtonLabel": "Visualizza licenze", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Seleziona le ore", "timePickerMinuteModeAnnouncement": "Seleziona i minuti", "signedInLabel": "Connesso", "hideAccountsLabel": "Nascondi account", "showAccountsLabel": "Mostra account", "modalBarrierDismissLabel": "Ignora", "drawerLabel": "Menu di navigazione", "popupMenuLabel": "Menu popup", "dialogLabel": "Finestra di dialogo", "alertDialogLabel": "Avviso", "searchFieldLabel": "Cerca", "reorderItemToStart": "Sposta all'inizio", "reorderItemToEnd": "Sposta alla fine", "reorderItemUp": "Sposta su", "reorderItemDown": "Sposta giù", "reorderItemLeft": "Sposta a sinistra", "reorderItemRight": "Sposta a destra", "expandedIconTapHint": "Comprimi", "collapsedIconTapHint": "Espandi", "remainingTextFieldCharacterCountOne": "1 carattere rimanente", "remainingTextFieldCharacterCountOther": "$remainingCount caratteri rimanenti", "refreshIndicatorSemanticLabel": "Aggiorna", "moreButtonTooltip": "Altro", "dateSeparator": "/", "dateHelpText": "mm/gg/aaaa", "selectYearSemanticsLabel": "Seleziona anno", "unspecifiedDate": "Data", "unspecifiedDateRange": "Intervallo di date", "dateInputLabel": "Inserisci data", "dateRangeStartLabel": "Data di inizio", "dateRangeEndLabel": "Data di fine", "dateRangeStartDateSemanticLabel": "Data di inizio $fullDate", "dateRangeEndDateSemanticLabel": "Data di fine $fullDate", "invalidDateFormatLabel": "Formato non valido.", "invalidDateRangeLabel": "Intervallo non valido.", "dateOutOfRangeLabel": "Fuori intervallo.", "saveButtonLabel": "Salva", "datePickerHelpText": "Seleziona data", "dateRangePickerHelpText": "Seleziona intervallo", "calendarModeButtonLabel": "Passa al calendario", "inputDateModeButtonLabel": "Passa alla modalità di immissione", "timePickerDialHelpText": "Seleziona ora", "timePickerInputHelpText": "Inserisci ora", "timePickerHourLabel": "Ora", "timePickerMinuteLabel": "Minuto", "invalidTimeLabel": "Inserisci un orario valido", "dialModeButtonLabel": "Passa alla modalità selettore del quadrante", "inputTimeModeButtonLabel": "Passa alla modalità immissione testo", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 licenza", "licensesPackageDetailTextOther": "$licenseCount licenze", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "Alt Gr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Bloc Maiusc", "keyboardKeyChannelDown": "Canale giù", "keyboardKeyChannelUp": "Canale su", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Canc", "keyboardKeyEject": "Espelli", "keyboardKeyEnd": "Fine", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Ins", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Bloc Num", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Invio", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "Pag giù", "keyboardKeyPageUp": "Pag su", "keyboardKeyPower": "Spegni/Accendi", "keyboardKeyPowerOff": "Spegni", "keyboardKeyPrintScreen": "Stamp", "keyboardKeyScrollLock": "Bloc Scorr", "keyboardKeySelect": "Seleziona", "keyboardKeySpace": "Barra spaziatrice", "keyboardKeyMetaMacOs": "Comando", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Menu barra dei menu", "currentDateLabel": "Oggi", "scrimLabel": "Rete", "bottomSheetLabel": "Riquadro inferiore", "scrimOnTapHint": "Chiudi $modalRouteContentName", "keyboardKeyShift": "Maiusc", "expansionTileExpandedHint": "tocca due volte per comprimere", "expansionTileCollapsedHint": "Tocca due volte per espandere", "expansionTileExpandedTapHint": "comprimere", "expansionTileCollapsedTapHint": "espandere e visualizzare altri dettagli", "expandedHint": "Compresso", "collapsedHint": "Espanso", "menuDismissLabel": "Ignora menu", "lookUpButtonLabel": "Cerca", "searchWebButtonLabel": "Cerca sul web", "shareButtonLabel": "Condividi…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_it.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_it.arb", "repo_id": "flutter", "token_count": 2250 }
775
{ "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": "၁ ခု ရွေးထားသည်", "selectedRowCountTitleOther": "$selectedRowCount ခု ရွေးထားသည်", "cancelButtonLabel": "မလုပ်တော့", "closeButtonLabel": "ပိတ်ရန်", "continueButtonLabel": "ရှေ့ဆက်ရန်", "copyButtonLabel": "မိတ္တူကူးရန်", "cutButtonLabel": "ဖြတ်ယူရန်", "scanTextButtonLabel": "စာသား စကင်ဖတ်ရန်", "okButtonLabel": "OK", "pasteButtonLabel": "ကူးထည့်ရန်", "selectAllButtonLabel": "အားလုံး ရွေးရန်", "viewLicensesButtonLabel": "လိုင်စင်များကြည့်ရန်", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "နာရီကို ရွေးပါ", "timePickerMinuteModeAnnouncement": "မိနစ်ကို ရွေးပါ", "modalBarrierDismissLabel": "ပယ်ရန်", "signedInLabel": "လက်မှတ်ထိုး ဝင်ထားသည်", "hideAccountsLabel": "အကောင့်များကို ဝှက်ရန်", "showAccountsLabel": "အကောင့်များကို ပြရန်", "drawerLabel": "လမ်းညွှန် မီနူး", "popupMenuLabel": "ပေါ့ပ်အပ်မီနူး", "dialogLabel": "ဒိုင်ယာလော့", "alertDialogLabel": "သတိပေးချက်", "searchFieldLabel": "ရှာဖွေရန်", "reorderItemToStart": "အစသို့ ရွှေ့ရန်", "reorderItemToEnd": "အဆုံးသို့ ‌ရွှေ့ရန်", "reorderItemUp": "အပေါ်သို့ ရွှေ့ရန်", "reorderItemDown": "အောက်သို့ရွှေ့ရန်", "reorderItemLeft": "ဘယ်ဘက်သို့ရွှေ့ရန်", "reorderItemRight": "ညာဘက်သို့ရွှေ့ရန်", "expandedIconTapHint": "လျှော့ပြရန်", "collapsedIconTapHint": "ချဲ့ရန်", "remainingTextFieldCharacterCountOne": "အက္ခရာ ၁ လုံးကျန်သည်", "remainingTextFieldCharacterCountOther": "အက္ခရာ $remainingCount လုံးကျန်သည်", "refreshIndicatorSemanticLabel": "ပြန်လည်စတင်ရန်", "moreButtonTooltip": "နောက်ထပ်", "dateSeparator": "-", "dateHelpText": "dd-mm-yyyy", "selectYearSemanticsLabel": "ခုနှစ် ရွေးရန်", "unspecifiedDate": "ရက်စွဲ", "unspecifiedDateRange": "ရက်အပိုင်းအခြား", "dateInputLabel": "ရက်စွဲ ထည့်ရန်", "dateRangeStartLabel": "စတင်သည့် ရက်စွဲ", "dateRangeEndLabel": "ပြီးဆုံးရက်စွဲ", "dateRangeStartDateSemanticLabel": "စတင်သည့် ရက်စွဲ $fullDate", "dateRangeEndDateSemanticLabel": "ပြီးဆုံးရက်စွဲ $fullDate", "invalidDateFormatLabel": "ဖော်မက် မမှန်ကန်ပါ။", "invalidDateRangeLabel": "အပိုင်းအခြား မမှန်ပါ။", "dateOutOfRangeLabel": "အပိုင်းအခြား ပြင်ပတွင်ဖြစ်နေသည်။", "saveButtonLabel": "သိမ်းရန်", "datePickerHelpText": "ရက်စွဲရွေးရန်", "dateRangePickerHelpText": "အပိုင်းအခြားရွေးရန်", "calendarModeButtonLabel": "ပြက္ခဒိန်သို့ ပြောင်းရန်", "inputDateModeButtonLabel": "ထည့်သွင်းမှုသို့ ပြောင်းရန်", "timePickerDialHelpText": "အချိန်ရွေးရန်", "timePickerInputHelpText": "အချိန်ထည့်ရန်", "timePickerHourLabel": "နာရီ", "timePickerMinuteLabel": "မိနစ်", "invalidTimeLabel": "မှန်ကန်သည့်အချိန် ထည့်ပါ", "dialModeButtonLabel": "နံပါတ်ရွေးချယ်ခြင်းမုဒ်သို့ ပြောင်းရန်", "inputTimeModeButtonLabel": "စာသား ထည့်သွင်းမှုမုဒ်သို့ ပြောင်းရန်", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "လိုင်စင် 1 ခု", "licensesPackageDetailTextOther": "လိုင်စင် $licenseCount ခု", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "နောက်ပြန်ခလုတ်", "keyboardKeyCapsLock": "စားလုံးကြီးလော့ခ်", "keyboardKeyChannelDown": "ချန်နယ်အောက်", "keyboardKeyChannelUp": "ချန်နယ်အပေါ်", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "ထုတ်ရန်", "keyboardKeyEnd": "အဆုံး", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "ပင်မခလုတ်", "keyboardKeyInsert": "ထည့်သွင်းခလုတ်", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "နံပါတ်လော့ခ်", "keyboardKeyNumpad1": "နံပါတ် ၁", "keyboardKeyNumpad2": "နံပါတ် ၂", "keyboardKeyNumpad3": "နံပါတ် ၃", "keyboardKeyNumpad4": "နံပါတ် ၄", "keyboardKeyNumpad5": "နံပါတ် ၅", "keyboardKeyNumpad6": "နံပါတ် ၆", "keyboardKeyNumpad7": "နံပါတ် ၇", "keyboardKeyNumpad8": "နံပါတ် ၈", "keyboardKeyNumpad9": "နံပါတ် ၉", "keyboardKeyNumpad0": "နံပါတ် ၀", "keyboardKeyNumpadAdd": "နံပါတ် +", "keyboardKeyNumpadComma": "နံပါတ် ၊", "keyboardKeyNumpadDecimal": "နံပါတ် ။", "keyboardKeyNumpadDivide": "နံပါတ် /", "keyboardKeyNumpadEnter": "နံပါတ် Enter ခလုတ်", "keyboardKeyNumpadEqual": "နံပါတ် =", "keyboardKeyNumpadMultiply": "နံပါတ် *", "keyboardKeyNumpadParenLeft": "နံပါတ် (", "keyboardKeyNumpadParenRight": "နံပါတ် )", "keyboardKeyNumpadSubtract": "နံပါတ် -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "ပါဝါခလုတ်", "keyboardKeyPowerOff": "စက်ပိတ်ရန်", "keyboardKeyPrintScreen": "ပရင့်စခရင်", "keyboardKeyScrollLock": "လှိမ့်သည့်လော့ခ်", "keyboardKeySelect": "ရွေးရန်", "keyboardKeySpace": "နေရာခြားခလုတ်", "keyboardKeyMetaMacOs": "ကွန်မန်း", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "မီနူးဘား မီနူး", "currentDateLabel": "ယနေ့", "scrimLabel": "Scrim", "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_my.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_my.arb", "repo_id": "flutter", "token_count": 6440 }
776
{ "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "Hap menynë e navigimit", "backButtonTooltip": "Prapa", "closeButtonTooltip": "Mbyll", "deleteButtonTooltip": "Fshi", "nextMonthTooltip": "Muaji i ardhshëm", "previousMonthTooltip": "Muaji i mëparshëm", "nextPageTooltip": "Faqja tjetër", "previousPageTooltip": "Faqja e mëparshme", "firstPageTooltip": "Faqja e parë", "lastPageTooltip": "Faqja e fundit", "showMenuTooltip": "Shfaq menynë", "aboutListTileTitle": "Rreth $applicationName", "licensesPageTitle": "Licencat", "pageRowsInfoTitle": "$firstRow–$lastRow nga $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow nga rreth $rowCount", "rowsPerPageTitle": "Rreshtat për faqe:", "tabLabel": "Skeda $tabIndex nga $tabCount", "selectedRowCountTitleOne": "U zgjodh 1 artikull", "selectedRowCountTitleOther": "$selectedRowCount artikuj u zgjodhën", "cancelButtonLabel": "Anulo", "closeButtonLabel": "Mbyll", "continueButtonLabel": "Vazhdo", "copyButtonLabel": "Kopjo", "cutButtonLabel": "Prit", "scanTextButtonLabel": "Skano tekstin", "okButtonLabel": "Në rregull", "pasteButtonLabel": "Ngjit", "selectAllButtonLabel": "Zgjidh të gjitha", "viewLicensesButtonLabel": "Shiko licencat", "anteMeridiemAbbreviation": "paradite", "postMeridiemAbbreviation": "pasdite", "timePickerHourModeAnnouncement": "Zgjidh orët", "timePickerMinuteModeAnnouncement": "Zgjidh minutat", "modalBarrierDismissLabel": "Hiq", "signedInLabel": "Je identifikuar", "hideAccountsLabel": "Fshih llogaritë", "showAccountsLabel": "Shfaq llogaritë", "drawerLabel": "Menyja e navigimit", "popupMenuLabel": "Menyja kërcyese", "dialogLabel": "Dialogu", "alertDialogLabel": "Sinjalizim", "searchFieldLabel": "Kërko", "reorderItemToStart": "Lëvize në fillim", "reorderItemToEnd": "Lëvize në fund", "reorderItemUp": "Lëvize lart", "reorderItemDown": "Lëvize poshtë", "reorderItemLeft": "Lëvize majtas", "reorderItemRight": "Lëvize djathtas", "expandedIconTapHint": "Palos", "collapsedIconTapHint": "Zgjero", "remainingTextFieldCharacterCountOne": "1 karakter i mbetur", "remainingTextFieldCharacterCountOther": "$remainingCount karaktere të mbetura", "refreshIndicatorSemanticLabel": "Rifresko", "moreButtonTooltip": "Më shumë", "dateSeparator": ".", "dateHelpText": "dd.mm.yyyy", "selectYearSemanticsLabel": "Zgjidh vitin", "unspecifiedDate": "Data", "unspecifiedDateRange": "Gama e datave", "dateInputLabel": "Vendos datën", "dateRangeStartLabel": "Data e fillimit", "dateRangeEndLabel": "Data e mbarimit", "dateRangeStartDateSemanticLabel": "Data e fillimit: $fullDate", "dateRangeEndDateSemanticLabel": "Data e mbarimit: $fullDate", "invalidDateFormatLabel": "Format i pavlefshëm.", "invalidDateRangeLabel": "Gamë e pavlefshme.", "dateOutOfRangeLabel": "Jashtë rrezes.", "saveButtonLabel": "Ruaj", "datePickerHelpText": "Zgjidh datën", "dateRangePickerHelpText": "Zgjidh gamën", "calendarModeButtonLabel": "Kalo te kalendari", "inputDateModeButtonLabel": "Kalo te hyrja", "timePickerDialHelpText": "Zgjidh orën", "timePickerInputHelpText": "Fut orën", "timePickerHourLabel": "Ora", "timePickerMinuteLabel": "Minuta", "invalidTimeLabel": "Fut një kohë të vlefshme", "dialModeButtonLabel": "Kalo te modaliteti i zgjedhësit të orës", "inputTimeModeButtonLabel": "Kalo te modaliteti i hyrjes së tekstit", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 licencë", "licensesPackageDetailTextOther": "$licenseCount licenca", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Delete", "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": "Menyja e shiritit të menysë", "currentDateLabel": "Sot", "scrimLabel": "Kanavacë", "bottomSheetLabel": "Fleta e poshtme", "scrimOnTapHint": "Mbyll $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "trokit dy herë për ta palosur", "expansionTileCollapsedHint": "trokit dy herë për ta zgjeruar", "expansionTileExpandedTapHint": "Palos", "expansionTileCollapsedTapHint": "Zgjero për më shumë detaje", "expandedHint": "U palos", "collapsedHint": "U zgjerua", "menuDismissLabel": "Hiqe menynë", "lookUpButtonLabel": "Kërko", "searchWebButtonLabel": "Kërko në ueb", "shareButtonLabel": "Ndaj...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_sq.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_sq.arb", "repo_id": "flutter", "token_count": 2376 }
777
{ "lookUpButtonLabel": "查詢", "searchWebButtonLabel": "搜尋", "shareButtonLabel": "分享…", "scanTextButtonLabel": "掃描文字", "menuDismissLabel": "關閉選單", "expansionTileExpandedHint": "輕觸兩下即可收合", "expansionTileCollapsedHint": "輕觸兩下即可展開", "expansionTileExpandedTapHint": "收合", "expansionTileCollapsedTapHint": "展開更多詳細資料", "expandedHint": "已收合", "collapsedHint": "已展開", "scrimLabel": "紗罩", "bottomSheetLabel": "底部功能表", "scrimOnTapHint": "關閉「$modalRouteContentName」", "currentDateLabel": "今天", "keyboardKeyShift": "Shift 鍵", "menuBarMenuLabel": "選單列選單", "keyboardKeyNumpad8": "數字鍵盤 8", "keyboardKeyChannelDown": "下一個頻道", "keyboardKeyBackspace": "Backspace", "keyboardKeyNumpad4": "數字鍵盤 4", "keyboardKeyNumpad5": "數字鍵盤 5", "keyboardKeyNumpad6": "數字鍵盤 6", "keyboardKeyNumpad7": "數字鍵盤 7", "keyboardKeyNumpad2": "數字鍵盤 2", "keyboardKeyNumpad0": "數字鍵盤 0", "keyboardKeyNumpadAdd": "數字鍵盤 +", "keyboardKeyNumpadComma": "數字鍵盤 ,", "keyboardKeyNumpadDecimal": "數字鍵盤 .", "keyboardKeyNumpadDivide": "數字鍵盤 /", "keyboardKeyNumpadEqual": "數字鍵盤 =", "keyboardKeyNumpadMultiply": "數字鍵盤 *", "keyboardKeyNumpadParenLeft": "數字鍵盤 (", "keyboardKeyInsert": "Insert", "keyboardKeyHome": "Home", "keyboardKeyEnd": "End", "keyboardKeyNumpadParenRight": "數字鍵盤 )", "keyboardKeyFn": "Fn", "keyboardKeyEscape": "Esc", "keyboardKeyEject": "Eject", "keyboardKeyDelete": "Del", "keyboardKeyControl": "Ctrl", "keyboardKeyNumpadSubtract": "數字鍵盤 -", "keyboardKeyChannelUp": "上一個頻道", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeySelect": "Select", "keyboardKeyAltGraph": "AltGr", "keyboardKeyAlt": "Alt", "keyboardKeyMeta": "Meta", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "數字鍵盤 1", "keyboardKeyPageDown": "PgDown", "keyboardKeySpace": "空格", "keyboardKeyNumpad3": "數字鍵盤 3", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeyNumpad9": "數字鍵盤 9", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyPowerOff": "關機", "keyboardKeyPower": "電源", "keyboardKeyPageUp": "PgUp", "keyboardKeyNumpadEnter": "數字鍵盤 Enter", "dialModeButtonLabel": "切換至鐘面挑選器模式", "licensesPackageDetailTextOne": "1 個授權", "timePickerDialHelpText": "選取時間", "timePickerInputHelpText": "輸入時間", "timePickerHourLabel": "時", "timePickerMinuteLabel": "分", "invalidTimeLabel": "請輸入有效的時間", "licensesPackageDetailTextOther": "$licenseCount 個授權", "inputTimeModeButtonLabel": "切換至文字輸入模式", "dateSeparator": "/", "dateInputLabel": "輸入日期", "calendarModeButtonLabel": "切換到日曆模式", "dateRangePickerHelpText": "選取日期範圍", "datePickerHelpText": "選取日期", "saveButtonLabel": "儲存", "dateOutOfRangeLabel": "超出範圍。", "invalidDateRangeLabel": "範圍無效。", "invalidDateFormatLabel": "格式無效。", "dateRangeEndDateSemanticLabel": "結束日期為 $fullDate", "dateRangeStartDateSemanticLabel": "開始日期為 $fullDate", "dateRangeEndLabel": "結束日期", "dateRangeStartLabel": "開始日期", "inputDateModeButtonLabel": "切換到輸入模式", "unspecifiedDateRange": "日期範圍", "unspecifiedDate": "日期", "selectYearSemanticsLabel": "選取年份", "dateHelpText": "yyyy/mm/dd", "moreButtonTooltip": "更多", "tabLabel": "第 $tabIndex 個分頁 (共 $tabCount 個)", "showAccountsLabel": "顯示帳戶", "modalBarrierDismissLabel": "關閉", "hideAccountsLabel": "隱藏帳戶", "signedInLabel": "已登入帳戶", "scriptCategory": "dense", "timeOfDayFormat": "ah:mm", "openAppDrawerTooltip": "開啟導覽選單", "backButtonTooltip": "返回", "closeButtonTooltip": "關閉", "deleteButtonTooltip": "刪除", "nextMonthTooltip": "下個月", "previousMonthTooltip": "上個月", "nextPageTooltip": "下一頁", "previousPageTooltip": "上一頁", "firstPageTooltip": "第一頁", "lastPageTooltip": "最後一頁", "showMenuTooltip": "顯示選單", "aboutListTileTitle": "關於「$applicationName」", "licensesPageTitle": "授權", "pageRowsInfoTitle": "第 $firstRow - $lastRow 列 (總共 $rowCount 列)", "pageRowsInfoTitleApproximate": "第 $firstRow - $lastRow 列 (總共約 $rowCount 列)", "rowsPerPageTitle": "每頁列數:", "selectedRowCountTitleOne": "已選取 1 個項目", "selectedRowCountTitleOther": "已選取 $selectedRowCount 個項目", "cancelButtonLabel": "取消", "closeButtonLabel": "關閉", "continueButtonLabel": "繼續", "copyButtonLabel": "複製", "cutButtonLabel": "剪下", "okButtonLabel": "確定", "pasteButtonLabel": "貼上", "selectAllButtonLabel": "全選", "viewLicensesButtonLabel": "查看授權", "anteMeridiemAbbreviation": "上午", "postMeridiemAbbreviation": "下午", "timePickerHourModeAnnouncement": "選取小時數", "timePickerMinuteModeAnnouncement": "選取分鐘數", "drawerLabel": "導覽選單", "popupMenuLabel": "彈出式選單", "dialogLabel": "對話方塊", "alertDialogLabel": "快訊", "searchFieldLabel": "搜尋", "reorderItemToStart": "移至開頭", "reorderItemToEnd": "移至結尾", "reorderItemUp": "向上移", "reorderItemDown": "向下移", "reorderItemLeft": "向左移", "reorderItemRight": "向右移", "expandedIconTapHint": "收合", "collapsedIconTapHint": "展開", "remainingTextFieldCharacterCountOne": "還可輸入 1 個字元", "remainingTextFieldCharacterCountOther": "還可輸入 $remainingCount 個字元", "refreshIndicatorSemanticLabel": "重新整理" }
flutter/packages/flutter_localizations/lib/src/l10n/material_zh_TW.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_zh_TW.arb", "repo_id": "flutter", "token_count": 2798 }
778
{ "reorderItemToStart": "Teisalda algusesse", "reorderItemToEnd": "Teisalda lõppu", "reorderItemUp": "Teisalda üles", "reorderItemDown": "Teisalda alla", "reorderItemLeft": "Teisalda vasakule", "reorderItemRight": "Teisalda paremale" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_et.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_et.arb", "repo_id": "flutter", "token_count": 110 }
779
{ "reorderItemToStart": "Færa fremst", "reorderItemToEnd": "Færa aftast", "reorderItemUp": "Færa upp", "reorderItemDown": "Færa niður", "reorderItemLeft": "Færa til vinstri", "reorderItemRight": "Færa til hægri" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_is.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_is.arb", "repo_id": "flutter", "token_count": 103 }
780
{ "reorderItemToStart": "Alih ke permulaan", "reorderItemToEnd": "Alih ke penghujung", "reorderItemUp": "Alih ke atas", "reorderItemDown": "Alih ke bawah", "reorderItemLeft": "Alih ke kiri", "reorderItemRight": "Alih ke kanan" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_ms.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_ms.arb", "repo_id": "flutter", "token_count": 100 }
781
{ "reorderItemToStart": "Premakni na začetek", "reorderItemToEnd": "Premakni na konec", "reorderItemUp": "Premakni navzgor", "reorderItemDown": "Premakni navzdol", "reorderItemLeft": "Premakni levo", "reorderItemRight": "Premakni desno" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_sl.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_sl.arb", "repo_id": "flutter", "token_count": 105 }
782
{ "reorderItemToStart": "移到開頭", "reorderItemToEnd": "移到最後", "reorderItemUp": "向上移", "reorderItemDown": "向下移", "reorderItemLeft": "向左移", "reorderItemRight": "向右移" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_zh_HK.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_zh_HK.arb", "repo_id": "flutter", "token_count": 112 }
783
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Encodes ARB file resource values with Unicode escapes. void encodeBundleTranslations(Map<String, dynamic> bundle) { for (final String key in bundle.keys) { // The ARB file resource "attributes" for foo are called @foo. Don't need // to encode them. if (key.startsWith('@')) { continue; } final String translation = bundle[key] as String; // Rewrite the string as a series of unicode characters in JSON format. // Like "\u0012\u0123\u1234". bundle[key] = translation.runes.map((int code) { final String codeString = '00${code.toRadixString(16)}'; return '\\u${codeString.substring(codeString.length - 4)}'; }).join(); } } String generateArbString(Map<String, dynamic> bundle) { final StringBuffer contents = StringBuffer(); contents.writeln('{'); for (final String key in bundle.keys) { contents.writeln(' "$key": "${bundle[key]}"${key == bundle.keys.last ? '' : ','}'); } contents.writeln('}'); return contents.toString(); }
flutter/packages/flutter_localizations/test/test_utils.dart/0
{ "file_path": "flutter/packages/flutter_localizations/test/test_utils.dart", "repo_id": "flutter", "token_count": 390 }
784
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/widgets.dart'; import 'binding.dart'; /// Ensure the appropriate test binding is initialized. TestWidgetsFlutterBinding ensureInitialized([@visibleForTesting Map<String, String>? environment]) { return AutomatedTestWidgetsFlutterBinding.ensureInitialized(); } /// This method is a noop on the web. void setupHttpOverrides() { } /// This method is a noop on the web. void mockFlutterAssets() { }
flutter/packages/flutter_test/lib/src/_binding_web.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/_binding_web.dart", "repo_id": "flutter", "token_count": 168 }
785
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' as ui show Image, Paragraph; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:matcher/expect.dart'; import 'finders.dart'; import 'recording_canvas.dart'; import 'test_async_utils.dart'; // Examples can assume: // late RenderObject myRenderObject; // late Symbol methodName; /// Matches objects or functions that paint a display list that matches the /// canvas calls described by the pattern. /// /// Specifically, this can be applied to [RenderObject]s, [Finder]s that /// correspond to a single [RenderObject], and functions that have either of the /// following signatures: /// /// ```dart /// void exampleOne(PaintingContext context, Offset offset) { } /// void exampleTwo(Canvas canvas) { } /// ``` /// /// In the case of functions that take a [PaintingContext] and an [Offset], the /// [paints] matcher will always pass a zero offset. /// /// To specify the pattern, call the methods on the returned object. For example: /// /// ```dart /// expect(myRenderObject, paints..circle(radius: 10.0)..circle(radius: 20.0)); /// ``` /// /// This particular pattern would verify that the render object `myRenderObject` /// paints, among other things, two circles of radius 10.0 and 20.0 (in that /// order). /// /// See [PaintPattern] for a discussion of the semantics of paint patterns. /// /// To match something which paints nothing, see [paintsNothing]. /// /// To match something which asserts instead of painting, see [paintsAssertion]. PaintPattern get paints => _TestRecordingCanvasPatternMatcher(); /// Matches objects or functions that does not paint anything on the canvas. Matcher get paintsNothing => _TestRecordingCanvasPaintsNothingMatcher(); /// Matches objects or functions that assert when they try to paint. Matcher get paintsAssertion => _TestRecordingCanvasPaintsAssertionMatcher(); /// Matches objects or functions that draw `methodName` exactly `count` number /// of times. Matcher paintsExactlyCountTimes(Symbol methodName, int count) { return _TestRecordingCanvasPaintsCountMatcher(methodName, count); } /// Signature for the [PaintPattern.something] and [PaintPattern.everything] /// predicate argument. /// /// Used by the [paints] matcher. /// /// The `methodName` argument is a [Symbol], and can be compared with the symbol /// literal syntax, for example: /// /// ```dart /// if (methodName == #drawCircle) { /// // ... /// } /// ``` typedef PaintPatternPredicate = bool Function(Symbol methodName, List<dynamic> arguments); /// The signature of [RenderObject.paint] functions. typedef _ContextPainterFunction = void Function(PaintingContext context, Offset offset); /// The signature of functions that paint directly on a canvas. typedef _CanvasPainterFunction = void Function(Canvas canvas); /// Builder interface for patterns used to match display lists (canvas calls). /// /// The [paints] matcher returns a [PaintPattern] so that you can build the /// pattern in the [expect] call. /// /// Patterns are subset matches, meaning that any calls not described by the /// pattern are ignored. This allows, for instance, transforms to be skipped. abstract class PaintPattern { /// Indicates that a transform is expected next. /// /// Calls are skipped until a call to [Canvas.transform] is found. The call's /// arguments are compared to those provided here. If any fail to match, or if /// no call to [Canvas.transform] is found, then the matcher fails. /// /// Dynamic so matchers can be more easily passed in. /// /// The `matrix4` argument is dynamic so it can be either a [Matcher], or a /// [Float64List] of [double]s. If it is a [Float64List] of [double]s then /// each value in the matrix must match in the expected matrix. A deep /// matching [Matcher] such as [equals] can be used to test each value in the /// matrix with utilities such as [moreOrLessEquals]. void transform({ dynamic matrix4 }); /// Indicates that a translation transform is expected next. /// /// Calls are skipped until a call to [Canvas.translate] is found. The call's /// arguments are compared to those provided here. If any fail to match, or if /// no call to [Canvas.translate] is found, then the matcher fails. void translate({ double? x, double? y }); /// Indicates that a scale transform is expected next. /// /// Calls are skipped until a call to [Canvas.scale] is found. The call's /// arguments are compared to those provided here. If any fail to match, or if /// no call to [Canvas.scale] is found, then the matcher fails. void scale({ double? x, double? y }); /// Indicates that a rotate transform is expected next. /// /// Calls are skipped until a call to [Canvas.rotate] is found. If the `angle` /// argument is provided here, the call's argument is compared to it. If that /// fails to match, or if no call to [Canvas.rotate] is found, then the /// matcher fails. void rotate({ double? angle }); /// Indicates that a save is expected next. /// /// Calls are skipped until a call to [Canvas.save] is found. If none is /// found, the matcher fails. /// /// See also: /// /// * [restore], which indicates that a restore is expected next. /// * [saveRestore], which indicates that a matching pair of save/restore /// calls is expected next. void save(); /// Indicates that a restore is expected next. /// /// Calls are skipped until a call to [Canvas.restore] is found. If none is /// found, the matcher fails. /// /// See also: /// /// * [save], which indicates that a save is expected next. /// * [saveRestore], which indicates that a matching pair of save/restore /// calls is expected next. void restore(); /// Indicates that a matching pair of save/restore calls is expected next. /// /// Calls are skipped until a call to [Canvas.save] is found, then, calls are /// skipped until the matching [Canvas.restore] call is found. If no matching /// pair of calls could be found, the matcher fails. /// /// See also: /// /// * [save], which indicates that a save is expected next. /// * [restore], which indicates that a restore is expected next. void saveRestore(); /// Indicates that a rectangular clip is expected next. /// /// The next rectangular clip is examined. Any arguments that are passed to /// this method are compared to the actual [Canvas.clipRect] call's argument /// and any mismatches result in failure. /// /// If no call to [Canvas.clipRect] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.clipRect] call are ignored. void clipRect({ Rect? rect }); /// Indicates that a path clip is expected next. /// /// The next path clip is examined. /// The path that is passed to the actual [Canvas.clipPath] call is matched /// using [pathMatcher]. /// /// If no call to [Canvas.clipPath] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.clipPath] call are ignored. void clipPath({ Matcher? pathMatcher }); /// Indicates that a rectangle is expected next. /// /// The next rectangle is examined. Any arguments that are passed to this /// method are compared to the actual [Canvas.drawRect] call's arguments /// and any mismatches result in failure. /// /// If no call to [Canvas.drawRect] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawRect] call are ignored. /// /// The [Paint]-related arguments (`color`, `strokeWidth`, `hasMaskFilter`, /// `style`) are compared against the state of the [Paint] object after the /// painting has completed, not at the time of the call. If the same [Paint] /// object is reused multiple times, then this may not match the actual /// arguments as they were seen by the method. void rect({ Rect? rect, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }); /// Indicates that a rounded rectangle clip is expected next. /// /// The next rounded rectangle clip is examined. Any arguments that are passed /// to this method are compared to the actual [Canvas.clipRRect] call's /// argument and any mismatches result in failure. /// /// If no call to [Canvas.clipRRect] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.clipRRect] call are ignored. void clipRRect({ RRect? rrect }); /// Indicates that a rounded rectangle is expected next. /// /// The next rounded rectangle is examined. Any arguments that are passed to /// this method are compared to the actual [Canvas.drawRRect] call's arguments /// and any mismatches result in failure. /// /// If no call to [Canvas.drawRRect] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawRRect] call are ignored. /// /// The [Paint]-related arguments (`color`, `strokeWidth`, `hasMaskFilter`, /// `style`) are compared against the state of the [Paint] object after the /// painting has completed, not at the time of the call. If the same [Paint] /// object is reused multiple times, then this may not match the actual /// arguments as they were seen by the method. void rrect({ RRect? rrect, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }); /// Indicates that a rounded rectangle outline is expected next. /// /// The next call to [Canvas.drawRRect] is examined. Any arguments that are /// passed to this method are compared to the actual [Canvas.drawRRect] call's /// arguments and any mismatches result in failure. /// /// If no call to [Canvas.drawRRect] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawRRect] call are ignored. /// /// The [Paint]-related arguments (`color`, `strokeWidth`, `hasMaskFilter`, /// `style`) are compared against the state of the [Paint] object after the /// painting has completed, not at the time of the call. If the same [Paint] /// object is reused multiple times, then this may not match the actual /// arguments as they were seen by the method. void drrect({ RRect? outer, RRect? inner, Color? color, double strokeWidth, bool hasMaskFilter, PaintingStyle style }); /// Indicates that a circle is expected next. /// /// The next circle is examined. Any arguments that are passed to this method /// are compared to the actual [Canvas.drawCircle] call's arguments and any /// mismatches result in failure. /// /// If no call to [Canvas.drawCircle] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawCircle] call are ignored. /// /// The [Paint]-related arguments (`color`, `strokeWidth`, `hasMaskFilter`, /// `style`) are compared against the state of the [Paint] object after the /// painting has completed, not at the time of the call. If the same [Paint] /// object is reused multiple times, then this may not match the actual /// arguments as they were seen by the method. void circle({ double? x, double? y, double? radius, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }); /// Indicates that a path is expected next. /// /// The next path is examined. Any arguments that are passed to this method /// are compared to the actual [Canvas.drawPath] call's `paint` argument, and /// any mismatches result in failure. /// /// To introspect the Path object (as it stands after the painting has /// completed), the `includes` and `excludes` arguments can be provided to /// specify points that should be considered inside or outside the path /// (respectively). /// /// If no call to [Canvas.drawPath] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawPath] call are ignored. /// /// The [Paint]-related arguments (`color`, `strokeWidth`, `hasMaskFilter`, /// `style`) are compared against the state of the [Paint] object after the /// painting has completed, not at the time of the call. If the same [Paint] /// object is reused multiple times, then this may not match the actual /// arguments as they were seen by the method. void path({ Iterable<Offset>? includes, Iterable<Offset>? excludes, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }); /// Indicates that a line is expected next. /// /// The next line is examined. Any arguments that are passed to this method /// are compared to the actual [Canvas.drawLine] call's `p1`, `p2`, and /// `paint` arguments, and any mismatches result in failure. /// /// If no call to [Canvas.drawLine] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawLine] call are ignored. /// /// The [Paint]-related arguments (`color`, `strokeWidth`, `hasMaskFilter`, /// `style`) are compared against the state of the [Paint] object after the /// painting has completed, not at the time of the call. If the same [Paint] /// object is reused multiple times, then this may not match the actual /// arguments as they were seen by the method. void line({ Offset? p1, Offset? p2, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }); /// Indicates that an arc is expected next. /// /// The next arc is examined. Any arguments that are passed to this method /// are compared to the actual [Canvas.drawArc] call's `paint` argument, and /// any mismatches result in failure. /// /// If no call to [Canvas.drawArc] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawArc] call are ignored. /// /// The [Paint]-related arguments (`color`, `strokeWidth`, `hasMaskFilter`, /// `style`) are compared against the state of the [Paint] object after the /// painting has completed, not at the time of the call. If the same [Paint] /// object is reused multiple times, then this may not match the actual /// arguments as they were seen by the method. void arc({ Rect? rect, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style, StrokeCap? strokeCap }); /// Indicates that a paragraph is expected next. /// /// Calls are skipped until a call to [Canvas.drawParagraph] is found. Any /// arguments that are passed to this method are compared to the actual /// [Canvas.drawParagraph] call's argument, and any mismatches result in /// failure. /// /// The `offset` argument can be either an [Offset] or a [Matcher]. If it is /// an [Offset] then the actual value must match the expected offset /// precisely. If it is a [Matcher] then the comparison is made according to /// the semantics of the [Matcher]. For example, [within] can be used to /// assert that the actual offset is within a given distance from the expected /// offset. /// /// If no call to [Canvas.drawParagraph] was made, then this results in /// failure. void paragraph({ ui.Paragraph? paragraph, dynamic offset }); /// Indicates that a shadow is expected next. /// /// The next shadow is examined. Any arguments that are passed to this method /// are compared to the actual [Canvas.drawShadow] call's `paint` argument, /// and any mismatches result in failure. /// /// In tests, shadows from framework features such as [BoxShadow] or /// [Material] are disabled by default, and thus this predicate would not /// match. The [debugDisableShadows] flag controls this. /// /// To introspect the Path object (as it stands after the painting has /// completed), the `includes` and `excludes` arguments can be provided to /// specify points that should be considered inside or outside the path /// (respectively). /// /// If no call to [Canvas.drawShadow] was made, then this results in failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawShadow] call are ignored. void shadow({ Iterable<Offset>? includes, Iterable<Offset>? excludes, Color? color, double? elevation, bool? transparentOccluder }); /// Indicates that an image is expected next. /// /// The next call to [Canvas.drawImage] is examined, and its arguments /// compared to those passed to _this_ method. /// /// If no call to [Canvas.drawImage] was made, then this results in /// failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawImage] call are ignored. /// /// The [Paint]-related arguments (`color`, `strokeWidth`, `hasMaskFilter`, /// `style`) are compared against the state of the [Paint] object after the /// painting has completed, not at the time of the call. If the same [Paint] /// object is reused multiple times, then this may not match the actual /// arguments as they were seen by the method. void image({ ui.Image? image, double? x, double? y, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }); /// Indicates that an image subsection is expected next. /// /// The next call to [Canvas.drawImageRect] is examined, and its arguments /// compared to those passed to _this_ method. /// /// If no call to [Canvas.drawImageRect] was made, then this results in /// failure. /// /// Any calls made between the last matched call (if any) and the /// [Canvas.drawImageRect] call are ignored. /// /// The [Paint]-related arguments (`color`, `strokeWidth`, `hasMaskFilter`, /// `style`) are compared against the state of the [Paint] object after the /// painting has completed, not at the time of the call. If the same [Paint] /// object is reused multiple times, then this may not match the actual /// arguments as they were seen by the method. void drawImageRect({ ui.Image? image, Rect? source, Rect? destination, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }); /// Provides a custom matcher. /// /// Each method call after the last matched call (if any) will be passed to /// the given predicate, along with the values of its (positional) arguments. /// /// For each one, the predicate must either return a boolean or throw a /// [String]. /// /// If the predicate returns true, the call is considered a successful match /// and the next step in the pattern is examined. If this was the last step, /// then any calls that were not yet matched are ignored and the [paints] /// [Matcher] is considered a success. /// /// If the predicate returns false, then the call is considered uninteresting /// and the predicate will be called again for the next [Canvas] call that was /// made by the [RenderObject] under test. If this was the last call, then the /// [paints] [Matcher] is considered to have failed. /// /// If the predicate throws a [String], then the [paints] [Matcher] is /// considered to have failed. The thrown string is used in the message /// displayed from the test framework and should be complete sentence /// describing the problem. void something(PaintPatternPredicate predicate); /// Provides a custom matcher. /// /// Each method call after the last matched call (if any) will be passed to /// the given predicate, along with the values of its (positional) arguments. /// /// For each one, the predicate must either return a boolean or throw a /// [String]. /// /// The predicate will be applied to each [Canvas] call until it returns false /// or all of the method calls have been tested. /// /// If the predicate returns false, then the [paints] [Matcher] is considered /// to have failed. If all calls are tested without failing, then the [paints] /// [Matcher] is considered a success. /// /// If the predicate throws a [String], then the [paints] [Matcher] is /// considered to have failed. The thrown string is used in the message /// displayed from the test framework and should be complete sentence /// describing the problem. void everything(PaintPatternPredicate predicate); } /// Matches a [Path] that contains (as defined by [Path.contains]) the given /// `includes` points and does not contain the given `excludes` points. Matcher isPathThat({ Iterable<Offset> includes = const <Offset>[], Iterable<Offset> excludes = const <Offset>[], }) { return _PathMatcher(includes.toList(), excludes.toList()); } class _PathMatcher extends Matcher { _PathMatcher(this.includes, this.excludes); List<Offset> includes; List<Offset> excludes; @override bool matches(Object? object, Map<dynamic, dynamic> matchState) { if (object is! Path) { matchState[this] = 'The given object ($object) was not a Path.'; return false; } final Path path = object; final List<String> errors = <String>[ for (final Offset offset in includes) if (!path.contains(offset)) 'Offset $offset should be inside the path, but is not.', for (final Offset offset in excludes) if (path.contains(offset)) 'Offset $offset should be outside the path, but is not.', ]; if (errors.isEmpty) { return true; } matchState[this] = 'Not all the given points were inside or outside the ' 'path as expected:\n ${errors.join("\n ")}'; return false; } @override Description describe(Description description) { String points(List<Offset> list) { final int count = list.length; if (count == 1) { return 'one particular point'; } return '$count particular points'; } return description.add('A Path that contains ${points(includes)} but does ' 'not contain ${points(excludes)}.'); } @override Description describeMismatch( dynamic item, Description description, Map<dynamic, dynamic> matchState, bool verbose, ) { return description.add(matchState[this] as String); } } class _MismatchedCall extends Error { _MismatchedCall(this.message, this.callIntroduction, this.call); final String message; final String callIntroduction; final RecordedInvocation call; } bool _evaluatePainter(Object? object, Canvas canvas, PaintingContext context) { switch (object) { case final _ContextPainterFunction function: function(context, Offset.zero); case final _CanvasPainterFunction function: function(canvas); case final Finder finder: TestAsyncUtils.guardSync(); final RenderObject? result = finder.evaluate().single.renderObject; return (result?..paint(context, Offset.zero)) != null; case final RenderObject renderObject: renderObject.paint(context, Offset.zero); default: return false; } return true; } abstract class _TestRecordingCanvasMatcher extends Matcher { @override bool matches(Object? object, Map<dynamic, dynamic> matchState) { final TestRecordingCanvas canvas = TestRecordingCanvas(); final TestRecordingPaintingContext context = TestRecordingPaintingContext(canvas); final StringBuffer description = StringBuffer(); String prefixMessage = 'unexpectedly failed.'; bool result = false; try { if (!_evaluatePainter(object, canvas, context)) { matchState[this] = 'was not one of the supported objects for the ' '"paints" matcher.'; return false; } result = _evaluatePredicates(canvas.invocations, description); if (!result) { prefixMessage = 'did not match the pattern.'; } } catch (error, stack) { prefixMessage = 'threw the following exception:'; description.writeln(error.toString()); description.write(stack.toString()); result = false; } if (!result) { if (canvas.invocations.isNotEmpty) { description.write('The complete display list was:'); for (final RecordedInvocation call in canvas.invocations) { description.write('\n * $call'); } } matchState[this] = '$prefixMessage\n$description'; } return result; } bool _evaluatePredicates(Iterable<RecordedInvocation> calls, StringBuffer description); @override Description describeMismatch( dynamic item, Description description, Map<dynamic, dynamic> matchState, bool verbose, ) { return description.add(matchState[this] as String); } } class _TestRecordingCanvasPaintsCountMatcher extends _TestRecordingCanvasMatcher { _TestRecordingCanvasPaintsCountMatcher(Symbol methodName, int count) : _methodName = methodName, _count = count; final Symbol _methodName; final int _count; @override Description describe(Description description) { return description.add('Object or closure painting $_methodName exactly $_count times'); } @override bool _evaluatePredicates(Iterable<RecordedInvocation> calls, StringBuffer description) { int count = 0; for (final RecordedInvocation call in calls) { if (call.invocation.isMethod && call.invocation.memberName == _methodName) { count++; } } if (count != _count) { description.write('It painted $_methodName $count times instead of $_count times.'); } return count == _count; } } class _TestRecordingCanvasPaintsNothingMatcher extends _TestRecordingCanvasMatcher { @override Description describe(Description description) { return description.add('An object or closure that paints nothing.'); } @override bool _evaluatePredicates(Iterable<RecordedInvocation> calls, StringBuffer description) { final Iterable<RecordedInvocation> paintingCalls = _filterCanvasCalls(calls); if (paintingCalls.isEmpty) { return true; } description.write( 'painted something, the first call having the following stack:\n' '${paintingCalls.first.stackToString(indent: " ")}\n', ); return false; } static const List<Symbol> _nonPaintingOperations = <Symbol> [ #save, #restore, ]; // Filters out canvas calls that are not painting anything. static Iterable<RecordedInvocation> _filterCanvasCalls(Iterable<RecordedInvocation> canvasCalls) { return canvasCalls.where((RecordedInvocation canvasCall) => !_nonPaintingOperations.contains(canvasCall.invocation.memberName), ); } } class _TestRecordingCanvasPaintsAssertionMatcher extends Matcher { @override bool matches(Object? object, Map<dynamic, dynamic> matchState) { final TestRecordingCanvas canvas = TestRecordingCanvas(); final TestRecordingPaintingContext context = TestRecordingPaintingContext(canvas); final StringBuffer description = StringBuffer(); String prefixMessage = 'unexpectedly failed.'; bool result = false; try { if (!_evaluatePainter(object, canvas, context)) { matchState[this] = 'was not one of the supported objects for the ' '"paints" matcher.'; return false; } prefixMessage = 'did not assert.'; } on AssertionError { result = true; } catch (error, stack) { prefixMessage = 'threw the following exception:'; description.writeln(error.toString()); description.write(stack.toString()); result = false; } if (!result) { if (canvas.invocations.isNotEmpty) { description.write('The complete display list was:'); for (final RecordedInvocation call in canvas.invocations) { description.write('\n * $call'); } } matchState[this] = '$prefixMessage\n$description'; } return result; } @override Description describe(Description description) { return description.add('An object or closure that asserts when it tries to paint.'); } @override Description describeMismatch( dynamic item, Description description, Map<dynamic, dynamic> matchState, bool verbose, ) { return description.add(matchState[this] as String); } } class _TestRecordingCanvasPatternMatcher extends _TestRecordingCanvasMatcher implements PaintPattern { final List<_PaintPredicate> _predicates = <_PaintPredicate>[]; @override void transform({ dynamic matrix4 }) { _predicates.add(_FunctionPaintPredicate(#transform, <dynamic>[matrix4])); } @override void translate({ double? x, double? y }) { _predicates.add(_FunctionPaintPredicate(#translate, <dynamic>[x, y])); } @override void scale({ double? x, double? y }) { _predicates.add(_FunctionPaintPredicate(#scale, <dynamic>[x, y])); } @override void rotate({ double? angle }) { _predicates.add(_FunctionPaintPredicate(#rotate, <dynamic>[angle])); } @override void save() { _predicates.add(_FunctionPaintPredicate(#save, <dynamic>[])); } @override void restore() { _predicates.add(_FunctionPaintPredicate(#restore, <dynamic>[])); } @override void saveRestore() { _predicates.add(_SaveRestorePairPaintPredicate()); } @override void clipRect({ Rect? rect }) { _predicates.add(_FunctionPaintPredicate(#clipRect, <dynamic>[rect])); } @override void clipPath({ Matcher? pathMatcher }) { _predicates.add(_FunctionPaintPredicate(#clipPath, <dynamic>[pathMatcher])); } @override void rect({ Rect? rect, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }) { _predicates.add(_RectPaintPredicate(rect: rect, color: color, strokeWidth: strokeWidth, hasMaskFilter: hasMaskFilter, style: style)); } @override void clipRRect({ RRect? rrect }) { _predicates.add(_FunctionPaintPredicate(#clipRRect, <dynamic>[rrect])); } @override void rrect({ RRect? rrect, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }) { _predicates.add(_RRectPaintPredicate(rrect: rrect, color: color, strokeWidth: strokeWidth, hasMaskFilter: hasMaskFilter, style: style)); } @override void drrect({ RRect? outer, RRect? inner, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }) { _predicates.add(_DRRectPaintPredicate(outer: outer, inner: inner, color: color, strokeWidth: strokeWidth, hasMaskFilter: hasMaskFilter, style: style)); } @override void circle({ double? x, double? y, double? radius, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }) { _predicates.add(_CirclePaintPredicate(x: x, y: y, radius: radius, color: color, strokeWidth: strokeWidth, hasMaskFilter: hasMaskFilter, style: style)); } @override void path({ Iterable<Offset>? includes, Iterable<Offset>? excludes, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }) { _predicates.add(_PathPaintPredicate(includes: includes, excludes: excludes, color: color, strokeWidth: strokeWidth, hasMaskFilter: hasMaskFilter, style: style)); } @override void line({ Offset? p1, Offset? p2, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }) { _predicates.add(_LinePaintPredicate(p1: p1, p2: p2, color: color, strokeWidth: strokeWidth, hasMaskFilter: hasMaskFilter, style: style)); } @override void arc({ Rect? rect, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style, StrokeCap? strokeCap }) { _predicates.add(_ArcPaintPredicate(rect: rect, color: color, strokeWidth: strokeWidth, hasMaskFilter: hasMaskFilter, style: style, strokeCap: strokeCap)); } @override void paragraph({ ui.Paragraph? paragraph, dynamic offset }) { _predicates.add(_FunctionPaintPredicate(#drawParagraph, <dynamic>[paragraph, offset])); } @override void shadow({ Iterable<Offset>? includes, Iterable<Offset>? excludes, Color? color, double? elevation, bool? transparentOccluder }) { _predicates.add(_ShadowPredicate(includes: includes, excludes: excludes, color: color, elevation: elevation, transparentOccluder: transparentOccluder)); } @override void image({ ui.Image? image, double? x, double? y, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }) { _predicates.add(_DrawImagePaintPredicate(image: image, x: x, y: y, color: color, strokeWidth: strokeWidth, hasMaskFilter: hasMaskFilter, style: style)); } @override void drawImageRect({ ui.Image? image, Rect? source, Rect? destination, Color? color, double? strokeWidth, bool? hasMaskFilter, PaintingStyle? style }) { _predicates.add(_DrawImageRectPaintPredicate(image: image, source: source, destination: destination, color: color, strokeWidth: strokeWidth, hasMaskFilter: hasMaskFilter, style: style)); } @override void something(PaintPatternPredicate predicate) { _predicates.add(_SomethingPaintPredicate(predicate)); } @override void everything(PaintPatternPredicate predicate) { _predicates.add(_EverythingPaintPredicate(predicate)); } @override Description describe(Description description) { if (_predicates.isEmpty) { return description.add('An object or closure and a paint pattern.'); } description.add('Object or closure painting:\n'); return description.addAll( '', '\n', '', _predicates.map<String>((_PaintPredicate predicate) => predicate.toString()), ); } @override bool _evaluatePredicates(Iterable<RecordedInvocation> calls, StringBuffer description) { if (calls.isEmpty) { description.writeln('It painted nothing.'); return false; } if (_predicates.isEmpty) { description.writeln( 'It painted something, but you must now add a pattern to the paints ' 'matcher in the test to verify that it matches the important parts of ' 'the following.', ); return false; } final Iterator<_PaintPredicate> predicate = _predicates.iterator; final Iterator<RecordedInvocation> call = calls.iterator..moveNext(); try { while (predicate.moveNext()) { predicate.current.match(call); } // We allow painting more than expected. } on _MismatchedCall catch (data) { description.writeln(data.message); description.writeln(data.callIntroduction); description.writeln(data.call.stackToString(indent: ' ')); return false; } on String catch (s) { description.writeln(s); try { description.write('The stack of the offending call was:\n${call.current.stackToString(indent: " ")}\n'); } on TypeError catch (_) { // All calls have been evaluated } return false; } return true; } } abstract class _PaintPredicate { void match(Iterator<RecordedInvocation> call); @protected void checkMethod(Iterator<RecordedInvocation> call, Symbol symbol) { int others = 0; final RecordedInvocation firstCall = call.current; while (!call.current.invocation.isMethod || call.current.invocation.memberName != symbol) { others += 1; if (!call.moveNext()) { throw _MismatchedCall( 'It called $others other method${ others == 1 ? "" : "s" } on the ' 'canvas, the first of which was $firstCall, but did not call ' '${_symbolName(symbol)}() at the time where $this was expected.', 'The first method that was called when the call to ' '${_symbolName(symbol)}() was expected, $firstCall, was called with ' 'the following stack:', firstCall, ); } } } @override String toString() { throw FlutterError('$runtimeType does not implement toString.'); } } abstract class _DrawCommandPaintPredicate extends _PaintPredicate { _DrawCommandPaintPredicate( this.symbol, this.name, this.argumentCount, this.paintArgumentIndex, { this.color, this.strokeWidth, this.hasMaskFilter, this.style, this.strokeCap, }); final Symbol symbol; final String name; final int argumentCount; final int paintArgumentIndex; final Color? color; final double? strokeWidth; final bool? hasMaskFilter; final PaintingStyle? style; final StrokeCap? strokeCap; String get methodName => _symbolName(symbol); @override void match(Iterator<RecordedInvocation> call) { checkMethod(call, symbol); final int actualArgumentCount = call.current.invocation.positionalArguments.length; if (actualArgumentCount != argumentCount) { throw FlutterError( 'It called $methodName with $actualArgumentCount ' 'argument${actualArgumentCount == 1 ? "" : "s"}; expected ' '$argumentCount.' ); } verifyArguments(call.current.invocation.positionalArguments); call.moveNext(); } @protected @mustCallSuper void verifyArguments(List<dynamic> arguments) { final Paint paintArgument = arguments[paintArgumentIndex] as Paint; if (color != null && paintArgument.color != color) { throw FlutterError( 'It called $methodName with a paint whose color, ' '${paintArgument.color}, was not exactly the expected color ($color).' ); } if (strokeWidth != null && paintArgument.strokeWidth != strokeWidth) { throw FlutterError( 'It called $methodName with a paint whose strokeWidth, ' '${paintArgument.strokeWidth}, was not exactly the expected ' 'strokeWidth ($strokeWidth).' ); } if (hasMaskFilter != null && (paintArgument.maskFilter != null) != hasMaskFilter) { if (hasMaskFilter!) { throw FlutterError( 'It called $methodName with a paint that did not have a mask filter, ' 'despite expecting one.' ); } else { throw FlutterError( 'It called $methodName with a paint that had a mask filter, ' 'despite not expecting one.' ); } } if (style != null && paintArgument.style != style) { throw FlutterError( 'It called $methodName with a paint whose style, ' '${paintArgument.style}, was not exactly the expected style ($style).' ); } if (strokeCap != null && paintArgument.strokeCap != strokeCap) { throw FlutterError( 'It called $methodName with a paint whose strokeCap, ' '${paintArgument.strokeCap}, was not exactly the expected ' 'strokeCap ($strokeCap).' ); } } @override String toString() { final List<String> description = <String>[]; debugFillDescription(description); String result = name; if (description.isNotEmpty) { result += ' with ${description.join(", ")}'; } return result; } @protected @mustCallSuper void debugFillDescription(List<String> description) { if (color != null) { description.add('$color'); } if (strokeWidth != null) { description.add('strokeWidth: $strokeWidth'); } if (hasMaskFilter != null) { description.add(hasMaskFilter! ? 'a mask filter' : 'no mask filter'); } if (style != null) { description.add('$style'); } } } class _OneParameterPaintPredicate<T> extends _DrawCommandPaintPredicate { _OneParameterPaintPredicate( Symbol symbol, String name, { required this.expected, required super.color, required super.strokeWidth, required super.hasMaskFilter, required super.style, }) : super(symbol, name, 2, 1); final T? expected; @override void verifyArguments(List<dynamic> arguments) { super.verifyArguments(arguments); final T actual = arguments[0] as T; if (expected != null && actual != expected) { throw FlutterError( 'It called $methodName with $T, $actual, which was not exactly the ' 'expected $T ($expected).' ); } } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); if (expected != null) { if (expected.toString().contains(T.toString())) { description.add('$expected'); } else { description.add('$T: $expected'); } } } } class _TwoParameterPaintPredicate<T1, T2> extends _DrawCommandPaintPredicate { _TwoParameterPaintPredicate( Symbol symbol, String name, { required this.expected1, required this.expected2, required super.color, required super.strokeWidth, required super.hasMaskFilter, required super.style, }) : super(symbol, name, 3, 2); final T1? expected1; final T2? expected2; @override void verifyArguments(List<dynamic> arguments) { super.verifyArguments(arguments); final T1 actual1 = arguments[0] as T1; if (expected1 != null && actual1 != expected1) { throw FlutterError( 'It called $methodName with its first argument (a $T1), $actual1, ' 'which was not exactly the expected $T1 ($expected1).' ); } final T2 actual2 = arguments[1] as T2; if (expected2 != null && actual2 != expected2) { throw FlutterError( 'It called $methodName with its second argument (a $T2), $actual2, ' 'which was not exactly the expected $T2 ($expected2).' ); } } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); if (expected1 != null) { if (expected1.toString().contains(T1.toString())) { description.add('$expected1'); } else { description.add('$T1: $expected1'); } } if (expected2 != null) { if (expected2.toString().contains(T2.toString())) { description.add('$expected2'); } else { description.add('$T2: $expected2'); } } } } class _RectPaintPredicate extends _OneParameterPaintPredicate<Rect> { _RectPaintPredicate({ Rect? rect, super.color, super.strokeWidth, super.hasMaskFilter, super.style, }) : super(#drawRect, 'a rectangle', expected: rect); } class _RRectPaintPredicate extends _DrawCommandPaintPredicate { _RRectPaintPredicate({ this.rrect, super.color, super.strokeWidth, super.hasMaskFilter, super.style, }) : super(#drawRRect, 'a rounded rectangle', 2, 1); final RRect? rrect; @override void verifyArguments(List<dynamic> arguments) { super.verifyArguments(arguments); const double eps = .0001; final RRect actual = arguments[0] as RRect; if (rrect != null && ((actual.left - rrect!.left).abs() > eps || (actual.right - rrect!.right).abs() > eps || (actual.top - rrect!.top).abs() > eps || (actual.bottom - rrect!.bottom).abs() > eps || (actual.blRadiusX - rrect!.blRadiusX).abs() > eps || (actual.blRadiusY - rrect!.blRadiusY).abs() > eps || (actual.brRadiusX - rrect!.brRadiusX).abs() > eps || (actual.brRadiusY - rrect!.brRadiusY).abs() > eps || (actual.tlRadiusX - rrect!.tlRadiusX).abs() > eps || (actual.tlRadiusY - rrect!.tlRadiusY).abs() > eps || (actual.trRadiusX - rrect!.trRadiusX).abs() > eps || (actual.trRadiusY - rrect!.trRadiusY).abs() > eps)) { throw FlutterError( 'It called $methodName with RRect, $actual, which was not exactly the ' 'expected RRect ($rrect).' ); } } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); if (rrect != null) { description.add('RRect: $rrect'); } } } class _DRRectPaintPredicate extends _TwoParameterPaintPredicate<RRect, RRect> { _DRRectPaintPredicate({ RRect? inner, RRect? outer, super.color, super.strokeWidth, super.hasMaskFilter, super.style, }) : super(#drawDRRect, 'a rounded rectangle outline', expected1: outer, expected2: inner); } class _CirclePaintPredicate extends _DrawCommandPaintPredicate { _CirclePaintPredicate({ this.x, this.y, this.radius, super.color, super.strokeWidth, super.hasMaskFilter, super.style, }) : super(#drawCircle, 'a circle', 3, 2); final double? x; final double? y; final double? radius; @override void verifyArguments(List<dynamic> arguments) { super.verifyArguments(arguments); final Offset pointArgument = arguments[0] as Offset; if (x != null && y != null) { final Offset point = Offset(x!, y!); if (point != pointArgument) { throw FlutterError( 'It called $methodName with a center coordinate, $pointArgument, ' 'which was not exactly the expected coordinate ($point).' ); } } else { if (x != null && pointArgument.dx != x) { throw FlutterError( 'It called $methodName with a center coordinate, $pointArgument, ' 'whose x-coordinate was not exactly the expected coordinate ' '(${x!.toStringAsFixed(1)}).' ); } if (y != null && pointArgument.dy != y) { throw FlutterError( 'It called $methodName with a center coordinate, $pointArgument, ' 'whose y-coordinate was not exactly the expected coordinate ' '(${y!.toStringAsFixed(1)}).' ); } } final double radiusArgument = arguments[1] as double; if (radius != null && radiusArgument != radius) { throw FlutterError( 'It called $methodName with radius, ' '${radiusArgument.toStringAsFixed(1)}, which was not exactly the ' 'expected radius (${radius!.toStringAsFixed(1)}).' ); } } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); if (x != null && y != null) { description.add('point ${Offset(x!, y!)}'); } else { if (x != null) { description.add('x-coordinate ${x!.toStringAsFixed(1)}'); } if (y != null) { description.add('y-coordinate ${y!.toStringAsFixed(1)}'); } } if (radius != null) { description.add('radius ${radius!.toStringAsFixed(1)}'); } } } class _PathPaintPredicate extends _DrawCommandPaintPredicate { _PathPaintPredicate({ this.includes, this.excludes, super.color, super.strokeWidth, super.hasMaskFilter, super.style, }) : super(#drawPath, 'a path', 2, 1); final Iterable<Offset>? includes; final Iterable<Offset>? excludes; @override void verifyArguments(List<dynamic> arguments) { super.verifyArguments(arguments); final Path pathArgument = arguments[0] as Path; if (includes != null) { for (final Offset offset in includes!) { if (!pathArgument.contains(offset)) { throw FlutterError( 'It called $methodName with a path that unexpectedly did not ' 'contain $offset.' ); } } } if (excludes != null) { for (final Offset offset in excludes!) { if (pathArgument.contains(offset)) { throw FlutterError( 'It called $methodName with a path that unexpectedly contained ' '$offset.' ); } } } } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); if (includes != null && excludes != null) { description.add('that contains $includes and does not contain $excludes'); } else if (includes != null) { description.add('that contains $includes'); } else if (excludes != null) { description.add('that does not contain $excludes'); } } } // TODO(ianh): add arguments to test the length, angle, that kind of thing class _LinePaintPredicate extends _DrawCommandPaintPredicate { _LinePaintPredicate({ this.p1, this.p2, super.color, super.strokeWidth, super.hasMaskFilter, super.style, }) : super(#drawLine, 'a line', 3, 2); final Offset? p1; final Offset? p2; @override void verifyArguments(List<dynamic> arguments) { super.verifyArguments(arguments); // Checks the 3rd argument, a Paint if (arguments.length != 3) { throw FlutterError( 'It called $methodName with ${arguments.length} arguments; expected 3.' ); } final Offset p1Argument = arguments[0] as Offset; final Offset p2Argument = arguments[1] as Offset; if (p1 != null && p1Argument != p1) { throw FlutterError( 'It called $methodName with p1 endpoint, $p1Argument, which was not ' 'exactly the expected endpoint ($p1).' ); } if (p2 != null && p2Argument != p2) { throw FlutterError( 'It called $methodName with p2 endpoint, $p2Argument, which was not ' 'exactly the expected endpoint ($p2).' ); } } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); if (p1 != null) { description.add('end point p1: $p1'); } if (p2 != null) { description.add('end point p2: $p2'); } } } class _ArcPaintPredicate extends _DrawCommandPaintPredicate { _ArcPaintPredicate({ this.rect, super.color, super.strokeWidth, super.hasMaskFilter, super.style, super.strokeCap, }) : super(#drawArc, 'an arc', 5, 4); final Rect? rect; @override void verifyArguments(List<dynamic> arguments) { super.verifyArguments(arguments); final Rect rectArgument = arguments[0] as Rect; if (rect != null && rectArgument != rect) { throw FlutterError( 'It called $methodName with a paint whose rect, $rectArgument, was not ' 'exactly the expected rect ($rect).' ); } } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); if (rect != null) { description.add('rect $rect'); } } } class _ShadowPredicate extends _PaintPredicate { _ShadowPredicate({ this.includes, this.excludes, this.color, this.elevation, this.transparentOccluder }); final Iterable<Offset>? includes; final Iterable<Offset>? excludes; final Color? color; final double? elevation; final bool? transparentOccluder; static const Symbol symbol = #drawShadow; String get methodName => _symbolName(symbol); @protected void verifyArguments(List<dynamic> arguments) { if (arguments.length != 4) { throw FlutterError( 'It called $methodName with ${arguments.length} arguments; expected 4.' ); } final Path pathArgument = arguments[0] as Path; if (includes != null) { for (final Offset offset in includes!) { if (!pathArgument.contains(offset)) { throw FlutterError( 'It called $methodName with a path that unexpectedly did not ' 'contain $offset.' ); } } } if (excludes != null) { for (final Offset offset in excludes!) { if (pathArgument.contains(offset)) { throw FlutterError( 'It called $methodName with a path that unexpectedly contained ' '$offset.' ); } } } final Color actualColor = arguments[1] as Color; if (color != null && actualColor != color) { throw FlutterError( 'It called $methodName with a color, $actualColor, which was not ' 'exactly the expected color ($color).' ); } final double actualElevation = arguments[2] as double; if (elevation != null && actualElevation != elevation) { throw FlutterError( 'It called $methodName with an elevation, $actualElevation, which was ' 'not exactly the expected value ($elevation).' ); } final bool actualTransparentOccluder = arguments[3] as bool; if (transparentOccluder != null && actualTransparentOccluder != transparentOccluder) { throw FlutterError( 'It called $methodName with a transparentOccluder value, ' '$actualTransparentOccluder, which was not exactly the expected value ' '($transparentOccluder).' ); } } @override void match(Iterator<RecordedInvocation> call) { checkMethod(call, symbol); verifyArguments(call.current.invocation.positionalArguments); call.moveNext(); } @protected void debugFillDescription(List<String> description) { if (includes != null && excludes != null) { description.add('that contains $includes and does not contain $excludes'); } else if (includes != null) { description.add('that contains $includes'); } else if (excludes != null) { description.add('that does not contain $excludes'); } if (color != null) { description.add('$color'); } if (elevation != null) { description.add('elevation: $elevation'); } if (transparentOccluder != null) { description.add('transparentOccluder: $transparentOccluder'); } } @override String toString() { final List<String> description = <String>[]; debugFillDescription(description); String result = methodName; if (description.isNotEmpty) { result += ' with ${description.join(", ")}'; } return result; } } class _DrawImagePaintPredicate extends _DrawCommandPaintPredicate { _DrawImagePaintPredicate({ this.image, this.x, this.y, super.color, super.strokeWidth, super.hasMaskFilter, super.style, }) : super(#drawImage, 'an image', 3, 2); final ui.Image? image; final double? x; final double? y; @override void verifyArguments(List<dynamic> arguments) { super.verifyArguments(arguments); final ui.Image imageArgument = arguments[0] as ui.Image; if (image != null && !image!.isCloneOf(imageArgument)) { throw FlutterError( 'It called $methodName with an image, $imageArgument, which was not ' 'exactly the expected image ($image).' ); } final Offset pointArgument = arguments[0] as Offset; if (x != null && y != null) { final Offset point = Offset(x!, y!); if (point != pointArgument) { throw FlutterError( 'It called $methodName with an offset coordinate, $pointArgument, ' 'which was not exactly the expected coordinate ($point).' ); } } else { if (x != null && pointArgument.dx != x) { throw FlutterError( 'It called $methodName with an offset coordinate, $pointArgument, ' 'whose x-coordinate was not exactly the expected coordinate ' '(${x!.toStringAsFixed(1)}).' ); } if (y != null && pointArgument.dy != y) { throw FlutterError( 'It called $methodName with an offset coordinate, $pointArgument, ' 'whose y-coordinate was not exactly the expected coordinate ' '(${y!.toStringAsFixed(1)}).' ); } } } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); if (image != null) { description.add('image $image'); } if (x != null && y != null) { description.add('point ${Offset(x!, y!)}'); } else { if (x != null) { description.add('x-coordinate ${x!.toStringAsFixed(1)}'); } if (y != null) { description.add('y-coordinate ${y!.toStringAsFixed(1)}'); } } } } class _DrawImageRectPaintPredicate extends _DrawCommandPaintPredicate { _DrawImageRectPaintPredicate({ this.image, this.source, this.destination, super.color, super.strokeWidth, super.hasMaskFilter, super.style, }) : super(#drawImageRect, 'an image', 4, 3); final ui.Image? image; final Rect? source; final Rect? destination; @override void verifyArguments(List<dynamic> arguments) { super.verifyArguments(arguments); final ui.Image imageArgument = arguments[0] as ui.Image; if (image != null && !image!.isCloneOf(imageArgument)) { throw FlutterError( 'It called $methodName with an image, $imageArgument, which was not ' 'exactly the expected image ($image).' ); } final Rect sourceArgument = arguments[1] as Rect; if (source != null && sourceArgument != source) { throw FlutterError( 'It called $methodName with a source rectangle, $sourceArgument, which ' 'was not exactly the expected rectangle ($source).' ); } final Rect destinationArgument = arguments[2] as Rect; if (destination != null && destinationArgument != destination) { throw FlutterError( 'It called $methodName with a destination rectangle, ' '$destinationArgument, which was not exactly the expected rectangle ' '($destination).' ); } } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); if (image != null) { description.add('image $image'); } if (source != null) { description.add('source $source'); } if (destination != null) { description.add('destination $destination'); } } } class _SomethingPaintPredicate extends _PaintPredicate { _SomethingPaintPredicate(this.predicate); final PaintPatternPredicate predicate; @override void match(Iterator<RecordedInvocation> call) { RecordedInvocation currentCall; bool testedAllCalls = false; do { if (testedAllCalls) { throw FlutterError( 'It painted methods that the predicate passed to a "something" step, ' 'in the paint pattern, none of which were considered correct.' ); } currentCall = call.current; if (!currentCall.invocation.isMethod) { throw FlutterError( 'It called $currentCall, which was not a method, when the paint ' 'pattern expected a method call' ); } testedAllCalls = !call.moveNext(); } while (!_runPredicate(currentCall.invocation.memberName, currentCall.invocation.positionalArguments)); } bool _runPredicate(Symbol methodName, List<dynamic> arguments) { try { return predicate(methodName, arguments); } on String catch (s) { throw FlutterError( 'It painted something that the predicate passed to a "something" step ' 'in the paint pattern considered incorrect:\n $s\n ' ); } } @override String toString() => 'a "something" step'; } class _EverythingPaintPredicate extends _PaintPredicate { _EverythingPaintPredicate(this.predicate); final PaintPatternPredicate predicate; @override void match(Iterator<RecordedInvocation> call) { do { final RecordedInvocation currentCall = call.current; if (!currentCall.invocation.isMethod) { throw FlutterError( 'It called $currentCall, which was not a method, when the paint ' 'pattern expected a method call' ); } if (!_runPredicate(currentCall.invocation.memberName, currentCall.invocation.positionalArguments)) { throw FlutterError( 'It painted something that the predicate passed to an "everything" ' 'step in the paint pattern considered incorrect.\n' ); } } while (call.moveNext()); } bool _runPredicate(Symbol methodName, List<dynamic> arguments) { try { return predicate(methodName, arguments); } on String catch (s) { throw FlutterError( 'It painted something that the predicate passed to an "everything" step ' 'in the paint pattern considered incorrect:\n $s\n ' ); } } @override String toString() => 'an "everything" step'; } class _FunctionPaintPredicate extends _PaintPredicate { _FunctionPaintPredicate(this.symbol, this.arguments); final Symbol symbol; final List<dynamic> arguments; @override void match(Iterator<RecordedInvocation> call) { checkMethod(call, symbol); if (call.current.invocation.positionalArguments.length != arguments.length) { throw FlutterError( 'It called ${_symbolName(symbol)} with ' '${call.current.invocation.positionalArguments.length} arguments; ' 'expected ${arguments.length}.' ); } for (int index = 0; index < arguments.length; index += 1) { final dynamic actualArgument = call.current.invocation.positionalArguments[index]; final dynamic desiredArgument = arguments[index]; if (desiredArgument is Matcher) { expect(actualArgument, desiredArgument); } else if (desiredArgument != null && desiredArgument != actualArgument) { throw FlutterError( 'It called ${_symbolName(symbol)} with argument $index having value ' '${_valueName(actualArgument)} when ${_valueName(desiredArgument)} ' 'was expected.' ); } } call.moveNext(); } @override String toString() { final List<String> adjectives = <String>[ for (int index = 0; index < arguments.length; index += 1) arguments[index] != null ? _valueName(arguments[index]) : '...', ]; return '${_symbolName(symbol)}(${adjectives.join(", ")})'; } } class _SaveRestorePairPaintPredicate extends _PaintPredicate { @override void match(Iterator<RecordedInvocation> call) { checkMethod(call, #save); int depth = 1; while (depth > 0) { if (!call.moveNext()) { throw FlutterError( 'It did not have a matching restore() for the save() that was found ' 'where $this was expected.' ); } if (call.current.invocation.isMethod) { if (call.current.invocation.memberName == #save) { depth += 1; } else if (call.current.invocation.memberName == #restore) { depth -= 1; } } } call.moveNext(); } @override String toString() => 'a matching save/restore pair'; } String _valueName(Object? value) { if (value is double) { return value.toStringAsFixed(1); } return value.toString(); } // Workaround for https://github.com/dart-lang/sdk/issues/28372 String _symbolName(Symbol symbol) { // WARNING: Assumes a fixed format for Symbol.toString which is *not* // guaranteed anywhere. final String s = '$symbol'; return s.substring(8, s.length - 2); }
flutter/packages/flutter_test/lib/src/mock_canvas.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/mock_canvas.dart", "repo_id": "flutter", "token_count": 21097 }
786
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart' show Tooltip; import 'package:flutter/rendering.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'package:matcher/expect.dart' as matcher_expect; import 'package:meta/meta.dart'; import 'package:test_api/scaffolding.dart' as test_package; import 'binding.dart'; import 'controller.dart'; import 'finders.dart'; import 'matchers.dart'; import 'restoration.dart'; import 'test_async_utils.dart'; import 'test_compat.dart'; import 'test_pointer.dart'; import 'test_text_input.dart'; import 'tree_traversal.dart'; // Keep users from needing multiple imports to test semantics. export 'package:flutter/rendering.dart' show SemanticsHandle; // We re-export the matcher package minus some features that we reimplement. // // - expect is reimplemented below, to catch incorrect async usage. // // - isInstanceOf is reimplemented in matchers.dart because we don't want to // mark it as deprecated (ours is just a method, not a class). // export 'package:matcher/expect.dart' hide expect, isInstanceOf; // We re-export the test package minus some features that we reimplement. // // Specifically: // // - test, group, setUpAll, tearDownAll, setUp, tearDown, and expect would // conflict with our own implementations in test_compat.dart. This handles // setting up a declarer when one is not defined, which can happen when a // test is executed via `flutter run`. // // The test_api package has a deprecation warning to discourage direct use but // that doesn't apply here. export 'package:test_api/hooks.dart' show TestFailure; export 'package:test_api/scaffolding.dart' show OnPlatform, Retry, Skip, Tags, TestOn, Timeout, addTearDown, markTestSkipped, printOnFailure, pumpEventQueue, registerException, spawnHybridCode, spawnHybridUri; /// Signature for callback to [testWidgets] and [benchmarkWidgets]. typedef WidgetTesterCallback = Future<void> Function(WidgetTester widgetTester); // Return the last element that satisfies `test`, or return null if not found. E? _lastWhereOrNull<E>(Iterable<E> list, bool Function(E) test) { late E result; bool foundMatching = false; for (final E element in list) { if (test(element)) { result = element; foundMatching = true; } } if (foundMatching) { return result; } return null; } // Examples can assume: // typedef MyWidget = Placeholder; /// Runs the [callback] inside the Flutter test environment. /// /// Use this function for testing custom [StatelessWidget]s and /// [StatefulWidget]s. /// /// The callback can be asynchronous (using `async`/`await` or /// using explicit [Future]s). /// /// The `timeout` argument specifies the backstop timeout implemented by the /// `test` package. If set, it should be relatively large (minutes). It defaults /// to ten minutes for tests run by `flutter test`, and is unlimited for tests /// run by `flutter run`; specifically, it defaults to /// [TestWidgetsFlutterBinding.defaultTestTimeout]. /// /// If the `semanticsEnabled` parameter is set to `true`, /// [WidgetTester.ensureSemantics] will have been called before the tester is /// passed to the `callback`, and that handle will automatically be disposed /// after the callback is finished. It defaults to true. /// /// This function uses the [test] function in the test package to /// register the given callback as a test. The callback, when run, /// will be given a new instance of [WidgetTester]. The [find] object /// provides convenient widget [Finder]s for use with the /// [WidgetTester]. /// /// When the [variant] argument is set, [testWidgets] will run the test once for /// each value of the [TestVariant.values]. If [variant] is not set, the test /// will be run once using the base test environment. /// /// If the [tags] are passed, they declare user-defined tags that are implemented by /// the `test` package. /// /// The argument [experimentalLeakTesting] is experimental and is not recommended /// for use outside of the Flutter framework. /// When [experimentalLeakTesting] is set, it is used to leak track objects created /// during test execution. /// Otherwise [LeakTesting.settings] is used. /// Adjust [LeakTesting.settings] in flutter_test_config.dart /// (see https://api.flutter.dev/flutter/flutter_test/flutter_test-library.html) /// for the entire package or folder, or in the test's main for a test file /// (don't use [setUp] or [setUpAll]). /// To turn off leak tracking just for one test, set [experimentalLeakTesting] to /// `LeakTrackingForTests.ignore()`. /// /// ## Sample code /// /// ```dart /// testWidgets('MyWidget', (WidgetTester tester) async { /// await tester.pumpWidget(const MyWidget()); /// await tester.tap(find.text('Save')); /// expect(find.text('Success'), findsOneWidget); /// }); /// ``` @isTest void testWidgets( String description, WidgetTesterCallback callback, { bool? skip, test_package.Timeout? timeout, bool semanticsEnabled = true, TestVariant<Object?> variant = const DefaultTestVariant(), dynamic tags, int? retry, LeakTesting? experimentalLeakTesting, }) { assert(variant.values.isNotEmpty, 'There must be at least one value to test in the testing variant.'); final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); final WidgetTester tester = WidgetTester._(binding); for (final dynamic value in variant.values) { final String variationDescription = variant.describeValue(value); // IDEs may make assumptions about the format of this suffix in order to // support running tests directly from the editor (where they may have // access to only the test name, provided by the analysis server). // See https://github.com/flutter/flutter/issues/86659. final String combinedDescription = variationDescription.isNotEmpty ? '$description (variant: $variationDescription)' : description; test( combinedDescription, () { tester._testDescription = combinedDescription; SemanticsHandle? semanticsHandle; tester._recordNumberOfSemanticsHandles(); if (semanticsEnabled) { semanticsHandle = tester.ensureSemantics(); } test_package.addTearDown(binding.postTest); return binding.runTest( () async { binding.reset(); // TODO(ianh): the binding should just do this itself in _runTest debugResetSemanticsIdCounter(); Object? memento; try { memento = await variant.setUp(value); maybeSetupLeakTrackingForTest(experimentalLeakTesting, combinedDescription); await callback(tester); } finally { await variant.tearDown(value, memento); maybeTearDownLeakTrackingForTest(); } semanticsHandle?.dispose(); }, tester._endOfTestVerifications, description: combinedDescription, ); }, skip: skip, timeout: timeout ?? binding.defaultTestTimeout, tags: tags, retry: retry, ); } } /// An abstract base class for describing test environment variants. /// /// These serve as elements of the `variants` argument to [testWidgets]. /// /// Use care when adding more testing variants: it multiplies the number of /// tests which run. This can drastically increase the time it takes to run all /// the tests. abstract class TestVariant<T> { /// A const constructor so that subclasses can be const. const TestVariant(); /// Returns an iterable of the variations that this test dimension represents. /// /// The variations returned should be unique so that the same variation isn't /// needlessly run twice. Iterable<T> get values; /// Returns the string that will be used to both add to the test description, and /// be printed when a test fails for this variation. String describeValue(T value); /// A function that will be called before each value is tested, with the /// value that will be tested. /// /// This function should preserve any state needed to restore the testing /// environment back to its base state when [tearDown] is called in the /// `Object` that is returned. The returned object will then be passed to /// [tearDown] as a `memento` when the test is complete. Future<Object?> setUp(T value); /// A function that is guaranteed to be called after a value is tested, even /// if it throws an exception. /// /// Calling this function must return the testing environment back to the base /// state it was in before [setUp] was called. The [memento] is the object /// returned from [setUp] when it was called. Future<void> tearDown(T value, covariant Object? memento); } /// The [TestVariant] that represents the "default" test that is run if no /// `variants` iterable is specified for [testWidgets]. /// /// This variant can be added into a list of other test variants to provide /// a "control" test where nothing is changed from the base test environment. class DefaultTestVariant extends TestVariant<void> { /// A const constructor for a [DefaultTestVariant]. const DefaultTestVariant(); @override Iterable<void> get values => const <void>[null]; @override String describeValue(void value) => ''; @override Future<void> setUp(void value) async {} @override Future<void> tearDown(void value, void memento) async {} } /// A [TestVariant] that runs tests with [debugDefaultTargetPlatformOverride] /// set to different values of [TargetPlatform]. class TargetPlatformVariant extends TestVariant<TargetPlatform> { /// Creates a [TargetPlatformVariant] that tests the given [values]. const TargetPlatformVariant(this.values); /// Creates a [TargetPlatformVariant] that tests all values from /// the [TargetPlatform] enum. If [excluding] is provided, will test all platforms /// except those in [excluding]. TargetPlatformVariant.all({ Set<TargetPlatform> excluding = const <TargetPlatform>{}, }) : values = TargetPlatform.values.toSet()..removeAll(excluding); /// Creates a [TargetPlatformVariant] that includes platforms that are /// considered desktop platforms. TargetPlatformVariant.desktop() : values = <TargetPlatform>{ TargetPlatform.linux, TargetPlatform.macOS, TargetPlatform.windows, }; /// Creates a [TargetPlatformVariant] that includes platforms that are /// considered mobile platforms. TargetPlatformVariant.mobile() : values = <TargetPlatform>{ TargetPlatform.android, TargetPlatform.iOS, TargetPlatform.fuchsia, }; /// Creates a [TargetPlatformVariant] that tests only the given value of /// [TargetPlatform]. TargetPlatformVariant.only(TargetPlatform platform) : values = <TargetPlatform>{platform}; @override final Set<TargetPlatform> values; @override String describeValue(TargetPlatform value) => value.toString(); @override Future<TargetPlatform?> setUp(TargetPlatform value) async { final TargetPlatform? previousTargetPlatform = debugDefaultTargetPlatformOverride; debugDefaultTargetPlatformOverride = value; return previousTargetPlatform; } @override Future<void> tearDown(TargetPlatform value, TargetPlatform? memento) async { debugDefaultTargetPlatformOverride = memento; } } /// A [TestVariant] that runs separate tests with each of the given values. /// /// To use this variant, define it before the test, and then access /// [currentValue] inside the test. /// /// The values are typically enums, but they don't have to be. The `toString` /// for the given value will be used to describe the variant. Values will have /// their type name stripped from their `toString` output, so that enum values /// will only print the value, not the type. /// /// {@tool snippet} /// This example shows how to set up the test to access the [currentValue]. In /// this example, two tests will be run, one with `value1`, and one with /// `value2`. The test with `value2` will fail. The names of the tests will be: /// /// - `Test handling of TestScenario (value1)` /// - `Test handling of TestScenario (value2)` /// /// ```dart /// enum TestScenario { /// value1, /// value2, /// value3, /// } /// /// final ValueVariant<TestScenario> variants = ValueVariant<TestScenario>( /// <TestScenario>{TestScenario.value1, TestScenario.value2}, /// ); /// void main() { /// testWidgets('Test handling of TestScenario', (WidgetTester tester) async { /// expect(variants.currentValue, equals(TestScenario.value1)); /// }, variant: variants); /// } /// ``` /// {@end-tool} class ValueVariant<T> extends TestVariant<T> { /// Creates a [ValueVariant] that tests the given [values]. ValueVariant(this.values); /// Returns the value currently under test. T? get currentValue => _currentValue; T? _currentValue; @override final Set<T> values; @override String describeValue(T value) => value.toString().replaceFirst('$T.', ''); @override Future<T> setUp(T value) async => _currentValue = value; @override Future<void> tearDown(T value, T memento) async {} } /// The warning message to show when a benchmark is performed with assert on. const String kDebugWarning = ''' ┏╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍┓ ┇ ⚠ THIS BENCHMARK IS BEING RUN IN DEBUG MODE ⚠ ┇ ┡╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍┦ │ │ │ Numbers obtained from a benchmark while asserts are │ │ enabled will not accurately reflect the performance │ │ that will be experienced by end users using release ╎ │ builds. Benchmarks should be run using this command ╎ │ line: "flutter run --profile test.dart" or ┊ │ or "flutter drive --profile -t test.dart". ┊ │ ┊ └─────────────────────────────────────────────────╌┄┈ 🐢 '''; /// Runs the [callback] inside the Flutter benchmark environment. /// /// Use this function for benchmarking custom [StatelessWidget]s and /// [StatefulWidget]s when you want to be able to use features from /// [TestWidgetsFlutterBinding]. The callback, when run, will be given /// a new instance of [WidgetTester]. The [find] object provides /// convenient widget [Finder]s for use with the [WidgetTester]. /// /// The callback can be asynchronous (using `async`/`await` or using /// explicit [Future]s). If it is, then [benchmarkWidgets] will return /// a [Future] that completes when the callback's does. Otherwise, it /// will return a Future that is always complete. /// /// If the callback is asynchronous, make sure you `await` the call /// to [benchmarkWidgets], otherwise it won't run! /// /// If the `semanticsEnabled` parameter is set to `true`, /// [WidgetTester.ensureSemantics] will have been called before the tester is /// passed to the `callback`, and that handle will automatically be disposed /// after the callback is finished. /// /// Benchmarks must not be run in debug mode, because the performance is not /// representative. To avoid this, this function will print a big message if it /// is run in debug mode. Unit tests of this method pass `mayRunWithAsserts`, /// but it should not be used for actual benchmarking. /// /// Example: /// /// main() async { /// assert(false); // fail in debug mode /// await benchmarkWidgets((WidgetTester tester) async { /// await tester.pumpWidget(MyWidget()); /// final Stopwatch timer = Stopwatch()..start(); /// for (int index = 0; index < 10000; index += 1) { /// await tester.tap(find.text('Tap me')); /// await tester.pump(); /// } /// timer.stop(); /// debugPrint('Time taken: ${timer.elapsedMilliseconds}ms'); /// }); /// exit(0); /// } Future<void> benchmarkWidgets( WidgetTesterCallback callback, { bool mayRunWithAsserts = false, bool semanticsEnabled = false, }) { assert(() { if (mayRunWithAsserts) { return true; } debugPrint(kDebugWarning); return true; }()); final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); assert(binding is! AutomatedTestWidgetsFlutterBinding); final WidgetTester tester = WidgetTester._(binding); SemanticsHandle? semanticsHandle; if (semanticsEnabled) { semanticsHandle = tester.ensureSemantics(); } tester._recordNumberOfSemanticsHandles(); return binding.runTest( () async { await callback(tester); semanticsHandle?.dispose(); }, tester._endOfTestVerifications, ); } /// Assert that `actual` matches `matcher`. /// /// See [matcher_expect.expect] for details. This is a variant of that function /// that additionally verifies that there are no asynchronous APIs /// that have not yet resolved. /// /// See also: /// /// * [expectLater] for use with asynchronous matchers. void expect( dynamic actual, dynamic matcher, { String? reason, dynamic skip, // true or a String }) { TestAsyncUtils.guardSync(); matcher_expect.expect(actual, matcher, reason: reason, skip: skip); } /// Assert that `actual` matches `matcher`. /// /// See [matcher_expect.expect] for details. This variant will _not_ check that /// there are no outstanding asynchronous API requests. As such, it can be /// called from, e.g., callbacks that are run during build or layout, or in the /// completion handlers of futures that execute in response to user input. /// /// Generally, it is better to use [expect], which does include checks to ensure /// that asynchronous APIs are not being called. void expectSync( dynamic actual, dynamic matcher, { String? reason, }) { matcher_expect.expect(actual, matcher, reason: reason); } /// Just like [expect], but returns a [Future] that completes when the matcher /// has finished matching. /// /// See [matcher_expect.expectLater] for details. /// /// If the matcher fails asynchronously, that failure is piped to the returned /// future where it can be handled by user code. If it is not handled by user /// code, the test will fail. Future<void> expectLater( dynamic actual, dynamic matcher, { String? reason, dynamic skip, // true or a String }) { // We can't wrap the delegate in a guard, or we'll hit async barriers in // [TestWidgetsFlutterBinding] while we're waiting for the matcher to complete TestAsyncUtils.guardSync(); return matcher_expect.expectLater(actual, matcher, reason: reason, skip: skip) .then<void>((dynamic value) => null); } /// Class that programmatically interacts with widgets and the test environment. /// /// Typically, a test uses [pumpWidget] to load a widget tree (in a manner very /// similar to how [runApp] works in a Flutter application). Then, methods such /// as [tap], [drag], [enterText], [fling], [longPress], etc, can be used to /// interact with the application. The application runs in a [FakeAsync] zone, /// which allows time to be stepped forward deliberately; this is done using the /// [pump] method. /// /// The [expect] function can then be used to examine the state of the /// application, typically using [Finder]s such as those in the [find] /// namespace, and [Matcher]s such as [findsOneWidget]. /// /// ```dart /// testWidgets('MyWidget', (WidgetTester tester) async { /// await tester.pumpWidget(const MyWidget()); /// await tester.tap(find.text('Save')); /// await tester.pump(); // allow the application to handle /// await tester.pump(const Duration(seconds: 1)); // skip past the animation /// expect(find.text('Success'), findsOneWidget); /// }); /// ``` /// /// For convenience, instances of this class (such as the one provided by /// `testWidgets`) can be used as the `vsync` for `AnimationController` objects. /// /// When the binding is [LiveTestWidgetsFlutterBinding], events from /// [LiveTestWidgetsFlutterBinding.deviceEventDispatcher] will be handled in /// [dispatchEvent]. Thus, using `flutter run` to run a test lets one tap on /// the screen to generate [Finder]s relevant to the test. class WidgetTester extends WidgetController implements HitTestDispatcher, TickerProvider { WidgetTester._(super.binding) { if (binding is LiveTestWidgetsFlutterBinding) { (binding as LiveTestWidgetsFlutterBinding).deviceEventDispatcher = this; } } /// The description string of the test currently being run. String get testDescription => _testDescription; String _testDescription = ''; /// The binding instance used by the testing framework. @override TestWidgetsFlutterBinding get binding => super.binding as TestWidgetsFlutterBinding; /// Renders the UI from the given [widget]. /// /// Calls [runApp] with the given widget, then triggers a frame and flushes /// microtasks, by calling [pump] with the same `duration` (if any). The /// supplied [EnginePhase] is the final phase reached during the pump pass; if /// not supplied, the whole pass is executed. /// /// Subsequent calls to this is different from [pump] in that it forces a full /// rebuild of the tree, even if [widget] is the same as the previous call. /// [pump] will only rebuild the widgets that have changed. /// /// This method should not be used as the first parameter to an [expect] or /// [expectLater] call to test that a widget throws an exception. Instead, use /// [TestWidgetsFlutterBinding.takeException]. /// /// {@tool snippet} /// ```dart /// testWidgets('MyWidget asserts invalid bounds', (WidgetTester tester) async { /// await tester.pumpWidget(const MyWidget()); /// expect(tester.takeException(), isAssertionError); // or isNull, as appropriate. /// }); /// ``` /// {@end-tool} /// /// By default, the provided `widget` is rendered into [WidgetTester.view], /// whose properties tests can modify to simulate different scenarios (e.g. /// running on a large/small screen). Tests that want to control the /// [FlutterView] into which content is rendered can set `wrapWithView` to /// false and use [View] widgets in the provided `widget` tree to specify the /// desired [FlutterView]s. /// /// See also [LiveTestWidgetsFlutterBindingFramePolicy], which affects how /// this method works when the test is run with `flutter run`. Future<void> pumpWidget( Widget widget, { Duration? duration, EnginePhase phase = EnginePhase.sendSemanticsUpdate, bool wrapWithView = true, }) { return TestAsyncUtils.guard<void>(() { binding.attachRootWidget(wrapWithView ? binding.wrapWithDefaultView(widget) : widget); binding.scheduleFrame(); return binding.pump(duration, phase); }); } @override Future<List<Duration>> handlePointerEventRecord(Iterable<PointerEventRecord> records) { assert(records.isNotEmpty); return TestAsyncUtils.guard<List<Duration>>(() async { final List<Duration> handleTimeStampDiff = <Duration>[]; DateTime? startTime; for (final PointerEventRecord record in records) { final DateTime now = binding.clock.now(); startTime ??= now; // So that the first event is promised to receive a zero timeDiff final Duration timeDiff = record.timeDelay - now.difference(startTime); if (timeDiff.isNegative) { // Flush all past events handleTimeStampDiff.add(-timeDiff); for (final PointerEvent event in record.events) { binding.handlePointerEventForSource(event, source: TestBindingEventSource.test); } } else { await binding.pump(); await binding.delayed(timeDiff); handleTimeStampDiff.add( binding.clock.now().difference(startTime) - record.timeDelay, ); for (final PointerEvent event in record.events) { binding.handlePointerEventForSource(event, source: TestBindingEventSource.test); } } } await binding.pump(); // This makes sure that a gesture is completed, with no more pointers // active. return handleTimeStampDiff; }); } /// Triggers a frame after `duration` amount of time. /// /// This makes the framework act as if the application had janked (missed /// frames) for `duration` amount of time, and then received a "Vsync" signal /// to paint the application. /// /// For a [FakeAsync] environment (typically in `flutter test`), this advances /// time and timeout counting; for a live environment this delays `duration` /// time. /// /// This is a convenience function that just calls /// [TestWidgetsFlutterBinding.pump]. /// /// See also [LiveTestWidgetsFlutterBindingFramePolicy], which affects how /// this method works when the test is run with `flutter run`. @override Future<void> pump([ Duration? duration, EnginePhase phase = EnginePhase.sendSemanticsUpdate, ]) { return TestAsyncUtils.guard<void>(() => binding.pump(duration, phase)); } /// Triggers a frame after `duration` amount of time, return as soon as the frame is drawn. /// /// This enables driving an artificially high CPU load by rendering frames in /// a tight loop. It must be used with the frame policy set to /// [LiveTestWidgetsFlutterBindingFramePolicy.benchmark]. /// /// Similarly to [pump], this doesn't actually wait for `duration`, just /// advances the clock. Future<void> pumpBenchmark(Duration duration) async { assert(() { final TestWidgetsFlutterBinding widgetsBinding = binding; return widgetsBinding is LiveTestWidgetsFlutterBinding && widgetsBinding.framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark; }()); dynamic caughtException; void handleError(dynamic error, StackTrace stackTrace) => caughtException ??= error; await Future<void>.microtask(() { binding.handleBeginFrame(duration); }).catchError(handleError); await idle(); await Future<void>.microtask(() { binding.handleDrawFrame(); }).catchError(handleError); await idle(); if (caughtException != null) { throw caughtException as Object; // ignore: only_throw_errors, rethrowing caught exception. } } @override Future<int> pumpAndSettle([ Duration duration = const Duration(milliseconds: 100), EnginePhase phase = EnginePhase.sendSemanticsUpdate, Duration timeout = const Duration(minutes: 10), ]) { assert(duration > Duration.zero); assert(timeout > Duration.zero); assert(() { final WidgetsBinding binding = this.binding; if (binding is LiveTestWidgetsFlutterBinding && binding.framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark) { matcher_expect.fail( 'When using LiveTestWidgetsFlutterBindingFramePolicy.benchmark, ' 'hasScheduledFrame is never set to true. This means that pumpAndSettle() ' 'cannot be used, because it has no way to know if the application has ' 'stopped registering new frames.', ); } return true; }()); return TestAsyncUtils.guard<int>(() async { final DateTime endTime = binding.clock.fromNowBy(timeout); int count = 0; do { if (binding.clock.now().isAfter(endTime)) { throw FlutterError('pumpAndSettle timed out'); } await binding.pump(duration, phase); count += 1; } while (binding.hasScheduledFrame); return count; }); } /// Repeatedly pump frames that render the `target` widget with a fixed time /// `interval` as many as `maxDuration` allows. /// /// The `maxDuration` argument is required. The `interval` argument defaults to /// 16.683 milliseconds (59.94 FPS). Future<void> pumpFrames( Widget target, Duration maxDuration, [ Duration interval = const Duration(milliseconds: 16, microseconds: 683), ]) { // The interval following the last frame doesn't have to be within the fullDuration. Duration elapsed = Duration.zero; return TestAsyncUtils.guard<void>(() async { binding.attachRootWidget(binding.wrapWithDefaultView(target)); binding.scheduleFrame(); while (elapsed < maxDuration) { await binding.pump(interval); elapsed += interval; } }); } /// Simulates restoring the state of the widget tree after the application /// is restarted. /// /// The method grabs the current serialized restoration data from the /// [RestorationManager], takes down the widget tree to destroy all in-memory /// state, and then restores the widget tree from the serialized restoration /// data. Future<void> restartAndRestore() async { assert( binding.restorationManager.debugRootBucketAccessed, 'The current widget tree did not inject the root bucket of the RestorationManager and ' 'therefore no restoration data has been collected to restore from. Did you forget to wrap ' 'your widget tree in a RootRestorationScope?', ); return TestAsyncUtils.guard<void>(() async { final RootWidget widget = binding.rootElement!.widget as RootWidget; final TestRestorationData restorationData = binding.restorationManager.restorationData; runApp(Container(key: UniqueKey())); await pump(); binding.restorationManager.restoreFrom(restorationData); binding.attachToBuildOwner(widget); binding.scheduleFrame(); return binding.pump(); }); } /// Retrieves the current restoration data from the [RestorationManager]. /// /// The returned [TestRestorationData] describes the current state of the /// widget tree under test and can be provided to [restoreFrom] to restore /// the widget tree to the state described by this data. Future<TestRestorationData> getRestorationData() async { assert( binding.restorationManager.debugRootBucketAccessed, 'The current widget tree did not inject the root bucket of the RestorationManager and ' 'therefore no restoration data has been collected. Did you forget to wrap your widget tree ' 'in a RootRestorationScope?', ); return binding.restorationManager.restorationData; } /// Restores the widget tree under test to the state described by the /// provided [TestRestorationData]. /// /// The data provided to this method is usually obtained from /// [getRestorationData]. Future<void> restoreFrom(TestRestorationData data) { binding.restorationManager.restoreFrom(data); return pump(); } /// Runs a [callback] that performs real asynchronous work. /// /// This is intended for callers who need to call asynchronous methods where /// the methods spawn isolates or OS threads and thus cannot be executed /// synchronously by calling [pump]. /// /// If callers were to run these types of asynchronous tasks directly in /// their test methods, they run the possibility of encountering deadlocks. /// /// If [callback] completes successfully, this will return the future /// returned by [callback]. /// /// If [callback] completes with an error, the error will be caught by the /// Flutter framework and made available via [takeException], and this method /// will return a future that completes with `null`. /// /// Re-entrant calls to this method are not allowed; callers of this method /// are required to wait for the returned future to complete before calling /// this method again. Attempts to do otherwise will result in a /// [TestFailure] error being thrown. /// /// If your widget test hangs and you are using [runAsync], chances are your /// code depends on the result of a task that did not complete. Fake async /// environment is unable to resolve a future that was created in [runAsync]. /// If you observe such behavior or flakiness, you have a number of options: /// /// * Consider restructuring your code so you do not need [runAsync]. This is /// the optimal solution as widget tests are designed to run in fake async /// environment. /// /// * Expose a [Future] in your application code that signals the readiness of /// your widget tree, then await that future inside [callback]. Future<T?> runAsync<T>( Future<T> Function() callback, { @Deprecated( 'This is no longer supported and has no effect. ' 'This feature was deprecated after v3.12.0-1.1.pre.' ) Duration additionalTime = const Duration(milliseconds: 1000), }) => binding.runAsync<T?>(callback); /// Whether there are any transient callbacks scheduled. /// /// This essentially checks whether all animations have completed. /// /// See also: /// /// * [pumpAndSettle], which essentially calls [pump] until there are no /// scheduled frames. /// * [SchedulerBinding.transientCallbackCount], which is the value on which /// this is based. /// * [SchedulerBinding.hasScheduledFrame], which is true whenever a frame is /// pending. [SchedulerBinding.hasScheduledFrame] is made true when a /// widget calls [State.setState], even if there are no transient callbacks /// scheduled. This is what [pumpAndSettle] uses. bool get hasRunningAnimations => binding.transientCallbackCount > 0; @override HitTestResult hitTestOnBinding(Offset location, {int? viewId}) { viewId ??= view.viewId; final RenderView renderView = binding.renderViews.firstWhere((RenderView r) => r.flutterView.viewId == viewId); location = binding.localToGlobal(location, renderView); return super.hitTestOnBinding(location, viewId: viewId); } @override Future<void> sendEventToBinding(PointerEvent event) { return TestAsyncUtils.guard<void>(() async { binding.handlePointerEventForSource(event, source: TestBindingEventSource.test); }); } /// Handler for device events caught by the binding in live test mode. /// /// [PointerDownEvent]s received here will only print a diagnostic message /// showing possible [Finder]s that can be used to interact with the widget at /// the location of [result]. @override void dispatchEvent(PointerEvent event, HitTestResult result) { if (event is PointerDownEvent) { final RenderObject innerTarget = result.path .map((HitTestEntry candidate) => candidate.target) .whereType<RenderObject>() .first; final Element? innerTargetElement = binding.renderViews.contains(innerTarget) ? null : _lastWhereOrNull( collectAllElementsFrom(binding.rootElement!, skipOffstage: true), (Element element) => element.renderObject == innerTarget, ); if (innerTargetElement == null) { printToConsole('No widgets found at ${event.position}.'); return; } final List<Element> candidates = <Element>[]; innerTargetElement.visitAncestorElements((Element element) { candidates.add(element); return true; }); assert(candidates.isNotEmpty); String? descendantText; int numberOfWithTexts = 0; int numberOfTypes = 0; int totalNumber = 0; printToConsole('Some possible finders for the widgets at ${event.position}:'); for (final Element element in candidates) { if (totalNumber > 13) { break; } totalNumber += 1; // optimistically assume we'll be able to describe it final Widget widget = element.widget; if (widget is Tooltip) { final String message = widget.message ?? widget.richMessage!.toPlainText(); final Iterable<Element> matches = find.byTooltip(message).evaluate(); if (matches.length == 1) { printToConsole(" find.byTooltip('$message')"); continue; } } if (widget is Text) { assert(descendantText == null); assert(widget.data != null || widget.textSpan != null); final String text = widget.data ?? widget.textSpan!.toPlainText(); final Iterable<Element> matches = find.text(text).evaluate(); descendantText = widget.data; if (matches.length == 1) { printToConsole(" find.text('$text')"); continue; } } final Key? key = widget.key; if (key is ValueKey<dynamic>) { String? keyLabel; if (key is ValueKey<int> || key is ValueKey<double> || key is ValueKey<bool>) { keyLabel = 'const ${key.runtimeType}(${key.value})'; } else if (key is ValueKey<String>) { keyLabel = "const Key('${key.value}')"; } if (keyLabel != null) { final Iterable<Element> matches = find.byKey(key).evaluate(); if (matches.length == 1) { printToConsole(' find.byKey($keyLabel)'); continue; } } } if (!_isPrivate(widget.runtimeType)) { if (numberOfTypes < 5) { final Iterable<Element> matches = find.byType(widget.runtimeType).evaluate(); if (matches.length == 1) { printToConsole(' find.byType(${widget.runtimeType})'); numberOfTypes += 1; continue; } } if (descendantText != null && numberOfWithTexts < 5) { final Iterable<Element> matches = find.widgetWithText(widget.runtimeType, descendantText).evaluate(); if (matches.length == 1) { printToConsole(" find.widgetWithText(${widget.runtimeType}, '$descendantText')"); numberOfWithTexts += 1; continue; } } } if (!_isPrivate(element.runtimeType)) { final Iterable<Element> matches = find.byElementType(element.runtimeType).evaluate(); if (matches.length == 1) { printToConsole(' find.byElementType(${element.runtimeType})'); continue; } } totalNumber -= 1; // if we got here, we didn't actually find something to say about it } if (totalNumber == 0) { printToConsole(' <could not come up with any unique finders>'); } } } bool _isPrivate(Type type) { // used above so that we don't suggest matchers for private types return '_'.matchAsPrefix(type.toString()) != null; } /// Returns the exception most recently caught by the Flutter framework. /// /// See [TestWidgetsFlutterBinding.takeException] for details. dynamic takeException() { return binding.takeException(); } /// {@macro flutter.flutter_test.TakeAccessibilityAnnouncements} /// /// See [TestWidgetsFlutterBinding.takeAnnouncements] for details. List<CapturedAccessibilityAnnouncement> takeAnnouncements() { return binding.takeAnnouncements(); } /// Acts as if the application went idle. /// /// Runs all remaining microtasks, including those scheduled as a result of /// running them, until there are no more microtasks scheduled. Then, runs any /// previously scheduled timers with zero time, and completes the returned future. /// /// May result in an infinite loop or run out of memory if microtasks continue /// to recursively schedule new microtasks. Will not run any timers scheduled /// after this method was invoked, even if they are zero-time timers. Future<void> idle() { return TestAsyncUtils.guard<void>(() => binding.idle()); } Set<Ticker>? _tickers; @override Ticker createTicker(TickerCallback onTick) { _tickers ??= <_TestTicker>{}; final _TestTicker result = _TestTicker(onTick, _removeTicker); _tickers!.add(result); return result; } void _removeTicker(_TestTicker ticker) { assert(_tickers != null); assert(_tickers!.contains(ticker)); _tickers!.remove(ticker); } /// Throws an exception if any tickers created by the [WidgetTester] are still /// active when the method is called. /// /// An argument can be specified to provide a string that will be used in the /// error message. It should be an adverbial phrase describing the current /// situation, such as "at the end of the test". void verifyTickersWereDisposed([ String when = 'when none should have been' ]) { if (_tickers != null) { for (final Ticker ticker in _tickers!) { if (ticker.isActive) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('A Ticker was active $when.'), ErrorDescription('All Tickers must be disposed.'), ErrorHint( 'Tickers used by AnimationControllers ' 'should be disposed by calling dispose() on the AnimationController itself. ' 'Otherwise, the ticker will leak.' ), ticker.describeForError('The offending ticker was'), ]); } } } } void _endOfTestVerifications() { verifyTickersWereDisposed('at the end of the test'); _verifySemanticsHandlesWereDisposed(); } void _verifySemanticsHandlesWereDisposed() { assert(_lastRecordedSemanticsHandles != null); // TODO(goderbauer): Fix known leak in web engine when running integration tests and remove this "correction", https://github.com/flutter/flutter/issues/121640. final int knownWebEngineLeakForLiveTestsCorrection = kIsWeb && binding is LiveTestWidgetsFlutterBinding ? 1 : 0; if (_currentSemanticsHandles - knownWebEngineLeakForLiveTestsCorrection > _lastRecordedSemanticsHandles!) { throw FlutterError.fromParts(<DiagnosticsNode>[ ErrorSummary('A SemanticsHandle was active at the end of the test.'), ErrorDescription( 'All SemanticsHandle instances must be disposed by calling dispose() on ' 'the SemanticsHandle.' ), ]); } _lastRecordedSemanticsHandles = null; } int? _lastRecordedSemanticsHandles; // TODO(goderbauer): Only use binding.debugOutstandingSemanticsHandles when deprecated binding.pipelineOwner is removed. int get _currentSemanticsHandles => binding.debugOutstandingSemanticsHandles + binding.pipelineOwner.debugOutstandingSemanticsHandles; void _recordNumberOfSemanticsHandles() { _lastRecordedSemanticsHandles = _currentSemanticsHandles; } /// Returns the TestTextInput singleton. /// /// Typical app tests will not need to use this value. To add text to widgets /// like [TextField] or [TextFormField], call [enterText]. /// /// Some of the properties and methods on this value are only valid if the /// binding's [TestWidgetsFlutterBinding.registerTestTextInput] flag is set to /// true as a test is starting (meaning that the keyboard is to be simulated /// by the test framework). If those members are accessed when using a binding /// that sets this flag to false, they will throw. TestTextInput get testTextInput => binding.testTextInput; /// Give the text input widget specified by [finder] the focus, as if the /// onscreen keyboard had appeared. /// /// Implies a call to [pump]. /// /// The widget specified by [finder] must be an [EditableText] or have /// an [EditableText] descendant. For example `find.byType(TextField)` /// or `find.byType(TextFormField)`, or `find.byType(EditableText)`. /// /// Tests that just need to add text to widgets like [TextField] /// or [TextFormField] only need to call [enterText]. Future<void> showKeyboard(FinderBase<Element> finder) async { bool skipOffstage = true; if (finder is Finder) { skipOffstage = finder.skipOffstage; } return TestAsyncUtils.guard<void>(() async { final EditableTextState editable = state<EditableTextState>( find.descendant( of: finder, matching: find.byType(EditableText, skipOffstage: skipOffstage), matchRoot: true, ), ); // Setting focusedEditable causes the binding to call requestKeyboard() // on the EditableTextState, which itself eventually calls TextInput.attach // to establish the connection. binding.focusedEditable = editable; await pump(); }); } /// Give the text input widget specified by [finder] the focus and replace its /// content with [text], as if it had been provided by the onscreen keyboard. /// /// The widget specified by [finder] must be an [EditableText] or have /// an [EditableText] descendant. For example `find.byType(TextField)` /// or `find.byType(TextFormField)`, or `find.byType(EditableText)`. /// /// When the returned future completes, the text input widget's text will be /// exactly `text`, and the caret will be placed at the end of `text`. /// /// To just give [finder] the focus without entering any text, /// see [showKeyboard]. /// /// To enter text into other widgets (e.g. a custom widget that maintains a /// TextInputConnection the way that a [EditableText] does), first ensure that /// that widget has an open connection (e.g. by using [tap] to focus it), /// then call `testTextInput.enterText` directly (see /// [TestTextInput.enterText]). Future<void> enterText(FinderBase<Element> finder, String text) async { return TestAsyncUtils.guard<void>(() async { await showKeyboard(finder); testTextInput.enterText(text); await idle(); }); } /// Makes an effort to dismiss the current page with a Material [Scaffold] or /// a [CupertinoPageScaffold]. /// /// Will throw an error if there is no back button in the page. Future<void> pageBack() async { return TestAsyncUtils.guard<void>(() async { Finder backButton = find.byTooltip('Back'); if (backButton.evaluate().isEmpty) { backButton = find.byType(CupertinoNavigationBarBackButton); } expectSync(backButton, findsOneWidget, reason: 'One back button expected on screen'); await tap(backButton); }); } @override void printToConsole(String message) { binding.debugPrintOverride(message); } } typedef _TickerDisposeCallback = void Function(_TestTicker ticker); class _TestTicker extends Ticker { _TestTicker(super.onTick, this._onDispose); final _TickerDisposeCallback _onDispose; @override void dispose() { _onDispose(this); super.dispose(); } }
flutter/packages/flutter_test/lib/src/widget_tester.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/widget_tester.dart", "repo_id": "flutter", "token_count": 15446 }
787
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:collection/collection.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stack_trace/stack_trace.dart'; class TestDragData { const TestDragData( this.slop, this.dragDistance, this.expectedOffsets, ); final Offset slop; final Offset dragDistance; final List<Offset> expectedOffsets; } void main() { testWidgets( 'WidgetTester.drag must break the offset into multiple parallel components if ' 'the drag goes outside the touch slop values', (WidgetTester tester) async { // This test checks to make sure that the total drag will be correctly split into // pieces such that the first (and potentially second) moveBy function call(s) in // controller.drag() will never have a component greater than the touch // slop in that component's respective axis. const List<TestDragData> offsetResults = <TestDragData>[ TestDragData( Offset(10.0, 10.0), Offset(-150.0, 200.0), <Offset>[ Offset(-7.5, 10.0), Offset(-2.5, 3.333333333333333), Offset(-140.0, 186.66666666666666), ], ), TestDragData( Offset(10.0, 10.0), Offset(150, -200), <Offset>[ Offset(7.5, -10), Offset(2.5, -3.333333333333333), Offset(140.0, -186.66666666666666), ], ), TestDragData( Offset(10.0, 10.0), Offset(-200, 150), <Offset>[ Offset(-10, 7.5), Offset(-3.333333333333333, 2.5), Offset(-186.66666666666666, 140.0), ], ), TestDragData( Offset(10.0, 10.0), Offset(200.0, -150.0), <Offset>[ Offset(10, -7.5), Offset(3.333333333333333, -2.5), Offset(186.66666666666666, -140.0), ], ), TestDragData( Offset(10.0, 10.0), Offset(-150.0, -200.0), <Offset>[ Offset(-7.5, -10.0), Offset(-2.5, -3.333333333333333), Offset(-140.0, -186.66666666666666), ], ), TestDragData( Offset(10.0, 10.0), Offset(8.0, 3.0), <Offset>[ Offset(8.0, 3.0), ], ), TestDragData( Offset(10.0, 10.0), Offset(3.0, 8.0), <Offset>[ Offset(3.0, 8.0), ], ), TestDragData( Offset(10.0, 10.0), Offset(20.0, 5.0), <Offset>[ Offset(10.0, 2.5), Offset(10.0, 2.5), ], ), TestDragData( Offset(10.0, 10.0), Offset(5.0, 20.0), <Offset>[ Offset(2.5, 10.0), Offset(2.5, 10.0), ], ), TestDragData( Offset(10.0, 10.0), Offset(20.0, 15.0), <Offset>[ Offset(10.0, 7.5), Offset(3.333333333333333, 2.5), Offset(6.666666666666668, 5.0), ], ), TestDragData( Offset(10.0, 10.0), Offset(15.0, 20.0), <Offset>[ Offset(7.5, 10.0), Offset(2.5, 3.333333333333333), Offset(5.0, 6.666666666666668), ], ), TestDragData( Offset(10.0, 10.0), Offset(20.0, 20.0), <Offset>[ Offset(10.0, 10.0), Offset(10.0, 10.0), ], ), TestDragData( Offset(10.0, 10.0), Offset(0.0, 5.0), <Offset>[ Offset(0.0, 5.0), ], ), //// Varying touch slops TestDragData( Offset(12.0, 5.0), Offset(0.0, 5.0), <Offset>[ Offset(0.0, 5.0), ], ), TestDragData( Offset(12.0, 5.0), Offset(20.0, 5.0), <Offset>[ Offset(12.0, 3.0), Offset(8.0, 2.0), ], ), TestDragData( Offset(12.0, 5.0), Offset(5.0, 20.0), <Offset>[ Offset(1.25, 5.0), Offset(3.75, 15.0), ], ), TestDragData( Offset(5.0, 12.0), Offset(5.0, 20.0), <Offset>[ Offset(3.0, 12.0), Offset(2.0, 8.0), ], ), TestDragData( Offset(5.0, 12.0), Offset(20.0, 5.0), <Offset>[ Offset(5.0, 1.25), Offset(15.0, 3.75), ], ), TestDragData( Offset(18.0, 18.0), Offset(0.0, 150.0), <Offset>[ Offset(0.0, 18.0), Offset(0.0, 132.0), ], ), TestDragData( Offset(18.0, 18.0), Offset(0.0, -150.0), <Offset>[ Offset(0.0, -18.0), Offset(0.0, -132.0), ], ), TestDragData( Offset(18.0, 18.0), Offset(-150.0, 0.0), <Offset>[ Offset(-18.0, 0.0), Offset(-132.0, 0.0), ], ), TestDragData( Offset.zero, Offset(-150.0, 0.0), <Offset>[ Offset(-150.0, 0.0), ], ), TestDragData( Offset(18.0, 18.0), Offset(-32.0, 0.0), <Offset>[ Offset(-18.0, 0.0), Offset(-14.0, 0.0), ], ), ]; final List<Offset> dragOffsets = <Offset>[]; await tester.pumpWidget( Listener( onPointerMove: (PointerMoveEvent event) { dragOffsets.add(event.delta); }, child: const Text('test', textDirection: TextDirection.ltr), ), ); for (int resultIndex = 0; resultIndex < offsetResults.length; resultIndex += 1) { final TestDragData testResult = offsetResults[resultIndex]; await tester.drag( find.text('test'), testResult.dragDistance, touchSlopX: testResult.slop.dx, touchSlopY: testResult.slop.dy, ); expect( testResult.expectedOffsets.length, dragOffsets.length, reason: 'There is a difference in the number of expected and actual split offsets for the drag with:\n' 'Touch Slop: ${testResult.slop}\n' 'Delta: ${testResult.dragDistance}\n', ); for (int valueIndex = 0; valueIndex < offsetResults[resultIndex].expectedOffsets.length; valueIndex += 1) { expect( testResult.expectedOffsets[valueIndex], offsetMoreOrLessEquals(dragOffsets[valueIndex]), reason: 'There is a difference in the expected and actual value of the ' '${valueIndex == 2 ? 'first' : valueIndex == 3 ? 'second' : 'third'}' ' split offset for the drag with:\n' 'Touch slop: ${testResult.slop}\n' 'Delta: ${testResult.dragDistance}\n' ); } dragOffsets.clear(); } }, ); testWidgets( 'WidgetTester.tap must respect buttons', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'), onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'), onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'), child: const Text('test'), ), ), ); await tester.tap(find.text('test'), buttons: kSecondaryMouseButton); const String b = '$kSecondaryMouseButton'; for (int i = 0; i < logs.length; i++) { if (i == 0) { expect(logs[i], 'down $b'); } else if (i != logs.length - 1) { expect(logs[i], 'move $b'); } else { expect(logs[i], 'up 0'); } } }, ); testWidgets( 'WidgetTester.press must respect buttons', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'), onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'), onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'), child: const Text('test'), ), ), ); await tester.press(find.text('test'), buttons: kSecondaryMouseButton); const String b = '$kSecondaryMouseButton'; expect(logs, equals(<String>['down $b'])); }, ); testWidgets( 'WidgetTester.longPress must respect buttons', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'), onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'), onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'), child: const Text('test'), ), ), ); await tester.longPress(find.text('test'), buttons: kSecondaryMouseButton); await tester.pumpAndSettle(); const String b = '$kSecondaryMouseButton'; for (int i = 0; i < logs.length; i++) { if (i == 0) { expect(logs[i], 'down $b'); } else if (i != logs.length - 1) { expect(logs[i], 'move $b'); } else { expect(logs[i], 'up 0'); } } }, ); testWidgets( 'WidgetTester.drag must respect buttons', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'), onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'), onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'), child: const Text('test'), ), ), ); await tester.drag(find.text('test'), const Offset(-150.0, 200.0), buttons: kSecondaryMouseButton); const String b = '$kSecondaryMouseButton'; for (int i = 0; i < logs.length; i++) { if (i == 0) { expect(logs[i], 'down $b'); } else if (i != logs.length - 1) { expect(logs[i], 'move $b'); } else { expect(logs[i], 'up 0'); } } }, ); testWidgets( 'WidgetTester.drag works with trackpad kind', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'), onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'), onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'), onPointerPanZoomStart: (PointerPanZoomStartEvent event) => logs.add('panZoomStart'), onPointerPanZoomUpdate: (PointerPanZoomUpdateEvent event) => logs.add('panZoomUpdate ${event.pan}'), onPointerPanZoomEnd: (PointerPanZoomEndEvent event) => logs.add('panZoomEnd'), child: const Text('test'), ), ), ); await tester.drag(find.text('test'), const Offset(-150.0, 200.0), kind: PointerDeviceKind.trackpad); for (int i = 0; i < logs.length; i++) { if (i == 0) { expect(logs[i], 'panZoomStart'); } else if (i != logs.length - 1) { expect(logs[i], startsWith('panZoomUpdate')); } else { expect(logs[i], 'panZoomEnd'); } } }, ); testWidgets( 'WidgetTester.fling must respect buttons', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'), onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'), onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'), child: const Text('test'), ), ), ); await tester.fling(find.text('test'), const Offset(-10.0, 0.0), 1000.0, buttons: kSecondaryMouseButton); await tester.pumpAndSettle(); const String b = '$kSecondaryMouseButton'; for (int i = 0; i < logs.length; i++) { if (i == 0) { expect(logs[i], 'down $b'); } else if (i != logs.length - 1) { expect(logs[i], 'move $b'); } else { expect(logs[i], 'up 0'); } } }, ); testWidgets( 'WidgetTester.fling produces strictly monotonically increasing timestamps, ' 'when given a large velocity', (WidgetTester tester) async { // Velocity trackers may misbehave if the `PointerMoveEvent`s' have the // same timestamp. This is more likely to happen when the velocity tracker // has a small sample size. final List<Duration> logs = <Duration>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerMove: (PointerMoveEvent event) => logs.add(event.timeStamp), child: const Text('test'), ), ), ); await tester.fling(find.text('test'), const Offset(0.0, -50.0), 10000.0); await tester.pumpAndSettle(); for (int i = 0; i + 1 < logs.length; i += 1) { expect(logs[i + 1], greaterThan(logs[i])); } }); testWidgets( 'WidgetTester.timedDrag must respect buttons', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.buttons}'), onPointerMove: (PointerMoveEvent event) => logs.add('move ${event.buttons}'), onPointerUp: (PointerUpEvent event) => logs.add('up ${event.buttons}'), child: const Text('test'), ), ), ); await tester.timedDrag( find.text('test'), const Offset(-200.0, 0.0), const Duration(seconds: 1), buttons: kSecondaryMouseButton, ); await tester.pumpAndSettle(); const String b = '$kSecondaryMouseButton'; for (int i = 0; i < logs.length; i++) { if (i == 0) { expect(logs[i], 'down $b'); } else if (i != logs.length - 1) { expect(logs[i], 'move $b'); } else { expect(logs[i], 'up 0'); } } }, ); testWidgets( 'WidgetTester.timedDrag uses correct pointer', (WidgetTester tester) async { final List<String> logs = <String>[]; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Listener( onPointerDown: (PointerDownEvent event) => logs.add('down ${event.pointer}'), child: const Text('test'), ), ), ); await tester.timedDrag( find.text('test'), const Offset(-200.0, 0.0), const Duration(seconds: 1), buttons: kSecondaryMouseButton, ); await tester.pumpAndSettle(); await tester.timedDrag( find.text('test'), const Offset(200.0, 0.0), const Duration(seconds: 1), buttons: kSecondaryMouseButton, ); await tester.pumpAndSettle(); expect(logs.length, 2); expect(logs[0], isNotNull); expect(logs[1], isNotNull); expect(logs[1] != logs[0], isTrue); }, ); testWidgets( 'WidgetTester.tap appears in stack trace on error', (WidgetTester tester) async { // Regression test from https://github.com/flutter/flutter/pull/123946 await tester.pumpWidget( const MaterialApp(home: Scaffold(body: Text('target')))); final TestGesture gesture = await tester.startGesture( tester.getCenter(find.text('target')), pointer: 1); addTearDown(() => gesture.up()); Trace? stackTrace; try { await tester.tap(find.text('target'), pointer: 1); } on Error catch (e) { stackTrace = Trace.from(e.stackTrace!); } expect(stackTrace, isNotNull); final int tapFrame = stackTrace!.frames.indexWhere( (Frame frame) => frame.member == 'WidgetController.tap'); expect(tapFrame, greaterThanOrEqualTo(0)); expect(stackTrace.frames[tapFrame].package, 'flutter_test'); expect(stackTrace.frames[tapFrame+1].member, 'main.<fn>'); expect(stackTrace.frames[tapFrame+1].package, null); }, ); testWidgets( 'ensureVisible: scrolls to make widget visible', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: ListView.builder( itemCount: 20, shrinkWrap: true, itemBuilder: (BuildContext context, int i) => ListTile(title: Text('Item $i')), ), ), ), ); // Make sure widget isn't on screen expect(find.text('Item 15'), findsNothing); await tester.ensureVisible(find.text('Item 15', skipOffstage: false)); await tester.pumpAndSettle(); expect(find.text('Item 15'), findsOneWidget); }, ); group('scrollUntilVisible: scrolls to make unbuilt widget visible', () { testWidgets( 'Vertical', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: ListView.builder( itemCount: 50, shrinkWrap: true, itemBuilder: (BuildContext context, int i) => ListTile(title: Text('Item $i')), ), ), ), ); // Make sure widget isn't built yet. expect(find.text('Item 45', skipOffstage: false), findsNothing); await tester.scrollUntilVisible( find.text('Item 45', skipOffstage: false), 100, ); await tester.pumpAndSettle(); // Now the widget is on screen. expect(find.text('Item 45'), findsOneWidget); }, ); testWidgets( 'Horizontal', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: ListView.builder( itemCount: 50, shrinkWrap: true, scrollDirection: Axis.horizontal, // ListTile does not support horizontal list itemBuilder: (BuildContext context, int i) => Text('Item $i'), ), ), ), ); // Make sure widget isn't built yet. expect(find.text('Item 45', skipOffstage: false), findsNothing); await tester.scrollUntilVisible( find.text('Item 45', skipOffstage: false), 100, ); await tester.pumpAndSettle(); // Now the widget is on screen. expect(find.text('Item 45'), findsOneWidget); }, ); testWidgets( 'Fail', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: ListView.builder( itemCount: 50, shrinkWrap: true, itemBuilder: (BuildContext context, int i) => ListTile(title: Text('Item $i')), ), ), ), ); try { await tester.scrollUntilVisible( find.text('Item 55', skipOffstage: false), 100, ); } on StateError catch (e) { expect(e.message, 'No element'); } }, ); testWidgets('Drag Until Visible', (WidgetTester tester) async { // when there are two implicit [Scrollable], `scrollUntilVisible` is hard // to use. await tester.pumpWidget( MaterialApp( home: Scaffold( body: Column( children: <Widget>[ SizedBox(height: 200, child: ListView.builder( key: const Key('listView-a'), itemCount: 50, shrinkWrap: true, itemBuilder: (BuildContext context, int i) => ListTile(title: Text('Item a-$i')), )), const Divider(thickness: 5), Expanded(child: ListView.builder( key: const Key('listView-b'), itemCount: 50, shrinkWrap: true, itemBuilder: (BuildContext context, int i) => ListTile(title: Text('Item b-$i')), )), ], ), ), ), ); await tester.pumpAndSettle(); expect(find.byType(Scrollable), findsNWidgets(2)); // Make sure widget isn't built yet. expect(find.text('Item b-45', skipOffstage: false), findsNothing); await tester.dragUntilVisible( find.text('Item b-45', skipOffstage: false), find.byKey(const ValueKey<String>('listView-b')), const Offset(0, -100), ); await tester.pumpAndSettle(); // Now the widget is on screen. expect(find.text('Item b-45'), findsOneWidget); }); }); testWidgets('platformDispatcher exposes the platformDispatcher from binding', (WidgetTester tester) async { expect(tester.platformDispatcher, tester.binding.platformDispatcher); }); testWidgets('view exposes the implicitView from platformDispatcher', (WidgetTester tester) async { expect(tester.view, tester.platformDispatcher.implicitView); }); testWidgets('viewOf finds a view when the view is implicit', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Center( child: Text('Test'), ) )); expect(() => tester.viewOf(find.text('Test')), isNot(throwsA(anything))); expect(tester.viewOf(find.text('Test')), isA<TestFlutterView>()); }); group('SemanticsController', () { group('find', () { testWidgets('throws when there are no semantics', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: Text('hello'), ), ), ); expect(() => tester.semantics.find(find.text('hello')), throwsStateError); }, semanticsEnabled: false); testWidgets('throws when there are multiple results from the finder', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: Row( children: <Widget>[ Text('hello'), Text('hello'), ], ), ), ), ); expect(() => tester.semantics.find(find.text('hello')), throwsStateError); }); testWidgets('Returns the correct SemanticsData', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: OutlinedButton( onPressed: () { }, child: const Text('hello'), ), ), ), ); final SemanticsNode node = tester.semantics.find(find.text('hello')); final SemanticsData semantics = node.getSemanticsData(); expect(semantics.label, 'hello'); expect(semantics.hasAction(SemanticsAction.tap), true); expect(semantics.hasFlag(SemanticsFlag.isButton), true); }); testWidgets('Can enable semantics for tests via semanticsEnabled', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: OutlinedButton( onPressed: () { }, child: const Text('hello'), ), ), ), ); final SemanticsNode node = tester.semantics.find(find.text('hello')); final SemanticsData semantics = node.getSemanticsData(); expect(semantics.label, 'hello'); expect(semantics.hasAction(SemanticsAction.tap), true); expect(semantics.hasFlag(SemanticsFlag.isButton), true); }); testWidgets('Returns merged SemanticsData', (WidgetTester tester) async { const Key key = Key('test'); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Semantics( label: 'A', child: Semantics( label: 'B', child: Semantics( key: key, label: 'C', child: Container(), ), ), ), ), ), ); final SemanticsNode node = tester.semantics.find(find.byKey(key)); final SemanticsData semantics = node.getSemanticsData(); expect(semantics.label, 'A\nB\nC'); }); testWidgets('Does not return partial semantics', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: MergeSemantics( child: Semantics( container: true, label: 'A', child: Semantics( container: true, key: key, label: 'B', child: Container(), ), ), ), ), ), ); final SemanticsNode node = tester.semantics.find(find.byKey(key)); final SemanticsData semantics = node.getSemanticsData(); expect(semantics.label, 'A\nB'); }); }); group('simulatedTraversal', () { final List<Matcher> fullTraversalMatchers = <Matcher>[ containsSemantics(isHeader: true, label: 'Semantics Test'), containsSemantics(label: 'Text Field'), containsSemantics(isTextField: true), containsSemantics(label: 'Off Switch'), containsSemantics(hasToggledState: true), containsSemantics(label: 'On Switch'), containsSemantics(hasToggledState: true, isToggled: true), containsSemantics(label: "Multiline\nIt's a\nmultiline label!"), containsSemantics(label: 'Slider'), containsSemantics(isSlider: true, value: '50%'), containsSemantics(label: 'Enabled Button'), containsSemantics(isButton: true, label: 'Tap'), containsSemantics(label: 'Disabled Button'), containsSemantics(isButton: true, label: "Don't Tap"), containsSemantics(label: 'Checked Radio'), containsSemantics(hasCheckedState: true, isChecked: true), containsSemantics(label: 'Unchecked Radio'), containsSemantics(hasCheckedState: true, isChecked: false), ]; testWidgets('produces expected traversal', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: _SemanticsTestWidget())); expect( tester.semantics.simulatedAccessibilityTraversal(), orderedEquals(fullTraversalMatchers)); }); testWidgets('starts traversal at semantics node for `start`', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: _SemanticsTestWidget())); // We're expecting the traversal to start where the slider is. final List<Matcher> expectedMatchers = <Matcher>[...fullTraversalMatchers]..removeRange(0, 9); expect( tester.semantics.simulatedAccessibilityTraversal(start: find.byType(Slider)), orderedEquals(expectedMatchers)); }); testWidgets('simulatedAccessibilityTraversal end Index supports empty traversal', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: Center( child: Column(), // No nodes! ), )); expect( tester.semantics.simulatedAccessibilityTraversal().map((SemanticsNode node) => node.label), <String>[], ); }); testWidgets('starts traversal at semantics node for `startNode`', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Center( child: Column( children: <Widget>[ for (int c = 0; c < 5; c++) Semantics(container: true, child: Text('Child$c')), ] ), ), )); expect( tester.semantics.simulatedAccessibilityTraversal( startNode: find.semantics.byLabel('Child1'), ).map((SemanticsNode node) => node.label), <String>[ 'Child1', 'Child2', 'Child3', 'Child4', ], ); }); testWidgets('throws StateError if `start` not found in traversal', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: _SemanticsTestWidget())); // We look for a SingleChildScrollView since the view itself isn't // important for accessibility, so it won't show up in the traversal expect( () => tester.semantics.simulatedAccessibilityTraversal(start: find.byType(SingleChildScrollView)), throwsA(isA<StateError>()), ); }); testWidgets('throws StateError if `startNode` not found in traversal', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Center( child: Column( children: <Widget>[ for (int c = 0; c < 5; c++) Semantics(container: true, child: Text('Child$c')), ] ), ), )); expect( () => tester.semantics.simulatedAccessibilityTraversal(startNode: find.semantics.byLabel('Child20')), throwsA(isA<StateError>()), ); }); testWidgets('ends traversal at semantics node for `end`', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: _SemanticsTestWidget())); // We're expecting the traversal to end where the slider is, inclusive. final Iterable<Matcher> expectedMatchers = <Matcher>[...fullTraversalMatchers].getRange(0, 10); expect( tester.semantics.simulatedAccessibilityTraversal(end: find.byType(Slider)), orderedEquals(expectedMatchers)); }); testWidgets('ends traversal at semantics node for `endNode`', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Center( child: Column( children: <Widget>[ for (int c = 0; c < 5; c++) Semantics(container: true, child: Text('Child$c')), ] ), ), )); expect( tester.semantics.simulatedAccessibilityTraversal( endNode: find.semantics.byLabel('Child1'), ).map((SemanticsNode node) => node.label), <String>[ 'Child0', 'Child1', ], ); }); testWidgets('throws StateError if `end` not found in traversal', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: _SemanticsTestWidget())); // We look for a SingleChildScrollView since the view itself isn't // important for semantics, so it won't show up in the traversal expect( () => tester.semantics.simulatedAccessibilityTraversal(end: find.byType(SingleChildScrollView)), throwsA(isA<StateError>()), ); }); testWidgets('throws StateError if `endNode` not found in traversal', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Center( child: Column( children: <Widget>[ for (int c = 0; c < 5; c++) Semantics(container: true, child: Text('Child$c')), ] ), ), )); expect( () => tester.semantics.simulatedAccessibilityTraversal(endNode: find.semantics.byLabel('Child20')), throwsA(isA<StateError>()), ); }); testWidgets('returns traversal between `start` and `end` if both are provided', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: _SemanticsTestWidget())); // We're expecting the traversal to start at the text field and end at the slider. final Iterable<Matcher> expectedMatchers = <Matcher>[...fullTraversalMatchers].getRange(1, 10); expect( tester.semantics.simulatedAccessibilityTraversal( start: find.byType(TextField), end: find.byType(Slider), ), orderedEquals(expectedMatchers)); }); testWidgets('returns traversal between `startNode` and `endNode` if both are provided', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Center( child: Column( children: <Widget>[ for (int c = 0; c < 5; c++) Semantics(container: true, child: Text('Child$c')), ] ), ), )); expect( tester.semantics.simulatedAccessibilityTraversal( startNode: find.semantics.byLabel('Child1'), endNode: find.semantics.byLabel('Child3'), ).map((SemanticsNode node) => node.label), <String>[ 'Child1', 'Child2', 'Child3', ], ); }); testWidgets('can do fuzzy traversal match with `containsAllInOrder`', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: _SemanticsTestWidget())); // Grab a sample of the matchers to validate that not every matcher is // needed to validate a traversal when using `containsAllInOrder`. final Iterable<Matcher> expectedMatchers = <Matcher>[...fullTraversalMatchers] ..removeAt(0) ..removeLast() ..mapIndexed<Matcher?>((int i, Matcher element) => i.isEven ? element : null) .whereNotNull(); expect( tester.semantics.simulatedAccessibilityTraversal(), containsAllInOrder(expectedMatchers)); }); testWidgets('merging node should not be visited', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: MergeSemantics( child: Column( children: <Widget>[ Semantics( container: true, child: const Text('1'), ), Semantics( container: true, child: const Text('2'), ), Semantics( container: true, child: const Text('3'), ), ], ), ), ), ); expect( tester.semantics.simulatedAccessibilityTraversal(), orderedEquals( <Matcher>[containsSemantics(label: '1\n2\n3')], ), ); }); }); group('actions', () { testWidgets('performAction with unsupported action throws StateError', (WidgetTester tester) async { await tester.pumpWidget(Semantics(onTap: () {})); expect( () => tester.semantics.performAction( find.semantics.byLabel('Test'), SemanticsAction.dismiss, ), throwsStateError, ); }); testWidgets('tap causes semantic tap', (WidgetTester tester) async { bool invoked = false; await tester.pumpWidget( MaterialApp( home: TextButton( onPressed: () => invoked = true, child: const Text('Test Button'), ), ), ); tester.semantics.tap(find.semantics.byAction(SemanticsAction.tap)); expect(invoked, isTrue); }); testWidgets('longPress causes semantic long press', (WidgetTester tester) async { bool invoked = false; await tester.pumpWidget( MaterialApp( home: TextButton( onPressed: () {}, onLongPress: () => invoked = true, child: const Text('Test Button'), ), ), ); tester.semantics.longPress(find.semantics.byAction(SemanticsAction.longPress)); expect(invoked, isTrue); }); testWidgets('scrollLeft and scrollRight scroll left and right respectively', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: ListView( scrollDirection: Axis.horizontal, children: <Widget>[ SizedBox( height: 40, width: tester.binding.window.physicalSize.width * 1.5, ) ], ), )); expect( find.semantics.scrollable(), containsSemantics(hasScrollLeftAction: true, hasScrollRightAction: false), reason: 'When not yet scrolled, a scrollview should only be able to support left scrolls.', ); tester.semantics.scrollLeft(); await tester.pump(); expect( find.semantics.scrollable(), containsSemantics(hasScrollLeftAction: true, hasScrollRightAction: true), reason: 'When partially scrolled, a scrollview should be able to support both left and right scrolls.', ); // This will scroll the listview until it's completely scrolled to the right. final SemanticsFinder leftScrollable = find.semantics.byAction(SemanticsAction.scrollLeft); while (leftScrollable.tryEvaluate()) { tester.semantics.scrollLeft(scrollable: leftScrollable); await tester.pump(); } expect( find.semantics.scrollable(), containsSemantics(hasScrollLeftAction: false, hasScrollRightAction: true), reason: 'When fully scrolled, a scrollview should only support right scrolls.', ); tester.semantics.scrollRight(); await tester.pump(); expect( find.semantics.scrollable(), containsSemantics(hasScrollLeftAction: true, hasScrollRightAction: true), reason: 'When partially scrolled, a scrollview should be able to support both left and right scrolls.', ); }); testWidgets('scrollUp and scrollDown scrolls up and down respectively', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: ListView( children: <Widget>[ SizedBox( height: tester.binding.window.physicalSize.height * 1.5, width: 40, ) ], ), )); expect( find.semantics.scrollable(), containsSemantics(hasScrollUpAction: true, hasScrollDownAction: false), reason: 'When not yet scrolled, a scrollview should only be able to support left scrolls.', ); tester.semantics.scrollUp(); await tester.pump(); expect( find.semantics.scrollable(), containsSemantics(hasScrollUpAction: true, hasScrollDownAction: true), reason: 'When partially scrolled, a scrollview should be able to support both left and right scrolls.', ); // This will scroll the listview until it's completely scrolled to the right. final SemanticsFinder upScrollable = find.semantics.byAction(SemanticsAction.scrollUp); while (upScrollable.tryEvaluate()) { tester.semantics.scrollUp(scrollable: upScrollable); await tester.pump(); } expect( find.semantics.scrollable(), containsSemantics(hasScrollUpAction: false, hasScrollDownAction: true), reason: 'When fully scrolled, a scrollview should only support right scrolls.', ); tester.semantics.scrollDown(); await tester.pump(); expect( find.semantics.scrollable(), containsSemantics(hasScrollUpAction: true, hasScrollDownAction: true), reason: 'When partially scrolled, a scrollview should be able to support both left and right scrolls.', ); }); testWidgets('increase causes semantic increase', (WidgetTester tester) async { bool invoked = false; await tester.pumpWidget(MaterialApp( home: Material( child: _StatefulSlider( initialValue: 0, onChanged: (double _) {invoked = true;}, ), ) )); final SemanticsFinder sliderFinder = find.semantics.byFlag(SemanticsFlag.isSlider); final String expected = sliderFinder.evaluate().single.increasedValue; tester.semantics.increase(sliderFinder); await tester.pumpAndSettle(); expect(invoked, isTrue); expect( find.semantics.byFlag(SemanticsFlag.isSlider).evaluate().single.value, equals(expected), ); }); testWidgets('decrease causes semantic decrease', (WidgetTester tester) async { bool invoked = false; await tester.pumpWidget(MaterialApp( home: Material( child: _StatefulSlider( initialValue: 1, onChanged: (double _) {invoked = true;}, ), ) )); final SemanticsFinder sliderFinder = find.semantics.byFlag(SemanticsFlag.isSlider); final String expected = sliderFinder.evaluate().single.decreasedValue; tester.semantics.decrease(sliderFinder); await tester.pumpAndSettle(); expect(invoked, isTrue); expect( tester.semantics.find(find.byType(Slider)).value, equals(expected), ); }); testWidgets('showOnScreen sends showOnScreen action', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: ListView( controller: ScrollController(initialScrollOffset: 50), children: <Widget>[ const MergeSemantics( child: SizedBox( height: 40, child: Text('Test'), ), ), SizedBox( width: 40, height: tester.binding.window.physicalSize.height * 1.5, ), ], ), )); expect( find.semantics.byLabel('Test'), containsSemantics(isHidden:true), ); tester.semantics.showOnScreen(find.semantics.byLabel('Test')); await tester.pump(); expect( tester.semantics.find(find.text('Test')), containsSemantics(isHidden: false), ); }); testWidgets('actions for moving the cursor without modifying selection can move the cursor forward and back by character and word', (WidgetTester tester) async { const String text = 'This is some text.'; int currentIndex = text.length; final TextEditingController controller = TextEditingController(text: text); await tester.pumpWidget(MaterialApp( home: Material(child: TextField(controller: controller)), )); void expectUnselectedIndex(int expectedIndex) { expect(controller.selection.start, equals(expectedIndex)); expect(controller.selection.end, equals(expectedIndex)); } final SemanticsFinder finder = find.semantics.byValue(text); // Get focus onto the text field tester.semantics.tap(finder); await tester.pump(); tester.semantics.moveCursorBackwardByCharacter(finder); await tester.pump(); expectUnselectedIndex(currentIndex - 1); currentIndex -= 1; tester.semantics.moveCursorBackwardByWord(finder); await tester.pump(); expectUnselectedIndex(currentIndex - 4); currentIndex -= 4; tester.semantics.moveCursorBackwardByWord(finder); await tester.pump(); expectUnselectedIndex(currentIndex - 5); currentIndex -= 5; tester.semantics.moveCursorForwardByCharacter(finder); await tester.pump(); expectUnselectedIndex(currentIndex + 1); currentIndex += 1; tester.semantics.moveCursorForwardByWord(finder); await tester.pump(); expectUnselectedIndex(currentIndex + 4); currentIndex += 4; }); testWidgets('actions for moving the cursor with modifying selection can update the selection forward and back by character and word', (WidgetTester tester) async { const String text = 'This is some text.'; int currentIndex = text.length; final TextEditingController controller = TextEditingController(text: text); await tester.pumpWidget(MaterialApp( home: Material(child: TextField(controller: controller)), )); void expectSelectedIndex(int start) { expect(controller.selection.start, equals(start)); expect(controller.selection.end, equals(text.length)); } final SemanticsFinder finder = find.semantics.byValue(text); // Get focus onto the text field tester.semantics.tap(finder); await tester.pump(); tester.semantics.moveCursorBackwardByCharacter(finder, shouldModifySelection: true); await tester.pump(); expectSelectedIndex(currentIndex - 1); currentIndex -= 1; tester.semantics.moveCursorBackwardByWord(finder, shouldModifySelection: true); await tester.pump(); expectSelectedIndex(currentIndex - 4); currentIndex -= 4; tester.semantics.moveCursorBackwardByWord(finder, shouldModifySelection: true); await tester.pump(); expectSelectedIndex(currentIndex - 5); currentIndex -= 5; tester.semantics.moveCursorForwardByCharacter(finder, shouldModifySelection: true); await tester.pump(); expectSelectedIndex(currentIndex + 1); currentIndex += 1; tester.semantics.moveCursorForwardByWord(finder, shouldModifySelection: true); await tester.pump(); expectSelectedIndex(currentIndex + 4); currentIndex += 4; }); testWidgets('setText causes semantics to set the text', (WidgetTester tester) async { const String expectedText = 'This is some text.'; final TextEditingController controller = TextEditingController(); await tester.pumpWidget(MaterialApp( home: Material(child: TextField(controller: controller)), )); final SemanticsFinder finder = find.semantics.byFlag(SemanticsFlag.isTextField); tester.semantics.tap(finder); await tester.pump(); tester.semantics.setText(finder, expectedText); await tester.pump(); expect(controller.text, equals(expectedText)); }); testWidgets('setSelection causes semantics to select text', (WidgetTester tester) async { const String text = 'This is some text.'; const int expectedStart = text.length - 8; const int expectedEnd = text.length - 4; final TextEditingController controller = TextEditingController(text: text); await tester.pumpWidget(MaterialApp( home: Material(child: TextField(controller: controller)), )); final SemanticsFinder finder = find.semantics.byFlag(SemanticsFlag.isTextField); tester.semantics.tap(finder); await tester.pump(); tester.semantics.setSelection( finder, base: expectedStart, extent: expectedEnd, ); await tester.pump(); expect(controller.selection.start, equals(expectedStart)); expect(controller.selection.end, equals(expectedEnd)); }); testWidgets('copy sends semantic copy', (WidgetTester tester) async { bool invoked = false; await tester.pumpWidget(MaterialApp( home: Semantics( label: 'test', onCopy: () => invoked = true, ), )); tester.semantics.copy(find.semantics.byLabel('test')); expect(invoked, isTrue); }); testWidgets('cut sends semantic cut', (WidgetTester tester) async { bool invoked = false; await tester.pumpWidget(MaterialApp( home: Semantics( label: 'test', onCut: () => invoked = true, ), )); tester.semantics.cut(find.semantics.byLabel('test')); expect(invoked, isTrue); }); testWidgets('paste sends semantic paste', (WidgetTester tester) async { bool invoked = false; await tester.pumpWidget(MaterialApp( home: Semantics( label: 'test', onPaste: () => invoked = true, ), )); tester.semantics.paste(find.semantics.byLabel('test')); expect(invoked, isTrue); }); testWidgets('didGainAccessibilityFocus causes semantic focus on node', (WidgetTester tester) async { bool invoked = false; await tester.pumpWidget(MaterialApp( home: Semantics( label: 'test', onDidGainAccessibilityFocus: () => invoked = true, ), )); tester.semantics.didGainAccessibilityFocus(find.semantics.byLabel('test')); expect(invoked, isTrue); }); testWidgets('didLoseAccessibility causes semantic focus to be lost', (WidgetTester tester) async { bool invoked = false; await tester.pumpWidget(MaterialApp( home: Semantics( label: 'test', onDidLoseAccessibilityFocus: () => invoked = true, ), )); tester.semantics.didLoseAccessibilityFocus(find.semantics.byLabel('test')); expect(invoked, isTrue); }); testWidgets('dismiss sends semantic dismiss', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); const Duration duration = Duration(seconds: 3); final Duration halfDuration = Duration(milliseconds: (duration.inMilliseconds / 2).floor()); late SnackBarClosedReason reason; await tester.pumpWidget(MaterialApp( home: Scaffold( key: key, ) )); final ScaffoldMessengerState messenger = ScaffoldMessenger.of(key.currentContext!); messenger.showSnackBar(const SnackBar( content: SizedBox(height: 40, width: 300,), duration: duration )).closed.then((SnackBarClosedReason result) => reason = result); await tester.pumpFrames(tester.widget(find.byType(MaterialApp)), halfDuration); tester.semantics.dismiss(find.semantics.byAction(SemanticsAction.dismiss)); await tester.pumpAndSettle(); expect(reason, equals(SnackBarClosedReason.dismiss)); }); testWidgets('customAction invokes appropriate custom action', (WidgetTester tester) async { const CustomSemanticsAction customAction = CustomSemanticsAction(label: 'test'); bool invoked = false; await tester.pumpWidget(MaterialApp( home: Semantics( label: 'test', customSemanticsActions: <CustomSemanticsAction, void Function()>{ customAction:() => invoked = true, }, ), )); tester.semantics.customAction(find.semantics.byLabel('test'), customAction); await tester.pump(); expect(invoked, isTrue); }); }); }); group('WidgetTester.tapOnText', () { final List<String > tapLogs = <String>[]; final TapGestureRecognizer tapA = TapGestureRecognizer()..onTap = () { tapLogs.add('A'); }; final TapGestureRecognizer tapB = TapGestureRecognizer()..onTap = () { tapLogs.add('B'); }; final TapGestureRecognizer tapC = TapGestureRecognizer()..onTap = () { tapLogs.add('C'); }; tearDown(tapLogs.clear); tearDownAll(() { tapA.dispose(); tapB.dispose(); tapC.dispose(); }); testWidgets('basic test', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Text.rich(TextSpan(text: 'match', recognizer: tapA)), ), ); await tester.tapOnText(find.textRange.ofSubstring('match')); expect(tapLogs, <String>['A']); }); testWidgets('partially obstructed: find a hit-testable Offset', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Stack( fit: StackFit.expand, children: <Widget>[ Positioned( left: 100.0 - 9 * 10.0, // Only the last character is visible. child: Text.rich(TextSpan(text: 'text match', style: const TextStyle(fontSize: 10), recognizer: tapA)), ), const Positioned( left: 0.0, right: 100.0, child: MetaData(behavior: HitTestBehavior.opaque), ), ], ), ), ); await expectLater( () => tester.tapOnText(find.textRange.ofSubstring('text match')), returnsNormally, ); }); testWidgets('multiline text partially obstructed: find a hit-testable Offset', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Stack( fit: StackFit.expand, children: <Widget>[ Positioned( width: 100.0, top: 23.0, left: 0.0, child: Text.rich( TextSpan( style: const TextStyle(fontSize: 10), children: <InlineSpan>[ TextSpan(text: 'AAAAAAAAA ', recognizer: tapA), TextSpan(text: 'BBBBBBBBB ', recognizer: tapB), // The only visible line TextSpan(text: 'CCCCCCCCC ', recognizer: tapC), ] ) ), ), const Positioned( top: 23.0, // Some random offset to test the global to local Offset conversion left: 0.0, right: 0.0, height: 10.0, child: MetaData(behavior: HitTestBehavior.opaque, child: SizedBox.expand()), ), const Positioned( top: 43.0, left: 0.0, right: 0.0, height: 10.0, child: MetaData(behavior: HitTestBehavior.opaque, child: SizedBox.expand()), ), ], ), ), ); await tester.tapOnText(find.textRange.ofSubstring('AAAAAAAAA BBBBBBBBB CCCCCCCCC ')); expect(tapLogs, <String>['B']); }); testWidgets('error message: no matching text', (WidgetTester tester) async { await tester.pumpWidget(const SizedBox()); await expectLater( () => tester.tapOnText(find.textRange.ofSubstring('nonexistent')), throwsA(isFlutterError.having( (FlutterError error) => error.message, 'message', contains('Found 0 non-overlapping TextRanges that match the Pattern "nonexistent": []'), )), ); }); testWidgets('error message: too many matches', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Text.rich( TextSpan( text: 'match', recognizer: tapA, children: <InlineSpan>[TextSpan(text: 'another match', recognizer: tapB)], ), ), ), ); await expectLater( () => tester.tapOnText(find.textRange.ofSubstring('match')), throwsA(isFlutterError.having( (FlutterError error) => error.message, 'message', stringContainsInOrder(<String>[ 'Found 2 non-overlapping TextRanges that match the Pattern "match"', 'TextRange(start: 0, end: 5)', 'TextRange(start: 13, end: 18)', 'The "tapOnText" method needs a single non-empty TextRange.', ]) )), ); }); testWidgets('error message: not hit-testable', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Stack( fit: StackFit.expand, children: <Widget>[ Text.rich(TextSpan(text: 'match', recognizer: tapA)), const MetaData(behavior: HitTestBehavior.opaque), ], ), ), ); await expectLater( () => tester.tapOnText(find.textRange.ofSubstring('match')), throwsA(isFlutterError.having( (FlutterError error) => error.message, 'message', stringContainsInOrder(<String>[ 'The finder used was: A finder that searches for non-overlapping TextRanges that match the Pattern "match".', 'Found a matching substring in a static text widget, within TextRange(start: 0, end: 5).', 'But the "tapOnText" method could not find a hit-testable Offset with in that text range.', ]) )), ); }); }); } class _SemanticsTestWidget extends StatelessWidget { const _SemanticsTestWidget(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Semantics Test')), body: SingleChildScrollView( child: Column( children: <Widget>[ const _SemanticsTestCard( label: 'Text Field', widget: TextField(), ), _SemanticsTestCard( label: 'Off Switch', widget: Switch(value: false, onChanged: (bool value) {}), ), _SemanticsTestCard( label: 'On Switch', widget: Switch(value: true, onChanged: (bool value) {}), ), const _SemanticsTestCard( label: 'Multiline', widget: Text("It's a\nmultiline label!", maxLines: 2), ), _SemanticsTestCard( label: 'Slider', widget: Slider(value: .5, onChanged: (double value) {}), ), _SemanticsTestCard( label: 'Enabled Button', widget: TextButton(onPressed: () {}, child: const Text('Tap')), ), const _SemanticsTestCard( label: 'Disabled Button', widget: TextButton(onPressed: null, child: Text("Don't Tap")), ), _SemanticsTestCard( label: 'Checked Radio', widget: Radio<String>( value: 'checked', groupValue: 'checked', onChanged: (String? value) {}, ), ), _SemanticsTestCard( label: 'Unchecked Radio', widget: Radio<String>( value: 'unchecked', groupValue: 'checked', onChanged: (String? value) {}, ), ), ], ), ), ); } } class _SemanticsTestCard extends StatelessWidget { const _SemanticsTestCard({required this.label, required this.widget}); final String label; final Widget widget; @override Widget build(BuildContext context) { return Card( child: ListTile( title: Text(label), trailing: SizedBox(width: 200, child: widget), ), ); } } class _StatefulSlider extends StatefulWidget { const _StatefulSlider({required this.initialValue, required this.onChanged}); final double initialValue; final ValueChanged<double> onChanged; @override _StatefulSliderState createState() => _StatefulSliderState(); } class _StatefulSliderState extends State<_StatefulSlider> { double _value = 0; @override void initState() { super.initState(); _value = widget.initialValue; } @override Widget build(BuildContext context) { return Slider( value: _value, onChanged: (double value) { setState(() { _value = value; }, ); widget.onChanged(value); }); } }
flutter/packages/flutter_test/test/controller_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/controller_test.dart", "repo_id": "flutter", "token_count": 29380 }
788
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'multi_view_testing.dart'; void main() { testWidgets('simulatedAccessibilityTraversal - start and end in same view', (WidgetTester tester) async { await pumpViews(tester: tester); expect( tester.semantics.simulatedAccessibilityTraversal( start: find.text('View2Child1'), end: find.text('View2Child3'), ).map((SemanticsNode node) => node.label), <String>[ 'View2Child1', 'View2Child2', 'View2Child3', ], ); }); testWidgets('simulatedAccessibilityTraversal - start not specified', (WidgetTester tester) async { await pumpViews(tester: tester); expect( tester.semantics.simulatedAccessibilityTraversal( end: find.text('View2Child3'), ).map((SemanticsNode node) => node.label), <String>[ 'View2Child0', 'View2Child1', 'View2Child2', 'View2Child3', ], ); }); testWidgets('simulatedAccessibilityTraversal - end not specified', (WidgetTester tester) async { await pumpViews(tester: tester); expect( tester.semantics.simulatedAccessibilityTraversal( start: find.text('View2Child1'), ).map((SemanticsNode node) => node.label), <String>[ 'View2Child1', 'View2Child2', 'View2Child3', 'View2Child4', ], ); }); testWidgets('simulatedAccessibilityTraversal - nothing specified', (WidgetTester tester) async { await pumpViews(tester: tester); expect( tester.semantics.simulatedAccessibilityTraversal().map((SemanticsNode node) => node.label), <String>[ 'View1Child0', 'View1Child1', 'View1Child2', 'View1Child3', 'View1Child4', ], ); // Should be traversing over tester.view. expect(tester.viewOf(find.text('View1Child0')), tester.view); }); testWidgets('simulatedAccessibilityTraversal - only view specified', (WidgetTester tester) async { await pumpViews(tester: tester); expect( tester.semantics.simulatedAccessibilityTraversal( view: tester.viewOf(find.text('View2Child1')), ).map((SemanticsNode node) => node.label), <String>[ 'View2Child0', 'View2Child1', 'View2Child2', 'View2Child3', 'View2Child4', ], ); }); testWidgets('simulatedAccessibilityTraversal - everything specified', (WidgetTester tester) async { await pumpViews(tester: tester); expect( tester.semantics.simulatedAccessibilityTraversal( start: find.text('View2Child1'), end: find.text('View2Child3'), view: tester.viewOf(find.text('View2Child1')), ).map((SemanticsNode node) => node.label), <String>[ 'View2Child1', 'View2Child2', 'View2Child3', ], ); }); testWidgets('simulatedAccessibilityTraversal - start and end not in same view', (WidgetTester tester) async { await pumpViews(tester: tester); expect( () => tester.semantics.simulatedAccessibilityTraversal( start: find.text('View2Child1'), end: find.text('View1Child3'), ), throwsA(isStateError.having( (StateError e) => e.message, 'message', contains('The start and end node are in different views.'), )), ); }); testWidgets('simulatedAccessibilityTraversal - start is not in view', (WidgetTester tester) async { await pumpViews(tester: tester); expect( () => tester.semantics.simulatedAccessibilityTraversal( start: find.text('View2Child1'), end: find.text('View1Child3'), view: tester.viewOf(find.text('View1Child3')), ), throwsA(isStateError.having( (StateError e) => e.message, 'message', contains('The start node is not part of the provided view.'), )), ); }); testWidgets('simulatedAccessibilityTraversal - end is not in view', (WidgetTester tester) async { await pumpViews(tester: tester); expect( () => tester.semantics.simulatedAccessibilityTraversal( start: find.text('View2Child1'), end: find.text('View1Child3'), view: tester.viewOf(find.text('View2Child1')), ), throwsA(isStateError.having( (StateError e) => e.message, 'message', contains('The end node is not part of the provided view.'), )), ); }); testWidgets('viewOf', (WidgetTester tester) async { await pumpViews(tester: tester); expect(tester.viewOf(find.text('View0Child0')).viewId, 100); expect(tester.viewOf(find.text('View1Child1')).viewId, tester.view.viewId); expect(tester.viewOf(find.text('View2Child2')).viewId, 102); }); testWidgets('layers includes layers from all views', (WidgetTester tester) async { await pumpViews(tester: tester); const int numberOfViews = 3; expect(tester.binding.renderViews.length, numberOfViews); // One RenderView for each FlutterView. final List<Layer> layers = tester.layers; // Each RenderView contributes a TransformLayer and a PictureLayer. expect(layers, hasLength(numberOfViews * 2)); expect(layers.whereType<TransformLayer>(), hasLength(numberOfViews)); expect(layers.whereType<PictureLayer>(), hasLength(numberOfViews)); expect( layers.whereType<TransformLayer>().map((TransformLayer l ) => l.owner), containsAll(tester.binding.renderViews), ); }); testWidgets('hitTestOnBinding', (WidgetTester tester) async { await pumpViews(tester: tester); // Not specifying a viewId hit tests on tester.view: HitTestResult result = tester.hitTestOnBinding(Offset.zero); expect(result.path.map((HitTestEntry h) => h.target).whereType<RenderView>().single.flutterView, tester.view); // Specifying a viewId is respected: result = tester.hitTestOnBinding(Offset.zero, viewId: 100); expect(result.path.map((HitTestEntry h) => h.target).whereType<RenderView>().single.flutterView.viewId, 100); result = tester.hitTestOnBinding(Offset.zero, viewId: 102); expect(result.path.map((HitTestEntry h) => h.target).whereType<RenderView>().single.flutterView.viewId, 102); }); testWidgets('hitTestable works in different Views', (WidgetTester tester) async { await pumpViews(tester: tester); expect((find.text('View0Child0').hitTestable().evaluate().single.widget as Text).data, 'View0Child0'); expect((find.text('View1Child1').hitTestable().evaluate().single.widget as Text).data, 'View1Child1'); expect((find.text('View2Child2').hitTestable().evaluate().single.widget as Text).data, 'View2Child2'); }); testWidgets('simulatedAccessibilityTraversal - startNode and endNode in same view', (WidgetTester tester) async { await pumpViews(tester: tester); expect( tester.semantics.simulatedAccessibilityTraversal( startNode: find.semantics.byLabel('View2Child1'), endNode: find.semantics.byLabel('View2Child3'), ).map((SemanticsNode node) => node.label), <String>[ 'View2Child1', 'View2Child2', 'View2Child3', ], ); }); } Future<void> pumpViews({required WidgetTester tester}) { final List<Widget> views = <Widget>[ for (int i = 0; i < 3; i++) View( view: i == 1 ? tester.view : FakeView(tester.view, viewId: i + 100), child: Center( child: Column( children: <Widget>[ for (int c = 0; c < 5; c++) Semantics(container: true, child: Text('View${i}Child$c')), ], ), ), ), ]; return tester.pumpWidget( wrapWithView: false, Directionality( textDirection: TextDirection.ltr, child: ViewCollection( views: views, ), ), ); }
flutter/packages/flutter_test/test/multi_view_controller_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/multi_view_controller_test.dart", "repo_id": "flutter", "token_count": 3277 }
789
// Copyright 2014 The Flutter Authors. 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('test', (WidgetTester tester) async { final AnimationSheetBuilder animationSheet = AnimationSheetBuilder(frameSize: const Size(48, 24)); // This line will remain unchanged as there is no replacement for the // `sheetSize` API. tester.binding.setSurfaceSize(animationSheet.sheetSize()); // These lines will replace the calls to `display` with a call to `collate` // but will still have a build error. // Changes made in https://github.com/flutter/flutter/pull/83337 final Widget display = await animationSheet.display(); final Widget display2 = await animationSheet.display(key: UniqueKey()); }); }
flutter/packages/flutter_test/test_fixes/flutter_test/animation_sheet_builder.dart/0
{ "file_path": "flutter/packages/flutter_test/test_fixes/flutter_test/animation_sheet_builder.dart", "repo_id": "flutter", "token_count": 286 }
790
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:args/args.dart'; import 'package:flutter_tools/src/asset.dart' hide defaultManifestPath; import 'package:flutter_tools/src/base/common.dart'; import 'package:flutter_tools/src/base/context.dart'; import 'package:flutter_tools/src/base/file_system.dart' as libfs; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/build_system/depfile.dart'; import 'package:flutter_tools/src/bundle.dart'; import 'package:flutter_tools/src/bundle_builder.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/context_runner.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/reporting/reporting.dart'; const String _kOptionPackages = 'packages'; const String _kOptionAsset = 'asset-dir'; const String _kOptionManifest = 'manifest'; const String _kOptionAssetManifestOut = 'asset-manifest-out'; const String _kOptionComponentName = 'component-name'; const String _kOptionDepfile = 'depfile'; const List<String> _kRequiredOptions = <String>[ _kOptionPackages, _kOptionAsset, _kOptionAssetManifestOut, _kOptionComponentName, ]; Future<void> main(List<String> args) { return runInContext<void>(() => run(args), overrides: <Type, Generator>{ Usage: () => DisabledUsage(), }); } Future<void> writeAssetFile(libfs.File outputFile, AssetBundleEntry asset) async { outputFile.createSync(recursive: true); final List<int> data = await asset.contentsAsBytes(); outputFile.writeAsBytesSync(data); } Future<void> run(List<String> args) async { final ArgParser parser = ArgParser() ..addOption(_kOptionPackages, help: 'The .packages file') ..addOption(_kOptionAsset, help: 'The directory where to put temporary files') ..addOption(_kOptionManifest, help: 'The manifest file') ..addOption(_kOptionAssetManifestOut) ..addOption(_kOptionComponentName) ..addOption(_kOptionDepfile); final ArgResults argResults = parser.parse(args); if (_kRequiredOptions .any((String option) => !argResults.options.contains(option))) { globals.printError('Missing option! All options must be specified.'); exit(1); } Cache.flutterRoot = globals.platform.environment['FLUTTER_ROOT']; final String assetDir = argResults[_kOptionAsset] as String; final AssetBundle? assets = await buildAssets( manifestPath: argResults[_kOptionManifest] as String? ?? defaultManifestPath, assetDirPath: assetDir, packagesPath: argResults[_kOptionPackages] as String?, targetPlatform: TargetPlatform.fuchsia_arm64 // This is not arch specific. ); if (assets == null) { throwToolExit('Unable to find assets.', exitCode: 1); } final List<Future<void>> calls = <Future<void>>[]; assets.entries.forEach((String fileName, AssetBundleEntry entry) { final libfs.File outputFile = globals.fs.file(globals.fs.path.join(assetDir, fileName)); calls.add(writeAssetFile(outputFile, entry)); }); await Future.wait<void>(calls); final String outputMan = argResults[_kOptionAssetManifestOut] as String; await writeFuchsiaManifest(assets, argResults[_kOptionAsset] as String, outputMan, argResults[_kOptionComponentName] as String); final String? depfilePath = argResults[_kOptionDepfile] as String?; if (depfilePath != null) { await writeDepfile(assets, outputMan, depfilePath); } } Future<void> writeDepfile(AssetBundle assets, String outputManifest, String depfilePath) async { final Depfile depfileContent = Depfile( assets.inputFiles, <libfs.File>[globals.fs.file(outputManifest)], ); final DepfileService depfileService = DepfileService( fileSystem: globals.fs, logger: globals.logger, ); final libfs.File depfile = globals.fs.file(depfilePath); await depfile.create(recursive: true); depfileService.writeToFile(depfileContent, depfile); } Future<void> writeFuchsiaManifest(AssetBundle assets, String outputBase, String fileDest, String componentName) async { final libfs.File destFile = globals.fs.file(fileDest); await destFile.create(recursive: true); final libfs.IOSink outFile = destFile.openWrite(); for (final String path in assets.entries.keys) { outFile.write('data/$componentName/$path=$outputBase/$path\n'); } await outFile.flush(); await outFile.close(); }
flutter/packages/flutter_tools/bin/fuchsia_asset_builder.dart/0
{ "file_path": "flutter/packages/flutter_tools/bin/fuchsia_asset_builder.dart", "repo_id": "flutter", "token_count": 1487 }
791
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. plugins { `java-gradle-plugin` `groovy` } group = "dev.flutter.plugin" version = "1.0.0" gradlePlugin { plugins { // The "flutterPlugin" name isn't used anywhere. create("flutterPlugin") { id = "dev.flutter.flutter-gradle-plugin" implementationClass = "FlutterPlugin" } // The "flutterAppPluginLoaderPlugin" name isn't used anywhere. create("flutterAppPluginLoaderPlugin") { id = "dev.flutter.flutter-plugin-loader" implementationClass = "FlutterAppPluginLoaderPlugin" } } } dependencies { // When bumping, also update: // * ndkVersion in FlutterExtension in packages/flutter_tools/gradle/src/main/groovy/flutter.groovy // * AGP version in the buildscript block in packages/flutter_tools/gradle/src/main/groovy/flutter.groovy // * AGP version in the buildscript block in packages/flutter_tools/gradle/src/main/kotlin/dependency_version_checker.gradle.kts // * AGP version constants in packages/flutter_tools/lib/src/android/gradle_utils.dart compileOnly("com.android.tools.build:gradle:7.3.0") }
flutter/packages/flutter_tools/gradle/build.gradle.kts/0
{ "file_path": "flutter/packages/flutter_tools/gradle/build.gradle.kts", "repo_id": "flutter", "token_count": 500 }
792
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="benchmarks - complex_layout" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/dev/benchmarks/complex_layout/lib/main.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/benchmarks___complex_layout.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/benchmarks___complex_layout.xml.copy.tmpl", "repo_id": "flutter", "token_count": 95 }
793
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="layers - lifecycle" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/layers/services/lifecycle.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___lifecycle.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___lifecycle.xml.copy.tmpl", "repo_id": "flutter", "token_count": 92 }
794
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="platform_view" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/platform_view/lib/main.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/plaform_view.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/plaform_view.xml.copy.tmpl", "repo_id": "flutter", "token_count": 90 }
795
# Flutter Tools for Android This section of the Flutter repository contains the command line developer tools for building Flutter applications on Android. What follows are some notes about updating this part of the tool. ## Updating Android dependencies The Android dependencies that Flutter uses to run on Android include the Android NDK and SDK versions, Gradle, the Kotlin Gradle Plugin, and the Android Gradle Plugin (AGP). The template versions of these dependencies can be found in [gradle_utils.dart](gradle_utils.dart). Follow the guides below when*... ### Updating the template version of... #### The Android SDK & NDK All of the Android SDK/NDK versions noted in `gradle_utils.dart` (`compileSdkVersion`, `minSdkVersion`, `targetSdkVersion`, `ndkVersion`) versions should match the values in Flutter Gradle Plugin (`FlutterExtension`), so updating any of these versions also requires an update in [flutter.groovy](../../../gradle/src/main/groovy/flutter.groovy). When updating the Android `compileSdkVersion`, `minSdkVersion`, or `targetSdkVersion`, make sure that: - Framework integration & benchmark tests are running with at least that SDK version. - Flutter tools tests that perform String checks with the current template SDK versions are updated (you should see these fail if you do not fix them preemptively). Also, make sure to also update to the same version in the following places: - The version in the buildscript block in `packages/flutter_tools/gradle/src/main/groovy/flutter.groovy`. - The version in the buildscript block in `packages/flutter_tools/gradle/src/main/kotlin/dependency_version_checker.gradle.kts`. - The version in the dependencies block in `packages/flutter_tools/gradle/build.gradle.kts`. #### Gradle When updating the Gradle version used in project templates (`templateDefaultGradleVersion`), make sure that: - Framework integration & benchmark tests are running with at least this Gradle version. - Flutter tools tests that perform String checks with the current template Gradle version are updated (you should see these fail if you do not fix them preemptively). #### The Kotlin Gradle Plugin When updating the Kotlin Gradle Plugin (KGP) version used in project templates (`templateKotlinGradlePluginVersion`), make sure that the framework integration & benchmark tests are running with at least this KGP version. For information about the latest version, check https://kotlinlang.org/docs/releases.html#release-details. #### The Android Gradle Plugin (AGP) When updating the Android Gradle Plugin (AGP) versions used in project templates (`templateAndroidGradlePluginVersion`, `templateAndroidGradlePluginVersionForModule`), make sure that: - Framework integration & benchmark tests are running with at least this AGP version. - Flutter tools tests that perform String checks with the current template AGP versions are updated (you should see these fail if you do not fix them preemptively). ### A new version becomes available for... #### Gradle When new versions of Gradle become available, make sure to: - Check if the maximum version of Gradle that we support (`maxKnownAndSupportedGradleVersion`) can be updated, and if so, take the necessary steps to ensure we are testing this version in CI. - Check that the Java version that is one higher than we currently support (`oneMajorVersionHigherJavaVersion`) based on current maximum supported Gradle version is up-to-date. - Update the `_javaGradleCompatList` that contains the Java/Gradle compatibility information known to the tool. - Update the test cases in [gradle_utils_test.dart](../../..test/general.shard/android/gradle_utils_test.dart) that test compatibility between Java and Gradle versions (relevant tests should fail if you do not fix them preemptively, but should also be marked inline). - Update the test cases in [create_test.dart](../../../test/commands.shard/permeable/create_test.dart) that test for a warning for Java/Gradle incompatibilities as needed (relevant tests should fail if you do not fix them preemptively). For more information about the latest version, check https://gradle.org/releases/. #### The Android Gradle Plugin (AGP) When new versions of the Android Gradle Plugin become available, make sure to: - Update the maximum version of AGP that we know of (`maxKnownAgpVersion`). - Check if the maximum version of AGP that we support (`maxKnownAndSupportedAgpVersion`) can be updated, and if so, take the necessary steps to ensure that we are testing this version in CI. - Update the `_javaAgpCompatList` that contains the Java/AGP compatibility information known to the tool. - Update the test cases in [gradle_utils_test.dart](../../..test/general.shard/android/gradle_utils_test.dart) that test compatibility between Java and AGP versions (relevant tests should fail if you do not fix them preemptively, but should also be marked inline). - Update the test cases in [create_test.dart](../../../test/commands.shard/permeable/create_test.dart) that test for a warning for Java/AGP incompatibilities as needed (relevant tests should fail if you do not fix them preemptively). For information about the latest version, check https://developer.android.com/studio/releases/gradle-plugin#updating-gradle. \* There is an ongoing effort to reduce these steps; see https://github.com/flutter/flutter/issues/134780.
flutter/packages/flutter_tools/lib/src/android/README.md/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/README.md", "repo_id": "flutter", "token_count": 1395 }
796
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '../base/common.dart'; import '../base/deferred_component.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../base/terminal.dart'; /// A class to configure and run deferred component setup verification checks /// and tasks. /// /// Once constructed, checks and tasks can be executed by calling the respective /// methods. The results of the checks are stored internally and can be /// displayed to the user by calling [displayResults]. /// /// The results of each check are handled internally as they are not meant to /// be run isolated. abstract class DeferredComponentsValidator { DeferredComponentsValidator(this.projectDir, this.logger, this.platform, { this.exitOnFail = true, String? title, }) : outputDir = projectDir .childDirectory('build') .childDirectory(kDeferredComponentsTempDirectory), inputs = <File>[], outputs = <File>[], title = title ?? 'Deferred components setup verification', generatedFiles = <String>[], modifiedFiles = <String>[], invalidFiles = <String, String>{}, diffLines = <String>[]; /// Logger to use for [displayResults] output. final Logger logger; final Platform platform; /// When true, failed checks and tasks will result in [attemptToolExit] /// triggering [throwToolExit]. final bool exitOnFail; /// The name of the golden file that tracks the latest loading units /// generated. static const String kLoadingUnitsCacheFileName = 'deferred_components_loading_units.yaml'; /// The directory in the build folder to generate missing/modified files into. static const String kDeferredComponentsTempDirectory = 'android_deferred_components_setup_files'; /// The title printed at the top of the results of [displayResults] final String title; /// The root directory of the flutter project. final Directory projectDir; /// The temporary directory that the validator writes recommended files into. final Directory outputDir; /// Files that were newly generated by this validator. final List<String> generatedFiles; /// Existing files that were modified by this validator. final List<String> modifiedFiles; /// Files that were invalid and unable to be checked. These files are input /// files that the validator tries to read rather than output files the /// validator generates. The key is the file name and the value is the message /// or reason it was invalid. final Map<String, String> invalidFiles; // TODO(garyq): implement the diff task. /// Output of the diff task. final List<String> diffLines; /// Tracks the new and missing loading units. Map<String, dynamic>? loadingUnitComparisonResults; /// All files read by the validator. final List<File> inputs; /// All files output by the validator. final List<File> outputs; /// Returns true if there were any recommended changes that should /// be applied. /// /// Returns false if no problems or recommendations were detected. /// /// If no checks are run, then this will default to false and will remain so /// until a failing check finishes running. bool get changesNeeded => generatedFiles.isNotEmpty || modifiedFiles.isNotEmpty || invalidFiles.isNotEmpty || (loadingUnitComparisonResults != null && !(loadingUnitComparisonResults!['match'] as bool)); /// Handles the results of all executed checks by calling [displayResults] and /// [attemptToolExit]. /// /// This should be called after all desired checks and tasks are executed. void handleResults() { displayResults(); attemptToolExit(); } static const String _thickDivider = '================================================================================='; static const String _thinDivider = '---------------------------------------------------------------------------------'; /// Displays the results of this validator's executed checks and tasks in a /// human readable format. /// /// All checks that are desired should be run before calling this method. void displayResults() { if (changesNeeded) { logger.printStatus(_thickDivider); logger.printStatus(title, indent: (_thickDivider.length - title.length) ~/ 2, emphasis: true); logger.printStatus(_thickDivider); // Log any file reading/existence errors. if (invalidFiles.isNotEmpty) { logger.printStatus('Errors checking the following files:\n', emphasis: true); for (final String key in invalidFiles.keys) { logger.printStatus(' - $key: ${invalidFiles[key]}\n'); } } // Log diff file contents, with color highlighting if (diffLines.isNotEmpty) { logger.printStatus('Diff between `android` and expected files:', emphasis: true); logger.printStatus(''); for (final String line in diffLines) { // We only care about diffs in files that have // counterparts. if (line.startsWith('Only in android')) { continue; } TerminalColor color = TerminalColor.grey; if (line.startsWith('+')) { color = TerminalColor.green; } else if (line.startsWith('-')) { color = TerminalColor.red; } logger.printStatus(line, color: color); } logger.printStatus(''); } // Log any newly generated and modified files. if (generatedFiles.isNotEmpty) { logger.printStatus('Newly generated android files:', emphasis: true); for (final String filePath in generatedFiles) { final String shortenedPath = filePath.substring(projectDir.parent.path.length + 1); logger.printStatus(' - $shortenedPath', color: TerminalColor.grey); } logger.printStatus(''); } if (modifiedFiles.isNotEmpty) { logger.printStatus('Modified android files:', emphasis: true); for (final String filePath in modifiedFiles) { final String shortenedPath = filePath.substring(projectDir.parent.path.length + 1); logger.printStatus(' - $shortenedPath', color: TerminalColor.grey); } logger.printStatus(''); } if (generatedFiles.isNotEmpty || modifiedFiles.isNotEmpty) { logger.printStatus(''' The above files have been placed into `build/$kDeferredComponentsTempDirectory`, a temporary directory. The files should be reviewed and moved into the project's `android` directory.'''); if (diffLines.isNotEmpty && !platform.isWindows) { logger.printStatus(r''' The recommended changes can be quickly applied by running: $ patch -p0 < build/setup_deferred_components.diff '''); } logger.printStatus('$_thinDivider\n'); } // Log loading unit golden changes, if any. if (loadingUnitComparisonResults != null) { if ((loadingUnitComparisonResults!['new'] as List<LoadingUnit>).isNotEmpty) { logger.printStatus('New loading units were found:', emphasis: true); for (final LoadingUnit unit in loadingUnitComparisonResults!['new'] as List<LoadingUnit>) { logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2); } logger.printStatus(''); } if ((loadingUnitComparisonResults!['missing'] as Set<LoadingUnit>).isNotEmpty) { logger.printStatus('Previously existing loading units no longer exist:', emphasis: true); for (final LoadingUnit unit in loadingUnitComparisonResults!['missing'] as Set<LoadingUnit>) { logger.printStatus(unit.toString(), color: TerminalColor.grey, indent: 2); } logger.printStatus(''); } if (loadingUnitComparisonResults!['match'] as bool) { logger.printStatus('No change in generated loading units.\n'); } else { logger.printStatus(''' It is recommended to verify that the changed loading units are expected and to update the `deferred-components` section in `pubspec.yaml` to incorporate any changes. The full list of generated loading units can be referenced in the $kLoadingUnitsCacheFileName file located alongside pubspec.yaml. This loading unit check will not fail again on the next build attempt if no additional changes to the loading units are detected. $_thinDivider\n'''); } } // TODO(garyq): Add link to web tutorial/guide once it is written. logger.printStatus(''' Setup verification can be skipped by passing the `--no-validate-deferred-components` flag, however, doing so may put your app at risk of not functioning even if the build is successful. $_thickDivider'''); return; } logger.printStatus('$title passed.'); } void attemptToolExit() { if (exitOnFail && changesNeeded) { throwToolExit('Setup for deferred components incomplete. See recommended actions.', exitCode: 1); } } }
flutter/packages/flutter_tools/lib/src/android/deferred_components_validator.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/deferred_components_validator.dart", "repo_id": "flutter", "token_count": 2912 }
797
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /// Throw a specialized exception for expected situations /// where the tool should exit with a clear message to the user /// and no stack trace unless the --verbose option is specified. /// For example: network errors. Never throwToolExit(String? message, { int? exitCode }) { throw ToolExit(message, exitCode: exitCode); } /// Specialized exception for expected situations /// where the tool should exit with a clear message to the user /// and no stack trace unless the --verbose option is specified. /// For example: network errors. class ToolExit implements Exception { ToolExit(this.message, { this.exitCode }); final String? message; final int? exitCode; @override String toString() => 'Error: $message'; }
flutter/packages/flutter_tools/lib/src/base/common.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/common.dart", "repo_id": "flutter", "token_count": 224 }
798
// Copyright 2014 The Flutter Authors. 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 '../base/process.dart'; import '../globals.dart' as globals; import 'async_guard.dart'; import 'io.dart'; typedef SignalHandler = FutureOr<void> Function(ProcessSignal signal); /// A class that manages signal handlers. /// /// Signal handlers are run in the order that they were added. abstract class Signals { @visibleForTesting factory Signals.test({ List<ProcessSignal> exitSignals = defaultExitSignals, ShutdownHooks? shutdownHooks, }) => LocalSignals._(exitSignals, shutdownHooks: shutdownHooks); // The default list of signals that should cause the process to exit. static const List<ProcessSignal> defaultExitSignals = <ProcessSignal>[ ProcessSignal.sigterm, ProcessSignal.sigint, ]; /// Adds a signal handler to run on receipt of signal. /// /// The handler will run after all handlers that were previously added for the /// signal. The function returns an abstract token that should be provided to /// removeHandler to remove the handler. Object addHandler(ProcessSignal signal, SignalHandler handler); /// Removes a signal handler. /// /// Removes the signal handler for the signal identified by the abstract /// token parameter. Returns true if the handler was removed and false /// otherwise. Future<bool> removeHandler(ProcessSignal signal, Object token); /// If a [SignalHandler] throws an error, either synchronously or /// asynchronously, it will be added to this stream instead of propagated. Stream<Object> get errors; } /// A class that manages the real dart:io signal handlers. /// /// We use a singleton instance of this class to ensure that all handlers for /// fatal signals run before this class calls exit(). class LocalSignals implements Signals { LocalSignals._( this.exitSignals, { ShutdownHooks? shutdownHooks, }) : _shutdownHooks = shutdownHooks ?? globals.shutdownHooks; static LocalSignals instance = LocalSignals._( Signals.defaultExitSignals, ); final List<ProcessSignal> exitSignals; final ShutdownHooks _shutdownHooks; // A table mapping (signal, token) -> signal handler. final Map<ProcessSignal, Map<Object, SignalHandler>> _handlersTable = <ProcessSignal, Map<Object, SignalHandler>>{}; // A table mapping (signal) -> signal handler list. The list is in the order // that the signal handlers should be run. final Map<ProcessSignal, List<SignalHandler>> _handlersList = <ProcessSignal, List<SignalHandler>>{}; // A table mapping (signal) -> low-level signal event stream. final Map<ProcessSignal, StreamSubscription<ProcessSignal>> _streamSubscriptions = <ProcessSignal, StreamSubscription<ProcessSignal>>{}; // The stream controller for errors coming from signal handlers. final StreamController<Object> _errorStreamController = StreamController<Object>.broadcast(); @override Stream<Object> get errors => _errorStreamController.stream; @override Object addHandler(ProcessSignal signal, SignalHandler handler) { final Object token = Object(); _handlersTable.putIfAbsent(signal, () => <Object, SignalHandler>{}); _handlersTable[signal]![token] = handler; _handlersList.putIfAbsent(signal, () => <SignalHandler>[]); _handlersList[signal]!.add(handler); // If we added the first one, then call signal.watch(), listen, and cache // the stream controller. if (_handlersList[signal]!.length == 1) { _streamSubscriptions[signal] = signal.watch().listen( _handleSignal, onError: (Object e) { _handlersTable[signal]?.remove(token); _handlersList[signal]?.remove(handler); }, ); } return token; } @override Future<bool> removeHandler(ProcessSignal signal, Object token) async { // We don't know about this signal. if (!_handlersTable.containsKey(signal)) { return false; } // We don't know about this token. if (!_handlersTable[signal]!.containsKey(token)) { return false; } final SignalHandler? handler = _handlersTable[signal]!.remove(token); if (handler == null) { return false; } final bool removed = _handlersList[signal]!.remove(handler); if (!removed) { return false; } // If _handlersList[signal] is empty, then lookup the cached stream // controller and unsubscribe from the stream. if (_handlersList.isEmpty) { await _streamSubscriptions[signal]?.cancel(); } return true; } Future<void> _handleSignal(ProcessSignal s) async { final List<SignalHandler>? handlers = _handlersList[s]; if (handlers != null) { final List<SignalHandler> handlersCopy = handlers.toList(); for (final SignalHandler handler in handlersCopy) { try { await asyncGuard<void>(() async => handler(s)); } on Exception catch (e) { if (_errorStreamController.hasListener) { _errorStreamController.add(e); } } } } // If this was a signal that should cause the process to go down, then // call exit(); if (_shouldExitFor(s)) { await exitWithHooks(0, shutdownHooks: _shutdownHooks); } } bool _shouldExitFor(ProcessSignal signal) => exitSignals.contains(signal); }
flutter/packages/flutter_tools/lib/src/base/signals.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/signals.dart", "repo_id": "flutter", "token_count": 1788 }
799
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '../artifacts.dart'; import '../base/file_system.dart'; import '../build_info.dart'; import 'build_system.dart'; import 'exceptions.dart'; /// A set of source files. abstract class ResolvedFiles { /// Whether any of the sources we evaluated contained a missing depfile. /// /// If so, the build system needs to rerun the visitor after executing the /// build to ensure all hashes are up to date. bool get containsNewDepfile; /// The resolved source files. List<File> get sources; } /// Collects sources for a [Target] into a single list of [FileSystemEntities]. class SourceVisitor implements ResolvedFiles { /// Create a new [SourceVisitor] from an [Environment]. SourceVisitor(this.environment, [ this.inputs = true ]); /// The current environment. final Environment environment; /// Whether we are visiting inputs or outputs. /// /// Defaults to `true`. final bool inputs; @override final List<File> sources = <File>[]; @override bool get containsNewDepfile => _containsNewDepfile; bool _containsNewDepfile = false; /// Visit a depfile which contains both input and output files. /// /// If the file is missing, this visitor is marked as [containsNewDepfile]. /// This is used by the [Node] class to tell the [BuildSystem] to /// defer hash computation until after executing the target. // depfile logic adopted from https://github.com/flutter/flutter/blob/7065e4330624a5a216c8ffbace0a462617dc1bf5/dev/devicelab/lib/framework/apk_utils.dart#L390 void visitDepfile(String name) { final File depfile = environment.buildDir.childFile(name); if (!depfile.existsSync()) { _containsNewDepfile = true; return; } final String contents = depfile.readAsStringSync(); final List<String> colonSeparated = contents.split(': '); if (colonSeparated.length != 2) { environment.logger.printError('Invalid depfile: ${depfile.path}'); return; } if (inputs) { sources.addAll(_processList(colonSeparated[1].trim())); } else { sources.addAll(_processList(colonSeparated[0].trim())); } } final RegExp _separatorExpr = RegExp(r'([^\\]) '); final RegExp _escapeExpr = RegExp(r'\\(.)'); Iterable<File> _processList(String rawText) { return rawText // Put every file on right-hand side on the separate line .replaceAllMapped(_separatorExpr, (Match match) => '${match.group(1)}\n') .split('\n') // Expand escape sequences, so that '\ ', for example,ß becomes ' ' .map<String>((String path) => path.replaceAllMapped(_escapeExpr, (Match match) => match.group(1)!).trim()) .where((String path) => path.isNotEmpty) .toSet() .map(environment.fileSystem.file); } /// Visit a [Source] which contains a file URL. /// /// The URL may include constants defined in an [Environment]. If /// [optional] is true, the file is not required to exist. In this case, it /// is never resolved as an input. void visitPattern(String pattern, bool optional) { // perform substitution of the environmental values and then // of the local values. final List<String> segments = <String>[]; final List<String> rawParts = pattern.split('/'); final bool hasWildcard = rawParts.last.contains('*'); String? wildcardFile; if (hasWildcard) { wildcardFile = rawParts.removeLast(); } // If the pattern does not start with an env variable, then we have nothing // to resolve it to, error out. switch (rawParts.first) { case Environment.kProjectDirectory: segments.addAll( environment.fileSystem.path.split(environment.projectDir.resolveSymbolicLinksSync())); case Environment.kBuildDirectory: segments.addAll(environment.fileSystem.path.split( environment.buildDir.resolveSymbolicLinksSync())); case Environment.kCacheDirectory: segments.addAll( environment.fileSystem.path.split(environment.cacheDir.resolveSymbolicLinksSync())); case Environment.kFlutterRootDirectory: // flutter root will not contain a symbolic link. segments.addAll( environment.fileSystem.path.split(environment.flutterRootDir.absolute.path)); case Environment.kOutputDirectory: segments.addAll( environment.fileSystem.path.split(environment.outputDir.resolveSymbolicLinksSync())); default: throw InvalidPatternException(pattern); } rawParts.skip(1).forEach(segments.add); final String filePath = environment.fileSystem.path.joinAll(segments); if (!hasWildcard) { if (optional && !environment.fileSystem.isFileSync(filePath)) { return; } sources.add(environment.fileSystem.file( environment.fileSystem.path.normalize(filePath))); return; } // Perform a simple match by splitting the wildcard containing file one // the `*`. For example, for `/*.dart`, we get [.dart]. We then check // that part of the file matches. If there are values before and after // the `*` we need to check that both match without overlapping. For // example, `foo_*_.dart`. We want to match `foo_b_.dart` but not // `foo_.dart`. To do so, we first subtract the first section from the // string if the first segment matches. final List<String> wildcardSegments = wildcardFile?.split('*') ?? <String>[]; if (wildcardSegments.length > 2) { throw InvalidPatternException(pattern); } if (!environment.fileSystem.directory(filePath).existsSync()) { environment.fileSystem.directory(filePath).createSync(recursive: true); } for (final FileSystemEntity entity in environment.fileSystem.directory(filePath).listSync()) { final String filename = environment.fileSystem.path.basename(entity.path); if (wildcardSegments.isEmpty) { sources.add(environment.fileSystem.file(entity.absolute)); } else if (wildcardSegments.length == 1) { if (filename.startsWith(wildcardSegments[0]) || filename.endsWith(wildcardSegments[0])) { sources.add(environment.fileSystem.file(entity.absolute)); } } else if (filename.startsWith(wildcardSegments[0])) { if (filename.substring(wildcardSegments[0].length).endsWith(wildcardSegments[1])) { sources.add(environment.fileSystem.file(entity.absolute)); } } } } /// Visit a [Source] which is defined by an [Artifact] from the flutter cache. /// /// If the [Artifact] points to a directory then all child files are included. /// To increase the performance of builds that use a known revision of Flutter, /// these are updated to point towards the engine.version file instead of /// the artifact itself. void visitArtifact(Artifact artifact, TargetPlatform? platform, BuildMode? mode) { // This is not a local engine. if (environment.engineVersion != null) { sources.add(environment.flutterRootDir .childDirectory('bin') .childDirectory('internal') .childFile('engine.version'), ); return; } final String path = environment.artifacts .getArtifactPath(artifact, platform: platform, mode: mode); if (environment.fileSystem.isDirectorySync(path)) { sources.addAll(<File>[ for (final FileSystemEntity entity in environment.fileSystem.directory(path).listSync(recursive: true)) if (entity is File) entity, ]); return; } sources.add(environment.fileSystem.file(path)); } /// Visit a [Source] which is defined by an [HostArtifact] from the flutter cache. /// /// If the [Artifact] points to a directory then all child files are included. /// To increase the performance of builds that use a known revision of Flutter, /// these are updated to point towards the engine.version file instead of /// the artifact itself. void visitHostArtifact(HostArtifact artifact) { // This is not a local engine. if (environment.engineVersion != null) { sources.add(environment.flutterRootDir .childDirectory('bin') .childDirectory('internal') .childFile('engine.version'), ); return; } final FileSystemEntity entity = environment.artifacts.getHostArtifact(artifact); if (entity is Directory) { sources.addAll(<File>[ for (final FileSystemEntity entity in entity.listSync(recursive: true)) if (entity is File) entity, ]); return; } sources.add(entity as File); } } /// A description of an input or output of a [Target]. abstract class Source { /// This source is a file URL which contains some references to magic /// environment variables. const factory Source.pattern(String pattern, { bool optional }) = _PatternSource; /// The source is provided by an [Artifact]. /// /// If [artifact] points to a directory then all child files are included. const factory Source.artifact(Artifact artifact, {TargetPlatform? platform, BuildMode? mode}) = _ArtifactSource; /// The source is provided by an [HostArtifact]. /// /// If [artifact] points to a directory then all child files are included. const factory Source.hostArtifact(HostArtifact artifact) = _HostArtifactSource; /// Visit the particular source type. void accept(SourceVisitor visitor); /// Whether the output source provided can be known before executing the rule. /// /// This does not apply to inputs, which are always explicit and must be /// evaluated before the build. /// /// For example, [Source.pattern] and [Source.version] are not implicit /// provided they do not use any wildcards. bool get implicit; } class _PatternSource implements Source { const _PatternSource(this.value, { this.optional = false }); final String value; final bool optional; @override void accept(SourceVisitor visitor) => visitor.visitPattern(value, optional); @override bool get implicit => value.contains('*'); } class _ArtifactSource implements Source { const _ArtifactSource(this.artifact, { this.platform, this.mode }); final Artifact artifact; final TargetPlatform? platform; final BuildMode? mode; @override void accept(SourceVisitor visitor) => visitor.visitArtifact(artifact, platform, mode); @override bool get implicit => false; } class _HostArtifactSource implements Source { const _HostArtifactSource(this.artifact); final HostArtifact artifact; @override void accept(SourceVisitor visitor) => visitor.visitHostArtifact(artifact); @override bool get implicit => false; }
flutter/packages/flutter_tools/lib/src/build_system/source.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/source.dart", "repo_id": "flutter", "token_count": 3554 }
800
// Copyright 2014 The Flutter Authors. 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 'dart:typed_data'; import 'package:meta/meta.dart'; import 'package:pool/pool.dart'; import 'package:process/process.dart'; import '../../artifacts.dart'; import '../../base/error_handling_io.dart'; import '../../base/file_system.dart'; import '../../base/io.dart'; import '../../base/logger.dart'; import '../../convert.dart'; import '../../devfs.dart'; import '../build_system.dart'; /// A wrapper around [SceneImporter] to support hot reload of 3D models. class DevelopmentSceneImporter { DevelopmentSceneImporter({ required SceneImporter sceneImporter, required FileSystem fileSystem, @visibleForTesting math.Random? random, }) : _sceneImporter = sceneImporter, _fileSystem = fileSystem, _random = random ?? math.Random(); final SceneImporter _sceneImporter; final FileSystem _fileSystem; final Pool _compilationPool = Pool(4); final math.Random _random; /// Recompile the input ipscene and return a devfs content that should be /// synced to the attached device in its place. Future<DevFSContent?> reimportScene(DevFSContent inputScene) async { final File output = _fileSystem.systemTempDirectory.childFile('${_random.nextDouble()}.temp'); late File inputFile; bool cleanupInput = false; Uint8List result; PoolResource? resource; try { resource = await _compilationPool.request(); if (inputScene is DevFSFileContent) { inputFile = inputScene.file as File; } else { inputFile = _fileSystem.systemTempDirectory.childFile('${_random.nextDouble()}.temp'); inputFile.writeAsBytesSync(await inputScene.contentsAsBytes()); cleanupInput = true; } final bool success = await _sceneImporter.importScene( input: inputFile, outputPath: output.path, fatal: false, ); if (!success) { return null; } result = output.readAsBytesSync(); } finally { resource?.release(); ErrorHandlingFileSystem.deleteIfExists(output); if (cleanupInput) { ErrorHandlingFileSystem.deleteIfExists(inputFile); } } return DevFSByteContent(result); } } /// A class the wraps the functionality of the Impeller Scene importer scenec. class SceneImporter { SceneImporter({ required ProcessManager processManager, required Logger logger, required FileSystem fileSystem, required Artifacts artifacts, }) : _processManager = processManager, _logger = logger, _fs = fileSystem, _artifacts = artifacts; final ProcessManager _processManager; final Logger _logger; final FileSystem _fs; final Artifacts _artifacts; /// The [Source] inputs that targets using this should depend on. /// /// See [Target.inputs]. static const List<Source> inputs = <Source>[ Source.pattern( '{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/tools/scene_importer.dart'), Source.hostArtifact(HostArtifact.scenec), ]; /// Calls scenec, which transforms the [input] 3D model into an imported /// ipscene at [outputPath]. /// /// All parameters are required. /// /// If the scene importer subprocess fails, it will print the stdout and /// stderr to the log and throw a [SceneImporterException]. Otherwise, it /// will return true. Future<bool> importScene({ required File input, required String outputPath, bool fatal = true, }) async { final File scenec = _fs.file( _artifacts.getHostArtifact(HostArtifact.scenec), ); if (!scenec.existsSync()) { throw SceneImporterException._( 'The scenec utility is missing at "${scenec.path}". ' 'Run "flutter doctor".', ); } final List<String> cmd = <String>[ scenec.path, '--input=${input.path}', '--output=$outputPath', ]; _logger.printTrace('scenec command: $cmd'); final Process scenecProcess = await _processManager.start(cmd); final int code = await scenecProcess.exitCode; if (code != 0) { final String stdout = await utf8.decodeStream(scenecProcess.stdout); final String stderr = await utf8.decodeStream(scenecProcess.stderr); _logger.printTrace(stdout); _logger.printError(stderr); if (fatal) { throw SceneImporterException._( 'Scene import of "${input.path}" to "$outputPath" ' 'failed with exit code $code.\n' 'scenec stdout:\n$stdout\n' 'scenec stderr:\n$stderr', ); } return false; } return true; } } class SceneImporterException implements Exception { SceneImporterException._(this.message); final String message; @override String toString() => 'SceneImporterException: $message\n\n'; }
flutter/packages/flutter_tools/lib/src/build_system/tools/scene_importer.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/tools/scene_importer.dart", "repo_id": "flutter", "token_count": 1791 }
801
// Copyright 2014 The Flutter Authors. 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:unified_analytics/unified_analytics.dart'; import '../android/android_builder.dart'; import '../android/build_validation.dart'; import '../android/gradle_utils.dart'; import '../build_info.dart'; import '../cache.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart' show FlutterCommandResult; import 'build.dart'; class BuildApkCommand extends BuildSubCommand { BuildApkCommand({ required super.logger, bool verboseHelp = false }) : super(verboseHelp: verboseHelp) { addTreeShakeIconsFlag(); usesTargetOption(); addBuildModeFlags(verboseHelp: verboseHelp); usesFlavorOption(); usesPubOption(); usesBuildNumberOption(); usesBuildNameOption(); addShrinkingFlag(verboseHelp: verboseHelp); addSplitDebugInfoOption(); addDartObfuscationOption(); usesDartDefineOption(); usesExtraDartFlagOptions(verboseHelp: verboseHelp); addBundleSkSLPathOption(hide: !verboseHelp); addEnableExperimentation(hide: !verboseHelp); addBuildPerformanceFile(hide: !verboseHelp); addNullSafetyModeOptions(hide: !verboseHelp); usesAnalyzeSizeFlag(); addAndroidSpecificBuildOptions(hide: !verboseHelp); addIgnoreDeprecationOption(); argParser ..addFlag('split-per-abi', negatable: false, help: 'Whether to split the APKs per ABIs. ' 'To learn more, see: https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split', ) ..addFlag('config-only', help: 'Generate build files used by flutter but ' 'do not build any artifacts.') ..addMultiOption('target-platform', defaultsTo: <String>['android-arm', 'android-arm64', 'android-x64'], allowed: <String>['android-arm', 'android-arm64', 'android-x86', 'android-x64'], help: 'The target platform for which the app is compiled.', ); usesTrackWidgetCreation(verboseHelp: verboseHelp); } @override final String name = 'apk'; @override DeprecationBehavior get deprecationBehavior => boolArg('ignore-deprecation') ? DeprecationBehavior.ignore : DeprecationBehavior.exit; bool get configOnly => boolArg('config-only'); @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{ DevelopmentArtifact.androidGenSnapshot, }; @override final String description = 'Build an Android APK file from your app.\n\n' "This command can build debug and release versions of your application. 'debug' builds support " "debugging and a quick development cycle. 'release' builds don't support debugging and are " 'suitable for deploying to app stores. If you are deploying the app to the Play Store, ' "it's recommended to use app bundles or split the APK to reduce the APK size. Learn more at:\n\n" ' * https://developer.android.com/guide/app-bundle\n' ' * https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split'; @override Future<CustomDimensions> get usageValues async { String buildMode; if (boolArg('release')) { buildMode = 'release'; } else if (boolArg('debug')) { buildMode = 'debug'; } else if (boolArg('profile')) { buildMode = 'profile'; } else { // The build defaults to release. buildMode = 'release'; } return CustomDimensions( commandBuildApkTargetPlatform: stringsArg('target-platform').join(','), commandBuildApkBuildMode: buildMode, commandBuildApkSplitPerAbi: boolArg('split-per-abi'), ); } @override Future<Event> unifiedAnalyticsUsageValues(String commandPath) async { final String buildMode; if (boolArg('release')) { buildMode = 'release'; } else if (boolArg('debug')) { buildMode = 'debug'; } else if (boolArg('profile')) { buildMode = 'profile'; } else { // The build defaults to release. buildMode = 'release'; } return Event.commandUsageValues( workflow: commandPath, commandHasTerminal: hasTerminal, buildApkTargetPlatform: stringsArg('target-platform').join(','), buildApkBuildMode: buildMode, buildApkSplitPerAbi: boolArg('split-per-abi'), ); } @override Future<FlutterCommandResult> runCommand() async { if (globals.androidSdk == null) { exitWithNoSdkMessage(); } final BuildInfo buildInfo = await getBuildInfo(); final AndroidBuildInfo androidBuildInfo = AndroidBuildInfo( buildInfo, splitPerAbi: boolArg('split-per-abi'), targetArchs: stringsArg('target-platform').map<AndroidArch>(getAndroidArchForName), ); validateBuild(androidBuildInfo); displayNullSafetyMode(androidBuildInfo.buildInfo); globals.terminal.usesTerminalUi = true; await androidBuilder?.buildApk( project: FlutterProject.current(), target: targetFile, androidBuildInfo: androidBuildInfo, configOnly: configOnly, ); return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/build_apk.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/build_apk.dart", "repo_id": "flutter", "token_count": 1861 }
802
// Copyright 2014 The Flutter Authors. 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:async/async.dart'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import '../base/common.dart'; import '../base/error_handling_io.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/os.dart'; import '../base/platform.dart'; import '../base/terminal.dart'; import '../convert.dart'; import '../custom_devices/custom_device.dart'; import '../custom_devices/custom_device_config.dart'; import '../custom_devices/custom_devices_config.dart'; import '../device_port_forwarder.dart'; import '../features.dart'; import '../runner/flutter_command.dart'; import '../runner/flutter_command_runner.dart'; /// just the function signature of the [print] function. /// The Object arg may be null. typedef PrintFn = void Function(Object); class CustomDevicesCommand extends FlutterCommand { factory CustomDevicesCommand({ required CustomDevicesConfig customDevicesConfig, required OperatingSystemUtils operatingSystemUtils, required Terminal terminal, required Platform platform, required ProcessManager processManager, required FileSystem fileSystem, required Logger logger, required FeatureFlags featureFlags, }) { return CustomDevicesCommand._common( customDevicesConfig: customDevicesConfig, operatingSystemUtils: operatingSystemUtils, terminal: terminal, platform: platform, processManager: processManager, fileSystem: fileSystem, logger: logger, featureFlags: featureFlags ); } @visibleForTesting factory CustomDevicesCommand.test({ required CustomDevicesConfig customDevicesConfig, required OperatingSystemUtils operatingSystemUtils, required Terminal terminal, required Platform platform, required ProcessManager processManager, required FileSystem fileSystem, required Logger logger, required FeatureFlags featureFlags, PrintFn usagePrintFn = print }) { return CustomDevicesCommand._common( customDevicesConfig: customDevicesConfig, operatingSystemUtils: operatingSystemUtils, terminal: terminal, platform: platform, processManager: processManager, fileSystem: fileSystem, logger: logger, featureFlags: featureFlags, usagePrintFn: usagePrintFn ); } CustomDevicesCommand._common({ required CustomDevicesConfig customDevicesConfig, required OperatingSystemUtils operatingSystemUtils, required Terminal terminal, required Platform platform, required ProcessManager processManager, required FileSystem fileSystem, required Logger logger, required FeatureFlags featureFlags, PrintFn usagePrintFn = print, }) : _customDevicesConfig = customDevicesConfig, _featureFlags = featureFlags, _usagePrintFn = usagePrintFn { addSubcommand(CustomDevicesListCommand( customDevicesConfig: customDevicesConfig, featureFlags: featureFlags, logger: logger, )); addSubcommand(CustomDevicesResetCommand( customDevicesConfig: customDevicesConfig, featureFlags: featureFlags, fileSystem: fileSystem, logger: logger, )); addSubcommand(CustomDevicesAddCommand( customDevicesConfig: customDevicesConfig, operatingSystemUtils: operatingSystemUtils, terminal: terminal, platform: platform, featureFlags: featureFlags, processManager: processManager, fileSystem: fileSystem, logger: logger, )); addSubcommand(CustomDevicesDeleteCommand( customDevicesConfig: customDevicesConfig, featureFlags: featureFlags, fileSystem: fileSystem, logger: logger, )); } final CustomDevicesConfig _customDevicesConfig; final FeatureFlags _featureFlags; final PrintFn _usagePrintFn; @override String get description { String configFileLine; if (_featureFlags.areCustomDevicesEnabled) { configFileLine = '\nMakes changes to the config file at "${_customDevicesConfig.configPath}".\n'; } else { configFileLine = ''; } return ''' List, reset, add and delete custom devices. $configFileLine This is just a collection of commonly used shorthands for things like adding ssh devices, resetting (with backup) and checking the config file. For advanced configuration or more complete documentation, edit the config file with an editor that supports JSON schemas like VS Code. Requires the custom devices feature to be enabled. You can enable it using "flutter config --enable-custom-devices". '''; } @override String get name => 'custom-devices'; @override String get category => FlutterCommandCategory.tools; @override Future<FlutterCommandResult> runCommand() async { return FlutterCommandResult.success(); } @override void printUsage() { _usagePrintFn(usage); } } /// This class is meant to provide some commonly used utility functions /// to the subcommands, like backing up the config file & checking if the /// feature is enabled. abstract class CustomDevicesCommandBase extends FlutterCommand { CustomDevicesCommandBase({ required this.customDevicesConfig, required this.featureFlags, required this.fileSystem, required this.logger, }); @protected final CustomDevicesConfig customDevicesConfig; @protected final FeatureFlags featureFlags; @protected final FileSystem? fileSystem; @protected final Logger logger; /// The path to the (potentially non-existing) backup of the config file. @protected String get configBackupPath => '${customDevicesConfig.configPath}.bak'; /// Copies the current config file to [configBackupPath], overwriting it /// if necessary. Returns false and does nothing if the current config file /// doesn't exist. (True otherwise) @protected bool backup() { final File configFile = fileSystem!.file(customDevicesConfig.configPath); if (configFile.existsSync()) { configFile.copySync(configBackupPath); return true; } return false; } /// Checks if the custom devices feature is enabled and returns true/false /// accordingly. Additionally, logs an error if it's not enabled with a hint /// on how to enable it. @protected void checkFeatureEnabled() { if (!featureFlags.areCustomDevicesEnabled) { throwToolExit( 'Custom devices feature must be enabled. ' 'Enable using `flutter config --enable-custom-devices`.' ); } } } class CustomDevicesListCommand extends CustomDevicesCommandBase { CustomDevicesListCommand({ required super.customDevicesConfig, required super.featureFlags, required super.logger, }) : super( fileSystem: null ); @override String get description => ''' List the currently configured custom devices, both enabled and disabled, reachable or not. '''; @override String get name => 'list'; @override Future<FlutterCommandResult> runCommand() async { checkFeatureEnabled(); late List<CustomDeviceConfig> devices; try { devices = customDevicesConfig.devices; } on Exception { throwToolExit('Could not list custom devices.'); } if (devices.isEmpty) { logger.printStatus('No custom devices found in "${customDevicesConfig.configPath}"'); } else { logger.printStatus('List of custom devices in "${customDevicesConfig.configPath}":'); for (final CustomDeviceConfig device in devices) { logger.printStatus('id: ${device.id}, label: ${device.label}, enabled: ${device.enabled}', indent: 2, hangingIndent: 2); } } return FlutterCommandResult.success(); } } class CustomDevicesResetCommand extends CustomDevicesCommandBase { CustomDevicesResetCommand({ required super.customDevicesConfig, required super.featureFlags, required FileSystem super.fileSystem, required super.logger, }); @override String get description => ''' Reset the config file to the default. The current config file will be backed up to the same path, but with a `.bak` appended. If a file already exists at the backup location, it will be overwritten. '''; @override String get name => 'reset'; @override Future<FlutterCommandResult> runCommand() async { checkFeatureEnabled(); final bool wasBackedUp = backup(); ErrorHandlingFileSystem.deleteIfExists(fileSystem!.file(customDevicesConfig.configPath)); customDevicesConfig.ensureFileExists(); logger.printStatus( wasBackedUp ? 'Successfully reset the custom devices config file and created a ' 'backup at "$configBackupPath".' : 'Successfully reset the custom devices config file.' ); return FlutterCommandResult.success(); } } class CustomDevicesAddCommand extends CustomDevicesCommandBase { CustomDevicesAddCommand({ required super.customDevicesConfig, required OperatingSystemUtils operatingSystemUtils, required Terminal terminal, required Platform platform, required super.featureFlags, required ProcessManager processManager, required FileSystem super.fileSystem, required super.logger, }) : _operatingSystemUtils = operatingSystemUtils, _terminal = terminal, _platform = platform, _processManager = processManager { argParser.addFlag( _kCheck, help: 'Make sure the config actually works. This will execute some of the ' 'commands in the config (if necessary with dummy arguments). This ' 'flag is enabled by default when "--json" is not specified. If ' '"--json" is given, it is disabled by default.\n' 'For example, a config with "null" as the "runDebug" command is ' 'invalid. If the "runDebug" command is valid (so it is an array of ' 'strings) but the command is not found (because you have a typo, for ' 'example), the config won\'t work and "--check" will spot that.' ); argParser.addOption( _kJson, help: 'Add the custom device described by this JSON-encoded string to the ' 'list of custom-devices instead of using the normal, interactive way ' 'of configuring. Useful if you want to use the "flutter custom-devices ' 'add" command from a script, or use it non-interactively for some ' 'other reason.\n' "By default, this won't check whether the passed in config actually " 'works. For more info see the "--check" option.', valueHelp: '{"id": "pi", ...}', aliases: _kJsonAliases ); argParser.addFlag( _kSsh, help: 'Add a ssh-device. This will automatically fill out some of the config ' 'options for you with good defaults, and in other cases save you some ' "typing. So you'll only need to enter some things like hostname and " 'username of the remote device instead of entering each individual ' 'command.', defaultsTo: true, negatable: false ); } static const String _kJson = 'json'; static const List<String> _kJsonAliases = <String>['js']; static const String _kCheck = 'check'; static const String _kSsh = 'ssh'; // A hostname consists of one or more "names", separated by a dot. // A name may consist of alpha-numeric characters. Hyphens are also allowed, // but not as the first or last character of the name. static final RegExp _hostnameRegex = RegExp(r'^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$'); final OperatingSystemUtils _operatingSystemUtils; final Terminal _terminal; final Platform _platform; final ProcessManager _processManager; late StreamQueue<String> inputs; @override String get description => 'Add a new device the custom devices config file.'; @override String get name => 'add'; void _printConfigCheckingError(String err) { logger.printError(err); } /// Check this config by executing some of the commands, see if they run /// fine. Future<bool> _checkConfigWithLogging(final CustomDeviceConfig config) async { final CustomDevice device = CustomDevice( config: config, logger: logger, processManager: _processManager ); bool result = true; try { final bool reachable = await device.tryPing(); if (!reachable) { _printConfigCheckingError("Couldn't ping device."); result = false; } } on Exception catch (e) { _printConfigCheckingError('While executing ping command: $e'); result = false; } final Directory temp = await fileSystem!.systemTempDirectory.createTemp(); try { final bool ok = await device.tryInstall( localPath: temp.path, appName: temp.basename ); if (!ok) { _printConfigCheckingError("Couldn't install test app on device."); result = false; } } on Exception catch (e) { _printConfigCheckingError('While executing install command: $e'); result = false; } await temp.delete(); try { final bool ok = await device.tryUninstall(appName: temp.basename); if (!ok) { _printConfigCheckingError("Couldn't uninstall test app from device."); result = false; } } on Exception catch (e) { _printConfigCheckingError('While executing uninstall command: $e'); result = false; } if (config.usesPortForwarding) { final CustomDevicePortForwarder portForwarder = CustomDevicePortForwarder( deviceName: device.name, forwardPortCommand: config.forwardPortCommand!, forwardPortSuccessRegex: config.forwardPortSuccessRegex!, processManager: _processManager, logger: logger, ); try { // find a random port we can forward final int port = await _operatingSystemUtils.findFreePort(); final ForwardedPort? forwardedPort = await portForwarder.tryForward(port, port); if (forwardedPort == null) { _printConfigCheckingError("Couldn't forward test port $port from device.",); result = false; } else { await portForwarder.unforward(forwardedPort); } } on Exception catch (e) { _printConfigCheckingError( 'While forwarding/unforwarding device port: $e', ); result = false; } } if (result) { logger.printStatus('Passed all checks successfully.'); } return result; } /// Run non-interactively (useful if running from scripts or bots), /// add value of the `--json` arg to the config. /// /// Only check if `--check` is explicitly specified. (Don't check by default) Future<FlutterCommandResult> runNonInteractively() async { final String jsonStr = stringArg(_kJson)!; final bool shouldCheck = boolArg(_kCheck); dynamic json; try { json = jsonDecode(jsonStr); } on FormatException catch (e) { throwToolExit('Could not decode json: $e'); } late CustomDeviceConfig config; try { config = CustomDeviceConfig.fromJson(json); } on CustomDeviceRevivalException catch (e) { throwToolExit('Invalid custom device config: $e'); } if (shouldCheck && !await _checkConfigWithLogging(config)) { throwToolExit("Custom device didn't pass all checks."); } customDevicesConfig.add(config); printSuccessfullyAdded(); return FlutterCommandResult.success(); } void printSuccessfullyAdded() { logger.printStatus('Successfully added custom device to config file at "${customDevicesConfig.configPath}".'); } bool _isValidHostname(String s) => _hostnameRegex.hasMatch(s); bool _isValidIpAddr(String s) => InternetAddress.tryParse(s) != null; /// Ask the user to input a string. Future<String?> askForString( String name, { String? description, String? example, String? defaultsTo, Future<bool> Function(String)? validator, }) async { String msg = description ?? name; final String exampleOrDefault = <String>[ if (example != null) 'example: $example', if (defaultsTo != null) 'empty for $defaultsTo', ].join(', '); if (exampleOrDefault.isNotEmpty) { msg += ' ($exampleOrDefault)'; } logger.printStatus(msg); while (true) { if (!await inputs.hasNext) { return null; } final String input = await inputs.next; if (validator != null && !await validator(input)) { logger.printStatus('Invalid input. Please enter $name:'); } else { return input; } } } /// Ask the user for a y(es) / n(o) or empty input. Future<bool> askForBool( String name, { String? description, bool defaultsTo = true, }) async { final String defaultsToStr = defaultsTo ? '[Y/n]' : '[y/N]'; logger.printStatus('$description $defaultsToStr (empty for default)'); while (true) { final String input = await inputs.next; if (input.isEmpty) { return defaultsTo; } else if (input.toLowerCase() == 'y') { return true; } else if (input.toLowerCase() == 'n') { return false; } else { logger.printStatus('Invalid input. Expected is either y, n or empty for default. $name? $defaultsToStr'); } } } /// Ask the user if he wants to apply the config. /// Shows a different prompt if errors or warnings exist in the config. Future<bool> askApplyConfig({bool hasErrorsOrWarnings = false}) { return askForBool( 'apply', description: hasErrorsOrWarnings ? 'Warnings or errors exist in custom device. ' 'Would you like to add the custom device to the config anyway?' : 'Would you like to add the custom device to the config now?', defaultsTo: !hasErrorsOrWarnings ); } /// Run interactively (with user prompts), the target device should be /// connected to via ssh. Future<FlutterCommandResult> runInteractivelySsh() async { final bool shouldCheck = boolArg(_kCheck); // Listen to the keystrokes stream as late as possible, since it's a // single-subscription stream apparently. // Also, _terminal.keystrokes can be closed unexpectedly, which will result // in StreamQueue.next throwing a StateError when make the StreamQueue listen // to that directly. // This caused errors when using Ctrl+C to terminate while the // custom-devices add command is waiting for user input. // So instead, we add the keystrokes stream events to a new single-subscription // stream and listen to that instead. final StreamController<String> nonClosingKeystrokes = StreamController<String>(); final StreamSubscription<String> keystrokesSubscription = _terminal.keystrokes.listen( (String s) => nonClosingKeystrokes.add(s.trim()), cancelOnError: true ); inputs = StreamQueue<String>(nonClosingKeystrokes.stream); final String id = (await askForString( 'id', description: 'Please enter the id you want to device to have. Must contain only ' 'alphanumeric or underscore characters.', example: 'pi', validator: (String s) async => RegExp(r'^\w+$').hasMatch(s), ))!; final String label = (await askForString( 'label', description: 'Please enter the label of the device, which is a slightly more verbose ' 'name for the device.', example: 'Raspberry Pi', ))!; final String sdkNameAndVersion = (await askForString( 'SDK name and version', example: 'Raspberry Pi 4 Model B+', ))!; final bool enabled = await askForBool( 'enabled', description: 'Should the device be enabled?', ); final String targetStr = (await askForString( 'target', description: 'Please enter the hostname or IPv4/v6 address of the device.', example: 'raspberrypi', validator: (String s) async => _isValidHostname(s) || _isValidIpAddr(s) ))!; final InternetAddress? targetIp = InternetAddress.tryParse(targetStr); final bool useIp = targetIp != null; final bool ipv6 = useIp && targetIp.type == InternetAddressType.IPv6; final InternetAddress loopbackIp = ipv6 ? InternetAddress.loopbackIPv6 : InternetAddress.loopbackIPv4; final String username = (await askForString( 'username', description: 'Please enter the username used for ssh-ing into the remote device.', example: 'pi', defaultsTo: 'no username', ))!; final String remoteRunDebugCommand = (await askForString( 'run command', description: 'Please enter the command executed on the remote device for starting ' r'the app. "/tmp/${appName}" is the path to the asset bundle.', example: r'flutter-pi /tmp/${appName}' ))!; final bool usePortForwarding = await askForBool( 'use port forwarding', description: 'Should the device use port forwarding? ' 'Using port forwarding is the default because it works in all cases, however if your ' 'remote device has a static IP address and you have a way of ' 'specifying the "--vm-service-host=<ip>" engine option, you might prefer ' 'not using port forwarding.', ); final String screenshotCommand = (await askForString( 'screenshot command', description: 'Enter the command executed on the remote device for taking a screenshot.', example: r"fbgrab /tmp/screenshot.png && cat /tmp/screenshot.png | base64 | tr -d ' \n\t'", defaultsTo: 'no screenshotting support', ))!; // SSH expects IPv6 addresses to use the bracket syntax like URIs do too, // but the IPv6 the user enters is a raw IPv6 address, so we need to wrap it. final String sshTarget = (username.isNotEmpty ? '$username@' : '') + (ipv6 ? '[${targetIp.address}]' : targetStr); final String formattedLoopbackIp = ipv6 ? '[${loopbackIp.address}]' : loopbackIp.address; CustomDeviceConfig config = CustomDeviceConfig( id: id, label: label, sdkNameAndVersion: sdkNameAndVersion, enabled: enabled, // host-platform specific, filled out later pingCommand: const <String>[], postBuildCommand: const <String>[], // just install to /tmp/${appName} by default installCommand: <String>[ 'scp', '-r', '-o', 'BatchMode=yes', if (ipv6) '-6', r'${localPath}', '$sshTarget:/tmp/\${appName}', ], uninstallCommand: <String>[ 'ssh', '-o', 'BatchMode=yes', if (ipv6) '-6', sshTarget, r'rm -rf "/tmp/${appName}"', ], runDebugCommand: <String>[ 'ssh', '-o', 'BatchMode=yes', if (ipv6) '-6', sshTarget, remoteRunDebugCommand, ], forwardPortCommand: usePortForwarding ? <String>[ 'ssh', '-o', 'BatchMode=yes', '-o', 'ExitOnForwardFailure=yes', if (ipv6) '-6', '-L', '$formattedLoopbackIp:\${hostPort}:$formattedLoopbackIp:\${devicePort}', sshTarget, "echo 'Port forwarding success'; read", ] : null, forwardPortSuccessRegex: usePortForwarding ? RegExp('Port forwarding success') : null, screenshotCommand: screenshotCommand.isNotEmpty ? <String>[ 'ssh', '-o', 'BatchMode=yes', if (ipv6) '-6', sshTarget, screenshotCommand, ] : null ); if (_platform.isWindows) { config = config.copyWith( pingCommand: <String>[ 'ping', if (ipv6) '-6', '-n', '1', '-w', '500', targetStr, ], explicitPingSuccessRegex: true, pingSuccessRegex: RegExp(r'[<=]\d+ms') ); } else if (_platform.isLinux || _platform.isMacOS) { config = config.copyWith( pingCommand: <String>[ 'ping', if (ipv6) '-6', '-c', '1', '-w', '1', targetStr, ], explicitPingSuccessRegex: true, ); } else { throw UnsupportedError('Unsupported operating system'); } final bool apply = await askApplyConfig( hasErrorsOrWarnings: shouldCheck && !(await _checkConfigWithLogging(config)) ); unawaited(keystrokesSubscription.cancel()); unawaited(nonClosingKeystrokes.close()); if (apply) { customDevicesConfig.add(config); printSuccessfullyAdded(); } return FlutterCommandResult.success(); } @override Future<FlutterCommandResult> runCommand() async { checkFeatureEnabled(); if (stringArg(_kJson) != null) { return runNonInteractively(); } if (boolArg(_kSsh)) { return runInteractivelySsh(); } throw UnsupportedError('Unknown run mode'); } } class CustomDevicesDeleteCommand extends CustomDevicesCommandBase { CustomDevicesDeleteCommand({ required super.customDevicesConfig, required super.featureFlags, required FileSystem super.fileSystem, required super.logger, }); @override String get description => ''' Delete a device from the config file. '''; @override String get name => 'delete'; @override Future<FlutterCommandResult> runCommand() async { checkFeatureEnabled(); final String? id = globalResults![FlutterGlobalOptions.kDeviceIdOption] as String?; if (id == null || !customDevicesConfig.contains(id)) { throwToolExit('Couldn\'t find device with id "$id" in config at "${customDevicesConfig.configPath}"'); } backup(); customDevicesConfig.remove(id); logger.printStatus('Successfully removed device with id "$id" from config at "${customDevicesConfig.configPath}"'); return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/custom_devices.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/custom_devices.dart", "repo_id": "flutter", "token_count": 9313 }
803
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import '../base/common.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../cache.dart'; import '../features.dart'; import '../runner/flutter_command.dart'; /// The flutter precache command allows downloading of cache artifacts without /// the use of device/artifact autodetection. class PrecacheCommand extends FlutterCommand { PrecacheCommand({ bool verboseHelp = false, required Cache cache, required Platform platform, required Logger logger, required FeatureFlags featureFlags, }) : _cache = cache, _platform = platform, _logger = logger, _featureFlags = featureFlags { argParser.addFlag('all-platforms', abbr: 'a', negatable: false, help: 'Precache artifacts for all host platforms.', aliases: const <String>['all']); argParser.addFlag('force', abbr: 'f', negatable: false, help: 'Force re-downloading of artifacts.'); argParser.addFlag('android', help: 'Precache artifacts for Android development.', hide: !verboseHelp); argParser.addFlag('android_gen_snapshot', help: 'Precache gen_snapshot for Android development.', hide: !verboseHelp); argParser.addFlag('android_maven', help: 'Precache Gradle dependencies for Android development.', hide: !verboseHelp); argParser.addFlag('android_internal_build', help: 'Precache dependencies for internal Android development.', hide: !verboseHelp); argParser.addFlag('ios', help: 'Precache artifacts for iOS development.'); argParser.addFlag('web', help: 'Precache artifacts for web development.'); argParser.addFlag('linux', help: 'Precache artifacts for Linux desktop development.'); argParser.addFlag('windows', help: 'Precache artifacts for Windows desktop development.'); argParser.addFlag('macos', help: 'Precache artifacts for macOS desktop development.'); argParser.addFlag('fuchsia', help: 'Precache artifacts for Fuchsia development.'); argParser.addFlag('universal', defaultsTo: true, help: 'Precache artifacts required for any development platform.'); argParser.addFlag('flutter_runner', help: 'Precache the flutter runner artifacts.', hide: !verboseHelp); argParser.addFlag('use-unsigned-mac-binaries', help: 'Precache the unsigned macOS binaries when available.', hide: !verboseHelp); } final Cache _cache; final Logger _logger; final Platform _platform; final FeatureFlags _featureFlags; @override final String name = 'precache'; @override final String description = "Populate the Flutter tool's cache of binary artifacts.\n\n" 'If no explicit platform flags are provided, this command will download the artifacts ' 'for all currently enabled platforms'; @override final String category = FlutterCommandCategory.sdk; @override bool get shouldUpdateCache => false; /// Some flags are umbrella names that expand to include multiple artifacts. static const Map<String, List<String>> _expandedArtifacts = <String, List<String>>{ 'android': <String>[ 'android_gen_snapshot', 'android_maven', 'android_internal_build', ], }; /// Returns a reverse mapping of _expandedArtifacts, from child artifact name /// to umbrella name. Map<String, String> _umbrellaForArtifactMap() { return <String, String>{ for (final MapEntry<String, List<String>> entry in _expandedArtifacts.entries) for (final String childArtifactName in entry.value) childArtifactName: entry.key, }; } /// Returns the name of all artifacts that were explicitly chosen via flags. /// /// If an umbrella is chosen, its children will be included as well. Set<String> _explicitArtifactSelections() { final Map<String, String> umbrellaForArtifact = _umbrellaForArtifactMap(); final Set<String> selections = <String>{}; bool explicitlySelected(String name) => boolArg(name) && argResults!.wasParsed(name); for (final DevelopmentArtifact artifact in DevelopmentArtifact.values) { final String? umbrellaName = umbrellaForArtifact[artifact.name]; if (explicitlySelected(artifact.name) || (umbrellaName != null && explicitlySelected(umbrellaName))) { selections.add(artifact.name); } } return selections; } @override Future<void> validateCommand() { _expandedArtifacts.forEach((String umbrellaName, List<String> childArtifactNames) { if (!argResults!.arguments.contains('--no-$umbrellaName')) { return; } for (final String childArtifactName in childArtifactNames) { if (argResults!.arguments.contains('--$childArtifactName')) { throwToolExit('--$childArtifactName requires --$umbrellaName'); } } }); return super.validateCommand(); } @override Future<FlutterCommandResult> runCommand() async { // Re-lock the cache. if (_platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') { await _cache.lock(); } if (boolArg('force')) { _cache.clearStampFiles(); } final bool includeAllPlatforms = boolArg('all-platforms'); if (includeAllPlatforms) { _cache.includeAllPlatforms = true; } if (boolArg('use-unsigned-mac-binaries')) { _cache.useUnsignedMacBinaries = true; } final Set<String> explicitlyEnabled = _explicitArtifactSelections(); _cache.platformOverrideArtifacts = explicitlyEnabled; // If the user did not provide any artifact flags, then download // all artifacts that correspond to an enabled platform. final bool downloadDefaultArtifacts = explicitlyEnabled.isEmpty; final Map<String, String> umbrellaForArtifact = _umbrellaForArtifactMap(); final Set<DevelopmentArtifact> requiredArtifacts = <DevelopmentArtifact>{}; for (final DevelopmentArtifact artifact in DevelopmentArtifact.values) { if (artifact.feature != null && !_featureFlags.isEnabled(artifact.feature!)) { continue; } final String argumentName = umbrellaForArtifact[artifact.name] ?? artifact.name; if (includeAllPlatforms || boolArg(argumentName) || downloadDefaultArtifacts) { requiredArtifacts.add(artifact); } } if (!await _cache.isUpToDate()) { await _cache.updateAll(requiredArtifacts); } else { _logger.printStatus('Already up-to-date.'); } return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/precache.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/precache.dart", "repo_id": "flutter", "token_count": 2268 }
804
// Copyright 2014 The Flutter Authors. 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:typed_data'; import 'package:meta/meta.dart'; import 'base/common.dart'; import 'base/io.dart'; import 'base/logger.dart'; import 'base/utils.dart'; import 'convert.dart'; /// A single message passed through the [DaemonConnection]. class DaemonMessage { DaemonMessage(this.data, [this.binary]); /// Content of the JSON message in the message. final Map<String, Object?> data; /// Stream of the binary content of the message. /// /// Must be listened to if binary data is present. final Stream<List<int>>? binary; } /// Data of an event passed through the [DaemonConnection]. class DaemonEventData { DaemonEventData(this.eventName, this.data, [this.binary]); /// The name of the event. final String eventName; /// The data of the event. final Object? data; /// Stream of the binary content of the event. /// /// Must be listened to if binary data is present. final Stream<List<int>>? binary; } const String _binaryLengthKey = '_binaryLength'; enum _InputStreamParseState { json, binary, } /// Converts a binary stream to a stream of [DaemonMessage]. /// /// The daemon JSON-RPC protocol is defined as follows: every single line of /// text that starts with `[{` and ends with `}]` will be parsed as a JSON /// message. The array should contain only one single object which contains the /// message data. /// /// If the JSON object contains the key [_binaryLengthKey] with an integer /// value (will be referred to as N), the following N bytes after the newline /// character will contain the binary part of the message. @visibleForTesting class DaemonInputStreamConverter { DaemonInputStreamConverter(this.inputStream) { // Lazily listen to the input stream. _controller.onListen = () { final StreamSubscription<List<int>> subscription = inputStream.listen((List<int> chunk) { _processChunk(chunk); }, onError: (Object error, StackTrace stackTrace) { _controller.addError(error, stackTrace); }, onDone: () { unawaited(_controller.close()); }); _controller.onCancel = subscription.cancel; // We should not handle onPause or onResume. When the stream is paused, we // still need to read from the input stream. }; } final Stream<List<int>> inputStream; final StreamController<DaemonMessage> _controller = StreamController<DaemonMessage>(); Stream<DaemonMessage> get convertedStream => _controller.stream; // Internal states /// The current parse state, whether we are expecting JSON or binary data. _InputStreamParseState state = _InputStreamParseState.json; /// The binary stream that is being transferred. late StreamController<List<int>> currentBinaryStream; /// Remaining length in bytes that have to be sent to the binary stream. int remainingBinaryLength = 0; /// Buffer to hold the current line of input data. final BytesBuilder bytesBuilder = BytesBuilder(copy: false); // Processes a single chunk received in the input stream. void _processChunk(List<int> chunk) { int start = 0; while (start < chunk.length) { switch (state) { case _InputStreamParseState.json: start += _processChunkInJsonMode(chunk, start); case _InputStreamParseState.binary: final int bytesSent = _addBinaryChunk(chunk, start, remainingBinaryLength); start += bytesSent; remainingBinaryLength -= bytesSent; if (remainingBinaryLength <= 0) { assert(remainingBinaryLength == 0); unawaited(currentBinaryStream.close()); state = _InputStreamParseState.json; } } } } /// Processes a chunk in JSON mode, and returns the number of bytes processed. int _processChunkInJsonMode(List<int> chunk, int start) { const int LF = 10; // The '\n' character // Search for newline character. final int indexOfNewLine = chunk.indexOf(LF, start); if (indexOfNewLine < 0) { bytesBuilder.add(chunk.sublist(start)); return chunk.length - start; } bytesBuilder.add(chunk.sublist(start, indexOfNewLine + 1)); // Process chunk here final Uint8List combinedChunk = bytesBuilder.takeBytes(); String jsonString = utf8.decode(combinedChunk).trim(); if (jsonString.startsWith('[{') && jsonString.endsWith('}]')) { jsonString = jsonString.substring(1, jsonString.length - 1); final Map<String, Object?>? value = castStringKeyedMap(json.decode(jsonString)); if (value != null) { // Check if we need to consume another binary blob. if (value[_binaryLengthKey] != null) { remainingBinaryLength = value[_binaryLengthKey]! as int; currentBinaryStream = StreamController<List<int>>(); state = _InputStreamParseState.binary; _controller.add(DaemonMessage(value, currentBinaryStream.stream)); } else { _controller.add(DaemonMessage(value)); } } } return indexOfNewLine + 1 - start; } int _addBinaryChunk(List<int> chunk, int start, int maximumSizeToRead) { if (start == 0 && chunk.length <= remainingBinaryLength) { currentBinaryStream.add(chunk); return chunk.length; } else { final int chunkRemainingLength = chunk.length - start; final int sizeToRead = chunkRemainingLength < remainingBinaryLength ? chunkRemainingLength : remainingBinaryLength; currentBinaryStream.add(chunk.sublist(start, start + sizeToRead)); return sizeToRead; } } } /// A stream that a [DaemonConnection] uses to communicate with each other. class DaemonStreams { DaemonStreams( Stream<List<int>> rawInputStream, StreamSink<List<int>> outputSink, { required Logger logger, }) : _outputSink = outputSink, inputStream = DaemonInputStreamConverter(rawInputStream).convertedStream, _logger = logger; /// Creates a [DaemonStreams] that uses stdin and stdout as the underlying streams. DaemonStreams.fromStdio(Stdio stdio, { required Logger logger }) : this(stdio.stdin, stdio.stdout, logger: logger); /// Creates a [DaemonStreams] that uses [Socket] as the underlying streams. DaemonStreams.fromSocket(Socket socket, { required Logger logger }) : this(socket, socket, logger: logger); /// Connects to a server and creates a [DaemonStreams] from the connection as the underlying streams. factory DaemonStreams.connect(String host, int port, { required Logger logger }) { final Future<Socket> socketFuture = Socket.connect(host, port); final StreamController<List<int>> inputStreamController = StreamController<List<int>>(); final StreamController<List<int>> outputStreamController = StreamController<List<int>>(); socketFuture.then<void>((Socket socket) { inputStreamController.addStream(socket); socket.addStream(outputStreamController.stream); }, onError: (Object error, StackTrace stackTrace) { logger.printError('Socket error: $error'); logger.printTrace('$stackTrace'); // Propagate the error to the streams. inputStreamController.addError(error, stackTrace); unawaited(outputStreamController.close()); }); return DaemonStreams(inputStreamController.stream, outputStreamController.sink, logger: logger); } final StreamSink<List<int>> _outputSink; final Logger _logger; /// Stream that contains input to the [DaemonConnection]. final Stream<DaemonMessage> inputStream; /// Outputs a message through the connection. void send(Map<String, Object?> message, [ List<int>? binary ]) { try { if (binary != null) { message[_binaryLengthKey] = binary.length; } _outputSink.add(utf8.encode('[${json.encode(message)}]\n')); if (binary != null) { _outputSink.add(binary); } } on StateError catch (error) { _logger.printError('Failed to write daemon command response: $error'); // Failed to send, close the connection _outputSink.close(); } on IOException catch (error) { _logger.printError('Failed to write daemon command response: $error'); // Failed to send, close the connection _outputSink.close(); } } /// Cleans up any resources used. Future<void> dispose() async { unawaited(_outputSink.close()); } } /// Connection between a flutter daemon and a client. class DaemonConnection { DaemonConnection({ required DaemonStreams daemonStreams, required Logger logger, }): _logger = logger, _daemonStreams = daemonStreams { _commandSubscription = daemonStreams.inputStream.listen( _handleMessage, onError: (Object error, StackTrace stackTrace) { // We have to listen for on error otherwise the error on the socket // will end up in the Zone error handler. // Do nothing here and let the stream close handlers handle shutting // down the daemon. } ); } final DaemonStreams _daemonStreams; final Logger _logger; late final StreamSubscription<DaemonMessage> _commandSubscription; int _outgoingRequestId = 0; final Map<String, Completer<Object?>> _outgoingRequestCompleters = <String, Completer<Object?>>{}; final StreamController<DaemonEventData> _events = StreamController<DaemonEventData>.broadcast(); final StreamController<DaemonMessage> _incomingCommands = StreamController<DaemonMessage>(); /// A stream that contains all the incoming requests. Stream<DaemonMessage> get incomingCommands => _incomingCommands.stream; /// Listens to the event with the event name [eventToListen]. Stream<DaemonEventData> listenToEvent(String eventToListen) { return _events.stream .where((DaemonEventData event) => event.eventName == eventToListen); } /// Sends a request to the other end of the connection. /// /// Returns a [Future] that resolves with the content. Future<Object?> sendRequest(String method, [Object? params, List<int>? binary]) async { final String id = '${++_outgoingRequestId}'; final Completer<Object?> completer = Completer<Object?>(); _outgoingRequestCompleters[id] = completer; final Map<String, Object?> data = <String, Object?>{ 'id': id, 'method': method, if (params != null) 'params': params, }; _logger.printTrace('-> Sending to daemon, id = $id, method = $method'); _daemonStreams.send(data, binary); return completer.future; } /// Sends a response to the other end of the connection. void sendResponse(Object id, [Object? result]) { _daemonStreams.send(<String, Object?>{ 'id': id, if (result != null) 'result': result, }); } /// Sends an error response to the other end of the connection. void sendErrorResponse(Object id, Object? error, StackTrace trace) { _daemonStreams.send(<String, Object?>{ 'id': id, 'error': error, 'trace': '$trace', }); } /// Sends an event to the client. void sendEvent(String name, [ Object? params, List<int>? binary ]) { _daemonStreams.send(<String, Object?>{ 'event': name, if (params != null) 'params': params, }, binary); } /// Handles the input from the stream. /// /// There are three kinds of data: Request, Response, Event. /// /// Request: /// {"id": <Object>. "method": <String>, "params": <optional, Object?>} /// /// Response: /// {"id": <Object>. "result": <optional, Object?>} for a successful response. /// {"id": <Object>. "error": <Object>, "stackTrace": <String>} for an error response. /// /// Event: /// {"event": <String>. "params": <optional, Object?>} void _handleMessage(DaemonMessage message) { final Map<String, Object?> data = message.data; if (data['id'] != null) { if (data['method'] == null) { // This is a response to previously sent request. final String id = data['id']! as String; if (data['error'] != null) { // This is an error response. _logger.printTrace('<- Error response received from daemon, id = $id'); final Object error = data['error']!; final String stackTrace = data['trace'] as String? ?? ''; _outgoingRequestCompleters.remove(id)?.completeError(error, StackTrace.fromString(stackTrace)); } else { _logger.printTrace('<- Response received from daemon, id = $id'); final Object? result = data['result']; _outgoingRequestCompleters.remove(id)?.complete(result); } } else { _incomingCommands.add(message); } } else if (data['event'] != null) { // This is an event _logger.printTrace('<- Event received: ${data['event']}'); final Object? eventName = data['event']; if (eventName is String) { _events.add(DaemonEventData( eventName, data['params'], message.binary, )); } else { throwToolExit('event name received is not string!'); } } else { _logger.printError('Unknown data received from daemon'); } } /// Cleans up any resources used in the connection. Future<void> dispose() async { await _commandSubscription.cancel(); await _daemonStreams.dispose(); unawaited(_events.close()); unawaited(_incomingCommands.close()); } }
flutter/packages/flutter_tools/lib/src/daemon.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/daemon.dart", "repo_id": "flutter", "token_count": 4650 }
805
// Copyright 2014 The Flutter Authors. 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:package_config/package_config.dart'; import 'package:process/process.dart'; import 'package:vm_service/vm_service.dart' as vm_service; import 'artifacts.dart'; import 'asset.dart'; import 'base/config.dart'; import 'base/context.dart'; import 'base/file_system.dart'; import 'base/io.dart'; import 'base/logger.dart'; import 'base/net.dart'; import 'base/os.dart'; import 'build_info.dart'; import 'build_system/tools/asset_transformer.dart'; import 'build_system/tools/scene_importer.dart'; import 'build_system/tools/shader_compiler.dart'; import 'compile.dart'; import 'convert.dart' show base64, utf8; import 'vmservice.dart'; const String _kFontManifest = 'FontManifest.json'; class DevFSConfig { /// Should DevFS assume that symlink targets are stable? bool cacheSymlinks = false; /// Should DevFS assume that there are no symlinks to directories? bool noDirectorySymlinks = false; } DevFSConfig? get devFSConfig => context.get<DevFSConfig>(); /// Common superclass for content copied to the device. abstract class DevFSContent { /// Return true if this is the first time this method is called /// or if the entry has been modified since this method was last called. bool get isModified; /// Return true if this is the first time this method is called /// or if the entry has been modified after the given time /// or if the given time is null. bool isModifiedAfter(DateTime time); int get size; Future<List<int>> contentsAsBytes(); Stream<List<int>> contentsAsStream(); Stream<List<int>> contentsAsCompressedStream( OperatingSystemUtils osUtils, ) { return osUtils.gzipLevel1Stream(contentsAsStream()); } } // File content to be copied to the device. class DevFSFileContent extends DevFSContent { DevFSFileContent(this.file); final FileSystemEntity file; File? _linkTarget; FileStat? _fileStat; File _getFile() { final File? linkTarget = _linkTarget; if (linkTarget != null) { return linkTarget; } if (file is Link) { // The link target. return file.fileSystem.file(file.resolveSymbolicLinksSync()); } return file as File; } void _stat() { final File? linkTarget = _linkTarget; if (linkTarget != null) { // Stat the cached symlink target. final FileStat fileStat = linkTarget.statSync(); if (fileStat.type == FileSystemEntityType.notFound) { _linkTarget = null; } else { _fileStat = fileStat; return; } } final FileStat fileStat = file.statSync(); _fileStat = fileStat.type == FileSystemEntityType.notFound ? null : fileStat; if (_fileStat != null && _fileStat?.type == FileSystemEntityType.link) { // Resolve, stat, and maybe cache the symlink target. final String resolved = file.resolveSymbolicLinksSync(); final File linkTarget = file.fileSystem.file(resolved); // Stat the link target. final FileStat fileStat = linkTarget.statSync(); if (fileStat.type == FileSystemEntityType.notFound) { _fileStat = null; _linkTarget = null; } else if (devFSConfig?.cacheSymlinks ?? false) { _linkTarget = linkTarget; } } } @override bool get isModified { final FileStat? oldFileStat = _fileStat; _stat(); final FileStat? newFileStat = _fileStat; if (oldFileStat == null && newFileStat == null) { return false; } return oldFileStat == null || newFileStat == null || newFileStat.modified.isAfter(oldFileStat.modified); } @override bool isModifiedAfter(DateTime time) { final FileStat? oldFileStat = _fileStat; _stat(); final FileStat? newFileStat = _fileStat; if (oldFileStat == null && newFileStat == null) { return false; } return oldFileStat == null || newFileStat == null || newFileStat.modified.isAfter(time); } @override int get size { if (_fileStat == null) { _stat(); } // Can still be null if the file wasn't found. return _fileStat?.size ?? 0; } @override Future<List<int>> contentsAsBytes() async => _getFile().readAsBytes(); @override Stream<List<int>> contentsAsStream() => _getFile().openRead(); } /// Byte content to be copied to the device. class DevFSByteContent extends DevFSContent { DevFSByteContent(this._bytes); final List<int> _bytes; final DateTime _creationTime = DateTime.now(); bool _isModified = true; List<int> get bytes => _bytes; /// Return true only once so that the content is written to the device only once. @override bool get isModified { final bool modified = _isModified; _isModified = false; return modified; } @override bool isModifiedAfter(DateTime time) { return _creationTime.isAfter(time); } @override int get size => _bytes.length; @override Future<List<int>> contentsAsBytes() async => _bytes; @override Stream<List<int>> contentsAsStream() => Stream<List<int>>.fromIterable(<List<int>>[_bytes]); } /// String content to be copied to the device. class DevFSStringContent extends DevFSByteContent { DevFSStringContent(String string) : _string = string, super(utf8.encode(string)); final String _string; String get string => _string; } /// A string compressing DevFSContent. /// /// A specialized DevFSContent similar to DevFSByteContent where the contents /// are the compressed bytes of a string. Its difference is that the original /// uncompressed string can be compared with directly without the indirection /// of a compute-expensive uncompress/decode and compress/encode to compare /// the strings. /// /// The `hintString` parameter is a zlib dictionary hinting mechanism to suggest /// the most common string occurrences to potentially assist with compression. class DevFSStringCompressingBytesContent extends DevFSContent { DevFSStringCompressingBytesContent(this._string, { String? hintString }) : _compressor = ZLibEncoder( dictionary: hintString == null ? null : utf8.encode(hintString), gzip: true, level: 9, ); final String _string; final ZLibEncoder _compressor; final DateTime _creationTime = DateTime.now(); bool _isModified = true; late final List<int> bytes = _compressor.convert(utf8.encode(_string)); /// Return true only once so that the content is written to the device only once. @override bool get isModified { final bool modified = _isModified; _isModified = false; return modified; } @override bool isModifiedAfter(DateTime time) { return _creationTime.isAfter(time); } @override int get size => bytes.length; @override Future<List<int>> contentsAsBytes() async => bytes; @override Stream<List<int>> contentsAsStream() => Stream<List<int>>.value(bytes); /// This checks the source string with another string. bool equals(String string) => _string == string; } class DevFSException implements Exception { DevFSException(this.message, [this.error, this.stackTrace]); final String message; final dynamic error; final StackTrace? stackTrace; @override String toString() => 'DevFSException($message, $error, $stackTrace)'; } /// Interface responsible for syncing asset files to a development device. abstract class DevFSWriter { /// Write the assets in [entries] to the target device. /// /// The keys of the map are relative from the [baseUri]. /// /// Throws a [DevFSException] if the process fails to complete. Future<void> write(Map<Uri, DevFSContent> entries, Uri baseUri, DevFSWriter parent); } class _DevFSHttpWriter implements DevFSWriter { _DevFSHttpWriter( this.fsName, FlutterVmService serviceProtocol, { required OperatingSystemUtils osUtils, required HttpClient httpClient, required Logger logger, Duration? uploadRetryThrottle, }) : httpAddress = serviceProtocol.httpAddress, _client = httpClient, _osUtils = osUtils, _uploadRetryThrottle = uploadRetryThrottle, _logger = logger; final HttpClient _client; final OperatingSystemUtils _osUtils; final Logger _logger; final Duration? _uploadRetryThrottle; final String fsName; final Uri? httpAddress; // 3 was chosen to try to limit the variance in the time it takes to execute // `await request.close()` since there is a known bug in Dart where it doesn't // always return a status code in response to a PUT request: // https://github.com/dart-lang/sdk/issues/43525. static const int kMaxInFlight = 3; int _inFlight = 0; late Map<Uri, DevFSContent> _outstanding; late Completer<void> _completer; @override Future<void> write(Map<Uri, DevFSContent> entries, Uri devFSBase, [DevFSWriter? parent]) async { try { _client.maxConnectionsPerHost = kMaxInFlight; _completer = Completer<void>(); _outstanding = Map<Uri, DevFSContent>.of(entries); _scheduleWrites(); await _completer.future; } on SocketException catch (socketException, stackTrace) { _logger.printTrace('DevFS sync failed. Lost connection to device: $socketException'); throw DevFSException('Lost connection to device.', socketException, stackTrace); } on Exception catch (exception, stackTrace) { _logger.printError('Could not update files on device: $exception'); throw DevFSException('Sync failed', exception, stackTrace); } } void _scheduleWrites() { while ((_inFlight < kMaxInFlight) && (!_completer.isCompleted) && _outstanding.isNotEmpty) { final Uri deviceUri = _outstanding.keys.first; final DevFSContent content = _outstanding.remove(deviceUri)!; _startWrite(deviceUri, content, retry: 10); _inFlight += 1; } if ((_inFlight == 0) && (!_completer.isCompleted) && _outstanding.isEmpty) { _completer.complete(); } } Future<void> _startWrite( Uri deviceUri, DevFSContent content, { int retry = 0, }) async { while (true) { try { final HttpClientRequest request = await _client.putUrl(httpAddress!); request.headers.removeAll(HttpHeaders.acceptEncodingHeader); request.headers.add('dev_fs_name', fsName); request.headers.add('dev_fs_uri_b64', base64.encode(utf8.encode('$deviceUri'))); final Stream<List<int>> contents = content.contentsAsCompressedStream( _osUtils, ); await request.addStream(contents); // Once the bug in Dart is solved we can remove the timeout // (https://github.com/dart-lang/sdk/issues/43525). try { final HttpClientResponse response = await request.close().timeout( const Duration(seconds: 60)); response.listen((_) {}, onError: (dynamic error) { _logger.printTrace('error: $error'); }, cancelOnError: true, ); } on TimeoutException { request.abort(); // This should throw "HttpException: Request has been aborted". await request.done; // Just to be safe we rethrow the TimeoutException. rethrow; } break; } on Exception catch (error, trace) { if (!_completer.isCompleted) { _logger.printTrace('Error writing "$deviceUri" to DevFS: $error'); if (retry > 0) { retry--; _logger.printTrace('trying again in a few - $retry more attempts left'); await Future<void>.delayed(_uploadRetryThrottle ?? const Duration(milliseconds: 500)); continue; } _completer.completeError(error, trace); } } } _inFlight -= 1; _scheduleWrites(); } } // Basic statistics for DevFS update operation. class UpdateFSReport { UpdateFSReport({ bool success = false, int invalidatedSourcesCount = 0, int syncedBytes = 0, int scannedSourcesCount = 0, Duration compileDuration = Duration.zero, Duration transferDuration = Duration.zero, Duration findInvalidatedDuration = Duration.zero, }) : _success = success, _invalidatedSourcesCount = invalidatedSourcesCount, _syncedBytes = syncedBytes, _scannedSourcesCount = scannedSourcesCount, _compileDuration = compileDuration, _transferDuration = transferDuration, _findInvalidatedDuration = findInvalidatedDuration; bool get success => _success; int get invalidatedSourcesCount => _invalidatedSourcesCount; int get syncedBytes => _syncedBytes; int get scannedSourcesCount => _scannedSourcesCount; Duration get compileDuration => _compileDuration; Duration get transferDuration => _transferDuration; Duration get findInvalidatedDuration => _findInvalidatedDuration; bool _success; int _invalidatedSourcesCount; int _syncedBytes; int _scannedSourcesCount; Duration _compileDuration; Duration _transferDuration; Duration _findInvalidatedDuration; void incorporateResults(UpdateFSReport report) { if (!report._success) { _success = false; } _invalidatedSourcesCount += report._invalidatedSourcesCount; _syncedBytes += report._syncedBytes; _scannedSourcesCount += report._scannedSourcesCount; _compileDuration += report._compileDuration; _transferDuration += report._transferDuration; _findInvalidatedDuration += report._findInvalidatedDuration; } } class DevFS { /// Create a [DevFS] named [fsName] for the local files in [rootDirectory]. /// /// Failed uploads are retried after [uploadRetryThrottle] duration, defaults to 500ms. DevFS( FlutterVmService serviceProtocol, this.fsName, this.rootDirectory, { required OperatingSystemUtils osUtils, required Logger logger, required FileSystem fileSystem, required ProcessManager processManager, required Artifacts artifacts, HttpClient? httpClient, Duration? uploadRetryThrottle, StopwatchFactory stopwatchFactory = const StopwatchFactory(), Config? config, }) : _vmService = serviceProtocol, _logger = logger, _fileSystem = fileSystem, _httpWriter = _DevFSHttpWriter( fsName, serviceProtocol, osUtils: osUtils, logger: logger, uploadRetryThrottle: uploadRetryThrottle, httpClient: httpClient ?? ((context.get<HttpClientFactory>() == null) ? HttpClient() : context.get<HttpClientFactory>()!())), _stopwatchFactory = stopwatchFactory, _config = config, _assetTransformer = DevelopmentAssetTransformer( transformer: AssetTransformer( processManager: processManager, fileSystem: fileSystem, dartBinaryPath: artifacts.getArtifactPath(Artifact.engineDartBinary), ), fileSystem: fileSystem, logger: logger, ); final FlutterVmService _vmService; final _DevFSHttpWriter _httpWriter; final Logger _logger; final FileSystem _fileSystem; final StopwatchFactory _stopwatchFactory; final Config? _config; final DevelopmentAssetTransformer _assetTransformer; final String fsName; final Directory rootDirectory; final Set<String> assetPathsToEvict = <String>{}; final Set<String> shaderPathsToEvict = <String>{}; final Set<String> scenePathsToEvict = <String>{}; // A flag to indicate whether we have called `setAssetDirectory` on the target device. bool hasSetAssetDirectory = false; /// Whether the font manifest was uploaded during [update]. bool didUpdateFontManifest = false; List<Uri> sources = <Uri>[]; DateTime? lastCompiled; DateTime? _previousCompiled; PackageConfig? lastPackageConfig; Uri? _baseUri; Uri? get baseUri => _baseUri; Uri deviceUriToHostUri(Uri deviceUri) { final String deviceUriString = deviceUri.toString(); final String baseUriString = baseUri.toString(); if (deviceUriString.startsWith(baseUriString)) { final String deviceUriSuffix = deviceUriString.substring(baseUriString.length); return rootDirectory.uri.resolve(deviceUriSuffix); } return deviceUri; } Future<Uri> create() async { _logger.printTrace('DevFS: Creating new filesystem on the device ($_baseUri)'); try { final vm_service.Response response = await _vmService.createDevFS(fsName); _baseUri = Uri.parse(response.json!['uri'] as String); } on vm_service.RPCError catch (rpcException) { if (rpcException.code == RPCErrorCodes.kServiceDisappeared) { // This can happen if the device has been disconnected, so translate to // a DevFSException, which the caller will handle. throw DevFSException('Service disconnected', rpcException); } // 1001 is kFileSystemAlreadyExists in //dart/runtime/vm/json_stream.h if (rpcException.code != 1001) { // Other RPCErrors are unexpected. Rethrow so it will hit crash // logging. rethrow; } _logger.printTrace('DevFS: Creating failed. Destroying and trying again'); await destroy(); final vm_service.Response response = await _vmService.createDevFS(fsName); _baseUri = Uri.parse(response.json!['uri'] as String); } _logger.printTrace('DevFS: Created new filesystem on the device ($_baseUri)'); return _baseUri!; } Future<void> destroy() async { _logger.printTrace('DevFS: Deleting filesystem on the device ($_baseUri)'); await _vmService.deleteDevFS(fsName); _logger.printTrace('DevFS: Deleted filesystem on the device ($_baseUri)'); } /// Mark the [lastCompiled] time to the previous successful compile. /// /// Sometimes a hot reload will be rejected by the VM due to a change in the /// structure of the code not supporting the hot reload. In these cases, /// the best resolution is a hot restart. However, the resident runner /// will not recognize this file as having been changed since the delta /// will already have been accepted. Instead, reset the compile time so /// that the last updated files are included in subsequent compilations until /// a reload is accepted. void resetLastCompiled() { lastCompiled = _previousCompiled; } /// Updates files on the device. /// /// Returns the number of bytes synced. Future<UpdateFSReport> update({ required Uri mainUri, required ResidentCompiler generator, required bool trackWidgetCreation, required String pathToReload, required List<Uri> invalidatedFiles, required PackageConfig packageConfig, required String dillOutputPath, required DevelopmentShaderCompiler shaderCompiler, DevelopmentSceneImporter? sceneImporter, DevFSWriter? devFSWriter, String? target, AssetBundle? bundle, bool bundleFirstUpload = false, bool fullRestart = false, File? dartPluginRegistrant, }) async { final DateTime candidateCompileTime = DateTime.now(); didUpdateFontManifest = false; lastPackageConfig = packageConfig; // Update modified files final Map<Uri, DevFSContent> dirtyEntries = <Uri, DevFSContent>{}; final List<Future<void>> pendingAssetBuilds = <Future<void>>[]; bool assetBuildFailed = false; int syncedBytes = 0; if (fullRestart) { generator.reset(); } // On a full restart, or on an initial compile for the attach based workflow, // this will produce a full dill. Subsequent invocations will produce incremental // dill files that depend on the invalidated files. _logger.printTrace('Compiling dart to kernel with ${invalidatedFiles.length} updated files'); // Await the compiler response after checking if the bundle is updated. This allows the file // stating to be done while waiting for the frontend_server response. final Stopwatch compileTimer = _stopwatchFactory.createStopwatch('compile')..start(); final Future<CompilerOutput?> pendingCompilerOutput = generator.recompile( mainUri, invalidatedFiles, outputPath: dillOutputPath, fs: _fileSystem, projectRootPath: rootDirectory.path, packageConfig: packageConfig, checkDartPluginRegistry: true, // The entry point is assumed not to have changed. dartPluginRegistrant: dartPluginRegistrant, ).then((CompilerOutput? result) { compileTimer.stop(); return result; }); if (bundle != null) { // Mark processing of bundle started for testability of starting the compile // before processing bundle. _logger.printTrace('Processing bundle.'); // await null to give time for telling the compiler to compile. await null; // The tool writes the assets into the AssetBundle working dir so that they // are in the same location in DevFS and the iOS simulator. final String assetDirectory = getAssetBuildDirectory(_config, _fileSystem); final String assetBuildDirPrefix = _asUriPath(assetDirectory); bundle.entries.forEach((String archivePath, AssetBundleEntry entry) { // If the content is backed by a real file, isModified will file stat and return true if // it was modified since the last time this was called. if (!entry.content.isModified || bundleFirstUpload) { return; } // Modified shaders must be recompiled per-target platform. final Uri deviceUri = _fileSystem.path.toUri(_fileSystem.path.join(assetDirectory, archivePath)); if (deviceUri.path.startsWith(assetBuildDirPrefix)) { archivePath = deviceUri.path.substring(assetBuildDirPrefix.length); } // If the font manifest is updated, mark this as true so the hot runner // can invoke a service extension to force the engine to reload fonts. if (archivePath == _kFontManifest) { didUpdateFontManifest = true; } final AssetKind? kind = bundle.entries[archivePath]?.kind; switch (kind) { case AssetKind.shader: final Future<DevFSContent?> pending = shaderCompiler.recompileShader(entry.content); pendingAssetBuilds.add(pending); pending.then((DevFSContent? content) { if (content == null) { assetBuildFailed = true; return; } dirtyEntries[deviceUri] = content; syncedBytes += content.size; if (!bundleFirstUpload) { shaderPathsToEvict.add(archivePath); } }); case AssetKind.model: if (sceneImporter == null) { break; } final Future<DevFSContent?> pending = sceneImporter.reimportScene(entry.content); pendingAssetBuilds.add(pending); pending.then((DevFSContent? content) { if (content == null) { assetBuildFailed = true; return; } dirtyEntries[deviceUri] = content; syncedBytes += content.size; if (!bundleFirstUpload) { scenePathsToEvict.add(archivePath); } }); case AssetKind.regular: case AssetKind.font: case null: final Future<DevFSContent?> pending = (() async { if (entry.transformers.isEmpty || kind != AssetKind.regular) { return entry.content; } return _assetTransformer.retransformAsset( inputAssetKey: archivePath, inputAssetContent: entry.content, transformerEntries: entry.transformers, workingDirectory: rootDirectory.path, ); })(); pendingAssetBuilds.add(pending); pending.then((DevFSContent? content) { if (content == null) { assetBuildFailed = true; return; } dirtyEntries[deviceUri] = content; syncedBytes += content.size; if (!bundleFirstUpload) { assetPathsToEvict.add(archivePath); } }); } }); // Mark processing of bundle done for testability of starting the compile // before processing bundle. _logger.printTrace('Bundle processing done.'); } final CompilerOutput? compilerOutput = await pendingCompilerOutput; if (compilerOutput == null || compilerOutput.errorCount > 0) { return UpdateFSReport(); } // Only update the last compiled time if we successfully compiled. _previousCompiled = lastCompiled; lastCompiled = candidateCompileTime; // list of sources that needs to be monitored are in [compilerOutput.sources] sources = compilerOutput.sources; // // Don't send full kernel file that would overwrite what VM already // started loading from. if (!bundleFirstUpload) { final String compiledBinary = compilerOutput.outputFilename; if (compiledBinary.isNotEmpty) { final Uri entryUri = _fileSystem.path.toUri(pathToReload); final DevFSFileContent content = DevFSFileContent(_fileSystem.file(compiledBinary)); syncedBytes += content.size; dirtyEntries[entryUri] = content; } } _logger.printTrace('Updating files.'); final Stopwatch transferTimer = _stopwatchFactory.createStopwatch('transfer')..start(); await Future.wait(pendingAssetBuilds); if (assetBuildFailed) { return UpdateFSReport(); } if (dirtyEntries.isNotEmpty) { await (devFSWriter ?? _httpWriter).write(dirtyEntries, _baseUri!, _httpWriter); } transferTimer.stop(); _logger.printTrace('DevFS: Sync finished'); return UpdateFSReport( success: true, syncedBytes: syncedBytes, invalidatedSourcesCount: invalidatedFiles.length, compileDuration: compileTimer.elapsed, transferDuration: transferTimer.elapsed, ); } /// Converts a platform-specific file path to a platform-independent URL path. String _asUriPath(String filePath) => '${_fileSystem.path.toUri(filePath).path}/'; } /// An implementation of a devFS writer which copies physical files for devices /// running on the same host. /// /// DevFS entries which correspond to physical files are copied using [File.copySync], /// while entries that correspond to arbitrary string/byte values are written from /// memory. /// /// Requires that the file system is the same for both the tool and application. class LocalDevFSWriter implements DevFSWriter { LocalDevFSWriter({ required FileSystem fileSystem, }) : _fileSystem = fileSystem; final FileSystem _fileSystem; @override Future<void> write(Map<Uri, DevFSContent> entries, Uri baseUri, [DevFSWriter? parent]) async { try { for (final MapEntry<Uri, DevFSContent> entry in entries.entries) { final Uri uri = entry.key; final DevFSContent devFSContent = entry.value; final File destination = _fileSystem.file(baseUri.resolveUri(uri)); if (!destination.parent.existsSync()) { destination.parent.createSync(recursive: true); } if (devFSContent is DevFSFileContent) { final File content = devFSContent.file as File; content.copySync(destination.path); continue; } destination.writeAsBytesSync(await devFSContent.contentsAsBytes()); } } on FileSystemException catch (err) { throw DevFSException(err.toString()); } } }
flutter/packages/flutter_tools/lib/src/devfs.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/devfs.dart", "repo_id": "flutter", "token_count": 9989 }
806
// Copyright 2014 The Flutter Authors. 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:vm_service/vm_service.dart' as vm_service; 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/process.dart'; import '../base/utils.dart'; import '../base/version.dart'; import '../build_info.dart'; import '../convert.dart'; import '../device.dart'; import '../device_port_forwarder.dart'; import '../globals.dart' as globals; import '../macos/xcdevice.dart'; import '../mdns_discovery.dart'; import '../project.dart'; import '../protocol_discovery.dart'; import '../vmservice.dart'; import 'application_package.dart'; import 'core_devices.dart'; import 'ios_deploy.dart'; import 'ios_workflow.dart'; import 'iproxy.dart'; import 'mac.dart'; import 'xcode_build_settings.dart'; import 'xcode_debug.dart'; import 'xcodeproj.dart'; class IOSDevices extends PollingDeviceDiscovery { IOSDevices({ required Platform platform, required this.xcdevice, required IOSWorkflow iosWorkflow, required Logger logger, }) : _platform = platform, _iosWorkflow = iosWorkflow, _logger = logger, super('iOS devices'); final Platform _platform; final IOSWorkflow _iosWorkflow; final Logger _logger; @visibleForTesting final XCDevice xcdevice; @override bool get supportsPlatform => _platform.isMacOS; @override bool get canListAnything => _iosWorkflow.canListDevices; @override bool get requiresExtendedWirelessDeviceDiscovery => true; StreamSubscription<XCDeviceEventNotification>? _observedDeviceEventsSubscription; /// Cache for all devices found by `xcdevice list`, including not connected /// devices. Used to minimize the need to call `xcdevice list`. /// /// Separate from `deviceNotifier` since `deviceNotifier` should only contain /// connected devices. final Map<String, IOSDevice> _cachedPolledDevices = <String, IOSDevice>{}; /// Maps device id to a map of the device's observed connections. When the /// mapped connection is `true`, that means that observed events indicated /// the device is connected via that particular interface. /// /// The device id must be missing from the map or both interfaces must be /// false for the device to be considered disconnected. /// /// Example: /// { /// device-id: { /// usb: false, /// wifi: false, /// }, /// } final Map<String, Map<XCDeviceEventInterface, bool>> _observedConnectionsByDeviceId = <String, Map<XCDeviceEventInterface, bool>>{}; @override Future<void> startPolling() async { if (!_platform.isMacOS) { throw UnsupportedError( 'Control of iOS devices or simulators only supported on macOS.' ); } if (!xcdevice.isInstalled) { return; } deviceNotifier ??= ItemListNotifier<Device>(); // Start by populating all currently attached devices. _updateCachedDevices(await pollingGetDevices()); _updateNotifierFromCache(); // cancel any outstanding subscriptions. await _observedDeviceEventsSubscription?.cancel(); _observedDeviceEventsSubscription = xcdevice.observedDeviceEvents()?.listen( onDeviceEvent, onError: (Object error, StackTrace stack) { _logger.printTrace('Process exception running xcdevice observe:\n$error\n$stack'); }, onDone: () { // If xcdevice is killed or otherwise dies, polling will be stopped. // No retry is attempted and the polling client will have to restart polling // (restart the IDE). Avoid hammering on a process that is // continuously failing. _logger.printTrace('xcdevice observe stopped'); }, cancelOnError: true, ); } @visibleForTesting Future<void> onDeviceEvent(XCDeviceEventNotification event) async { final ItemListNotifier<Device>? notifier = deviceNotifier; if (notifier == null) { return; } Device? knownDevice; for (final Device device in notifier.items) { if (device.id == event.deviceIdentifier) { knownDevice = device; } } final Map<XCDeviceEventInterface, bool> deviceObservedConnections = _observedConnectionsByDeviceId[event.deviceIdentifier] ?? <XCDeviceEventInterface, bool>{ XCDeviceEventInterface.usb: false, XCDeviceEventInterface.wifi: false, }; if (event.eventType == XCDeviceEvent.attach) { // Update device's observed connections. deviceObservedConnections[event.eventInterface] = true; _observedConnectionsByDeviceId[event.deviceIdentifier] = deviceObservedConnections; // If device was not already in notifier, add it. if (knownDevice == null) { if (_cachedPolledDevices[event.deviceIdentifier] == null) { // If device is not found in cache, there's no way to get details // for an individual attached device, so repopulate them all. _updateCachedDevices(await pollingGetDevices()); } _updateNotifierFromCache(); } } else { // Update device's observed connections. deviceObservedConnections[event.eventInterface] = false; _observedConnectionsByDeviceId[event.deviceIdentifier] = deviceObservedConnections; // If device is in the notifier and does not have other observed // connections, remove it. if (knownDevice != null && !_deviceHasObservedConnection(deviceObservedConnections)) { notifier.removeItem(knownDevice); } } } /// Adds or updates devices in cache. Does not remove devices from cache. void _updateCachedDevices(List<Device> devices) { for (final Device device in devices) { if (device is! IOSDevice) { continue; } _cachedPolledDevices[device.id] = device; } } /// Updates notifier with devices found in the cache that are determined /// to be connected. void _updateNotifierFromCache() { final ItemListNotifier<Device>? notifier = deviceNotifier; if (notifier == null) { return; } // Device is connected if it has either an observed usb or wifi connection // or it has not been observed but was found as connected in the cache. final List<Device> connectedDevices = _cachedPolledDevices.values.where((Device device) { final Map<XCDeviceEventInterface, bool>? deviceObservedConnections = _observedConnectionsByDeviceId[device.id]; return (deviceObservedConnections != null && _deviceHasObservedConnection(deviceObservedConnections)) || (deviceObservedConnections == null && device.isConnected); }).toList(); notifier.updateWithNewList(connectedDevices); } bool _deviceHasObservedConnection( Map<XCDeviceEventInterface, bool> deviceObservedConnections, ) { return (deviceObservedConnections[XCDeviceEventInterface.usb] ?? false) || (deviceObservedConnections[XCDeviceEventInterface.wifi] ?? false); } @override Future<void> stopPolling() async { await _observedDeviceEventsSubscription?.cancel(); } @override Future<List<Device>> pollingGetDevices({ Duration? timeout }) async { if (!_platform.isMacOS) { throw UnsupportedError( 'Control of iOS devices or simulators only supported on macOS.' ); } return xcdevice.getAvailableIOSDevices(timeout: timeout); } Future<Device?> waitForDeviceToConnect( IOSDevice device, Logger logger, ) async { final XCDeviceEventNotification? eventDetails = await xcdevice.waitForDeviceToConnect(device.id); if (eventDetails != null) { device.isConnected = true; device.connectionInterface = eventDetails.eventInterface.connectionInterface; return device; } return null; } void cancelWaitForDeviceToConnect() { xcdevice.cancelWaitForDeviceToConnect(); } @override Future<List<String>> getDiagnostics() async { if (!_platform.isMacOS) { return const <String>[ 'Control of iOS devices or simulators only supported on macOS.', ]; } return xcdevice.getDiagnostics(); } @override List<String> get wellKnownIds => const <String>[]; } class IOSDevice extends Device { IOSDevice(super.id, { required FileSystem fileSystem, required this.name, required this.cpuArchitecture, required this.connectionInterface, required this.isConnected, required this.isPaired, required this.devModeEnabled, required this.isCoreDevice, String? sdkVersion, required Platform platform, required IOSDeploy iosDeploy, required IMobileDevice iMobileDevice, required IOSCoreDeviceControl coreDeviceControl, required XcodeDebug xcodeDebug, required IProxy iProxy, required Logger logger, }) : _sdkVersion = sdkVersion, _iosDeploy = iosDeploy, _iMobileDevice = iMobileDevice, _coreDeviceControl = coreDeviceControl, _xcodeDebug = xcodeDebug, _iproxy = iProxy, _fileSystem = fileSystem, _logger = logger, _platform = platform, super( category: Category.mobile, platformType: PlatformType.ios, ephemeral: true, ) { if (!_platform.isMacOS) { assert(false, 'Control of iOS devices or simulators only supported on Mac OS.'); return; } } final String? _sdkVersion; final IOSDeploy _iosDeploy; final FileSystem _fileSystem; final Logger _logger; final Platform _platform; final IMobileDevice _iMobileDevice; final IOSCoreDeviceControl _coreDeviceControl; final XcodeDebug _xcodeDebug; final IProxy _iproxy; Version? get sdkVersion { return Version.parse(_sdkVersion); } /// May be 0 if version cannot be parsed. int get majorSdkVersion { return sdkVersion?.major ?? 0; } @override final String name; @override bool supportsRuntimeMode(BuildMode buildMode) => buildMode != BuildMode.jitRelease; final DarwinArch cpuArchitecture; @override /// The [connectionInterface] provided from `XCDevice.getAvailableIOSDevices` /// may not be accurate. Sometimes if it doesn't have a long enough time /// to connect, wireless devices will have an interface of `usb`/`attached`. /// This may change after waiting for the device to connect in /// `waitForDeviceToConnect`. DeviceConnectionInterface connectionInterface; @override bool isConnected; bool devModeEnabled = false; /// Device has trusted this computer and paired. bool isPaired = false; /// CoreDevice is a device connectivity stack introduced in Xcode 15. Devices /// with iOS 17 or greater are CoreDevices. final bool isCoreDevice; final Map<IOSApp?, DeviceLogReader> _logReaders = <IOSApp?, DeviceLogReader>{}; DevicePortForwarder? _portForwarder; @visibleForTesting IOSDeployDebugger? iosDeployDebugger; @override Future<bool> get isLocalEmulator async => false; @override Future<String?> get emulatorId async => null; @override bool get supportsStartPaused => false; @override bool get supportsFlavors => true; @override Future<bool> isAppInstalled( ApplicationPackage app, { String? userIdentifier, }) async { bool result; try { if (isCoreDevice) { result = await _coreDeviceControl.isAppInstalled( bundleId: app.id, deviceId: id, ); } else { result = await _iosDeploy.isAppInstalled( bundleId: app.id, deviceId: id, ); } } on ProcessException catch (e) { _logger.printError(e.message); return false; } return result; } @override Future<bool> isLatestBuildInstalled(ApplicationPackage app) async => false; @override Future<bool> installApp( covariant IOSApp app, { String? userIdentifier, }) async { final Directory bundle = _fileSystem.directory(app.deviceBundlePath); if (!bundle.existsSync()) { _logger.printError('Could not find application bundle at ${bundle.path}; have you run "flutter build ios"?'); return false; } int installationResult; try { if (isCoreDevice) { installationResult = await _coreDeviceControl.installApp( deviceId: id, bundlePath: bundle.path, ) ? 0 : 1; } else { installationResult = await _iosDeploy.installApp( deviceId: id, bundlePath: bundle.path, appDeltaDirectory: app.appDeltaDirectory, launchArguments: <String>[], interfaceType: connectionInterface, ); } } on ProcessException catch (e) { _logger.printError(e.message); return false; } if (installationResult != 0) { _logger.printError('Could not install ${bundle.path} on $id.'); _logger.printError('Try launching Xcode and selecting "Product > Run" to fix the problem:'); _logger.printError(' open ios/Runner.xcworkspace'); _logger.printError(''); return false; } return true; } @override Future<bool> uninstallApp( ApplicationPackage app, { String? userIdentifier, }) async { int uninstallationResult; try { if (isCoreDevice) { uninstallationResult = await _coreDeviceControl.uninstallApp( deviceId: id, bundleId: app.id, ) ? 0 : 1; } else { uninstallationResult = await _iosDeploy.uninstallApp( deviceId: id, bundleId: app.id, ); } } on ProcessException catch (e) { _logger.printError(e.message); return false; } if (uninstallationResult != 0) { _logger.printError('Could not uninstall ${app.id} on $id.'); return false; } return true; } @override // 32-bit devices are not supported. bool isSupported() => cpuArchitecture == DarwinArch.arm64; @override Future<LaunchResult> startApp( IOSApp package, { String? mainPath, String? route, required DebuggingOptions debuggingOptions, Map<String, Object?> platformArgs = const <String, Object?>{}, bool prebuiltApplication = false, bool ipv6 = false, String? userIdentifier, @visibleForTesting Duration? discoveryTimeout, @visibleForTesting ShutdownHooks? shutdownHooks, }) async { String? packageId; if (isWirelesslyConnected && debuggingOptions.debuggingEnabled && debuggingOptions.disablePortPublication) { throwToolExit('Cannot start app on wirelessly tethered iOS device. Try running again with the --publish-port flag'); } if (!prebuiltApplication) { _logger.printTrace('Building ${package.name} for $id'); // Step 1: Build the precompiled/DBC application if necessary. final XcodeBuildResult buildResult = await buildXcodeProject( app: package as BuildableIOSApp, buildInfo: debuggingOptions.buildInfo, targetOverride: mainPath, activeArch: cpuArchitecture, deviceID: id, disablePortPublication: debuggingOptions.usingCISystem && debuggingOptions.disablePortPublication, ); if (!buildResult.success) { _logger.printError('Could not build the precompiled application for the device.'); await diagnoseXcodeBuildFailure(buildResult, globals.flutterUsage, _logger, globals.analytics); _logger.printError(''); return LaunchResult.failed(); } packageId = buildResult.xcodeBuildExecution?.buildSettings[IosProject.kProductBundleIdKey]; } packageId ??= package.id; // Step 2: Check that the application exists at the specified path. final Directory bundle = _fileSystem.directory(package.deviceBundlePath); if (!bundle.existsSync()) { _logger.printError('Could not find the built application bundle at ${bundle.path}.'); return LaunchResult.failed(); } // Step 3: Attempt to install the application on the device. final List<String> launchArguments = debuggingOptions.getIOSLaunchArguments( EnvironmentType.physical, route, platformArgs, ipv6: ipv6, interfaceType: connectionInterface, isCoreDevice: isCoreDevice, ); Status startAppStatus = _logger.startProgress( 'Installing and launching...', ); try { ProtocolDiscovery? vmServiceDiscovery; int installationResult = 1; if (debuggingOptions.debuggingEnabled) { _logger.printTrace('Debugging is enabled, connecting to vmService'); vmServiceDiscovery = _setupDebuggerAndVmServiceDiscovery( package: package, bundle: bundle, debuggingOptions: debuggingOptions, launchArguments: launchArguments, ipv6: ipv6, uninstallFirst: debuggingOptions.uninstallFirst, ); } if (isCoreDevice) { installationResult = await _startAppOnCoreDevice( debuggingOptions: debuggingOptions, package: package, launchArguments: launchArguments, mainPath: mainPath, discoveryTimeout: discoveryTimeout, shutdownHooks: shutdownHooks ?? globals.shutdownHooks, ) ? 0 : 1; } else if (iosDeployDebugger == null) { installationResult = await _iosDeploy.launchApp( deviceId: id, bundlePath: bundle.path, appDeltaDirectory: package.appDeltaDirectory, launchArguments: launchArguments, interfaceType: connectionInterface, uninstallFirst: debuggingOptions.uninstallFirst, ); } else { installationResult = await iosDeployDebugger!.launchAndAttach() ? 0 : 1; } if (installationResult != 0) { _printInstallError(bundle); await dispose(); return LaunchResult.failed(); } if (!debuggingOptions.debuggingEnabled) { return LaunchResult.succeeded(); } _logger.printTrace('Application launched on the device. Waiting for Dart VM Service url.'); final int defaultTimeout; if (isCoreDevice && debuggingOptions.debuggingEnabled) { // Core devices with debugging enabled takes longer because this // includes time to install and launch the app on the device. defaultTimeout = isWirelesslyConnected ? 75 : 60; } else if (isWirelesslyConnected) { defaultTimeout = 45; } else { defaultTimeout = 30; } final Timer timer = Timer(discoveryTimeout ?? Duration(seconds: defaultTimeout), () { _logger.printError('The Dart VM Service was not discovered after $defaultTimeout seconds. This is taking much longer than expected...'); if (isCoreDevice && debuggingOptions.debuggingEnabled) { _logger.printError( 'Open the Xcode window the project is opened in to ensure the app ' 'is running. If the app is not running, try selecting "Product > Run" ' 'to fix the problem.', ); } // If debugging with a wireless device and the timeout is reached, remind the // user to allow local network permissions. if (isWirelesslyConnected) { _logger.printError( '\nClick "Allow" to the prompt asking if you would like to find and connect devices on your local network. ' 'This is required for wireless debugging. If you selected "Don\'t Allow", ' 'you can turn it on in Settings > Your App Name > Local Network. ' "If you don't see your app in the Settings, uninstall the app and rerun to see the prompt again." ); } else { iosDeployDebugger?.checkForSymbolsFiles(_fileSystem); iosDeployDebugger?.pauseDumpBacktraceResume(); } }); Uri? localUri; if (isCoreDevice) { localUri = await _discoverDartVMForCoreDevice( debuggingOptions: debuggingOptions, packageId: packageId, ipv6: ipv6, vmServiceDiscovery: vmServiceDiscovery, ); } else if (isWirelesslyConnected) { // Wait for the Dart VM url to be discovered via logs (from `ios-deploy`) // in ProtocolDiscovery. Then via mDNS, construct the Dart VM url using // the device IP as the host by finding Dart VM services matching the // app bundle id and Dart VM port. // Wait for Dart VM Service to start up. final Uri? serviceURL = await vmServiceDiscovery?.uri; if (serviceURL == null) { await iosDeployDebugger?.stopAndDumpBacktrace(); await dispose(); return LaunchResult.failed(); } // If Dart VM Service URL with the device IP is not found within 5 seconds, // change the status message to prompt users to click Allow. Wait 5 seconds because it // should only show this message if they have not already approved the permissions. // MDnsVmServiceDiscovery usually takes less than 5 seconds to find it. final Timer mDNSLookupTimer = Timer(const Duration(seconds: 5), () { startAppStatus.stop(); startAppStatus = _logger.startProgress( 'Waiting for approval of local network permissions...', ); }); // Get Dart VM Service URL with the device IP as the host. localUri = await MDnsVmServiceDiscovery.instance!.getVMServiceUriForLaunch( packageId, this, usesIpv6: ipv6, deviceVmservicePort: serviceURL.port, useDeviceIPAsHost: true, ); mDNSLookupTimer.cancel(); } else { localUri = await vmServiceDiscovery?.uri; // If the `ios-deploy` debugger loses connection before it finds the // Dart Service VM url, try starting the debugger and launching the // app again. if (localUri == null && debuggingOptions.usingCISystem && iosDeployDebugger != null && iosDeployDebugger!.lostConnection) { _logger.printStatus('Lost connection to device. Trying to connect again...'); await dispose(); vmServiceDiscovery = _setupDebuggerAndVmServiceDiscovery( package: package, bundle: bundle, debuggingOptions: debuggingOptions, launchArguments: launchArguments, ipv6: ipv6, uninstallFirst: false, skipInstall: true, ); installationResult = await iosDeployDebugger!.launchAndAttach() ? 0 : 1; if (installationResult != 0) { _printInstallError(bundle); await dispose(); return LaunchResult.failed(); } localUri = await vmServiceDiscovery.uri; } } timer.cancel(); if (localUri == null) { await iosDeployDebugger?.stopAndDumpBacktrace(); await dispose(); return LaunchResult.failed(); } return LaunchResult.succeeded(vmServiceUri: localUri); } on ProcessException catch (e) { await iosDeployDebugger?.stopAndDumpBacktrace(); _logger.printError(e.message); await dispose(); return LaunchResult.failed(); } finally { startAppStatus.stop(); if (isCoreDevice && debuggingOptions.debuggingEnabled && package is BuildableIOSApp) { // When debugging via Xcode, after the app launches, reset the Generated // settings to not include the custom configuration build directory. // This is to prevent confusion if the project is later ran via Xcode // rather than the Flutter CLI. await updateGeneratedXcodeProperties( project: FlutterProject.current(), buildInfo: debuggingOptions.buildInfo, targetOverride: mainPath, ); } } } void _printInstallError(Directory bundle) { _logger.printError('Could not run ${bundle.path} on $id.'); _logger.printError('Try launching Xcode and selecting "Product > Run" to fix the problem:'); _logger.printError(' open ios/Runner.xcworkspace'); _logger.printError(''); } /// Find the Dart VM url using ProtocolDiscovery (logs from `idevicesyslog`) /// and mDNS simultaneously, using whichever is found first. `idevicesyslog` /// does not work on wireless devices, so only use mDNS for wireless devices. /// Wireless devices require using the device IP as the host. Future<Uri?> _discoverDartVMForCoreDevice({ required String packageId, required bool ipv6, required DebuggingOptions debuggingOptions, ProtocolDiscovery? vmServiceDiscovery, }) async { Timer? maxWaitForCI; final Completer<Uri?> cancelCompleter = Completer<Uri?>(); // When testing in CI, wait a max of 10 minutes for the Dart VM to be found. // Afterwards, stop the app from running and upload DerivedData Logs to debug // logs directory. CoreDevices are run through Xcode and launch logs are // therefore found in DerivedData. if (debuggingOptions.usingCISystem && debuggingOptions.debugLogsDirectoryPath != null) { maxWaitForCI = Timer(const Duration(minutes: 10), () async { _logger.printError('Failed to find Dart VM after 10 minutes.'); await _xcodeDebug.exit(); final String? homePath = _platform.environment['HOME']; Directory? derivedData; if (homePath != null) { derivedData = _fileSystem.directory( _fileSystem.path.join(homePath, 'Library', 'Developer', 'Xcode', 'DerivedData'), ); } if (derivedData != null && derivedData.existsSync()) { final Directory debugLogsDirectory = _fileSystem.directory( debuggingOptions.debugLogsDirectoryPath, ); debugLogsDirectory.createSync(recursive: true); for (final FileSystemEntity entity in derivedData.listSync()) { if (entity is! Directory || !entity.childDirectory('Logs').existsSync()) { continue; } final Directory logsToCopy = entity.childDirectory('Logs'); final Directory copyDestination = debugLogsDirectory .childDirectory('DerivedDataLogs') .childDirectory(entity.basename) .childDirectory('Logs'); _logger.printTrace('Copying logs ${logsToCopy.path} to ${copyDestination.path}...'); copyDirectory(logsToCopy, copyDestination); } } cancelCompleter.complete(); }); } final Future<Uri?> vmUrlFromMDns = MDnsVmServiceDiscovery.instance!.getVMServiceUriForLaunch( packageId, this, usesIpv6: ipv6, useDeviceIPAsHost: isWirelesslyConnected, ); final List<Future<Uri?>> discoveryOptions = <Future<Uri?>>[ vmUrlFromMDns, ]; // vmServiceDiscovery uses device logs (`idevicesyslog`), which doesn't work // on wireless devices. if (vmServiceDiscovery != null && !isWirelesslyConnected) { final Future<Uri?> vmUrlFromLogs = vmServiceDiscovery.uri; discoveryOptions.add(vmUrlFromLogs); } Uri? localUri = await Future.any( <Future<Uri?>>[...discoveryOptions, cancelCompleter.future], ); // If the first future to return is null, wait for the other to complete // unless canceled. if (localUri == null && !cancelCompleter.isCompleted) { final Future<List<Uri?>> allDiscoveryOptionsComplete = Future.wait(discoveryOptions); await Future.any(<Future<Object?>>[ allDiscoveryOptionsComplete, cancelCompleter.future, ]); if (!cancelCompleter.isCompleted) { // If it wasn't cancelled, that means one of the discovery options completed. final List<Uri?> vmUrls = await allDiscoveryOptionsComplete; localUri = vmUrls.where((Uri? vmUrl) => vmUrl != null).firstOrNull; } } maxWaitForCI?.cancel(); return localUri; } ProtocolDiscovery _setupDebuggerAndVmServiceDiscovery({ required IOSApp package, required Directory bundle, required DebuggingOptions debuggingOptions, required List<String> launchArguments, required bool ipv6, required bool uninstallFirst, bool skipInstall = false, }) { final DeviceLogReader deviceLogReader = getLogReader( app: package, usingCISystem: debuggingOptions.usingCISystem, ); // If the device supports syslog reading, prefer launching the app without // attaching the debugger to avoid the overhead of the unnecessary extra running process. if (majorSdkVersion >= IOSDeviceLogReader.minimumUniversalLoggingSdkVersion) { iosDeployDebugger = _iosDeploy.prepareDebuggerForLaunch( deviceId: id, bundlePath: bundle.path, appDeltaDirectory: package.appDeltaDirectory, launchArguments: launchArguments, interfaceType: connectionInterface, uninstallFirst: uninstallFirst, skipInstall: skipInstall, ); if (deviceLogReader is IOSDeviceLogReader) { deviceLogReader.debuggerStream = iosDeployDebugger; } } // Don't port forward if debugging with a wireless device. return ProtocolDiscovery.vmService( deviceLogReader, portForwarder: isWirelesslyConnected ? null : portForwarder, hostPort: debuggingOptions.hostVmServicePort, devicePort: debuggingOptions.deviceVmServicePort, ipv6: ipv6, logger: _logger, ); } /// Starting with Xcode 15 and iOS 17, `ios-deploy` stopped working due to /// the new CoreDevice connectivity stack. Previously, `ios-deploy` was used /// to install the app, launch the app, and start `debugserver`. /// Xcode 15 introduced a new command line tool called `devicectl` that /// includes much of the functionality supplied by `ios-deploy`. However, /// `devicectl` lacks the ability to start a `debugserver` and therefore `ptrace`, which are needed /// for debug mode due to using a JIT Dart VM. /// /// Therefore, when starting an app on a CoreDevice, use `devicectl` when /// debugging is not enabled. Otherwise, use Xcode automation. Future<bool> _startAppOnCoreDevice({ required DebuggingOptions debuggingOptions, required IOSApp package, required List<String> launchArguments, required String? mainPath, required ShutdownHooks shutdownHooks, @visibleForTesting Duration? discoveryTimeout, }) async { if (!debuggingOptions.debuggingEnabled) { // Release mode // Install app to device final bool installSuccess = await _coreDeviceControl.installApp( deviceId: id, bundlePath: package.deviceBundlePath, ); if (!installSuccess) { return installSuccess; } // Launch app to device final bool launchSuccess = await _coreDeviceControl.launchApp( deviceId: id, bundleId: package.id, launchArguments: launchArguments, ); return launchSuccess; } else { _logger.printStatus( 'You may be prompted to give access to control Xcode. Flutter uses Xcode ' 'to run your app. If access is not allowed, you can change this through ' 'your Settings > Privacy & Security > Automation.', ); final int launchTimeout = isWirelesslyConnected ? 45 : 30; final Timer timer = Timer(discoveryTimeout ?? Duration(seconds: launchTimeout), () { _logger.printError( 'Xcode is taking longer than expected to start debugging the app. ' 'Ensure the project is opened in Xcode.', ); }); XcodeDebugProject debugProject; final FlutterProject flutterProject = FlutterProject.current(); if (package is PrebuiltIOSApp) { debugProject = await _xcodeDebug.createXcodeProjectWithCustomBundle( package.deviceBundlePath, templateRenderer: globals.templateRenderer, verboseLogging: _logger.isVerbose, ); } else if (package is BuildableIOSApp) { // Before installing/launching/debugging with Xcode, update the build // settings to use a custom configuration build directory so Xcode // knows where to find the app bundle to launch. final Directory bundle = _fileSystem.directory( package.deviceBundlePath, ); await updateGeneratedXcodeProperties( project: flutterProject, buildInfo: debuggingOptions.buildInfo, targetOverride: mainPath, configurationBuildDir: bundle.parent.absolute.path, ); final IosProject project = package.project; final XcodeProjectInfo? projectInfo = await project.projectInfo(); if (projectInfo == null) { globals.printError('Xcode project not found.'); return false; } if (project.xcodeWorkspace == null) { globals.printError('Unable to get Xcode workspace.'); return false; } final String? scheme = projectInfo.schemeFor(debuggingOptions.buildInfo); if (scheme == null) { projectInfo.reportFlavorNotFoundAndExit(); } _xcodeDebug.ensureXcodeDebuggerLaunchAction(project.xcodeProjectSchemeFile(scheme: scheme)); debugProject = XcodeDebugProject( scheme: scheme, xcodeProject: project.xcodeProject, xcodeWorkspace: project.xcodeWorkspace!, hostAppProjectName: project.hostAppProjectName, expectedConfigurationBuildDir: bundle.parent.absolute.path, verboseLogging: _logger.isVerbose, ); } else { // This should not happen. Currently, only PrebuiltIOSApp and // BuildableIOSApp extend from IOSApp. _logger.printError('IOSApp type ${package.runtimeType} is not recognized.'); return false; } final bool debugSuccess = await _xcodeDebug.debugApp( project: debugProject, deviceId: id, launchArguments:launchArguments, ); timer.cancel(); // Kill Xcode on shutdown when running from CI if (debuggingOptions.usingCISystem) { shutdownHooks.addShutdownHook(() => _xcodeDebug.exit(force: true)); } return debugSuccess; } } @override Future<bool> stopApp( ApplicationPackage? app, { String? userIdentifier, }) async { // If the debugger is not attached, killing the ios-deploy process won't stop the app. final IOSDeployDebugger? deployDebugger = iosDeployDebugger; if (deployDebugger != null && deployDebugger.debuggerAttached) { return deployDebugger.exit(); } if (_xcodeDebug.debugStarted) { return _xcodeDebug.exit(); } return false; } @override Future<TargetPlatform> get targetPlatform async => TargetPlatform.ios; @override Future<String> get sdkNameAndVersion async => 'iOS ${_sdkVersion ?? 'unknown version'}'; @override DeviceLogReader getLogReader({ covariant IOSApp? app, bool includePastLogs = false, bool usingCISystem = false, }) { assert(!includePastLogs, 'Past log reading not supported on iOS devices.'); return _logReaders.putIfAbsent(app, () => IOSDeviceLogReader.create( device: this, app: app, iMobileDevice: _iMobileDevice, usingCISystem: usingCISystem, )); } @visibleForTesting void setLogReader(IOSApp app, DeviceLogReader logReader) { _logReaders[app] = logReader; } @override DevicePortForwarder get portForwarder => _portForwarder ??= IOSDevicePortForwarder( logger: _logger, iproxy: _iproxy, id: id, operatingSystemUtils: globals.os, ); @visibleForTesting set portForwarder(DevicePortForwarder forwarder) { _portForwarder = forwarder; } @override void clearLogs() { } @override bool get supportsScreenshot { if (isCoreDevice) { // `idevicescreenshot` stopped working with iOS 17 / Xcode 15 // (https://github.com/flutter/flutter/issues/128598). return false; } return _iMobileDevice.isInstalled; } @override Future<void> takeScreenshot(File outputFile) async { await _iMobileDevice.takeScreenshot(outputFile, id, connectionInterface); } @override bool isSupportedForProject(FlutterProject flutterProject) { return flutterProject.ios.existsSync(); } @override Future<void> dispose() async { for (final DeviceLogReader logReader in _logReaders.values) { logReader.dispose(); } _logReaders.clear(); await _portForwarder?.dispose(); } } /// Decodes a vis-encoded syslog string to a UTF-8 representation. /// /// Apple's syslog logs are encoded in 7-bit form. Input bytes are encoded as follows: /// 1. 0x00 to 0x19: non-printing range. Some ignored, some encoded as <...>. /// 2. 0x20 to 0x7f: as-is, with the exception of 0x5c (backslash). /// 3. 0x5c (backslash): octal representation \134. /// 4. 0x80 to 0x9f: \M^x (using control-character notation for range 0x00 to 0x40). /// 5. 0xa0: octal representation \240. /// 6. 0xa1 to 0xf7: \M-x (where x is the input byte stripped of its high-order bit). /// 7. 0xf8 to 0xff: unused in 4-byte UTF-8. /// /// See: [vis(3) manpage](https://www.freebsd.org/cgi/man.cgi?query=vis&sektion=3) String decodeSyslog(String line) { // UTF-8 values for \, M, -, ^. const int kBackslash = 0x5c; const int kM = 0x4d; const int kDash = 0x2d; const int kCaret = 0x5e; // Mask for the UTF-8 digit range. const int kNum = 0x30; // Returns true when `byte` is within the UTF-8 7-bit digit range (0x30 to 0x39). bool isDigit(int byte) => (byte & 0xf0) == kNum; // Converts a three-digit ASCII (UTF-8) representation of an octal number `xyz` to an integer. int decodeOctal(int x, int y, int z) => (x & 0x3) << 6 | (y & 0x7) << 3 | z & 0x7; try { final List<int> bytes = utf8.encode(line); final List<int> out = <int>[]; for (int i = 0; i < bytes.length;) { if (bytes[i] != kBackslash || i > bytes.length - 4) { // Unmapped byte: copy as-is. out.add(bytes[i++]); } else { // Mapped byte: decode next 4 bytes. if (bytes[i + 1] == kM && bytes[i + 2] == kCaret) { // \M^x form: bytes in range 0x80 to 0x9f. out.add((bytes[i + 3] & 0x7f) + 0x40); } else if (bytes[i + 1] == kM && bytes[i + 2] == kDash) { // \M-x form: bytes in range 0xa0 to 0xf7. out.add(bytes[i + 3] | 0x80); } else if (bytes.getRange(i + 1, i + 3).every(isDigit)) { // \ddd form: octal representation (only used for \134 and \240). out.add(decodeOctal(bytes[i + 1], bytes[i + 2], bytes[i + 3])); } else { // Unknown form: copy as-is. out.addAll(bytes.getRange(0, 4)); } i += 4; } } return utf8.decode(out); } on Exception { // Unable to decode line: return as-is. return line; } } class IOSDeviceLogReader extends DeviceLogReader { IOSDeviceLogReader._( this._iMobileDevice, this._majorSdkVersion, this._deviceId, this.name, this._isWirelesslyConnected, this._isCoreDevice, String appName, bool usingCISystem, ) : // Match for lines for the runner in syslog. // // iOS 9 format: Runner[297] <Notice>: // iOS 10 format: Runner(Flutter)[297] <Notice>: _runnerLineRegex = RegExp(appName + r'(\(Flutter\))?\[[\d]+\] <[A-Za-z]+>: '), _usingCISystem = usingCISystem; /// Create a new [IOSDeviceLogReader]. factory IOSDeviceLogReader.create({ required IOSDevice device, IOSApp? app, required IMobileDevice iMobileDevice, bool usingCISystem = false, }) { final String appName = app?.name?.replaceAll('.app', '') ?? ''; return IOSDeviceLogReader._( iMobileDevice, device.majorSdkVersion, device.id, device.name, device.isWirelesslyConnected, device.isCoreDevice, appName, usingCISystem, ); } /// Create an [IOSDeviceLogReader] for testing. factory IOSDeviceLogReader.test({ required IMobileDevice iMobileDevice, bool useSyslog = true, bool usingCISystem = false, int? majorSdkVersion, bool isWirelesslyConnected = false, bool isCoreDevice = false, }) { final int sdkVersion = majorSdkVersion ?? (useSyslog ? 12 : 13); return IOSDeviceLogReader._( iMobileDevice, sdkVersion, '1234', 'test', isWirelesslyConnected, isCoreDevice, 'Runner', usingCISystem); } @override final String name; final int _majorSdkVersion; final String _deviceId; final bool _isWirelesslyConnected; final bool _isCoreDevice; final IMobileDevice _iMobileDevice; final bool _usingCISystem; // Matches a syslog line from the runner. RegExp _runnerLineRegex; // Similar to above, but allows ~arbitrary components instead of "Runner" // and "Flutter". The regex tries to strike a balance between not producing // false positives and not producing false negatives. final RegExp _anyLineRegex = RegExp(r'\w+(\([^)]*\))?\[\d+\] <[A-Za-z]+>: '); // Logging from native code/Flutter engine is prefixed by timestamp and process metadata: // 2020-09-15 19:15:10.931434-0700 Runner[541:226276] Did finish launching. // 2020-09-15 19:15:10.931434-0700 Runner[541:226276] [Category] Did finish launching. // // Logging from the dart code has no prefixing metadata. final RegExp _debuggerLoggingRegex = RegExp(r'^\S* \S* \S*\[[0-9:]*] (.*)'); @visibleForTesting late final StreamController<String> linesController = StreamController<String>.broadcast( onListen: _listenToSysLog, onCancel: dispose, ); // Sometimes (race condition?) we try to send a log after the controller has // been closed. See https://github.com/flutter/flutter/issues/99021 for more // context. @visibleForTesting void addToLinesController(String message, IOSDeviceLogSource source) { if (!linesController.isClosed) { if (_excludeLog(message, source)) { return; } linesController.add(message); } } /// Used to track messages prefixed with "flutter:" from the fallback log source. final List<String> _fallbackStreamFlutterMessages = <String>[]; /// Used to track if a message prefixed with "flutter:" has been received from the primary log. bool primarySourceFlutterLogReceived = false; /// There are three potential logging sources: `idevicesyslog`, `ios-deploy`, /// and Unified Logging (Dart VM). When using more than one of these logging /// sources at a time, prefer to use the primary source. However, if the /// primary source is not working, use the fallback. bool _excludeLog(String message, IOSDeviceLogSource source) { // If no fallback, don't exclude any logs. if (logSources.fallbackSource == null) { return false; } // If log is from primary source, don't exclude it unless the fallback was // quicker and added the message first. if (source == logSources.primarySource) { if (!primarySourceFlutterLogReceived && message.startsWith('flutter:')) { primarySourceFlutterLogReceived = true; } // If the message was already added by the fallback, exclude it to // prevent duplicates. final bool foundAndRemoved = _fallbackStreamFlutterMessages.remove(message); if (foundAndRemoved) { return true; } return false; } // If a flutter log was received from the primary source, that means it's // working so don't use any messages from the fallback. if (primarySourceFlutterLogReceived) { return true; } // When using logs from fallbacks, skip any logs not prefixed with "flutter:". // This is done because different sources often have different prefixes for // non-flutter messages, which makes duplicate matching difficult. Also, // non-flutter messages are not critical for CI tests. if (!message.startsWith('flutter:')) { return true; } _fallbackStreamFlutterMessages.add(message); return false; } final List<StreamSubscription<void>> _loggingSubscriptions = <StreamSubscription<void>>[]; @override Stream<String> get logLines => linesController.stream; @override FlutterVmService? get connectedVMService => _connectedVMService; FlutterVmService? _connectedVMService; @override set connectedVMService(FlutterVmService? connectedVmService) { if (connectedVmService != null) { _listenToUnifiedLoggingEvents(connectedVmService); } _connectedVMService = connectedVmService; } static const int minimumUniversalLoggingSdkVersion = 13; /// Determine the primary and fallback source for device logs. /// /// There are three potential logging sources: `idevicesyslog`, `ios-deploy`, /// and Unified Logging (Dart VM). @visibleForTesting _IOSDeviceLogSources get logSources { // `ios-deploy` stopped working with iOS 17 / Xcode 15, so use `idevicesyslog` instead. // However, `idevicesyslog` is sometimes unreliable so use Dart VM as a fallback. // Also, `idevicesyslog` does not work with iOS 17 wireless devices, so use the // Dart VM for wireless devices. if (_isCoreDevice) { if (_isWirelesslyConnected) { return _IOSDeviceLogSources( primarySource: IOSDeviceLogSource.unifiedLogging, ); } return _IOSDeviceLogSources( primarySource: IOSDeviceLogSource.idevicesyslog, fallbackSource: IOSDeviceLogSource.unifiedLogging, ); } // Use `idevicesyslog` for iOS 12 or less. // Syslog stopped working on iOS 13 (https://github.com/flutter/flutter/issues/41133). // However, from at least iOS 16, it has began working again. It's unclear // why it started working again. if (_majorSdkVersion < minimumUniversalLoggingSdkVersion) { return _IOSDeviceLogSources( primarySource: IOSDeviceLogSource.idevicesyslog, ); } // Use `idevicesyslog` as a fallback to `ios-deploy` when debugging from // CI system since sometimes `ios-deploy` does not return the device logs: // https://github.com/flutter/flutter/issues/121231 if (_usingCISystem && _majorSdkVersion >= 16) { return _IOSDeviceLogSources( primarySource: IOSDeviceLogSource.iosDeploy, fallbackSource: IOSDeviceLogSource.idevicesyslog, ); } // Use `ios-deploy` to stream logs from the device when the device is not a // CoreDevice and has iOS 13 or greater. // When using `ios-deploy` and the Dart VM, prefer the more complete logs // from the attached debugger, if available. if (connectedVMService != null && (_iosDeployDebugger == null || !_iosDeployDebugger!.debuggerAttached)) { return _IOSDeviceLogSources( primarySource: IOSDeviceLogSource.unifiedLogging, fallbackSource: IOSDeviceLogSource.iosDeploy, ); } return _IOSDeviceLogSources( primarySource: IOSDeviceLogSource.iosDeploy, fallbackSource: IOSDeviceLogSource.unifiedLogging, ); } /// Whether `idevicesyslog` is used as either the primary or fallback source for device logs. @visibleForTesting bool get useSyslogLogging { return logSources.primarySource == IOSDeviceLogSource.idevicesyslog || logSources.fallbackSource == IOSDeviceLogSource.idevicesyslog; } /// Whether the Dart VM is used as either the primary or fallback source for device logs. /// /// Unified Logging only works after the Dart VM has been connected to. @visibleForTesting bool get useUnifiedLogging { return logSources.primarySource == IOSDeviceLogSource.unifiedLogging || logSources.fallbackSource == IOSDeviceLogSource.unifiedLogging; } /// Whether `ios-deploy` is used as either the primary or fallback source for device logs. @visibleForTesting bool get useIOSDeployLogging { return logSources.primarySource == IOSDeviceLogSource.iosDeploy || logSources.fallbackSource == IOSDeviceLogSource.iosDeploy; } /// Listen to Dart VM for logs on iOS 13 or greater. Future<void> _listenToUnifiedLoggingEvents(FlutterVmService connectedVmService) async { if (!useUnifiedLogging) { return; } try { // The VM service will not publish logging events unless the debug stream is being listened to. // Listen to this stream as a side effect. unawaited(connectedVmService.service.streamListen('Debug')); await Future.wait(<Future<void>>[ connectedVmService.service.streamListen(vm_service.EventStreams.kStdout), connectedVmService.service.streamListen(vm_service.EventStreams.kStderr), ]); } on vm_service.RPCError { // Do nothing, since the tool is already subscribed. } void logMessage(vm_service.Event event) { final String message = processVmServiceMessage(event); if (message.isNotEmpty) { addToLinesController(message, IOSDeviceLogSource.unifiedLogging); } } _loggingSubscriptions.addAll(<StreamSubscription<void>>[ connectedVmService.service.onStdoutEvent.listen(logMessage), connectedVmService.service.onStderrEvent.listen(logMessage), ]); } /// Log reader will listen to [debugger.logLines] and will detach debugger on dispose. IOSDeployDebugger? get debuggerStream => _iosDeployDebugger; /// Send messages from ios-deploy debugger stream to device log reader stream. set debuggerStream(IOSDeployDebugger? debugger) { // Logging is gathered from syslog on iOS earlier than 13. if (!useIOSDeployLogging) { return; } _iosDeployDebugger = debugger; if (debugger == null) { return; } // Add the debugger logs to the controller created on initialization. _loggingSubscriptions.add(debugger.logLines.listen( (String line) => addToLinesController( _debuggerLineHandler(line), IOSDeviceLogSource.iosDeploy, ), onError: linesController.addError, onDone: linesController.close, cancelOnError: true, )); } IOSDeployDebugger? _iosDeployDebugger; // Strip off the logging metadata (leave the category), or just echo the line. String _debuggerLineHandler(String line) => _debuggerLoggingRegex.firstMatch(line)?.group(1) ?? line; /// Start and listen to idevicesyslog to get device logs for iOS versions /// prior to 13 or if [useBothLogDeviceReaders] is true. void _listenToSysLog() { if (!useSyslogLogging) { return; } _iMobileDevice.startLogger(_deviceId, _isWirelesslyConnected).then<void>((Process process) { process.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_newSyslogLineHandler()); process.stderr.transform<String>(utf8.decoder).transform<String>(const LineSplitter()).listen(_newSyslogLineHandler()); process.exitCode.whenComplete(() { if (!linesController.hasListener) { return; } // When using both log readers, do not close the stream on exit. // This is to allow ios-deploy to be the source of authority to close // the stream. if (useSyslogLogging && useIOSDeployLogging && debuggerStream != null) { return; } linesController.close(); }); assert(idevicesyslogProcess == null); idevicesyslogProcess = process; }); } @visibleForTesting Process? idevicesyslogProcess; // Returns a stateful line handler to properly capture multiline output. // // For multiline log messages, any line after the first is logged without // any specific prefix. To properly capture those, we enter "printing" mode // after matching a log line from the runner. When in printing mode, we print // all lines until we find the start of another log message (from any app). void Function(String line) _newSyslogLineHandler() { bool printing = false; return (String line) { if (printing) { if (!_anyLineRegex.hasMatch(line)) { addToLinesController(decodeSyslog(line), IOSDeviceLogSource.idevicesyslog); return; } printing = false; } final Match? match = _runnerLineRegex.firstMatch(line); if (match != null) { final String logLine = line.substring(match.end); // Only display the log line after the initial device and executable information. addToLinesController(decodeSyslog(logLine), IOSDeviceLogSource.idevicesyslog); printing = true; } }; } @override void dispose() { for (final StreamSubscription<void> loggingSubscription in _loggingSubscriptions) { loggingSubscription.cancel(); } idevicesyslogProcess?.kill(); _iosDeployDebugger?.detach(); } } enum IOSDeviceLogSource { /// Gets logs from ios-deploy debugger. iosDeploy, /// Gets logs from idevicesyslog. idevicesyslog, /// Gets logs from the Dart VM Service. unifiedLogging, } class _IOSDeviceLogSources { _IOSDeviceLogSources({ required this.primarySource, this.fallbackSource, }); final IOSDeviceLogSource primarySource; final IOSDeviceLogSource? fallbackSource; } /// A [DevicePortForwarder] specialized for iOS usage with iproxy. class IOSDevicePortForwarder extends DevicePortForwarder { /// Create a new [IOSDevicePortForwarder]. IOSDevicePortForwarder({ required Logger logger, required String id, required IProxy iproxy, required OperatingSystemUtils operatingSystemUtils, }) : _logger = logger, _id = id, _iproxy = iproxy, _operatingSystemUtils = operatingSystemUtils; /// Create a [IOSDevicePortForwarder] for testing. /// /// This specifies the path to iproxy as 'iproxy` and the dyLdLibEntry as /// 'DYLD_LIBRARY_PATH: /path/to/libs'. /// /// The device id may be provided, but otherwise defaults to '1234'. factory IOSDevicePortForwarder.test({ required ProcessManager processManager, required Logger logger, String? id, required OperatingSystemUtils operatingSystemUtils, }) { return IOSDevicePortForwarder( logger: logger, iproxy: IProxy.test( logger: logger, processManager: processManager, ), id: id ?? '1234', operatingSystemUtils: operatingSystemUtils, ); } final Logger _logger; final String _id; final IProxy _iproxy; final OperatingSystemUtils _operatingSystemUtils; @override List<ForwardedPort> forwardedPorts = <ForwardedPort>[]; @visibleForTesting void addForwardedPorts(List<ForwardedPort> ports) { ports.forEach(forwardedPorts.add); } static const Duration _kiProxyPortForwardTimeout = Duration(seconds: 1); @override Future<int> forward(int devicePort, { int? hostPort }) async { final bool autoselect = hostPort == null || hostPort == 0; if (autoselect) { final int freePort = await _operatingSystemUtils.findFreePort(); // Dynamic port range 49152 - 65535. hostPort = freePort == 0 ? 49152 : freePort; } Process? process; bool connected = false; while (!connected) { _logger.printTrace('Attempting to forward device port $devicePort to host port $hostPort'); process = await _iproxy.forward(devicePort, hostPort!, _id); // TODO(ianh): This is a flaky race condition, https://github.com/libimobiledevice/libimobiledevice/issues/674 connected = !await process.stdout.isEmpty.timeout(_kiProxyPortForwardTimeout, onTimeout: () => false); if (!connected) { process.kill(); if (autoselect) { hostPort += 1; if (hostPort > 65535) { throw Exception('Could not find open port on host.'); } } else { throw Exception('Port $hostPort is not available.'); } } } assert(connected); assert(process != null); final ForwardedPort forwardedPort = ForwardedPort.withContext( hostPort!, devicePort, process, ); _logger.printTrace('Forwarded port $forwardedPort'); forwardedPorts.add(forwardedPort); return hostPort; } @override Future<void> unforward(ForwardedPort forwardedPort) async { if (!forwardedPorts.remove(forwardedPort)) { // Not in list. Nothing to remove. return; } _logger.printTrace('Un-forwarding port $forwardedPort'); forwardedPort.dispose(); } @override Future<void> dispose() async { for (final ForwardedPort forwardedPort in forwardedPorts) { forwardedPort.dispose(); } } }
flutter/packages/flutter_tools/lib/src/ios/devices.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/ios/devices.dart", "repo_id": "flutter", "token_count": 20824 }
807
// Copyright 2014 The Flutter Authors. 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:xml/xml.dart'; import 'package:xml/xpath.dart'; import '../base/common.dart'; import '../base/error_handling_io.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/process.dart'; import '../base/template.dart'; import '../convert.dart'; import '../macos/xcode.dart'; import '../template.dart'; /// A class to handle interacting with Xcode via OSA (Open Scripting Architecture) /// Scripting to debug Flutter applications. class XcodeDebug { XcodeDebug({ required Logger logger, required ProcessManager processManager, required Xcode xcode, required FileSystem fileSystem, }) : _logger = logger, _processUtils = ProcessUtils(logger: logger, processManager: processManager), _xcode = xcode, _fileSystem = fileSystem; final ProcessUtils _processUtils; final Logger _logger; final Xcode _xcode; final FileSystem _fileSystem; /// Process to start Xcode's debug action. @visibleForTesting Process? startDebugActionProcess; /// Information about the project that is currently being debugged. @visibleForTesting XcodeDebugProject? currentDebuggingProject; /// Whether the debug action has been started. bool get debugStarted => currentDebuggingProject != null; /// Install, launch, and start a debug session for app through Xcode interface, /// automated by OSA scripting. First checks if the project is opened in /// Xcode. If it isn't, open it with the `open` command. /// /// The OSA script waits until the project is opened and the debug action /// has started. It does not wait for the app to install, launch, or start /// the debug session. Future<bool> debugApp({ required XcodeDebugProject project, required String deviceId, required List<String> launchArguments, }) async { // If project is not already opened in Xcode, open it. if (!await _isProjectOpenInXcode(project: project)) { final bool openResult = await _openProjectInXcode(xcodeWorkspace: project.xcodeWorkspace); if (!openResult) { return openResult; } } currentDebuggingProject = project; StreamSubscription<String>? stdoutSubscription; StreamSubscription<String>? stderrSubscription; try { startDebugActionProcess = await _processUtils.start( <String>[ ..._xcode.xcrunCommand(), 'osascript', '-l', 'JavaScript', _xcode.xcodeAutomationScriptPath, 'debug', '--xcode-path', _xcode.xcodeAppPath, '--project-path', project.xcodeProject.path, '--workspace-path', project.xcodeWorkspace.path, '--project-name', project.hostAppProjectName, if (project.expectedConfigurationBuildDir != null) ...<String>[ '--expected-configuration-build-dir', project.expectedConfigurationBuildDir!, ], '--device-id', deviceId, '--scheme', project.scheme, '--skip-building', '--launch-args', json.encode(launchArguments), if (project.verboseLogging) '--verbose', ], ); final StringBuffer stdoutBuffer = StringBuffer(); stdoutSubscription = startDebugActionProcess!.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { _logger.printTrace(line); stdoutBuffer.write(line); }); final StringBuffer stderrBuffer = StringBuffer(); bool permissionWarningPrinted = false; // console.log from the script are found in the stderr stderrSubscription = startDebugActionProcess!.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { _logger.printTrace('stderr: $line'); stderrBuffer.write(line); // This error may occur if Xcode automation has not been allowed. // Example: Failed to get workspace: Error: An error occurred. if (!permissionWarningPrinted && line.contains('Failed to get workspace') && line.contains('An error occurred')) { _logger.printError( 'There was an error finding the project in Xcode. Ensure permission ' 'has been given to control Xcode in Settings > Privacy & Security > Automation.', ); permissionWarningPrinted = true; } }); final int exitCode = await startDebugActionProcess!.exitCode.whenComplete(() async { await stdoutSubscription?.cancel(); await stderrSubscription?.cancel(); startDebugActionProcess = null; }); if (exitCode != 0) { _logger.printError('Error executing osascript: $exitCode\n$stderrBuffer'); return false; } final XcodeAutomationScriptResponse? response = parseScriptResponse( stdoutBuffer.toString(), ); if (response == null) { return false; } if (response.status == false) { _logger.printError('Error starting debug session in Xcode: ${response.errorMessage}'); return false; } if (response.debugResult == null) { _logger.printError('Unable to get debug results from response: $stdoutBuffer'); return false; } if (response.debugResult?.status != 'running') { _logger.printError( 'Unexpected debug results: \n' ' Status: ${response.debugResult?.status}\n' ' Completed: ${response.debugResult?.completed}\n' ' Error Message: ${response.debugResult?.errorMessage}\n' ); return false; } return true; } on ProcessException catch (exception) { _logger.printError('Error executing osascript: $exitCode\n$exception'); await stdoutSubscription?.cancel(); await stderrSubscription?.cancel(); startDebugActionProcess = null; return false; } } /// Kills [startDebugActionProcess] if it's still running. If [force] is true, it /// will kill all Xcode app processes. Otherwise, it will stop the debug /// session in Xcode. If the project is temporary, it will close the Xcode /// window of the project and then delete the project. Future<bool> exit({ bool force = false, @visibleForTesting bool skipDelay = false, }) async { final bool success = (startDebugActionProcess == null) || startDebugActionProcess!.kill(); if (force) { await _forceExitXcode(); if (currentDebuggingProject != null) { final XcodeDebugProject project = currentDebuggingProject!; if (project.isTemporaryProject) { // Only delete if it exists. This is to prevent crashes when racing // with shutdown hooks to delete temporary files. ErrorHandlingFileSystem.deleteIfExists( project.xcodeProject.parent, recursive: true, ); } currentDebuggingProject = null; } } if (currentDebuggingProject != null) { final XcodeDebugProject project = currentDebuggingProject!; await stopDebuggingApp( project: project, closeXcode: project.isTemporaryProject, ); if (project.isTemporaryProject) { // Wait a couple seconds before deleting the project. If project is // still opened in Xcode and it's deleted, it will prompt the user to // restore it. if (!skipDelay) { await Future<void>.delayed(const Duration(seconds: 2)); } try { project.xcodeProject.parent.deleteSync(recursive: true); } on FileSystemException { _logger.printError('Failed to delete temporary Xcode project: ${project.xcodeProject.parent.path}'); } } currentDebuggingProject = null; } return success; } /// Kill all opened Xcode applications. Future<bool> _forceExitXcode() async { final RunResult result = await _processUtils.run( <String>[ 'killall', '-9', 'Xcode', ], ); if (result.exitCode != 0) { _logger.printError('Error killing Xcode: ${result.exitCode}\n${result.stderr}'); return false; } return true; } Future<bool> _isProjectOpenInXcode({ required XcodeDebugProject project, }) async { final RunResult result = await _processUtils.run( <String>[ ..._xcode.xcrunCommand(), 'osascript', '-l', 'JavaScript', _xcode.xcodeAutomationScriptPath, 'check-workspace-opened', '--xcode-path', _xcode.xcodeAppPath, '--project-path', project.xcodeProject.path, '--workspace-path', project.xcodeWorkspace.path, if (project.verboseLogging) '--verbose', ], ); if (result.exitCode != 0) { _logger.printError('Error executing osascript: ${result.exitCode}\n${result.stderr}'); return false; } final XcodeAutomationScriptResponse? response = parseScriptResponse(result.stdout); if (response == null) { return false; } if (response.status == false) { _logger.printTrace('Error checking if project opened in Xcode: ${response.errorMessage}'); return false; } return true; } @visibleForTesting XcodeAutomationScriptResponse? parseScriptResponse(String results) { try { final Object decodeResult = json.decode(results) as Object; if (decodeResult is Map<String, Object?>) { final XcodeAutomationScriptResponse response = XcodeAutomationScriptResponse.fromJson(decodeResult); // Status should always be found if (response.status != null) { return response; } } _logger.printError('osascript returned unexpected JSON response: $results'); return null; } on FormatException { _logger.printError('osascript returned non-JSON response: $results'); return null; } } Future<bool> _openProjectInXcode({ required Directory xcodeWorkspace, }) async { try { await _processUtils.run( <String>[ 'open', '-a', _xcode.xcodeAppPath, '-g', // Do not bring the application to the foreground. '-j', // Launches the app hidden. '-F', // Open "fresh", without restoring windows. xcodeWorkspace.path ], throwOnError: true, ); return true; } on ProcessException catch (error, stackTrace) { _logger.printError('$error', stackTrace: stackTrace); } return false; } /// Using OSA Scripting, stop the debug session in Xcode. /// /// If [closeXcode] is true, it will close the Xcode window that has the /// project opened. If [promptToSaveOnClose] is true, it will ask the user if /// they want to save any changes before it closes. Future<bool> stopDebuggingApp({ required XcodeDebugProject project, bool closeXcode = false, bool promptToSaveOnClose = false, }) async { final RunResult result = await _processUtils.run( <String>[ ..._xcode.xcrunCommand(), 'osascript', '-l', 'JavaScript', _xcode.xcodeAutomationScriptPath, 'stop', '--xcode-path', _xcode.xcodeAppPath, '--project-path', project.xcodeProject.path, '--workspace-path', project.xcodeWorkspace.path, if (closeXcode) '--close-window', if (promptToSaveOnClose) '--prompt-to-save', if (project.verboseLogging) '--verbose', ], ); if (result.exitCode != 0) { _logger.printError('Error executing osascript: ${result.exitCode}\n${result.stderr}'); return false; } final XcodeAutomationScriptResponse? response = parseScriptResponse(result.stdout); if (response == null) { return false; } if (response.status == false) { _logger.printError('Error stopping app in Xcode: ${response.errorMessage}'); return false; } return true; } /// Create a temporary empty Xcode project with the application bundle /// location explicitly set. Future<XcodeDebugProject> createXcodeProjectWithCustomBundle( String deviceBundlePath, { required TemplateRenderer templateRenderer, @visibleForTesting Directory? projectDestination, bool verboseLogging = false, }) async { final Directory tempXcodeProject = projectDestination ?? _fileSystem.systemTempDirectory.createTempSync('flutter_empty_xcode.'); final Template template = await Template.fromName( _fileSystem.path.join('xcode', 'ios', 'custom_application_bundle'), fileSystem: _fileSystem, templateManifest: null, logger: _logger, templateRenderer: templateRenderer, ); template.render( tempXcodeProject, <String, Object>{ 'applicationBundlePath': deviceBundlePath }, printStatusWhenWriting: false, ); return XcodeDebugProject( scheme: 'Runner', hostAppProjectName: 'Runner', xcodeProject: tempXcodeProject.childDirectory('Runner.xcodeproj'), xcodeWorkspace: tempXcodeProject.childDirectory('Runner.xcworkspace'), isTemporaryProject: true, verboseLogging: verboseLogging, ); } /// Ensure the Xcode project is set up to launch an LLDB debugger. If these /// settings are not set, the launch will fail with a "Cannot create a /// FlutterEngine instance in debug mode without Flutter tooling or Xcode." /// error message. These settings should be correct by default, but some users /// reported them not being so after upgrading to Xcode 15. void ensureXcodeDebuggerLaunchAction(File schemeFile) { if (!schemeFile.existsSync()) { _logger.printError('Failed to find ${schemeFile.path}'); return; } final String schemeXml = schemeFile.readAsStringSync(); try { final XmlDocument document = XmlDocument.parse(schemeXml); final Iterable<XmlNode> nodes = document.xpath('/Scheme/LaunchAction'); if (nodes.isEmpty) { _logger.printError('Failed to find LaunchAction for the Scheme in ${schemeFile.path}.'); return; } final XmlNode launchAction = nodes.first; final XmlAttribute? debuggerIdentifier = launchAction.attributes .where((XmlAttribute attribute) => attribute.localName == 'selectedDebuggerIdentifier') .firstOrNull; final XmlAttribute? launcherIdentifier = launchAction.attributes .where((XmlAttribute attribute) => attribute.localName == 'selectedLauncherIdentifier') .firstOrNull; if (debuggerIdentifier == null || launcherIdentifier == null || !debuggerIdentifier.value.contains('LLDB') || !launcherIdentifier.value.contains('LLDB')) { throwToolExit(''' Your Xcode project is not setup to start a debugger. To fix this, launch Xcode and select "Product > Scheme > Edit Scheme", select "Run" in the sidebar, and ensure "Debug executable" is checked in the "Info" tab. '''); } } on XmlException catch (exception) { _logger.printError('Failed to parse ${schemeFile.path}: $exception'); } } } @visibleForTesting class XcodeAutomationScriptResponse { XcodeAutomationScriptResponse._({ this.status, this.errorMessage, this.debugResult, }); factory XcodeAutomationScriptResponse.fromJson(Map<String, Object?> data) { XcodeAutomationScriptDebugResult? debugResult; if (data['debugResult'] != null && data['debugResult'] is Map<String, Object?>) { debugResult = XcodeAutomationScriptDebugResult.fromJson( data['debugResult']! as Map<String, Object?>, ); } return XcodeAutomationScriptResponse._( status: data['status'] is bool? ? data['status'] as bool? : null, errorMessage: data['errorMessage']?.toString(), debugResult: debugResult, ); } final bool? status; final String? errorMessage; final XcodeAutomationScriptDebugResult? debugResult; } @visibleForTesting class XcodeAutomationScriptDebugResult { XcodeAutomationScriptDebugResult._({ required this.completed, required this.status, required this.errorMessage, }); factory XcodeAutomationScriptDebugResult.fromJson(Map<String, Object?> data) { return XcodeAutomationScriptDebugResult._( completed: data['completed'] is bool? ? data['completed'] as bool? : null, status: data['status']?.toString(), errorMessage: data['errorMessage']?.toString(), ); } /// Whether this scheme action has completed (successfully or otherwise). Will /// be false if still running. final bool? completed; /// The status of the debug action. Potential statuses include: /// `not yet started`, `‌running`, `‌cancelled`, `‌failed`, `‌error occurred`, /// and `‌succeeded`. /// /// Only the status of `‌running` indicates the debug action has started successfully. /// For example, `‌succeeded` often does not indicate success as if the action fails, /// it will sometimes return `‌succeeded`. final String? status; /// When [status] is `‌error occurred`, an error message is provided. /// Otherwise, this will be null. final String? errorMessage; } class XcodeDebugProject { XcodeDebugProject({ required this.scheme, required this.xcodeWorkspace, required this.xcodeProject, required this.hostAppProjectName, this.expectedConfigurationBuildDir, this.isTemporaryProject = false, this.verboseLogging = false, }); final String scheme; final Directory xcodeWorkspace; final Directory xcodeProject; final String hostAppProjectName; final String? expectedConfigurationBuildDir; final bool isTemporaryProject; /// When [verboseLogging] is true, the xcode_debug.js script will log /// additional information via console.log, which is sent to stderr. final bool verboseLogging; }
flutter/packages/flutter_tools/lib/src/ios/xcode_debug.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/ios/xcode_debug.dart", "repo_id": "flutter", "token_count": 6881 }
808
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:package_config/package_config.dart'; import 'base/file_system.dart'; /// Processes dependencies into a string representing the NOTICES file. /// /// Reads the NOTICES or LICENSE file from each package in the .packages file, /// splitting each one into each component license so that it can be de-duped /// if possible. If the NOTICES file exists, it is preferred over the LICENSE /// file. /// /// Individual licenses inside each LICENSE file should be separated by 80 /// hyphens on their own on a line. /// /// If a LICENSE or NOTICES file contains more than one component license, /// then each component license must start with the names of the packages to /// which the component license applies, with each package name on its own line /// and the list of package names separated from the actual license text by a /// blank line. The packages need not match the names of the pub package. For /// example, a package might itself contain code from multiple third-party /// sources, and might need to include a license for each one. class LicenseCollector { LicenseCollector({ required FileSystem fileSystem }) : _fileSystem = fileSystem; final FileSystem _fileSystem; /// The expected separator for multiple licenses. static final String licenseSeparator = '\n${'-' * 80}\n'; /// Obtain licenses from the `packageMap` into a single result. /// /// [additionalLicenses] should contain aggregated license files from all /// of the current applications dependencies. LicenseResult obtainLicenses( PackageConfig packageConfig, Map<String, List<File>> additionalLicenses, ) { final Map<String, Set<String>> packageLicenses = <String, Set<String>>{}; final Set<String> allPackages = <String>{}; final List<File> dependencies = <File>[]; for (final Package package in packageConfig.packages) { final Uri packageUri = package.packageUriRoot; if (packageUri.scheme != 'file') { continue; } // First check for NOTICES, then fallback to LICENSE File file = _fileSystem.file(packageUri.resolve('../NOTICES')); if (!file.existsSync()) { file = _fileSystem.file(packageUri.resolve('../LICENSE')); } if (!file.existsSync()) { continue; } dependencies.add(file); final List<String> rawLicenses = file .readAsStringSync() .split(licenseSeparator); for (final String rawLicense in rawLicenses) { List<String> packageNames = <String>[]; String? licenseText; if (rawLicenses.length > 1) { final int split = rawLicense.indexOf('\n\n'); if (split >= 0) { packageNames = rawLicense.substring(0, split).split('\n'); licenseText = rawLicense.substring(split + 2); } } if (licenseText == null) { packageNames = <String>[package.name]; licenseText = rawLicense; } packageLicenses.putIfAbsent(licenseText, () => <String>{}).addAll(packageNames); allPackages.addAll(packageNames); } } final List<String> combinedLicensesList = packageLicenses.entries .map<String>((MapEntry<String, Set<String>> entry) { final List<String> packageNames = entry.value.toList()..sort(); return '${packageNames.join('\n')}\n\n${entry.key}'; }).toList(); combinedLicensesList.sort(); /// Append additional LICENSE files as specified in the pubspec.yaml. final List<String> additionalLicenseText = <String>[]; final List<String> errorMessages = <String>[]; for (final String package in additionalLicenses.keys) { for (final File license in additionalLicenses[package]!) { if (!license.existsSync()) { errorMessages.add( 'package $package specified an additional license at ${license.path}, but this file ' 'does not exist.' ); continue; } dependencies.add(license); try { additionalLicenseText.add(license.readAsStringSync()); } on FormatException catch (err) { // File has an invalid encoding. errorMessages.add( 'package $package specified an additional license at ${license.path}, but this file ' 'could not be read:\n$err' ); } on FileSystemException catch (err) { // File cannot be parsed. errorMessages.add( 'package $package specified an additional license at ${license.path}, but this file ' 'could not be read:\n$err' ); } } } if (errorMessages.isNotEmpty) { return LicenseResult( combinedLicenses: '', dependencies: <File>[], errorMessages: errorMessages, ); } final String combinedLicenses = combinedLicensesList .followedBy(additionalLicenseText) .join(licenseSeparator); return LicenseResult( combinedLicenses: combinedLicenses, dependencies: dependencies, errorMessages: errorMessages, ); } } /// The result of processing licenses with a [LicenseCollector]. class LicenseResult { const LicenseResult({ required this.combinedLicenses, required this.dependencies, required this.errorMessages, }); /// The raw text of the consumed licenses. final String combinedLicenses; /// Each license file that was consumed as input. final List<File> dependencies; /// If non-empty, license collection failed and this messages should /// be displayed by the asset parser. final List<String> errorMessages; }
flutter/packages/flutter_tools/lib/src/license_collector.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/license_collector.dart", "repo_id": "flutter", "token_count": 2014 }
809
// Copyright 2014 The Flutter Authors. 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/user_messages.dart'; import '../doctor_validator.dart'; import 'cocoapods.dart'; /// A validator that confirms cocoapods is in a valid state. /// /// See also: /// * [CocoaPods], for the interface to the cocoapods command line tool. class CocoaPodsValidator extends DoctorValidator { CocoaPodsValidator( CocoaPods cocoaPods, UserMessages userMessages, ) : _cocoaPods = cocoaPods, _userMessages = userMessages, super('CocoaPods subvalidator'); final CocoaPods _cocoaPods; final UserMessages _userMessages; @override Future<ValidationResult> validate() async { final List<ValidationMessage> messages = <ValidationMessage>[]; final CocoaPodsStatus cocoaPodsStatus = await _cocoaPods .evaluateCocoaPodsInstallation; ValidationType status = ValidationType.success; switch (cocoaPodsStatus) { case CocoaPodsStatus.recommended: messages.add(ValidationMessage(_userMessages.cocoaPodsVersion((await _cocoaPods.cocoaPodsVersionText).toString()))); case CocoaPodsStatus.notInstalled: status = ValidationType.missing; messages.add(ValidationMessage.error( _userMessages.cocoaPodsMissing(noCocoaPodsConsequence, cocoaPodsInstallInstructions))); case CocoaPodsStatus.brokenInstall: status = ValidationType.missing; messages.add(ValidationMessage.error( _userMessages.cocoaPodsBrokenInstall(brokenCocoaPodsConsequence, cocoaPodsInstallInstructions))); case CocoaPodsStatus.unknownVersion: status = ValidationType.partial; messages.add(ValidationMessage.hint( _userMessages.cocoaPodsUnknownVersion(unknownCocoaPodsConsequence, cocoaPodsInstallInstructions))); case CocoaPodsStatus.belowMinimumVersion: case CocoaPodsStatus.belowRecommendedVersion: status = ValidationType.partial; final String currentVersionText = (await _cocoaPods.cocoaPodsVersionText).toString(); messages.add(ValidationMessage.hint( _userMessages.cocoaPodsOutdated(currentVersionText, cocoaPodsRecommendedVersion.toString(), noCocoaPodsConsequence, cocoaPodsUpdateInstructions))); } return ValidationResult(status, messages); } }
flutter/packages/flutter_tools/lib/src/macos/cocoapods_validator.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/macos/cocoapods_validator.dart", "repo_id": "flutter", "token_count": 869 }
810
// Copyright 2014 The Flutter Authors. 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'; // Migrate Xcode build phases that build and embed the Flutter and // compiled dart frameworks. class XcodeScriptBuildPhaseMigration extends ProjectMigrator { XcodeScriptBuildPhaseMigration(XcodeBasedProject project, super.logger) : _xcodeProjectInfoFile = project.xcodeProjectInfoFile; final File _xcodeProjectInfoFile; @override void migrate() { if (!_xcodeProjectInfoFile.existsSync()) { logger.printTrace('Xcode project not found, skipping script build phase dependency analysis removal.'); return; } final String originalProjectContents = _xcodeProjectInfoFile.readAsStringSync(); // Uncheck "Based on dependency analysis" which causes a warning in Xcode 14. // Unchecking sets "alwaysOutOfDate = 1" in the Xcode project file. // Example: // 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { // isa = PBXShellScriptBuildPhase; // buildActionMask = 2147483647; final List<String> scriptIdentifierLinesToMigrate = <String>[ '3B06AD1E1E4923F5004D2608 /* Thin Binary */', // iOS template '9740EEB61CF901F6004384FC /* Run Script */', // iOS template '3399D490228B24CF009A79C7 /* ShellScript */', // macOS Runner target (not Flutter Assemble) ]; String newProjectContents = originalProjectContents; for (final String scriptIdentifierLine in scriptIdentifierLinesToMigrate) { final String scriptBuildPhaseOriginal = ''' $scriptIdentifierLine = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; '''; final String scriptBuildPhaseReplacement = ''' $scriptIdentifierLine = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; buildActionMask = 2147483647; '''; newProjectContents = newProjectContents.replaceAll(scriptBuildPhaseOriginal, scriptBuildPhaseReplacement); } if (originalProjectContents != newProjectContents) { logger.printStatus('Removing script build phase dependency analysis.'); _xcodeProjectInfoFile.writeAsStringSync(newProjectContents); } } }
flutter/packages/flutter_tools/lib/src/migrations/xcode_script_build_phase_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/migrations/xcode_script_build_phase_migration.dart", "repo_id": "flutter", "token_count": 754 }
811
Flutter reports data to two separate systems: 1. Anonymous usage statistics are reported to Google Analytics (for statistics such as the number of times the `flutter` tool was run within a given time period). The code that manages this is in [usage.dart]. 1. Crash reports for the `flutter` tool. These are not reports of when Flutter applications crash, but rather when the command-line `flutter` tool itself crashes. The code that manages this is in [crash_reporting.dart]. ## Opting out Users can opt out of all reporting in a single place by running `flutter config --no-analytics`.
flutter/packages/flutter_tools/lib/src/reporting/README.md/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/reporting/README.md", "repo_id": "flutter", "token_count": 157 }
812
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:package_config/package_config.dart'; import '../artifacts.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../base/user_messages.dart'; import '../cache.dart'; import '../dart/package_map.dart'; /// A strategy for locating the `out/` directory of a local engine build. /// /// The flutter tool can be run with the output files of one or more engine builds /// replacing the cached artifacts. Typically this is done by setting the /// `--local-engine` command line flag to the name of the desired engine variant /// (e.g. "host_debug_unopt"). Provided that the `flutter/` and `engine/` directories /// are located adjacent to one another, the output folder will be located /// automatically. /// /// For scenarios where the engine is not adjacent to flutter, the /// `--local-engine-src-path` can be provided to give an exact path. /// /// For more information on local engines, see README.md. class LocalEngineLocator { LocalEngineLocator({ required Platform platform, required Logger logger, required FileSystem fileSystem, required String flutterRoot, required UserMessages userMessages, }) : _platform = platform, _logger = logger, _fileSystem = fileSystem, _flutterRoot = flutterRoot, _userMessages = userMessages; final Platform _platform; final Logger _logger; final FileSystem _fileSystem; final String _flutterRoot; final UserMessages _userMessages; /// Returns the engine build path of a local engine if one is located, otherwise `null`. Future<EngineBuildPaths?> findEnginePath({ String? engineSourcePath, String? localEngine, String? localHostEngine, String? localWebSdk, String? packagePath, }) async { engineSourcePath ??= _platform.environment[kFlutterEngineEnvironmentVariableName]; if (engineSourcePath == null && localEngine == null && localWebSdk == null && packagePath == null) { return null; } if (engineSourcePath == null) { try { if (localEngine != null) { engineSourcePath = _findEngineSourceByBuildPath(localEngine); } if (localWebSdk != null) { engineSourcePath ??= _findEngineSourceByBuildPath(localWebSdk); } engineSourcePath ??= await _findEngineSourceByPackageConfig(packagePath); } on FileSystemException catch (e) { _logger.printTrace('Local engine auto-detection file exception: $e'); engineSourcePath = null; } // If engineSourcePath is still not set, try to determine it by flutter root. engineSourcePath ??= _tryEnginePath( _fileSystem.path.join(_fileSystem.directory(_flutterRoot).parent.path, 'engine', 'src'), ); } if (engineSourcePath != null && _tryEnginePath(engineSourcePath) == null) { throwToolExit( _userMessages.runnerNoEngineBuildDirInPath(engineSourcePath), exitCode: 2, ); } if (engineSourcePath != null) { _logger.printTrace('Local engine source at $engineSourcePath'); return _findEngineBuildPath( engineSourcePath: engineSourcePath, localEngine: localEngine, localWebSdk: localWebSdk, localHostEngine: localHostEngine, ); } if (localEngine != null || localWebSdk != null) { throwToolExit( _userMessages.runnerNoEngineSrcDir( kFlutterEnginePackageName, kFlutterEngineEnvironmentVariableName, ), exitCode: 2, ); } return null; } String? _findEngineSourceByBuildPath(String buildPath) { // When the local engine is an absolute path to a variant inside the // out directory, parse the engine source. // --local-engine /path/to/cache/builder/src/out/host_debug_unopt if (_fileSystem.path.isAbsolute(buildPath)) { final Directory buildDirectory = _fileSystem.directory(buildPath); final Directory outDirectory = buildDirectory.parent; final Directory srcDirectory = outDirectory.parent; if (buildDirectory.existsSync() && outDirectory.basename == 'out' && srcDirectory.basename == 'src') { _logger.printTrace('Parsed engine source from local engine as ${srcDirectory.path}.'); return srcDirectory.path; } } return null; } Future<String?> _findEngineSourceByPackageConfig(String? packagePath) async { final PackageConfig packageConfig = await loadPackageConfigWithLogging( _fileSystem.file( // TODO(zanderso): update to package_config packagePath ?? _fileSystem.path.join('.packages'), ), logger: _logger, throwOnError: false, ); // Skip if sky_engine is the version in bin/cache. Uri? engineUri = packageConfig[kFlutterEnginePackageName]?.packageUriRoot; final String cachedPath = _fileSystem.path.join(_flutterRoot, 'bin', 'cache', 'pkg', kFlutterEnginePackageName, 'lib'); if (engineUri != null && _fileSystem.identicalSync(cachedPath, engineUri.path)) { _logger.printTrace('Local engine auto-detection sky_engine in $packagePath is the same version in bin/cache.'); engineUri = null; } // If sky_engine is specified and the engineSourcePath not set, try to // determine the engineSourcePath by sky_engine setting. A typical engine Uri // looks like: // file://flutter-engine-local-path/src/out/host_debug_unopt/gen/dart-pkg/sky_engine/lib/ String? engineSourcePath; final String? engineUriPath = engineUri?.path; if (engineUriPath != null) { engineSourcePath = _fileSystem.directory(engineUriPath) .parent .parent .parent .parent .parent .parent .path; if (engineSourcePath == _fileSystem.path.dirname(engineSourcePath) || engineSourcePath.isEmpty) { engineSourcePath = null; throwToolExit( _userMessages.runnerNoEngineSrcDir( kFlutterEnginePackageName, kFlutterEngineEnvironmentVariableName, ), exitCode: 2, ); } } return engineSourcePath; } EngineBuildPaths _findEngineBuildPath({ required String engineSourcePath, String? localEngine, String? localWebSdk, String? localHostEngine, }) { if (localEngine == null && localWebSdk == null) { throwToolExit(_userMessages.runnerLocalEngineOrWebSdkRequired, exitCode: 2); } String? engineBuildPath; String? engineHostBuildPath; if (localEngine != null) { engineBuildPath = _fileSystem.path.normalize(_fileSystem.path.join(engineSourcePath, 'out', localEngine)); if (!_fileSystem.isDirectorySync(engineBuildPath)) { throwToolExit(_userMessages.runnerNoEngineBuild(engineBuildPath), exitCode: 2); } if (localHostEngine == null) { throwToolExit(_userMessages.runnerLocalEngineRequiresHostEngine); } engineHostBuildPath = _fileSystem.path.normalize( _fileSystem.path.join(_fileSystem.path.dirname(engineBuildPath), localHostEngine), ); if (!_fileSystem.isDirectorySync(engineHostBuildPath)) { throwToolExit(_userMessages.runnerNoEngineBuild(engineHostBuildPath), exitCode: 2); } } String? webSdkPath; if (localWebSdk != null) { webSdkPath = _fileSystem.path.normalize(_fileSystem.path.join(engineSourcePath, 'out', localWebSdk)); if (!_fileSystem.isDirectorySync(webSdkPath)) { throwToolExit(_userMessages.runnerNoWebSdk(webSdkPath), exitCode: 2); } } return EngineBuildPaths(targetEngine: engineBuildPath, webSdk: webSdkPath, hostEngine: engineHostBuildPath); } String? _tryEnginePath(String enginePath) { if (_fileSystem.isDirectorySync(_fileSystem.path.join(enginePath, 'out'))) { return enginePath; } return null; } }
flutter/packages/flutter_tools/lib/src/runner/local_engine.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/runner/local_engine.dart", "repo_id": "flutter", "token_count": 2899 }
813
// Copyright 2014 The Flutter Authors. 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/logger.dart'; /// Utility class that can record time used in different phases of a test run. class TestTimeRecorder { TestTimeRecorder(this.logger, {this.stopwatchFactory = const StopwatchFactory()}) : _phaseRecords = List<TestTimeRecord>.generate( TestTimePhases.values.length, (_) => TestTimeRecord(stopwatchFactory), ); final List<TestTimeRecord> _phaseRecords; final Logger logger; final StopwatchFactory stopwatchFactory; Stopwatch start(TestTimePhases phase) { return _phaseRecords[phase.index].start(); } void stop(TestTimePhases phase, Stopwatch stopwatch) { _phaseRecords[phase.index].stop(stopwatch); } void print() { for (final TestTimePhases phase in TestTimePhases.values) { logger.printTrace(_getPrintStringForPhase(phase)); } } @visibleForTesting List<String> getPrintAsListForTesting() { final List<String> result = <String>[]; for (final TestTimePhases phase in TestTimePhases.values) { result.add(_getPrintStringForPhase(phase)); } return result; } @visibleForTesting Stopwatch getPhaseWallClockStopwatchForTesting(final TestTimePhases phase) { return _phaseRecords[phase.index]._wallClockRuntime; } String _getPrintStringForPhase(final TestTimePhases phase) { assert(_phaseRecords[phase.index].isDone()); return 'Runtime for phase ${phase.name}: ${_phaseRecords[phase.index]}'; } } /// Utility class that can record time used in a specific phase of a test run. class TestTimeRecord { TestTimeRecord(this.stopwatchFactory) : _wallClockRuntime = stopwatchFactory.createStopwatch(); final StopwatchFactory stopwatchFactory; Duration _combinedRuntime = Duration.zero; final Stopwatch _wallClockRuntime; int _currentlyRunningCount = 0; Stopwatch start() { final Stopwatch stopwatch = stopwatchFactory.createStopwatch()..start(); if (_currentlyRunningCount == 0) { _wallClockRuntime.start(); } _currentlyRunningCount++; return stopwatch; } void stop(Stopwatch stopwatch) { _currentlyRunningCount--; if (_currentlyRunningCount == 0) { _wallClockRuntime.stop(); } _combinedRuntime = _combinedRuntime + stopwatch.elapsed; assert(_currentlyRunningCount >= 0); } @override String toString() { return 'Wall-clock: ${_wallClockRuntime.elapsed}; combined: $_combinedRuntime.'; } bool isDone() { return _currentlyRunningCount == 0; } } enum TestTimePhases { /// Covers entire TestRunner run, i.e. from the test runner was asked to `runTests` until it is done. /// /// This implicitly includes all the other phases. TestRunner, /// Covers time spent compiling, including subsequent copying of files. Compile, /// Covers time spent running, i.e. from starting the test device until the test has finished. Run, /// Covers all time spent collecting coverage. CoverageTotal, /// Covers collecting the coverage, but not parsing nor adding to hit map. /// /// This is included in [CoverageTotal] CoverageCollect, /// Covers parsing the json from the coverage collected. /// /// This is included in [CoverageTotal] CoverageParseJson, /// Covers adding the parsed coverage to the hitmap. /// /// This is included in [CoverageTotal] CoverageAddHitmap, /// Covers time spent in `collectCoverageData`, mostly formatting and writing coverage data to file. CoverageDataCollect, /// Covers time spend in the Watchers `handleFinishedTest` call. This is probably collecting coverage. WatcherFinishedTest, }
flutter/packages/flutter_tools/lib/src/test/test_time_recorder.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/test/test_time_recorder.dart", "repo_id": "flutter", "token_count": 1179 }
814
// Copyright 2014 The Flutter Authors. 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 '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/os.dart' show HostPlatform, OperatingSystemUtils; import '../base/platform.dart'; import '../base/process.dart'; import '../base/version.dart'; import '../convert.dart'; /// Encapsulates information about the installed copy of Visual Studio, if any. class VisualStudio { VisualStudio({ required FileSystem fileSystem, required ProcessManager processManager, required Platform platform, required Logger logger, required OperatingSystemUtils osUtils, }) : _platform = platform, _fileSystem = fileSystem, _processUtils = ProcessUtils(processManager: processManager, logger: logger), _logger = logger, _osUtils = osUtils; final FileSystem _fileSystem; final Platform _platform; final ProcessUtils _processUtils; final Logger _logger; final OperatingSystemUtils _osUtils; /// Matches the description property from the vswhere.exe JSON output. final RegExp _vswhereDescriptionProperty = RegExp(r'\s*"description"\s*:\s*".*"\s*,?'); /// True if Visual Studio installation was found. /// /// Versions older than 2017 Update 2 won't be detected, so error messages to /// users should take into account that [false] may mean that the user may /// have an old version rather than no installation at all. bool get isInstalled => _bestVisualStudioDetails != null; bool get isAtLeastMinimumVersion { final int? installedMajorVersion = _majorVersion; return installedMajorVersion != null && installedMajorVersion >= _minimumSupportedVersion; } /// True if there is a version of Visual Studio with all the components /// necessary to build the project. bool get hasNecessaryComponents => _bestVisualStudioDetails?.isUsable ?? false; /// The name of the Visual Studio install. /// /// For instance: "Visual Studio Community 2019". This should only be used for /// display purposes. String? get displayName => _bestVisualStudioDetails?.displayName; /// The user-friendly version number of the Visual Studio install. /// /// For instance: "15.4.0". This should only be used for display purposes. /// Logic based off the installation's version should use the `fullVersion`. String? get displayVersion => _bestVisualStudioDetails?.catalogDisplayVersion; /// The directory where Visual Studio is installed. String? get installLocation => _bestVisualStudioDetails?.installationPath; /// The full version of the Visual Studio install. /// /// For instance: "15.4.27004.2002". String? get fullVersion => _bestVisualStudioDetails?.fullVersion; // Properties that determine the status of the installation. There might be // Visual Studio versions that don't include them, so default to a "valid" value to // avoid false negatives. /// True if there is a complete installation of Visual Studio. /// /// False if installation is not found. bool get isComplete { if (_bestVisualStudioDetails == null) { return false; } return _bestVisualStudioDetails.isComplete ?? true; } /// True if Visual Studio is launchable. /// /// False if installation is not found. bool get isLaunchable { if (_bestVisualStudioDetails == null) { return false; } return _bestVisualStudioDetails.isLaunchable ?? true; } /// True if the Visual Studio installation is a pre-release version. bool get isPrerelease => _bestVisualStudioDetails?.isPrerelease ?? false; /// True if a reboot is required to complete the Visual Studio installation. bool get isRebootRequired => _bestVisualStudioDetails?.isRebootRequired ?? false; /// The name of the recommended Visual Studio installer workload. String get workloadDescription => 'Desktop development with C++'; /// Returns the highest installed Windows 10 SDK version, or null if none is /// found. /// /// For instance: 10.0.18362.0. String? getWindows10SDKVersion() { final String? sdkLocation = _getWindows10SdkLocation(); if (sdkLocation == null) { return null; } final Directory sdkIncludeDirectory = _fileSystem.directory(sdkLocation).childDirectory('Include'); if (!sdkIncludeDirectory.existsSync()) { return null; } // The directories in this folder are named by the SDK version. Version? highestVersion; for (final FileSystemEntity versionEntry in sdkIncludeDirectory.listSync()) { if (versionEntry.basename.startsWith('10.')) { // Version only handles 3 components; strip off the '10.' to leave three // components, since they all start with that. final Version? version = Version.parse(versionEntry.basename.substring(3)); if (highestVersion == null || (version != null && version > highestVersion)) { highestVersion = version; } } } if (highestVersion == null) { return null; } return '10.$highestVersion'; } /// The names of the components within the workload that must be installed. /// /// The descriptions of some components differ from version to version. When /// a supported version is present, the descriptions used will be for that /// version. List<String> necessaryComponentDescriptions() { return _requiredComponents().values.toList(); } /// The consumer-facing version name of the minimum supported version. /// /// E.g., for Visual Studio 2019 this returns "2019" rather than "16". String get minimumVersionDescription { return '2019'; } /// The path to CMake, or null if no Visual Studio installation has /// the components necessary to build. String? get cmakePath { final VswhereDetails? details = _bestVisualStudioDetails; if (details == null || !details.isUsable || details.installationPath == null) { return null; } return _fileSystem.path.joinAll(<String>[ details.installationPath!, 'Common7', 'IDE', 'CommonExtensions', 'Microsoft', 'CMake', 'CMake', 'bin', 'cmake.exe', ]); } /// The generator string to pass to CMake to select this Visual Studio /// version. String? get cmakeGenerator { // From https://cmake.org/cmake/help/v3.22/manual/cmake-generators.7.html#visual-studio-generators switch (_majorVersion) { case 17: return 'Visual Studio 17 2022'; case 16: default: return 'Visual Studio 16 2019'; } } /// The path to cl.exe, or null if no Visual Studio installation has /// the components necessary to build. String? get clPath { return _getMsvcBinPath('cl.exe'); } /// The path to lib.exe, or null if no Visual Studio installation has /// the components necessary to build. String? get libPath { return _getMsvcBinPath('lib.exe'); } /// The path to link.exe, or null if no Visual Studio installation has /// the components necessary to build. String? get linkPath { return _getMsvcBinPath('link.exe'); } String? _getMsvcBinPath(String executable) { final VswhereDetails? details = _bestVisualStudioDetails; if (details == null || !details.isUsable || details.installationPath == null || details.msvcVersion == null) { return null; } final String arch = _osUtils.hostPlatform == HostPlatform.windows_arm64 ? 'arm64': 'x64'; return _fileSystem.path.joinAll(<String>[ details.installationPath!, 'VC', 'Tools', 'MSVC', details.msvcVersion!, 'bin', 'Host$arch', arch, executable, ]); } /// The path to vcvars64.exe, or null if no Visual Studio installation has /// the components necessary to build. String? get vcvarsPath { final VswhereDetails? details = _bestVisualStudioDetails; if (details == null || !details.isUsable || details.installationPath == null) { return null; } final String arch = _osUtils.hostPlatform == HostPlatform.windows_arm64 ? 'arm64': '64'; return _fileSystem.path.joinAll(<String>[ details.installationPath!, 'VC', 'Auxiliary', 'Build', 'vcvars$arch.bat', ]); } /// The major version of the Visual Studio install, as an integer. int? get _majorVersion => fullVersion != null ? int.tryParse(fullVersion!.split('.')[0]) : null; /// The path to vswhere.exe. /// /// vswhere should be installed for VS 2017 Update 2 and later; if it's not /// present then there isn't a new enough installation of VS. This path is /// not user-controllable, unlike the install location of Visual Studio /// itself. String get _vswherePath { const String programFilesEnv = 'PROGRAMFILES(X86)'; if (!_platform.environment.containsKey(programFilesEnv)) { throwToolExit('%$programFilesEnv% environment variable not found.'); } return _fileSystem.path.join( _platform.environment[programFilesEnv]!, 'Microsoft Visual Studio', 'Installer', 'vswhere.exe', ); } /// Workload ID for use with vswhere requirements. /// /// Workload ID is different between Visual Studio IDE and Build Tools. /// See https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids static const List<String> _requiredWorkloads = <String>[ 'Microsoft.VisualStudio.Workload.NativeDesktop', 'Microsoft.VisualStudio.Workload.VCTools', ]; /// Components for use with vswhere requirements. /// /// Maps from component IDs to description in the installer UI. /// See https://docs.microsoft.com/en-us/visualstudio/install/workload-and-component-ids Map<String, String> _requiredComponents([int? majorVersion]) { // The description of the C++ toolchain required by the template. The // component name is significantly different in different versions. // When a new major version of VS is supported, its toolchain description // should be added below. It should also be made the default, so that when // there is no installation, the message shows the string that will be // relevant for the most likely fresh install case). String cppToolchainDescription; switch (majorVersion ?? _majorVersion) { case 16: default: cppToolchainDescription = 'MSVC v142 - VS 2019 C++ x64/x86 build tools'; } // The 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64' ID is assigned to the latest // release of the toolchain, and there can be minor updates within a given version of // Visual Studio. Since it changes over time, listing a precise version would become // wrong after each VC++ toolchain update, so just instruct people to install the // latest version. cppToolchainDescription += '\n - If there are multiple build tool versions available, install the latest'; // Things which are required by the workload (e.g., MSBuild) don't need to // be included here. return <String, String>{ // The C++ toolchain required by the template. 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64': cppToolchainDescription, // CMake 'Microsoft.VisualStudio.Component.VC.CMake.Project': 'C++ CMake tools for Windows', }; } /// The minimum supported major version. static const int _minimumSupportedVersion = 16; // '16' is VS 2019. /// vswhere argument to specify the minimum version. static const String _vswhereMinVersionArgument = '-version'; /// vswhere argument to allow prerelease versions. static const String _vswherePrereleaseArgument = '-prerelease'; /// The registry path for Windows 10 SDK installation details. static const String _windows10SdkRegistryPath = r'HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs\Windows\v10.0'; /// The registry key in _windows10SdkRegistryPath for the folder where the /// SDKs are installed. static const String _windows10SdkRegistryKey = 'InstallationFolder'; /// Returns the details of the newest version of Visual Studio. /// /// If [validateRequirements] is set, the search will be limited to versions /// that have all of the required workloads and components. VswhereDetails? _visualStudioDetails({ bool validateRequirements = false, List<String>? additionalArguments, String? requiredWorkload }) { final List<String> requirementArguments = validateRequirements ? <String>[ if (requiredWorkload != null) ...<String>[ '-requires', requiredWorkload, ], ..._requiredComponents(_minimumSupportedVersion).keys, ] : <String>[]; try { final List<String> defaultArguments = <String>[ '-format', 'json', '-products', '*', '-utf8', '-latest', ]; // Ignore replacement characters as vswhere.exe is known to output them. // See: https://github.com/flutter/flutter/issues/102451 const Encoding encoding = Utf8Codec(reportErrors: false); final RunResult whereResult = _processUtils.runSync(<String>[ _vswherePath, ...defaultArguments, ...?additionalArguments, ...requirementArguments, ], encoding: encoding); if (whereResult.exitCode == 0) { final List<Map<String, dynamic>>? installations = _tryDecodeVswhereJson(whereResult.stdout); if (installations != null && installations.isNotEmpty) { final String? msvcVersion = _findMsvcVersion(installations); return VswhereDetails.fromJson( validateRequirements, installations[0], msvcVersion, ); } } } on ArgumentError { // Thrown if vswhere doesn't exist; ignore and return null below. } on ProcessException { // Ignored, return null below. } return null; } String? _findMsvcVersion(List<Map<String, dynamic>> installations) { final String? installationPath = installations[0]['installationPath'] as String?; String? msvcVersion; if (installationPath != null) { final Directory installationDir = _fileSystem.directory(installationPath); final Directory msvcDir = installationDir .childDirectory('VC') .childDirectory('Tools') .childDirectory('MSVC'); if (msvcDir.existsSync()) { final Iterable<Directory> msvcVersionDirs = msvcDir.listSync().whereType<Directory>(); if (msvcVersionDirs.isEmpty) { return null; } msvcVersion = msvcVersionDirs.last.uri.pathSegments .where((String e) => e.isNotEmpty) .last; } } return msvcVersion; } List<Map<String, dynamic>>? _tryDecodeVswhereJson(String vswhereJson) { List<dynamic>? result; FormatException? originalError; try { // Some versions of vswhere.exe are known to encode their output incorrectly, // resulting in invalid JSON in the 'description' property when interpreted // as UTF-8. First, try to decode without any pre-processing. try { result = json.decode(vswhereJson) as List<dynamic>; } on FormatException catch (error) { // If that fails, remove the 'description' property and try again. // See: https://github.com/flutter/flutter/issues/106601 vswhereJson = vswhereJson.replaceFirst(_vswhereDescriptionProperty, ''); _logger.printTrace('Failed to decode vswhere.exe JSON output. $error' 'Retrying after removing the unused description property:\n$vswhereJson'); originalError = error; result = json.decode(vswhereJson) as List<dynamic>; } } on FormatException { // Removing the description property didn't help. // Report the original decoding error on the unprocessed JSON. _logger.printWarning('Warning: Unexpected vswhere.exe JSON output. $originalError' 'To see the full JSON, run flutter doctor -vv.'); return null; } return result.cast<Map<String, dynamic>>(); } /// Returns the details of the best available version of Visual Studio. /// /// If there's a version that has all the required components, that /// will be returned, otherwise returns the latest installed version regardless /// of components and version, or null if no such installation is found. late final VswhereDetails? _bestVisualStudioDetails = () { // First, attempt to find the latest version of Visual Studio that satisfies // both the minimum supported version and the required workloads. // Check in the order of stable VS, stable BT, pre-release VS, pre-release BT. final List<String> minimumVersionArguments = <String>[ _vswhereMinVersionArgument, _minimumSupportedVersion.toString(), ]; for (final bool checkForPrerelease in <bool>[false, true]) { for (final String requiredWorkload in _requiredWorkloads) { final VswhereDetails? result = _visualStudioDetails( validateRequirements: true, additionalArguments: checkForPrerelease ? <String>[...minimumVersionArguments, _vswherePrereleaseArgument] : minimumVersionArguments, requiredWorkload: requiredWorkload); if (result != null) { return result; } } } // An installation that satisfies requirements could not be found. // Fallback to the latest Visual Studio installation. return _visualStudioDetails( additionalArguments: <String>[_vswherePrereleaseArgument, '-all']); }(); /// Returns the installation location of the Windows 10 SDKs, or null if the /// registry doesn't contain that information. String? _getWindows10SdkLocation() { try { final RunResult result = _processUtils.runSync(<String>[ 'reg', 'query', _windows10SdkRegistryPath, '/v', _windows10SdkRegistryKey, ]); if (result.exitCode == 0) { final RegExp pattern = RegExp(r'InstallationFolder\s+REG_SZ\s+(.+)'); final RegExpMatch? match = pattern.firstMatch(result.stdout); if (match != null) { return match.group(1)!.trim(); } } } on ArgumentError { // Thrown if reg somehow doesn't exist; ignore and return null below. } on ProcessException { // Ignored, return null below. } return null; } /// Returns the highest-numbered SDK version in [dir], which should be the /// Windows 10 SDK installation directory. /// /// Returns null if no Windows 10 SDKs are found. String? findHighestVersionInSdkDirectory(Directory dir) { // This contains subfolders that are named by the SDK version. final Directory includeDir = dir.childDirectory('Includes'); if (!includeDir.existsSync()) { return null; } Version? highestVersion; for (final FileSystemEntity versionEntry in includeDir.listSync()) { if (!versionEntry.basename.startsWith('10.')) { continue; } // Version only handles 3 components; strip off the '10.' to leave three // components, since they all start with that. final Version? version = Version.parse(versionEntry.basename.substring(3)); if (highestVersion == null || (version != null && version > highestVersion)) { highestVersion = version; } } // Re-add the leading '10.' that was removed for comparison. return highestVersion == null ? null : '10.$highestVersion'; } } /// The details of a Visual Studio installation according to vswhere. @visibleForTesting class VswhereDetails { const VswhereDetails({ required this.meetsRequirements, required this.installationPath, required this.displayName, required this.fullVersion, required this.isComplete, required this.isLaunchable, required this.isRebootRequired, required this.isPrerelease, required this.catalogDisplayVersion, required this.msvcVersion, }); /// Create a `VswhereDetails` from the JSON output of vswhere.exe. factory VswhereDetails.fromJson( bool meetsRequirements, Map<String, dynamic> details, String? msvcVersion, ) { final Map<String, dynamic>? catalog = details['catalog'] as Map<String, dynamic>?; return VswhereDetails( meetsRequirements: meetsRequirements, isComplete: details['isComplete'] as bool?, isLaunchable: details['isLaunchable'] as bool?, isRebootRequired: details['isRebootRequired'] as bool?, isPrerelease: details['isPrerelease'] as bool?, // Below are strings that must be well-formed without replacement characters. installationPath: _validateString(details['installationPath'] as String?), fullVersion: _validateString(details['installationVersion'] as String?), // Below are strings that are used only for display purposes and are allowed to // contain replacement characters. displayName: details['displayName'] as String?, catalogDisplayVersion: catalog == null ? null : catalog['productDisplayVersion'] as String?, msvcVersion: msvcVersion, ); } /// Verify JSON strings from vswhere.exe output are valid. /// /// The output of vswhere.exe is known to output replacement characters. /// Use this to ensure values that must be well-formed are valid. Strings that /// are only used for display purposes should skip this check. /// See: https://github.com/flutter/flutter/issues/102451 static String? _validateString(String? value) { if (value != null && value.contains('\u{FFFD}')) { throwToolExit( 'Bad UTF-8 encoding (U+FFFD; REPLACEMENT CHARACTER) found in string: $value. ' 'The Flutter team would greatly appreciate if you could file a bug explaining ' 'exactly what you were doing when this happened:\n' 'https://github.com/flutter/flutter/issues/new/choose\n'); } return value; } /// Whether the installation satisfies the required workloads and minimum version. final bool meetsRequirements; /// The root directory of the Visual Studio installation. final String? installationPath; /// The user-friendly name of the installation. final String? displayName; /// The complete version. final String? fullVersion; /// Keys for the status of the installation. final bool? isComplete; final bool? isLaunchable; final bool? isRebootRequired; /// The key for a pre-release version. final bool? isPrerelease; /// The user-friendly version. final String? catalogDisplayVersion; /// The MSVC versions. final String? msvcVersion; /// Checks if the Visual Studio installation can be used by Flutter. /// /// Returns false if the installation has issues the user must resolve. /// This may return true even if required information is missing as older /// versions of Visual Studio might not include them. bool get isUsable { if (!meetsRequirements) { return false; } if (!(isComplete ?? true)) { return false; } if (!(isLaunchable ?? true)) { return false; } if (isRebootRequired ?? false) { return false; } return true; } }
flutter/packages/flutter_tools/lib/src/windows/visual_studio.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/windows/visual_studio.dart", "repo_id": "flutter", "token_count": 7653 }
815
<component name="libraryTable"> <library name="Dart SDK"> <CLASSES> <root url="file://{{{dartSdk}}}/lib/async" /> <root url="file://{{{dartSdk}}}/lib/collection" /> <root url="file://{{{dartSdk}}}/lib/convert" /> <root url="file://{{{dartSdk}}}/lib/core" /> <root url="file://{{{dartSdk}}}/lib/developer" /> <root url="file://{{{dartSdk}}}/lib/html" /> <root url="file://{{{dartSdk}}}/lib/io" /> <root url="file://{{{dartSdk}}}/lib/isolate" /> <root url="file://{{{dartSdk}}}/lib/math" /> <root url="file://{{{dartSdk}}}/lib/mirrors" /> <root url="file://{{{dartSdk}}}/lib/typed_data" /> </CLASSES> <JAVADOC /> <SOURCES /> </library> </component>
flutter/packages/flutter_tools/templates/app_shared/.idea/libraries/Dart_SDK.xml.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/app_shared/.idea/libraries/Dart_SDK.xml.tmpl", "repo_id": "flutter", "token_count": 345 }
816
package {{androidIdentifier}}.host; import io.flutter.embedding.android.FlutterActivity; public class MainActivity extends FlutterActivity { }
flutter/packages/flutter_tools/templates/module/android/host_app_common/app.tmpl/src/main/java/androidIdentifier/host/MainActivity.java.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/module/android/host_app_common/app.tmpl/src/main/java/androidIdentifier/host/MainActivity.java.tmpl", "repo_id": "flutter", "token_count": 40 }
817
# {{projectName}} {{description}} ## Getting Started For help getting started with Flutter development, view the online [documentation](https://flutter.dev/). For instructions integrating Flutter modules to your existing applications, see the [add-to-app documentation](https://flutter.dev/docs/development/add-to-app).
flutter/packages/flutter_tools/templates/module/common/README.md.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/templates/module/common/README.md.tmpl", "repo_id": "flutter", "token_count": 84 }
818
#import "AppDelegate.h" #import "FlutterPluginRegistrant/GeneratedPluginRegistrant.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GeneratedPluginRegistrant registerWithRegistry:self]; return [super application:application didFinishLaunchingWithOptions:launchOptions]; } @end
flutter/packages/flutter_tools/templates/module/ios/host_app_ephemeral_cocoapods/Runner.tmpl/AppDelegate.m/0
{ "file_path": "flutter/packages/flutter_tools/templates/module/ios/host_app_ephemeral_cocoapods/Runner.tmpl/AppDelegate.m", "repo_id": "flutter", "token_count": 111 }
819