text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { const DatePickerThemeData datePickerTheme = DatePickerThemeData( backgroundColor: Color(0xfffffff0), elevation: 6, shadowColor: Color(0xfffffff1), surfaceTintColor: Color(0xfffffff2), shape: RoundedRectangleBorder(), headerBackgroundColor: Color(0xfffffff3), headerForegroundColor: Color(0xfffffff4), headerHeadlineStyle: TextStyle(fontSize: 10), headerHelpStyle: TextStyle(fontSize: 11), weekdayStyle: TextStyle(fontSize: 12), dayStyle: TextStyle(fontSize: 13), dayForegroundColor: MaterialStatePropertyAll<Color>(Color(0xfffffff5)), dayBackgroundColor: MaterialStatePropertyAll<Color>(Color(0xfffffff6)), dayOverlayColor: MaterialStatePropertyAll<Color>(Color(0xfffffff7)), dayShape: MaterialStatePropertyAll<OutlinedBorder>(RoundedRectangleBorder()), todayForegroundColor: MaterialStatePropertyAll<Color>(Color(0xfffffff8)), todayBackgroundColor: MaterialStatePropertyAll<Color>(Color(0xfffffff9)), todayBorder: BorderSide(width: 3), yearStyle: TextStyle(fontSize: 13), yearForegroundColor: MaterialStatePropertyAll<Color>(Color(0xfffffffa)), yearBackgroundColor: MaterialStatePropertyAll<Color>(Color(0xfffffffb)), yearOverlayColor: MaterialStatePropertyAll<Color>(Color(0xfffffffc)), rangePickerBackgroundColor: Color(0xfffffffd), rangePickerElevation: 7, rangePickerShadowColor: Color(0xfffffffe), rangePickerSurfaceTintColor: Color(0xffffffff), rangePickerShape: RoundedRectangleBorder(), rangePickerHeaderBackgroundColor: Color(0xffffff0f), rangePickerHeaderForegroundColor: Color(0xffffff1f), rangePickerHeaderHeadlineStyle: TextStyle(fontSize: 14), rangePickerHeaderHelpStyle: TextStyle(fontSize: 15), rangeSelectionBackgroundColor: Color(0xffffff2f), rangeSelectionOverlayColor: MaterialStatePropertyAll<Color>(Color(0xffffff3f)), dividerColor: Color(0xffffff4f), inputDecorationTheme: InputDecorationTheme( fillColor: Color(0xffffff5f), border: UnderlineInputBorder(), ), cancelButtonStyle: ButtonStyle(foregroundColor: MaterialStatePropertyAll<Color>(Color(0xffffff6f))), confirmButtonStyle: ButtonStyle(foregroundColor: MaterialStatePropertyAll<Color>(Color(0xffffff7f))), ); Material findDialogMaterial(WidgetTester tester) { return tester.widget<Material>( find.descendant( of: find.byType(Dialog), matching: find.byType(Material) ).first ); } Material findHeaderMaterial(WidgetTester tester, String text) { return tester.widget<Material>( find.ancestor( of: find.text(text), matching: find.byType(Material) ).first, ); } BoxDecoration? findTextDecoration(WidgetTester tester, String date) { final Container container = tester.widget<Container>( find.ancestor( of: find.text(date), matching: find.byType(Container) ).first, ); return container.decoration as BoxDecoration?; } ShapeDecoration? findDayDecoration(WidgetTester tester, String day) { return tester.widget<DecoratedBox>( find.ancestor( of: find.text(day), matching: find.byType(DecoratedBox) ), ).decoration as ShapeDecoration?; } ButtonStyle actionButtonStyle(WidgetTester tester, String text) { return tester.widget<TextButton>(find.widgetWithText(TextButton, text)).style!; } const Size wideWindowSize = Size(1920.0, 1080.0); const Size narrowWindowSize = Size(1070.0, 1770.0); test('DatePickerThemeData copyWith, ==, hashCode basics', () { expect(const DatePickerThemeData(), const DatePickerThemeData().copyWith()); expect(const DatePickerThemeData().hashCode, const DatePickerThemeData().copyWith().hashCode); }); test('DatePickerThemeData lerp special cases', () { const DatePickerThemeData data = DatePickerThemeData(); expect(identical(DatePickerThemeData.lerp(data, data, 0.5), data), true); }); test('DatePickerThemeData defaults', () { const DatePickerThemeData theme = DatePickerThemeData(); expect(theme.backgroundColor, null); expect(theme.elevation, null); expect(theme.shadowColor, null); expect(theme.surfaceTintColor, null); expect(theme.shape, null); expect(theme.headerBackgroundColor, null); expect(theme.headerForegroundColor, null); expect(theme.headerHeadlineStyle, null); expect(theme.headerHelpStyle, null); expect(theme.weekdayStyle, null); expect(theme.dayStyle, null); expect(theme.dayForegroundColor, null); expect(theme.dayBackgroundColor, null); expect(theme.dayOverlayColor, null); expect(theme.dayShape, null); expect(theme.todayForegroundColor, null); expect(theme.todayBackgroundColor, null); expect(theme.todayBorder, null); expect(theme.yearStyle, null); expect(theme.yearForegroundColor, null); expect(theme.yearBackgroundColor, null); expect(theme.yearOverlayColor, null); expect(theme.rangePickerBackgroundColor, null); expect(theme.rangePickerElevation, null); expect(theme.rangePickerShadowColor, null); expect(theme.rangePickerSurfaceTintColor, null); expect(theme.rangePickerShape, null); expect(theme.rangePickerHeaderBackgroundColor, null); expect(theme.rangePickerHeaderForegroundColor, null); expect(theme.rangePickerHeaderHeadlineStyle, null); expect(theme.rangePickerHeaderHelpStyle, null); expect(theme.rangeSelectionBackgroundColor, null); expect(theme.rangeSelectionOverlayColor, null); expect(theme.dividerColor, null); expect(theme.inputDecorationTheme, null); expect(theme.cancelButtonStyle, null); expect(theme.confirmButtonStyle, null); }); testWidgets('DatePickerTheme.defaults M3 defaults', (WidgetTester tester) async { late final DatePickerThemeData m3; // M3 Defaults late final ThemeData theme; late final ColorScheme colorScheme; late final TextTheme textTheme; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), home: Builder( builder: (BuildContext context) { m3 = DatePickerTheme.defaults(context); theme = Theme.of(context); colorScheme = theme.colorScheme; textTheme = theme.textTheme; return Container(); }, ), ), ); expect(m3.backgroundColor, colorScheme.surfaceContainerHigh); expect(m3.elevation, 6); expect(m3.shadowColor, const Color(0x00000000)); // Colors.transparent expect(m3.surfaceTintColor, Colors.transparent); expect(m3.shape, RoundedRectangleBorder(borderRadius: BorderRadius.circular(28))); expect(m3.headerBackgroundColor, const Color(0x00000000)); // Colors.transparent expect(m3.headerForegroundColor, colorScheme.onSurfaceVariant); expect(m3.headerHeadlineStyle, textTheme.headlineLarge); expect(m3.headerHelpStyle, textTheme.labelLarge); expect(m3.weekdayStyle, textTheme.bodyLarge?.apply(color: colorScheme.onSurface)); expect(m3.dayStyle, textTheme.bodyLarge); expect(m3.dayForegroundColor?.resolve(<MaterialState>{}), colorScheme.onSurface); expect(m3.dayForegroundColor?.resolve(<MaterialState>{MaterialState.selected}), colorScheme.onPrimary); expect(m3.dayForegroundColor?.resolve(<MaterialState>{MaterialState.disabled}), colorScheme.onSurface.withOpacity(0.38)); expect(m3.dayBackgroundColor?.resolve(<MaterialState>{}), null); expect(m3.dayBackgroundColor?.resolve(<MaterialState>{MaterialState.selected}), colorScheme.primary); expect(m3.dayOverlayColor?.resolve(<MaterialState>{}), null); expect(m3.dayOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.hovered}), colorScheme.onPrimary.withOpacity(0.08)); expect(m3.dayOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.focused}), colorScheme.onPrimary.withOpacity(0.1)); expect(m3.dayOverlayColor?.resolve(<MaterialState>{MaterialState.hovered}), colorScheme.onSurfaceVariant.withOpacity(0.08)); expect(m3.dayOverlayColor?.resolve(<MaterialState>{MaterialState.focused}), colorScheme.onSurfaceVariant.withOpacity(0.1)); expect(m3.dayOverlayColor?.resolve(<MaterialState>{MaterialState.pressed}), colorScheme.onSurfaceVariant.withOpacity(0.1)); expect(m3.dayOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.hovered, MaterialState.focused}), colorScheme.onPrimary.withOpacity(0.08)); expect(m3.dayOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.hovered, MaterialState.pressed}), colorScheme.onPrimary.withOpacity(0.1)); expect(m3.dayOverlayColor?.resolve(<MaterialState>{MaterialState.hovered, MaterialState.focused}), colorScheme.onSurfaceVariant.withOpacity(0.08)); expect(m3.dayOverlayColor?.resolve(<MaterialState>{MaterialState.hovered, MaterialState.pressed}), colorScheme.onSurfaceVariant.withOpacity(0.1)); expect(m3.dayShape?.resolve(<MaterialState>{}), const CircleBorder()); expect(m3.todayForegroundColor?.resolve(<MaterialState>{}), colorScheme.primary); expect(m3.todayForegroundColor?.resolve(<MaterialState>{MaterialState.disabled}), colorScheme.primary.withOpacity(0.38)); expect(m3.todayBorder, BorderSide(color: colorScheme.primary)); expect(m3.yearStyle, textTheme.bodyLarge); expect(m3.yearForegroundColor?.resolve(<MaterialState>{}), colorScheme.onSurfaceVariant); expect(m3.yearForegroundColor?.resolve(<MaterialState>{MaterialState.selected}), colorScheme.onPrimary); expect(m3.yearForegroundColor?.resolve(<MaterialState>{MaterialState.disabled}), colorScheme.onSurfaceVariant.withOpacity(0.38)); expect(m3.yearBackgroundColor?.resolve(<MaterialState>{}), null); expect(m3.yearBackgroundColor?.resolve(<MaterialState>{MaterialState.selected}), colorScheme.primary); expect(m3.yearOverlayColor?.resolve(<MaterialState>{}), null); expect(m3.yearOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.hovered}), colorScheme.onPrimary.withOpacity(0.08)); expect(m3.yearOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.focused}), colorScheme.onPrimary.withOpacity(0.1)); expect(m3.yearOverlayColor?.resolve(<MaterialState>{MaterialState.hovered}), colorScheme.onSurfaceVariant.withOpacity(0.08)); expect(m3.yearOverlayColor?.resolve(<MaterialState>{MaterialState.focused}), colorScheme.onSurfaceVariant.withOpacity(0.1)); expect(m3.yearOverlayColor?.resolve(<MaterialState>{MaterialState.pressed}), colorScheme.onSurfaceVariant.withOpacity(0.1)); expect(m3.rangePickerElevation, 0); expect(m3.rangePickerShape, const RoundedRectangleBorder()); expect(m3.rangePickerShadowColor, Colors.transparent); expect(m3.rangePickerSurfaceTintColor, Colors.transparent); expect(m3.rangeSelectionOverlayColor?.resolve(<MaterialState>{}), null); expect(m3.rangePickerHeaderBackgroundColor, Colors.transparent); expect(m3.rangePickerHeaderForegroundColor, colorScheme.onSurfaceVariant); expect(m3.rangePickerHeaderHeadlineStyle, textTheme.titleLarge); expect(m3.rangePickerHeaderHelpStyle, textTheme.titleSmall); expect(m3.dividerColor, null); expect(m3.inputDecorationTheme, null); expect(m3.cancelButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString())); expect(m3.confirmButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString())); }); testWidgets('DatePickerTheme.defaults M2 defaults', (WidgetTester tester) async { late final DatePickerThemeData m2; // M2 defaults late final ThemeData theme; late final ColorScheme colorScheme; late final TextTheme textTheme; await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Builder( builder: (BuildContext context) { m2 = DatePickerTheme.defaults(context); theme = Theme.of(context); colorScheme = theme.colorScheme; textTheme = theme.textTheme; return Container(); }, ), ), ); expect(m2.elevation, 24); expect(m2.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)))); expect(m2.headerBackgroundColor, colorScheme.primary); expect(m2.headerForegroundColor, colorScheme.onPrimary); expect(m2.headerHeadlineStyle, textTheme.headlineSmall); expect(m2.headerHelpStyle, textTheme.labelSmall); expect(m2.weekdayStyle, textTheme.bodySmall?.apply(color: colorScheme.onSurface.withOpacity(0.60))); expect(m2.dayStyle, textTheme.bodySmall); expect(m2.dayForegroundColor?.resolve(<MaterialState>{}), colorScheme.onSurface); expect(m2.dayForegroundColor?.resolve(<MaterialState>{MaterialState.selected}), colorScheme.onPrimary); expect(m2.dayForegroundColor?.resolve(<MaterialState>{MaterialState.disabled}), colorScheme.onSurface.withOpacity(0.38)); expect(m2.dayBackgroundColor?.resolve(<MaterialState>{}), null); expect(m2.dayBackgroundColor?.resolve(<MaterialState>{MaterialState.selected}), colorScheme.primary); expect(m2.dayOverlayColor?.resolve(<MaterialState>{}), null); expect(m2.dayOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.hovered}), colorScheme.onPrimary.withOpacity(0.08)); expect(m2.dayOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.focused}), colorScheme.onPrimary.withOpacity(0.12)); expect(m2.dayOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.pressed}), colorScheme.onPrimary.withOpacity(0.38)); expect(m2.dayOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.hovered, MaterialState.focused}), colorScheme.onPrimary.withOpacity(0.08)); expect(m2.dayOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.hovered, MaterialState.pressed}), colorScheme.onPrimary.withOpacity(0.38)); expect(m2.dayOverlayColor?.resolve(<MaterialState>{MaterialState.hovered}), colorScheme.onSurfaceVariant.withOpacity(0.08)); expect(m2.dayOverlayColor?.resolve(<MaterialState>{MaterialState.focused}), colorScheme.onSurfaceVariant.withOpacity(0.12)); expect(m2.dayOverlayColor?.resolve(<MaterialState>{MaterialState.pressed}), colorScheme.onSurfaceVariant.withOpacity(0.12)); expect(m2.dayShape?.resolve(<MaterialState>{}), const CircleBorder()); expect(m2.todayForegroundColor?.resolve(<MaterialState>{}), colorScheme.primary); expect(m2.todayForegroundColor?.resolve(<MaterialState>{MaterialState.disabled}), colorScheme.onSurface.withOpacity(0.38)); expect(m2.todayBorder, BorderSide(color: colorScheme.primary)); expect(m2.yearStyle, textTheme.bodyLarge); expect(m2.rangePickerBackgroundColor, colorScheme.surface); expect(m2.rangePickerElevation, 0); expect(m2.rangePickerShape, const RoundedRectangleBorder()); expect(m2.rangePickerShadowColor, Colors.transparent); expect(m2.rangePickerSurfaceTintColor, Colors.transparent); expect(m2.rangeSelectionOverlayColor?.resolve(<MaterialState>{}), null); expect(m2.rangeSelectionOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.hovered}), colorScheme.onPrimary.withOpacity(0.08)); expect(m2.rangeSelectionOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.focused}), colorScheme.onPrimary.withOpacity(0.12)); expect(m2.rangeSelectionOverlayColor?.resolve(<MaterialState>{MaterialState.selected, MaterialState.pressed}), colorScheme.onPrimary.withOpacity(0.38)); expect(m2.rangeSelectionOverlayColor?.resolve(<MaterialState>{MaterialState.hovered}), colorScheme.onSurfaceVariant.withOpacity(0.08)); expect(m2.rangeSelectionOverlayColor?.resolve(<MaterialState>{MaterialState.focused}), colorScheme.onSurfaceVariant.withOpacity(0.12)); expect(m2.rangeSelectionOverlayColor?.resolve(<MaterialState>{MaterialState.pressed}), colorScheme.onSurfaceVariant.withOpacity(0.12)); expect(m2.rangePickerHeaderBackgroundColor, colorScheme.primary); expect(m2.rangePickerHeaderForegroundColor, colorScheme.onPrimary); expect(m2.rangePickerHeaderHeadlineStyle, textTheme.headlineSmall); expect(m2.rangePickerHeaderHelpStyle, textTheme.labelSmall); expect(m2.dividerColor, null); expect(m2.inputDecorationTheme, null); expect(m2.cancelButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString())); expect(m2.confirmButtonStyle.toString(), equalsIgnoringHashCodes(TextButton.styleFrom().toString())); }); testWidgets('Default DatePickerThemeData debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const DatePickerThemeData().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('DatePickerThemeData implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); datePickerTheme.debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, equalsIgnoringHashCodes(<String>[ 'backgroundColor: Color(0xfffffff0)', 'elevation: 6.0', 'shadowColor: Color(0xfffffff1)', 'surfaceTintColor: Color(0xfffffff2)', 'shape: RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.zero)', 'headerBackgroundColor: Color(0xfffffff3)', 'headerForegroundColor: Color(0xfffffff4)', 'headerHeadlineStyle: TextStyle(inherit: true, size: 10.0)', 'headerHelpStyle: TextStyle(inherit: true, size: 11.0)', 'weekDayStyle: TextStyle(inherit: true, size: 12.0)', 'dayStyle: TextStyle(inherit: true, size: 13.0)', 'dayForegroundColor: WidgetStatePropertyAll(Color(0xfffffff5))', 'dayBackgroundColor: WidgetStatePropertyAll(Color(0xfffffff6))', 'dayOverlayColor: WidgetStatePropertyAll(Color(0xfffffff7))', 'dayShape: WidgetStatePropertyAll(RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.zero))', 'todayForegroundColor: WidgetStatePropertyAll(Color(0xfffffff8))', 'todayBackgroundColor: WidgetStatePropertyAll(Color(0xfffffff9))', 'todayBorder: BorderSide(width: 3.0)', 'yearStyle: TextStyle(inherit: true, size: 13.0)', 'yearForegroundColor: WidgetStatePropertyAll(Color(0xfffffffa))', 'yearBackgroundColor: WidgetStatePropertyAll(Color(0xfffffffb))', 'yearOverlayColor: WidgetStatePropertyAll(Color(0xfffffffc))', 'rangePickerBackgroundColor: Color(0xfffffffd)', 'rangePickerElevation: 7.0', 'rangePickerShadowColor: Color(0xfffffffe)', 'rangePickerSurfaceTintColor: Color(0xffffffff)', 'rangePickerShape: RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.zero)', 'rangePickerHeaderBackgroundColor: Color(0xffffff0f)', 'rangePickerHeaderForegroundColor: Color(0xffffff1f)', 'rangePickerHeaderHeadlineStyle: TextStyle(inherit: true, size: 14.0)', 'rangePickerHeaderHelpStyle: TextStyle(inherit: true, size: 15.0)', 'rangeSelectionBackgroundColor: Color(0xffffff2f)', 'rangeSelectionOverlayColor: WidgetStatePropertyAll(Color(0xffffff3f))', 'dividerColor: Color(0xffffff4f)', 'inputDecorationTheme: InputDecorationTheme#00000(fillColor: Color(0xffffff5f), border: UnderlineInputBorder())', 'cancelButtonStyle: ButtonStyle#00000(foregroundColor: WidgetStatePropertyAll(Color(0xffffff6f)))', 'confirmButtonStyle: ButtonStyle#00000(foregroundColor: WidgetStatePropertyAll(Color(0xffffff7f)))' ])); }); testWidgets('DatePickerDialog uses ThemeData datePicker theme (calendar mode)', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData( datePickerTheme: datePickerTheme, useMaterial3: true, ), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: DatePickerDialog( initialDate: DateTime(2023, DateTime.january, 25), firstDate: DateTime(2022), lastDate: DateTime(2024, DateTime.december, 31), currentDate: DateTime(2023, DateTime.january, 24), ), ), ), ), ), ); final Material material = findDialogMaterial(tester); expect(material.color, datePickerTheme.backgroundColor); expect(material.elevation, datePickerTheme.elevation); expect(material.shadowColor, datePickerTheme.shadowColor); expect(material.surfaceTintColor, datePickerTheme.surfaceTintColor); expect(material.shape, datePickerTheme.shape); final Text selectDate = tester.widget<Text>(find.text('Select date')); final Material headerMaterial = findHeaderMaterial(tester, 'Select date'); expect(selectDate.style?.color, datePickerTheme.headerForegroundColor); expect(selectDate.style?.fontSize, datePickerTheme.headerHelpStyle?.fontSize); expect(headerMaterial.color, datePickerTheme.headerBackgroundColor); final Text weekday = tester.widget<Text>(find.text('W')); expect(weekday.style?.color, datePickerTheme.weekdayStyle?.color); expect(weekday.style?.fontSize, datePickerTheme.weekdayStyle?.fontSize); final Text selectedDate = tester.widget<Text>(find.text('Wed, Jan 25')); expect(selectedDate.style?.color, datePickerTheme.headerForegroundColor); expect(selectedDate.style?.fontSize, datePickerTheme.headerHeadlineStyle?.fontSize); final Text day31 = tester.widget<Text>(find.text('31')); final ShapeDecoration day31Decoration = findDayDecoration(tester, '31')!; expect(day31.style?.color, datePickerTheme.dayForegroundColor?.resolve(<MaterialState>{})); expect(day31.style?.fontSize, datePickerTheme.dayStyle?.fontSize); expect(day31Decoration.color, datePickerTheme.dayBackgroundColor?.resolve(<MaterialState>{})); expect(day31Decoration.shape, datePickerTheme.dayShape?.resolve(<MaterialState>{})); final Text day24 = tester.widget<Text>(find.text('24')); // DatePickerDialog.currentDate final ShapeDecoration day24Decoration = findDayDecoration(tester, '24')!; final OutlinedBorder day24Shape = day24Decoration.shape as OutlinedBorder; expect(day24.style?.fontSize, datePickerTheme.dayStyle?.fontSize); expect(day24.style?.color, datePickerTheme.todayForegroundColor?.resolve(<MaterialState>{})); expect(day24Decoration.color, datePickerTheme.todayBackgroundColor?.resolve(<MaterialState>{})); expect( day24Decoration.shape, datePickerTheme.dayShape?.resolve(<MaterialState>{})! .copyWith(side: datePickerTheme.todayBorder?.copyWith(color: datePickerTheme.todayForegroundColor?.resolve(<MaterialState>{}))), ); expect(day24Shape.side.width, datePickerTheme.todayBorder?.width); // Test the day overlay color. final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.text('25'))); await tester.pumpAndSettle(); expect(inkFeatures, paints..circle(color: datePickerTheme.dayOverlayColor?.resolve(<MaterialState>{}))); // Show the year selector. await tester.tap(find.text('January 2023')); await tester.pumpAndSettle(); final Text year2022 = tester.widget<Text>(find.text('2022')); final BoxDecoration year2022Decoration = findTextDecoration(tester, '2022')!; expect(year2022.style?.fontSize, datePickerTheme.yearStyle?.fontSize); expect(year2022.style?.color, datePickerTheme.yearForegroundColor?.resolve(<MaterialState>{})); expect(year2022Decoration.color, datePickerTheme.yearBackgroundColor?.resolve(<MaterialState>{})); final Text year2023 = tester.widget<Text>(find.text('2023')); // DatePickerDialog.currentDate final BoxDecoration year2023Decoration = findTextDecoration(tester, '2023')!; expect(year2023.style?.fontSize, datePickerTheme.yearStyle?.fontSize); expect(year2023.style?.color, datePickerTheme.todayForegroundColor?.resolve(<MaterialState>{})); expect(year2023Decoration.color, datePickerTheme.todayBackgroundColor?.resolve(<MaterialState>{})); expect(year2023Decoration.border?.top.width, datePickerTheme.todayBorder?.width); expect(year2023Decoration.border?.bottom.width, datePickerTheme.todayBorder?.width); expect(year2023Decoration.border?.top.color, datePickerTheme.todayForegroundColor?.resolve(<MaterialState>{})); expect(year2023Decoration.border?.bottom.color, datePickerTheme.todayForegroundColor?.resolve(<MaterialState>{})); // Test the year overlay color. await gesture.moveTo(tester.getCenter(find.text('2024'))); await tester.pumpAndSettle(); expect(inkFeatures, paints..rect(color: datePickerTheme.yearOverlayColor?.resolve(<MaterialState>{}))); final ButtonStyle cancelButtonStyle = actionButtonStyle(tester, 'Cancel'); expect(cancelButtonStyle.toString(), equalsIgnoringHashCodes(datePickerTheme.cancelButtonStyle.toString())); final ButtonStyle confirmButtonStyle = actionButtonStyle(tester, 'OK'); expect(confirmButtonStyle.toString(), equalsIgnoringHashCodes(datePickerTheme.confirmButtonStyle.toString())); }); testWidgets('DatePickerDialog uses ThemeData datePicker theme (input mode)', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData( datePickerTheme: datePickerTheme, useMaterial3: true, ), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: DatePickerDialog( initialEntryMode: DatePickerEntryMode.input, initialDate: DateTime(2023, DateTime.january, 25), firstDate: DateTime(2022), lastDate: DateTime(2024, DateTime.december, 31), currentDate: DateTime(2023, DateTime.january, 24), ), ), ), ), ), ); final Material material = findDialogMaterial(tester); expect(material.color, datePickerTheme.backgroundColor); expect(material.elevation, datePickerTheme.elevation); expect(material.shadowColor, datePickerTheme.shadowColor); expect(material.surfaceTintColor, datePickerTheme.surfaceTintColor); expect(material.shape, datePickerTheme.shape); final Text selectDate = tester.widget<Text>(find.text('Select date')); final Material headerMaterial = findHeaderMaterial(tester, 'Select date'); expect(selectDate.style?.color, datePickerTheme.headerForegroundColor); expect(selectDate.style?.fontSize, datePickerTheme.headerHelpStyle?.fontSize); expect(headerMaterial.color, datePickerTheme.headerBackgroundColor); final InputDecoration inputDecoration = tester.widget<TextField>(find.byType(TextField)).decoration!; expect(inputDecoration.fillColor, datePickerTheme.inputDecorationTheme?.fillColor); final ButtonStyle cancelButtonStyle = actionButtonStyle(tester, 'Cancel'); expect(cancelButtonStyle.toString(), equalsIgnoringHashCodes(datePickerTheme.cancelButtonStyle.toString())); final ButtonStyle confirmButtonStyle = actionButtonStyle(tester, 'OK'); expect(confirmButtonStyle.toString(), equalsIgnoringHashCodes(datePickerTheme.confirmButtonStyle.toString())); }); testWidgets('DateRangePickerDialog uses ThemeData datePicker theme', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData( datePickerTheme: datePickerTheme, useMaterial3: true, ), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: DateRangePickerDialog( firstDate: DateTime(2023), lastDate: DateTime(2023, DateTime.january, 31), initialDateRange: DateTimeRange( start: DateTime(2023, DateTime.january, 17), end: DateTime(2023, DateTime.january, 20), ), currentDate: DateTime(2023, DateTime.january, 23), ), ), ), ), ), ); final Material material = findDialogMaterial(tester); expect(material.color, datePickerTheme.backgroundColor); //!! expect(tester.widget<Scaffold>(find.byType(Scaffold)).backgroundColor, datePickerTheme.rangePickerBackgroundColor); expect(material.elevation, datePickerTheme.rangePickerElevation); expect(material.shadowColor, datePickerTheme.rangePickerShadowColor); expect(material.surfaceTintColor, datePickerTheme.rangePickerSurfaceTintColor); expect(material.shape, datePickerTheme.rangePickerShape); final AppBar appBar = tester.widget<AppBar>(find.byType(AppBar)); expect(appBar.backgroundColor, datePickerTheme.rangePickerHeaderBackgroundColor); final Text selectRange = tester.widget<Text>(find.text('Select range')); expect(selectRange.style?.color, datePickerTheme.rangePickerHeaderForegroundColor); expect(selectRange.style?.fontSize, datePickerTheme.rangePickerHeaderHelpStyle?.fontSize); final Text selectedDate = tester.widget<Text>(find.text('Jan 17')); expect(selectedDate.style?.color, datePickerTheme.rangePickerHeaderForegroundColor); expect(selectedDate.style?.fontSize, datePickerTheme.rangePickerHeaderHeadlineStyle?.fontSize); // Test the day overlay color. final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.text('16'))); await tester.pumpAndSettle(); expect(inkFeatures, paints..circle(color: datePickerTheme.dayOverlayColor?.resolve(<MaterialState>{}))); // Test the range selection overlay color. await gesture.moveTo(tester.getCenter(find.text('18'))); await tester.pumpAndSettle(); expect(inkFeatures, paints..circle(color: datePickerTheme.rangeSelectionOverlayColor?.resolve(<MaterialState>{}))); }); testWidgets('Dividers use DatePickerThemeData.dividerColor', (WidgetTester tester) async { Future<void> showPicker(WidgetTester tester, Size size) async { tester.view.physicalSize = size; tester.view.devicePixelRatio = 1.0; addTearDown(tester.view.reset); await tester.pumpWidget( MaterialApp( theme: ThemeData( datePickerTheme: datePickerTheme, useMaterial3: true, ), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: DatePickerDialog( initialDate: DateTime(2023, DateTime.january, 25), firstDate: DateTime(2022), lastDate: DateTime(2024, DateTime.december, 31), currentDate: DateTime(2023, DateTime.january, 24), ), ), ), ), ), ); } await showPicker(tester, wideWindowSize); // Test vertical divider. final VerticalDivider verticalDivider = tester.widget(find.byType(VerticalDivider)); expect(verticalDivider.color, datePickerTheme.dividerColor); // Test portrait layout. await showPicker(tester, narrowWindowSize); // Test horizontal divider. final Divider horizontalDivider = tester.widget(find.byType(Divider)); expect(horizontalDivider.color, datePickerTheme.dividerColor); }); testWidgets( 'DatePicker uses ThemeData.inputDecorationTheme properties ' 'which are null in DatePickerThemeData.inputDecorationTheme', (WidgetTester tester) async { Widget buildWidget({ InputDecorationTheme? inputDecorationTheme, DatePickerThemeData? datePickerTheme, }) { return MaterialApp( theme: ThemeData( useMaterial3: true, inputDecorationTheme: inputDecorationTheme, datePickerTheme: datePickerTheme, ), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: DatePickerDialog( initialEntryMode: DatePickerEntryMode.input, initialDate: DateTime(2023, DateTime.january, 25), firstDate: DateTime(2022), lastDate: DateTime(2024, DateTime.december, 31), currentDate: DateTime(2023, DateTime.january, 24), ), ), ), ), ); } // Test DatePicker with DatePickerThemeData.inputDecorationTheme. await tester.pumpWidget(buildWidget( inputDecorationTheme: const InputDecorationTheme(filled: true), datePickerTheme: datePickerTheme, )); InputDecoration inputDecoration = tester.widget<TextField>(find.byType(TextField)).decoration!; expect(inputDecoration.fillColor, datePickerTheme.inputDecorationTheme!.fillColor); expect(inputDecoration.border , datePickerTheme.inputDecorationTheme!.border); // Test DatePicker with ThemeData.inputDecorationTheme. await tester.pumpWidget(buildWidget( inputDecorationTheme: const InputDecorationTheme( filled: true, fillColor: Color(0xFF00FF00), border: OutlineInputBorder(), ), )); await tester.pumpAndSettle(); inputDecoration = tester.widget<TextField>(find.byType(TextField)).decoration!; expect(inputDecoration.fillColor, const Color(0xFF00FF00)); expect(inputDecoration.border , const OutlineInputBorder()); }); testWidgets('DatePickerDialog resolves DatePickerTheme.dayOverlayColor states', (WidgetTester tester) async { final MaterialStateProperty<Color> dayOverlayColor = MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) { if (states.contains(MaterialState.hovered)) { return const Color(0xff00ff00); } if (states.contains(MaterialState.focused)) { return const Color(0xffff00ff); } if (states.contains(MaterialState.pressed)) { return const Color(0xffffff00); } return Colors.transparent; }); await tester.pumpWidget( MaterialApp( theme: ThemeData( datePickerTheme: DatePickerThemeData( dayOverlayColor: dayOverlayColor, ), useMaterial3: true, ), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: Focus( child: DatePickerDialog( initialDate: DateTime(2023, DateTime.january, 25), firstDate: DateTime(2022), lastDate: DateTime(2024, DateTime.december, 31), currentDate: DateTime(2023, DateTime.january, 24), ), ), ), ), ), ), ); // Test the hover overlay color. final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.text('20'))); await tester.pumpAndSettle(); expect( inkFeatures, paints ..circle(color: dayOverlayColor.resolve(<MaterialState>{MaterialState.hovered})), ); // Test the pressed overlay color. await gesture.down(tester.getCenter(find.text('20'))); await tester.pumpAndSettle(); if (kIsWeb) { // An extra circle is painted on the web for the hovered state. expect( inkFeatures, paints ..circle(color: dayOverlayColor.resolve(<MaterialState>{MaterialState.hovered})) ..circle(color: dayOverlayColor.resolve(<MaterialState>{MaterialState.hovered})) ..circle(color: dayOverlayColor.resolve(<MaterialState>{MaterialState.pressed})), ); } else { expect( inkFeatures, paints ..circle(color: dayOverlayColor.resolve(<MaterialState>{MaterialState.hovered})) ..circle(color: dayOverlayColor.resolve(<MaterialState>{MaterialState.pressed})), ); } await gesture.removePointer(); await tester.pumpAndSettle(); // Focus day selection. for (int i = 0; i < 5; i++) { await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); } // Test the focused overlay color. expect( inkFeatures, paints ..circle(color: dayOverlayColor.resolve(<MaterialState>{MaterialState.focused})), ); }); testWidgets('DatePickerDialog resolves DatePickerTheme.yearOverlayColor states', (WidgetTester tester) async { final MaterialStateProperty<Color> yearOverlayColor = MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) { if (states.contains(MaterialState.hovered)) { return const Color(0xff00ff00); } if (states.contains(MaterialState.focused)) { return const Color(0xffff00ff); } if (states.contains(MaterialState.pressed)) { return const Color(0xffffff00); } return Colors.transparent; }); await tester.pumpWidget( MaterialApp( theme: ThemeData( datePickerTheme: DatePickerThemeData( yearOverlayColor: yearOverlayColor, ), useMaterial3: true, ), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: Focus( child: DatePickerDialog( initialDate: DateTime(2023, DateTime.january, 25), firstDate: DateTime(2022), lastDate: DateTime(2024, DateTime.december, 31), currentDate: DateTime(2023, DateTime.january, 24), initialCalendarMode: DatePickerMode.year, ), ), ), ), ), ), ); // Test the hover overlay color. final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.text('2022'))); await tester.pumpAndSettle(); expect( inkFeatures, paints ..rect(color: yearOverlayColor.resolve(<MaterialState>{MaterialState.hovered})), ); // Test the pressed overlay color. await gesture.down(tester.getCenter(find.text('2022'))); await tester.pumpAndSettle(); expect( inkFeatures, paints ..rect(color: yearOverlayColor.resolve(<MaterialState>{MaterialState.hovered})) ..rect(color: yearOverlayColor.resolve(<MaterialState>{MaterialState.pressed})), ); await gesture.removePointer(); await tester.pumpAndSettle(); // Focus year selection. for (int i = 0; i < 3; i++) { await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pumpAndSettle(); } // Test the focused overlay color. expect( inkFeatures, paints ..rect(color: yearOverlayColor.resolve(<MaterialState>{MaterialState.focused})), ); }); testWidgets('DateRangePickerDialog resolves DatePickerTheme.rangeSelectionOverlayColor states', (WidgetTester tester) async { final MaterialStateProperty<Color> rangeSelectionOverlayColor = MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) { if (states.contains(MaterialState.hovered)) { return const Color(0xff00ff00); } if (states.contains(MaterialState.pressed)) { return const Color(0xffffff00); } return Colors.transparent; }); await tester.pumpWidget( MaterialApp( theme: ThemeData( datePickerTheme: DatePickerThemeData( rangeSelectionOverlayColor: rangeSelectionOverlayColor, ), useMaterial3: true, ), home: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: DateRangePickerDialog( firstDate: DateTime(2023), lastDate: DateTime(2023, DateTime.january, 31), initialDateRange: DateTimeRange( start: DateTime(2023, DateTime.january, 17), end: DateTime(2023, DateTime.january, 20), ), currentDate: DateTime(2023, DateTime.january, 23), ), ), ), ), ), ); // Test the hover overlay color. final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.text('18'))); await tester.pumpAndSettle(); expect( inkFeatures, paints ..circle(color: rangeSelectionOverlayColor.resolve(<MaterialState>{MaterialState.hovered})), ); // Test the pressed overlay color. await gesture.down(tester.getCenter(find.text('18'))); await tester.pumpAndSettle(); if (kIsWeb) { // An extra circle is painted on the web for the hovered state. expect( inkFeatures, paints ..circle(color: rangeSelectionOverlayColor.resolve(<MaterialState>{MaterialState.hovered})) ..circle(color: rangeSelectionOverlayColor.resolve(<MaterialState>{MaterialState.hovered})) ..circle(color: rangeSelectionOverlayColor.resolve(<MaterialState>{MaterialState.pressed})), ); } else { expect( inkFeatures, paints ..circle(color: rangeSelectionOverlayColor.resolve(<MaterialState>{MaterialState.hovered})) ..circle(color: rangeSelectionOverlayColor.resolve(<MaterialState>{MaterialState.pressed})), ); } }); }
flutter/packages/flutter/test/material/date_picker_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/date_picker_theme_test.dart", "repo_id": "flutter", "token_count": 16698 }
712
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; void main() { testWidgets('ElevatedButton, ElevatedButton.icon defaults', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); final ThemeData theme = ThemeData.from(colorScheme: colorScheme); final bool material3 = theme.useMaterial3; // Enabled ElevatedButton await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: ElevatedButton( onPressed: () { }, child: const Text('button'), ), ), ), ); final Finder buttonMaterial = find.descendant( of: find.byType(ElevatedButton), matching: find.byType(Material), ); Material material = tester.widget<Material>(buttonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderOnForeground, true); expect(material.borderRadius, null); expect(material.clipBehavior, Clip.none); expect(material.color, material3 ? colorScheme.onPrimary : colorScheme.primary); expect(material.elevation, material3 ? 1: 2); expect(material.shadowColor, const Color(0xff000000)); expect(material.shape, material3 ? const StadiumBorder() : const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))); expect(material.textStyle!.color, material3 ? colorScheme.primary : colorScheme.onPrimary); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(material.type, MaterialType.button); final Align align = tester.firstWidget<Align>(find.ancestor(of: find.text('button'), matching: find.byType(Align))); expect(align.alignment, Alignment.center); final Offset center = tester.getCenter(find.byType(ElevatedButton)); final TestGesture gesture = await tester.startGesture(center); await tester.pump(); // start the splash animation await tester.pump(const Duration(milliseconds: 100)); // splash is underway // Material 3 uses the InkSparkle which uses a shader, so we can't capture // the effect with paint methods. if (!material3) { final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..circle(color: colorScheme.onPrimary.withOpacity(0.24))); } // Only elevation changes when enabled and pressed. material = tester.widget<Material>(buttonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderOnForeground, true); expect(material.borderRadius, null); expect(material.clipBehavior, Clip.none); expect(material.color, material3 ? colorScheme.onPrimary : colorScheme.primary); expect(material.elevation, material3 ? 1 : 8); expect(material.shadowColor, const Color(0xff000000)); expect(material.shape, material3 ? const StadiumBorder() : const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))); expect(material.textStyle!.color, material3 ? colorScheme.primary : colorScheme.onPrimary); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(material.type, MaterialType.button); await gesture.up(); await tester.pumpAndSettle(); // Enabled ElevatedButton.icon final Key iconButtonKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: ElevatedButton.icon( key: iconButtonKey, onPressed: () { }, icon: const Icon(Icons.add), label: const Text('label'), ), ), ), ); final Finder iconButtonMaterial = find.descendant( of: find.byKey(iconButtonKey), matching: find.byType(Material), ); material = tester.widget<Material>(iconButtonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderOnForeground, true); expect(material.borderRadius, null); expect(material.clipBehavior, Clip.none); expect(material.color, material3 ? colorScheme.onPrimary : colorScheme.primary); expect(material.elevation, material3? 1 : 2); expect(material.shadowColor, const Color(0xff000000)); expect(material.shape, material3 ? const StadiumBorder() : const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))); expect(material.textStyle!.color, material3 ? colorScheme.primary : colorScheme.onPrimary); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(material.type, MaterialType.button); // Disabled ElevatedButton await tester.pumpWidget( MaterialApp( theme: theme, home: const Center( child: ElevatedButton( onPressed: null, child: Text('button'), ), ), ), ); // Finish the elevation animation, final background color change. await tester.pumpAndSettle(); material = tester.widget<Material>(buttonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderOnForeground, true); expect(material.borderRadius, null); expect(material.clipBehavior, Clip.none); expect(material.color, colorScheme.onSurface.withOpacity(0.12)); expect(material.elevation, 0.0); expect(material.shadowColor, const Color(0xff000000)); expect(material.shape, material3 ? const StadiumBorder() : const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))); expect(material.textStyle!.color, colorScheme.onSurface.withOpacity(0.38)); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(material.type, MaterialType.button); }); testWidgets('ElevatedButton.icon produces the correct widgets if icon is null', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); final ThemeData theme = ThemeData.from(colorScheme: colorScheme); final Key iconButtonKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: ElevatedButton.icon( key: iconButtonKey, onPressed: () { }, icon: const Icon(Icons.add), label: const Text('label'), ), ), ), ); expect(find.byIcon(Icons.add), findsOneWidget); expect(find.text('label'), findsOneWidget); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: ElevatedButton.icon( key: iconButtonKey, onPressed: () { }, // No icon specified. label: const Text('label'), ), ), ), ); expect(find.byIcon(Icons.add), findsNothing); expect(find.text('label'), findsOneWidget); }); testWidgets('Default ElevatedButton meets a11y contrast guidelines', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light()), home: Scaffold( body: Center( child: ElevatedButton( onPressed: () { }, focusNode: focusNode, child: const Text('ElevatedButton'), ), ), ), ), ); // Default, not disabled. await expectLater(tester, meetsGuideline(textContrastGuideline)); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); await expectLater(tester, meetsGuideline(textContrastGuideline)); // Hovered. final Offset center = tester.getCenter(find.byType(ElevatedButton)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); await expectLater(tester, meetsGuideline(textContrastGuideline)); focusNode.dispose(); }, skip: isBrowser, // https://github.com/flutter/flutter/issues/44115 ); testWidgets('ElevatedButton default overlayColor and elevation resolve pressed state', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: Center( child: ElevatedButton( onPressed: () {}, focusNode: focusNode, child: const Text('ElevatedButton'), ), ), ), ), ); RenderObject overlayColor() { return tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); } double elevation() { return tester.widget<PhysicalShape>( find.descendant( of: find.byType(ElevatedButton), matching: find.byType(PhysicalShape), ), ).elevation; } // Hovered. final Offset center = tester.getCenter(find.byType(ElevatedButton)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(elevation(), 3.0); expect(overlayColor(), paints..rect(color: theme.colorScheme.primary.withOpacity(0.08))); // Highlighted (pressed). await gesture.down(center); await tester.pumpAndSettle(); expect(elevation(), 1.0); expect(overlayColor(), paints..rect()..rect(color: theme.colorScheme.primary.withOpacity(0.1))); // Remove pressed and hovered states await gesture.up(); await tester.pumpAndSettle(); await gesture.moveTo(const Offset(0, 50)); await tester.pumpAndSettle(); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(elevation(), 1.0); expect(overlayColor(), paints..rect(color: theme.colorScheme.primary.withOpacity(0.1))); focusNode.dispose(); }); testWidgets('ElevatedButton uses stateful color for text color in different states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); Color getTextColor(Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return pressedColor; } if (states.contains(MaterialState.hovered)) { return hoverColor; } if (states.contains(MaterialState.focused)) { return focusedColor; } return defaultColor; } await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: ElevatedButtonTheme( data: ElevatedButtonThemeData( style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith<Color>(getTextColor), ), ), child: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () {}, focusNode: focusNode, child: const Text('ElevatedButton'), ); }, ), ), ), ), ), ); Color textColor() { return tester.renderObject<RenderParagraph>(find.text('ElevatedButton')).text.style!.color!; } // Default, not disabled. expect(textColor(), equals(defaultColor)); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(textColor(), focusedColor); // Hovered. final Offset center = tester.getCenter(find.byType(ElevatedButton)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(textColor(), hoverColor); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. expect(textColor(), pressedColor); focusNode.dispose(); }); testWidgets('ElevatedButton uses stateful color for icon color in different states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); final Key buttonKey = UniqueKey(); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); Color getTextColor(Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return pressedColor; } if (states.contains(MaterialState.hovered)) { return hoverColor; } if (states.contains(MaterialState.focused)) { return focusedColor; } return defaultColor; } await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: ElevatedButtonTheme( data: ElevatedButtonThemeData( style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith<Color>(getTextColor), ), ), child: Builder( builder: (BuildContext context) { return ElevatedButton.icon( key: buttonKey, icon: const Icon(Icons.add), label: const Text('ElevatedButton'), onPressed: () {}, focusNode: focusNode, ); }, ), ), ), ), ), ); Color iconColor() => _iconStyle(tester, Icons.add).color!; // Default, not disabled. expect(iconColor(), equals(defaultColor)); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(iconColor(), focusedColor); // Hovered. final Offset center = tester.getCenter(find.byKey(buttonKey)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(iconColor(), hoverColor); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. expect(iconColor(), pressedColor); focusNode.dispose(); }); testWidgets('ElevatedButton onPressed and onLongPress callbacks are correctly called when non-null', (WidgetTester tester) async { bool wasPressed; Finder elevatedButton; Widget buildFrame({ VoidCallback? onPressed, VoidCallback? onLongPress }) { return Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( onPressed: onPressed, onLongPress: onLongPress, child: const Text('button'), ), ); } // onPressed not null, onLongPress null. wasPressed = false; await tester.pumpWidget( buildFrame(onPressed: () { wasPressed = true; }), ); elevatedButton = find.byType(ElevatedButton); expect(tester.widget<ElevatedButton>(elevatedButton).enabled, true); await tester.tap(elevatedButton); expect(wasPressed, true); // onPressed null, onLongPress not null. wasPressed = false; await tester.pumpWidget( buildFrame(onLongPress: () { wasPressed = true; }), ); elevatedButton = find.byType(ElevatedButton); expect(tester.widget<ElevatedButton>(elevatedButton).enabled, true); await tester.longPress(elevatedButton); expect(wasPressed, true); // onPressed null, onLongPress null. await tester.pumpWidget( buildFrame(), ); elevatedButton = find.byType(ElevatedButton); expect(tester.widget<ElevatedButton>(elevatedButton).enabled, false); }); testWidgets('ElevatedButton onPressed and onLongPress callbacks are distinctly recognized', (WidgetTester tester) async { bool didPressButton = false; bool didLongPressButton = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( onPressed: () { didPressButton = true; }, onLongPress: () { didLongPressButton = true; }, child: const Text('button'), ), ), ); final Finder elevatedButton = find.byType(ElevatedButton); expect(tester.widget<ElevatedButton>(elevatedButton).enabled, true); expect(didPressButton, isFalse); await tester.tap(elevatedButton); expect(didPressButton, isTrue); expect(didLongPressButton, isFalse); await tester.longPress(elevatedButton); expect(didLongPressButton, isTrue); }); testWidgets("ElevatedButton response doesn't hover when disabled", (WidgetTester tester) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch; final FocusNode focusNode = FocusNode(debugLabel: 'ElevatedButton Focus'); final GlobalKey childKey = GlobalKey(); bool hovering = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 100, height: 100, child: ElevatedButton( autofocus: true, onPressed: () {}, onLongPress: () {}, onHover: (bool value) { hovering = value; }, focusNode: focusNode, child: SizedBox(key: childKey), ), ), ), ); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byKey(childKey))); await tester.pumpAndSettle(); expect(hovering, isTrue); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 100, height: 100, child: ElevatedButton( focusNode: focusNode, onHover: (bool value) { hovering = value; }, onPressed: null, child: SizedBox(key: childKey), ), ), ), ); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isFalse); focusNode.dispose(); }); testWidgets('disabled and hovered ElevatedButton responds to mouse-exit', (WidgetTester tester) async { int onHoverCount = 0; late bool hover; Widget buildFrame({ required bool enabled }) { return Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 100, height: 100, child: ElevatedButton( onPressed: enabled ? () { } : null, onHover: (bool value) { onHoverCount += 1; hover = value; }, child: const Text('ElevatedButton'), ), ), ), ); } await tester.pumpWidget(buildFrame(enabled: true)); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(ElevatedButton))); await tester.pumpAndSettle(); expect(onHoverCount, 1); expect(hover, true); await tester.pumpWidget(buildFrame(enabled: false)); await tester.pumpAndSettle(); await gesture.moveTo(Offset.zero); // Even though the ElevatedButton has been disabled, the mouse-exit still // causes onHover(false) to be called. expect(onHoverCount, 2); expect(hover, false); await gesture.moveTo(tester.getCenter(find.byType(ElevatedButton))); await tester.pumpAndSettle(); // We no longer see hover events because the ElevatedButton is disabled // and it's no longer in the "hovering" state. expect(onHoverCount, 2); expect(hover, false); await tester.pumpWidget(buildFrame(enabled: true)); await tester.pumpAndSettle(); // The ElevatedButton was enabled while it contained the mouse, however // we do not call onHover() because it may call setState(). expect(onHoverCount, 2); expect(hover, false); await gesture.moveTo(tester.getCenter(find.byType(ElevatedButton)) - const Offset(1, 1)); await tester.pumpAndSettle(); // Moving the mouse a little within the ElevatedButton doesn't change anything. expect(onHoverCount, 2); expect(hover, false); }); testWidgets('Can set ElevatedButton focus and Can set unFocus.', (WidgetTester tester) async { final FocusNode node = FocusNode(debugLabel: 'ElevatedButton Focus'); bool gotFocus = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( focusNode: node, onFocusChange: (bool focused) => gotFocus = focused, onPressed: () { }, child: const SizedBox(), ), ), ); 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('When ElevatedButton disable, Can not set ElevatedButton focus.', (WidgetTester tester) async { final FocusNode node = FocusNode(debugLabel: 'ElevatedButton Focus'); bool gotFocus = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( focusNode: node, onFocusChange: (bool focused) => gotFocus = focused, onPressed: null, child: const SizedBox(), ), ), ); node.requestFocus(); await tester.pump(); expect(gotFocus, isFalse); expect(node.hasFocus, isFalse); node.dispose(); }); testWidgets('Does ElevatedButton work with hover', (WidgetTester tester) async { const Color hoverColor = Color(0xff001122); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) { return states.contains(MaterialState.hovered) ? hoverColor : null; }), ), onPressed: () { }, child: const Text('button'), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(ElevatedButton))); await tester.pumpAndSettle(); final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..rect(color: hoverColor)); }); testWidgets('Does ElevatedButton work with focus', (WidgetTester tester) async { const Color focusColor = Color(0xff001122); final FocusNode focusNode = FocusNode(debugLabel: 'ElevatedButton Node'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) { return states.contains(MaterialState.focused) ? focusColor : null; }), ), focusNode: focusNode, onPressed: () { }, child: const Text('button'), ), ), ); FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; focusNode.requestFocus(); await tester.pumpAndSettle(); final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..rect(color: focusColor)); focusNode.dispose(); }); testWidgets('Does ElevatedButton work with autofocus', (WidgetTester tester) async { const Color focusColor = Color(0xff001122); Color? getOverlayColor(Set<MaterialState> states) { return states.contains(MaterialState.focused) ? focusColor : null; } final FocusNode focusNode = FocusNode(debugLabel: 'ElevatedButton Node'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( autofocus: true, style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color?>(getOverlayColor), ), focusNode: focusNode, onPressed: () { }, child: const Text('button'), ), ), ); FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; await tester.pumpAndSettle(); final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..rect(color: focusColor)); focusNode.dispose(); }); testWidgets('Does ElevatedButton contribute semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: ElevatedButton( style: const ButtonStyle( // Specifying minimumSize to mimic the original minimumSize for // RaisedButton so that the semantics tree's rect and transform // match the original version of this test. minimumSize: MaterialStatePropertyAll<Size>(Size(88, 36)), ), onPressed: () { }, child: const Text('ABC'), ), ), ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( actions: <SemanticsAction>[ SemanticsAction.tap, ], label: 'ABC', rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0), transform: Matrix4.translationValues(356.0, 276.0, 0.0), flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], ), ], ), ignoreId: true, )); semantics.dispose(); }); testWidgets('ElevatedButton size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async { const ButtonStyle style = ButtonStyle( // Specifying minimumSize to mimic the original minimumSize for // RaisedButton so that the corresponding button size matches // the original version of this test. minimumSize: MaterialStatePropertyAll<Size>(Size(88, 36)), ); Widget buildFrame(MaterialTapTargetSize tapTargetSize, Key key) { return Theme( data: ThemeData(useMaterial3: false, materialTapTargetSize: tapTargetSize), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: ElevatedButton( key: key, style: style, child: const SizedBox(width: 50.0, height: 8.0), onPressed: () { }, ), ), ), ); } final Key key1 = UniqueKey(); await tester.pumpWidget(buildFrame(MaterialTapTargetSize.padded, key1)); expect(tester.getSize(find.byKey(key1)), const Size(88.0, 48.0)); final Key key2 = UniqueKey(); await tester.pumpWidget(buildFrame(MaterialTapTargetSize.shrinkWrap, key2)); expect(tester.getSize(find.byKey(key2)), const Size(88.0, 36.0)); }); testWidgets('ElevatedButton has no clip by default', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( onPressed: () { /* to make sure the button is enabled */ }, child: const Text('button'), ), ), ); expect( tester.renderObject(find.byType(ElevatedButton)), paintsExactlyCountTimes(#clipPath, 0), ); }); testWidgets('ElevatedButton responds to density changes.', (WidgetTester tester) async { const Key key = Key('test'); const Key childKey = Key('test child'); Future<void> buildTest(VisualDensity visualDensity, {bool useText = false}) async { return tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Directionality( textDirection: TextDirection.rtl, child: Center( child: ElevatedButton( style: ButtonStyle( visualDensity: visualDensity, // Specifying minimumSize to mimic the original minimumSize for // RaisedButton so that the corresponding button size matches // the original version of this test. minimumSize: const MaterialStatePropertyAll<Size>(Size(88, 36)), ), key: key, onPressed: () {}, child: useText ? const Text('Text', key: childKey) : Container(key: childKey, width: 100, height: 100, color: const Color(0xffff0000)), ), ), ), ), ); } await buildTest(VisualDensity.standard); final RenderBox box = tester.renderObject(find.byKey(key)); Rect childRect = tester.getRect(find.byKey(childKey)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(132, 100))); expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350))); await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0)); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(156, 124))); expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350))); await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0)); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(132, 100))); expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350))); await buildTest(VisualDensity.standard, useText: true); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(88, 48))); expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0))); await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0), useText: true); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(112, 60))); expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0))); await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0), useText: true); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(88, 36))); expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0))); }); testWidgets('ElevatedButton.icon responds to applied padding', (WidgetTester tester) async { const Key buttonKey = Key('test'); const Key labelKey = Key('label'); await tester.pumpWidget( // When textDirection is set to TextDirection.ltr, the label appears on the // right side of the icon. This is important in determining whether the // horizontal padding is applied correctly later on Directionality( textDirection: TextDirection.ltr, child: Center( child: ElevatedButton.icon( key: buttonKey, style: const ButtonStyle( padding: MaterialStatePropertyAll<EdgeInsets>(EdgeInsets.fromLTRB(16, 5, 10, 12)), ), onPressed: () {}, icon: const Icon(Icons.add), label: const Text( 'Hello', key: labelKey, ), ), ), ), ); final Rect paddingRect = tester.getRect(find.byType(Padding)); final Rect labelRect = tester.getRect(find.byKey(labelKey)); final Rect iconRect = tester.getRect(find.byType(Icon)); // The right padding should be applied on the right of the label, whereas the // left padding should be applied on the left side of the icon. expect(paddingRect.right, labelRect.right + 10); expect(paddingRect.left, iconRect.left - 16); // Use the taller widget to check the top and bottom padding. final Rect tallerWidget = iconRect.height > labelRect.height ? iconRect : labelRect; expect(paddingRect.top, tallerWidget.top - 5); expect(paddingRect.bottom, tallerWidget.bottom + 12); }); group('Default ElevatedButton padding for textScaleFactor, textDirection', () { const ValueKey<String> buttonKey = ValueKey<String>('button'); const ValueKey<String> labelKey = ValueKey<String>('label'); const ValueKey<String> iconKey = ValueKey<String>('icon'); const List<double> textScaleFactorOptions = <double>[0.5, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0]; const List<TextDirection> textDirectionOptions = <TextDirection>[TextDirection.ltr, TextDirection.rtl]; const List<Widget?> iconOptions = <Widget?>[null, Icon(Icons.add, size: 18, key: iconKey)]; // Expected values for each textScaleFactor. final Map<double, double> paddingWithoutIconStart = <double, double>{ 0.5: 16, 1: 16, 1.25: 14, 1.5: 12, 2: 8, 2.5: 6, 3: 4, 4: 4, }; final Map<double, double> paddingWithoutIconEnd = <double, double>{ 0.5: 16, 1: 16, 1.25: 14, 1.5: 12, 2: 8, 2.5: 6, 3: 4, 4: 4, }; final Map<double, double> paddingWithIconStart = <double, double>{ 0.5: 12, 1: 12, 1.25: 11, 1.5: 10, 2: 8, 2.5: 8, 3: 8, 4: 8, }; final Map<double, double> paddingWithIconEnd = <double, double>{ 0.5: 16, 1: 16, 1.25: 14, 1.5: 12, 2: 8, 2.5: 6, 3: 4, 4: 4, }; final Map<double, double> paddingWithIconGap = <double, double>{ 0.5: 8, 1: 8, 1.25: 7, 1.5: 6, 2: 4, 2.5: 4, 3: 4, 4: 4, }; Rect globalBounds(RenderBox renderBox) { final Offset topLeft = renderBox.localToGlobal(Offset.zero); return topLeft & renderBox.size; } /// Computes the padding between two [Rect]s, one inside the other. EdgeInsets paddingBetween({ required Rect parent, required Rect child }) { assert (parent.intersect(child) == child); return EdgeInsets.fromLTRB( child.left - parent.left, child.top - parent.top, parent.right - child.right, parent.bottom - child.bottom, ); } for (final double textScaleFactor in textScaleFactorOptions) { for (final TextDirection textDirection in textDirectionOptions) { for (final Widget? icon in iconOptions) { final String testName = <String>[ 'ElevatedButton, text scale $textScaleFactor', if (icon != null) 'with icon', if (textDirection == TextDirection.rtl) 'RTL', ].join(', '); testWidgets(testName, (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData( useMaterial3: false, colorScheme: const ColorScheme.light(), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom(minimumSize: const Size(64, 36)), ), ), home: Builder( builder: (BuildContext context) { return MediaQuery.withClampedTextScaling( minScaleFactor: textScaleFactor, maxScaleFactor: textScaleFactor, child: Directionality( textDirection: textDirection, child: Scaffold( body: Center( child: icon == null ? ElevatedButton( key: buttonKey, onPressed: () {}, child: const Text('button', key: labelKey), ) : ElevatedButton.icon( key: buttonKey, onPressed: () {}, icon: icon, label: const Text('button', key: labelKey), ), ), ), ), ); }, ), ), ); final Element paddingElement = tester.element( find.descendant( of: find.byKey(buttonKey), matching: find.byType(Padding), ), ); expect(Directionality.of(paddingElement), textDirection); final Padding paddingWidget = paddingElement.widget as Padding; // Compute expected padding, and check. final double expectedStart = icon != null ? paddingWithIconStart[textScaleFactor]! : paddingWithoutIconStart[textScaleFactor]!; final double expectedEnd = icon != null ? paddingWithIconEnd[textScaleFactor]! : paddingWithoutIconEnd[textScaleFactor]!; final EdgeInsets expectedPadding = EdgeInsetsDirectional.fromSTEB(expectedStart, 0, expectedEnd, 0) .resolve(textDirection); expect(paddingWidget.padding.resolve(textDirection), expectedPadding); // Measure padding in terms of the difference between the button and its label child // and check that. final RenderBox labelRenderBox = tester.renderObject<RenderBox>(find.byKey(labelKey)); final Rect labelBounds = globalBounds(labelRenderBox); final RenderBox? iconRenderBox = icon == null ? null : tester.renderObject<RenderBox>(find.byKey(iconKey)); final Rect? iconBounds = icon == null ? null : globalBounds(iconRenderBox!); final Rect childBounds = icon == null ? labelBounds : labelBounds.expandToInclude(iconBounds!); // We measure the `InkResponse` descendant of the button // element, because the button has a larger `RenderBox` // which accommodates the minimum tap target with a height // of 48. final RenderBox buttonRenderBox = tester.renderObject<RenderBox>( find.descendant( of: find.byKey(buttonKey), matching: find.byWidgetPredicate( (Widget widget) => widget is InkResponse, ), ), ); final Rect buttonBounds = globalBounds(buttonRenderBox); final EdgeInsets visuallyMeasuredPadding = paddingBetween( parent: buttonBounds, child: childBounds, ); // Since there is a requirement of a minimum width of 64 // and a minimum height of 36 on material buttons, the visual // padding of smaller buttons may not match their settings. // Therefore, we only test buttons that are large enough. if (buttonBounds.width > 64) { expect( visuallyMeasuredPadding.left, expectedPadding.left, ); expect( visuallyMeasuredPadding.right, expectedPadding.right, ); } if (buttonBounds.height > 36) { expect( visuallyMeasuredPadding.top, expectedPadding.top, ); expect( visuallyMeasuredPadding.bottom, expectedPadding.bottom, ); } // Check the gap between the icon and the label if (icon != null) { final double gapWidth = textDirection == TextDirection.ltr ? labelBounds.left - iconBounds!.right : iconBounds!.left - labelBounds.right; expect(gapWidth, paddingWithIconGap[textScaleFactor]); } // Check the text's height - should be consistent with the textScaleFactor. final RenderBox textRenderObject = tester.renderObject<RenderBox>( find.descendant( of: find.byKey(labelKey), matching: find.byElementPredicate( (Element element) => element.widget is RichText, ), ), ); final double textHeight = textRenderObject.paintBounds.size.height; final double expectedTextHeight = 14 * textScaleFactor; expect(textHeight, moreOrLessEquals(expectedTextHeight, epsilon: 0.5)); }); } } } }); testWidgets('Override theme fontSize changes padding', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData.from( colorScheme: const ColorScheme.light(), textTheme: const TextTheme(labelLarge: TextStyle(fontSize: 28.0)), ), home: Builder( builder: (BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( onPressed: () {}, child: const Text('text'), ), ), ); }, ), ), ); final Padding paddingWidget = tester.widget<Padding>( find.descendant( of: find.byType(ElevatedButton), matching: find.byType(Padding), ), ); expect(paddingWidget.padding, const EdgeInsets.symmetric(horizontal: 12)); }); testWidgets('Override ElevatedButton default padding', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light()), home: Builder( builder: (BuildContext context) { return MediaQuery.withClampedTextScaling( minScaleFactor: 2, maxScaleFactor: 2, child: Scaffold( body: Center( child: ElevatedButton( style: ElevatedButton.styleFrom(padding: const EdgeInsets.all(22)), onPressed: () {}, child: const Text('ElevatedButton'), ), ), ), ); }, ), ), ); final Padding paddingWidget = tester.widget<Padding>( find.descendant( of: find.byType(ElevatedButton), matching: find.byType(Padding), ), ); expect(paddingWidget.padding, const EdgeInsets.all(22)); }); testWidgets('M3 ElevatedButton has correct padding', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true), home: Scaffold( body: Center( child: ElevatedButton( key: key, onPressed: () {}, child: const Text('ElevatedButton'), ), ), ), ), ); final Padding paddingWidget = tester.widget<Padding>( find.descendant( of: find.byKey(key), matching: find.byType(Padding), ), ); expect(paddingWidget.padding, const EdgeInsets.symmetric(horizontal: 24)); }); testWidgets('M3 ElevatedButton.icon has correct padding', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true), home: Scaffold( body: Center( child: ElevatedButton.icon( key: key, icon: const Icon(Icons.favorite), onPressed: () {}, label: const Text('ElevatedButton'), ), ), ), ), ); final Padding paddingWidget = tester.widget<Padding>( find.descendant( of: find.byKey(key), matching: find.byType(Padding), ), ); expect(paddingWidget.padding, const EdgeInsetsDirectional.fromSTEB(16.0, 0.0, 24.0, 0.0)); }); testWidgets('Elevated buttons animate elevation before color on disable', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/387 const ColorScheme colorScheme = ColorScheme.light(); final Color backgroundColor = colorScheme.primary; final Color disabledBackgroundColor = colorScheme.onSurface.withOpacity(0.12); Widget buildFrame({ required bool enabled }) { return MaterialApp( theme: ThemeData.from(colorScheme: colorScheme, useMaterial3: false), home: Center( child: ElevatedButton( onPressed: enabled ? () { } : null, child: const Text('button'), ), ), ); } PhysicalShape physicalShape() { return tester.widget<PhysicalShape>( find.descendant( of: find.byType(ElevatedButton), matching: find.byType(PhysicalShape), ), ); } // Default elevation is 2, background color is primary. await tester.pumpWidget(buildFrame(enabled: true)); expect(physicalShape().elevation, 2); expect(physicalShape().color, backgroundColor); // Disabled elevation animates to 0 over 200ms, THEN the background // color changes to onSurface.withOpacity(0.12) await tester.pumpWidget(buildFrame(enabled: false)); await tester.pump(const Duration(milliseconds: 50)); expect(physicalShape().elevation, lessThan(2)); expect(physicalShape().color, backgroundColor); await tester.pump(const Duration(milliseconds: 150)); expect(physicalShape().elevation, 0); expect(physicalShape().color, backgroundColor); await tester.pumpAndSettle(); expect(physicalShape().elevation, 0); expect(physicalShape().color, disabledBackgroundColor); }); testWidgets('By default, ElevatedButton shape outline is defined by shape.side', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/69544 const Color borderColor = Color(0xff4caf50); await tester.pumpWidget( MaterialApp( theme: ThemeData(colorScheme: const ColorScheme.light(), textTheme: Typography.englishLike2014, useMaterial3: false), home: Center( child: ElevatedButton( style: ElevatedButton.styleFrom( shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(16)), side: BorderSide(width: 10, color: borderColor), ), minimumSize: const Size(64, 36), ), onPressed: () {}, child: const Text('button'), ), ), ), ); expect(find.byType(ElevatedButton), paints ..drrect( // Outer and inner rect that give the outline a width of 10. outer: RRect.fromLTRBR(0.0, 0.0, 116.0, 36.0, const Radius.circular(16)), inner: RRect.fromLTRBR(10.0, 10.0, 106.0, 26.0, const Radius.circular(16 - 10)), color: borderColor) ); }); testWidgets('Fixed size ElevatedButtons', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ ElevatedButton( style: ElevatedButton.styleFrom(fixedSize: const Size(100, 100)), onPressed: () {}, child: const Text('100x100'), ), ElevatedButton( style: ElevatedButton.styleFrom(fixedSize: const Size.fromWidth(200)), onPressed: () {}, child: const Text('200xh'), ), ElevatedButton( style: ElevatedButton.styleFrom(fixedSize: const Size.fromHeight(200)), onPressed: () {}, child: const Text('wx200'), ), ], ), ), ), ); expect(tester.getSize(find.widgetWithText(ElevatedButton, '100x100')), const Size(100, 100)); expect(tester.getSize(find.widgetWithText(ElevatedButton, '200xh')).width, 200); expect(tester.getSize(find.widgetWithText(ElevatedButton, 'wx200')).height, 200); }); testWidgets('ElevatedButton with NoSplash splashFactory paints nothing', (WidgetTester tester) async { Widget buildFrame({ InteractiveInkFeatureFactory? splashFactory }) { return MaterialApp( home: Scaffold( body: Center( child: ElevatedButton( style: ElevatedButton.styleFrom( splashFactory: splashFactory, ), onPressed: () { }, child: const Text('test'), ), ), ), ); } // NoSplash.splashFactory, no splash circles drawn await tester.pumpWidget(buildFrame(splashFactory: NoSplash.splashFactory)); { final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('test'))); final MaterialInkController material = Material.of(tester.element(find.text('test'))); await tester.pump(const Duration(milliseconds: 200)); expect(material, paintsExactlyCountTimes(#drawCircle, 0)); await gesture.up(); await tester.pumpAndSettle(); } // InkRipple.splashFactory, one splash circle drawn. await tester.pumpWidget(buildFrame(splashFactory: InkRipple.splashFactory)); { final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('test'))); final MaterialInkController material = Material.of(tester.element(find.text('test'))); await tester.pump(const Duration(milliseconds: 200)); expect(material, paintsExactlyCountTimes(#drawCircle, 1)); await gesture.up(); await tester.pumpAndSettle(); } }); testWidgets('ElevatedButton uses InkSparkle only for Android non-web when useMaterial3 is true', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: ElevatedButton( onPressed: () { }, child: const Text('button'), ), ), ), ); final InkWell buttonInkWell = tester.widget<InkWell>(find.descendant( of: find.byType(ElevatedButton), matching: find.byType(InkWell), )); if (debugDefaultTargetPlatformOverride! == TargetPlatform.android && !kIsWeb) { expect(buttonInkWell.splashFactory, equals(InkSparkle.splashFactory)); } else { expect(buttonInkWell.splashFactory, equals(InkRipple.splashFactory)); } }, variant: TargetPlatformVariant.all()); testWidgets('ElevatedButton uses InkRipple when useMaterial3 is false', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: false); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: ElevatedButton( onPressed: () { }, child: const Text('button'), ), ), ), ); final InkWell buttonInkWell = tester.widget<InkWell>(find.descendant( of: find.byType(ElevatedButton), matching: find.byType(InkWell), )); expect(buttonInkWell.splashFactory, equals(InkRipple.splashFactory)); }, variant: TargetPlatformVariant.all()); testWidgets('ElevatedButton.icon does not overflow', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/77815 await tester.pumpWidget( MaterialApp( home: Scaffold( body: SizedBox( width: 200, child: ElevatedButton.icon( onPressed: () {}, icon: const Icon(Icons.add), label: const Text( // Much wider than 200 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a euismod nibh. Morbi laoreet purus.', ), ), ), ), ), ); expect(tester.takeException(), null); }); testWidgets('ElevatedButton.icon icon,label layout', (WidgetTester tester) async { final Key buttonKey = UniqueKey(); final Key iconKey = UniqueKey(); final Key labelKey = UniqueKey(); final ButtonStyle style = ElevatedButton.styleFrom( padding: EdgeInsets.zero, visualDensity: VisualDensity.standard, // dx=0, dy=0 ); await tester.pumpWidget( MaterialApp( home: Scaffold( body: SizedBox( width: 200, child: ElevatedButton.icon( key: buttonKey, style: style, onPressed: () {}, icon: SizedBox(key: iconKey, width: 50, height: 100), label: SizedBox(key: labelKey, width: 50, height: 100), ), ), ), ), ); // The button's label and icon are separated by a gap of 8: // 46 [icon 50] 8 [label 50] 46 // The overall button width is 200. So: // icon.x = 46 // label.x = 46 + 50 + 8 = 104 expect(tester.getRect(find.byKey(buttonKey)), const Rect.fromLTRB(0.0, 0.0, 200.0, 100.0)); expect(tester.getRect(find.byKey(iconKey)), const Rect.fromLTRB(46.0, 0.0, 96.0, 100.0)); expect(tester.getRect(find.byKey(labelKey)), const Rect.fromLTRB(104.0, 0.0, 154.0, 100.0)); }); testWidgets('ElevatedButton maximumSize', (WidgetTester tester) async { final Key key0 = UniqueKey(); final Key key1 = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(textTheme: Typography.englishLike2014), home: Scaffold( body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ ElevatedButton( key: key0, style: ElevatedButton.styleFrom( minimumSize: const Size(24, 36), maximumSize: const Size.fromWidth(64), ), onPressed: () { }, child: const Text('A B C D E F G H I J K L M N O P'), ), ElevatedButton.icon( key: key1, style: ElevatedButton.styleFrom( minimumSize: const Size(24, 36), maximumSize: const Size.fromWidth(104), ), onPressed: () {}, icon: Container(color: Colors.red, width: 32, height: 32), label: const Text('A B C D E F G H I J K L M N O P'), ), ], ), ), ), ), ); expect(tester.getSize(find.byKey(key0)), const Size(64.0, 224.0)); expect(tester.getSize(find.byKey(key1)), const Size(104.0, 224.0)); }); testWidgets('Fixed size ElevatedButton, same as minimumSize == maximumSize', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ ElevatedButton( style: ElevatedButton.styleFrom(fixedSize: const Size(200, 200)), onPressed: () { }, child: const Text('200x200'), ), ElevatedButton( style: ElevatedButton.styleFrom( minimumSize: const Size(200, 200), maximumSize: const Size(200, 200), ), onPressed: () { }, child: const Text('200,200'), ), ], ), ), ), ); expect(tester.getSize(find.widgetWithText(ElevatedButton, '200x200')), const Size(200, 200)); expect(tester.getSize(find.widgetWithText(ElevatedButton, '200,200')), const Size(200, 200)); }); testWidgets('ElevatedButton changes mouse cursor when hovered', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: ElevatedButton( style: ElevatedButton.styleFrom( enabledMouseCursor: SystemMouseCursors.text, disabledMouseCursor: SystemMouseCursors.grab, ), onPressed: () {}, child: const Text('button'), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: Offset.zero); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); // Test cursor when disabled await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: ElevatedButton( style: ElevatedButton.styleFrom( enabledMouseCursor: SystemMouseCursors.text, disabledMouseCursor: SystemMouseCursors.grab, ), onPressed: null, child: const Text('button'), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab); // Test default cursor await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: ElevatedButton( onPressed: () {}, child: const Text('button'), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); // Test default cursor when disabled await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: ElevatedButton( onPressed: null, child: Text('button'), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }); testWidgets('ElevatedButton in SelectionArea changes mouse cursor when hovered', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/104595. await tester.pumpWidget(MaterialApp( home: SelectionArea( child: ElevatedButton( style: ElevatedButton.styleFrom( enabledMouseCursor: SystemMouseCursors.click, disabledMouseCursor: SystemMouseCursors.grab, ), onPressed: () {}, child: const Text('button'), ), ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: tester.getCenter(find.byType(Text))); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); }); testWidgets('Ink Response shape matches Material shape', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/91844 Widget buildFrame({BorderSide? side}) { return MaterialApp( home: Scaffold( body: Center( child: ElevatedButton( style: ElevatedButton.styleFrom( side: side, shape: const RoundedRectangleBorder( side: BorderSide( color: Color(0xff0000ff), width: 0, ), ), ), onPressed: () { }, child: const Text('ElevatedButton'), ), ), ), ); } const BorderSide borderSide = BorderSide(width: 10, color: Color(0xff00ff00)); await tester.pumpWidget(buildFrame(side: borderSide)); expect( tester.widget<InkWell>(find.byType(InkWell)).customBorder, const RoundedRectangleBorder(side: borderSide), ); await tester.pumpWidget(buildFrame()); await tester.pumpAndSettle(); expect( tester.widget<InkWell>(find.byType(InkWell)).customBorder, const RoundedRectangleBorder( side: BorderSide( color: Color(0xff0000ff), width: 0.0, ), ), ); }); testWidgets('ElevatedButton.styleFrom can be used to set foreground and background colors', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: ElevatedButton( style: ElevatedButton.styleFrom( foregroundColor: Colors.white, backgroundColor: Colors.purple, ), onPressed: () {}, child: const Text('button'), ), ), ), ); final Material material = tester.widget<Material>(find.descendant( of: find.byType(ElevatedButton), matching: find.byType(Material), )); expect(material.color, Colors.purple); expect(material.textStyle!.color, Colors.white); }); Future<void> testStatesController(Widget? icon, WidgetTester tester) async { int count = 0; void valueChanged() { count += 1; } final MaterialStatesController controller = MaterialStatesController(); addTearDown(controller.dispose); controller.addListener(valueChanged); await tester.pumpWidget( MaterialApp( home: Center( child: icon == null ? ElevatedButton( statesController: controller, onPressed: () { }, child: const Text('button'), ) : ElevatedButton.icon( statesController: controller, onPressed: () { }, icon: icon, label: const Text('button'), ), ), ), ); expect(controller.value, <MaterialState>{}); expect(count, 0); final Offset center = tester.getCenter(find.byType(Text)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered}); expect(count, 1); await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{}); expect(count, 2); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered}); expect(count, 3); await gesture.down(center); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed}); expect(count, 4); await gesture.up(); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered}); expect(count, 5); await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{}); expect(count, 6); await gesture.down(center); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed}); expect(count, 8); // adds hovered and pressed - two changes // If the button is rebuilt disabled, then the pressed state is // removed. await tester.pumpWidget( MaterialApp( home: Center( child: icon == null ? ElevatedButton( statesController: controller, onPressed: null, child: const Text('button'), ) : ElevatedButton.icon( statesController: controller, onPressed: null, icon: icon, label: const Text('button'), ), ), ), ); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.disabled}); expect(count, 10); // removes pressed and adds disabled - two changes await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.disabled}); expect(count, 11); await gesture.removePointer(); } testWidgets('ElevatedButton statesController', (WidgetTester tester) async { testStatesController(null, tester); }); testWidgets('ElevatedButton.icon statesController', (WidgetTester tester) async { testStatesController(const Icon(Icons.add), tester); }); testWidgets('Disabled ElevatedButton statesController', (WidgetTester tester) async { int count = 0; void valueChanged() { count += 1; } final MaterialStatesController controller = MaterialStatesController(); addTearDown(controller.dispose); controller.addListener(valueChanged); await tester.pumpWidget( MaterialApp( home: Center( child: ElevatedButton( statesController: controller, onPressed: null, child: const Text('button'), ), ), ), ); expect(controller.value, <MaterialState>{MaterialState.disabled}); expect(count, 1); }); testWidgets('ElevatedButton backgroundBuilder and foregroundBuilder', (WidgetTester tester) async { const Color backgroundColor = Color(0xFF000011); const Color foregroundColor = Color(0xFF000022); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return DecoratedBox( decoration: const BoxDecoration( color: backgroundColor, ), child: child, ); }, foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return DecoratedBox( decoration: const BoxDecoration( color: foregroundColor, ), child: child, ); }, ), onPressed: () { }, child: const Text('button'), ), ), ); BoxDecoration boxDecorationOf(Finder finder) { return tester.widget<DecoratedBox>(finder).decoration as BoxDecoration; } final Finder decorations = find.descendant( of: find.byType(ElevatedButton), matching: find.byType(DecoratedBox), ); expect(boxDecorationOf(decorations.at(0)).color, backgroundColor); expect(boxDecorationOf(decorations.at(1)).color, foregroundColor); Text textChildOf(Finder finder) { return tester.widget<Text>( find.descendant( of: finder, matching: find.byType(Text), ), ); } expect(textChildOf(decorations.at(0)).data, 'button'); expect(textChildOf(decorations.at(1)).data, 'button'); }); testWidgets('ElevatedButton backgroundBuilder drops button child and foregroundBuilder return value', (WidgetTester tester) async { const Color backgroundColor = Color(0xFF000011); const Color foregroundColor = Color(0xFF000022); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return const DecoratedBox( decoration: BoxDecoration( color: backgroundColor, ), ); }, foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return const DecoratedBox( decoration: BoxDecoration( color: foregroundColor, ), ); }, ), onPressed: () { }, child: const Text('button'), ), ), ); final Finder background = find.descendant( of: find.byType(ElevatedButton), matching: find.byType(DecoratedBox), ); expect(background, findsOneWidget); expect(find.text('button'), findsNothing); }); testWidgets('ElevatedButton foregroundBuilder drops button child', (WidgetTester tester) async { const Color foregroundColor = Color(0xFF000022); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ElevatedButton( style: ElevatedButton.styleFrom( foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return const DecoratedBox( decoration: BoxDecoration( color: foregroundColor, ), ); }, ), onPressed: () { }, child: const Text('button'), ), ), ); final Finder foreground = find.descendant( of: find.byType(ElevatedButton), matching: find.byType(DecoratedBox), ); expect(foreground, findsOneWidget); expect(find.text('button'), findsNothing); }); testWidgets('ElevatedButton foreground and background builders are applied to the correct states', (WidgetTester tester) async { Set<MaterialState> foregroundStates = <MaterialState>{}; Set<MaterialState> backgroundStates = <MaterialState>{}; final FocusNode focusNode = FocusNode(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: ElevatedButton( style: ButtonStyle( backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { backgroundStates = states; return child!; }, foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { foregroundStates = states; return child!; }, ), onPressed: () {}, focusNode: focusNode, child: const Text('button'), ), ), ), ), ); // Default. expect(backgroundStates.isEmpty, isTrue); expect(foregroundStates.isEmpty, isTrue); const Set<MaterialState> focusedStates = <MaterialState>{MaterialState.focused}; const Set<MaterialState> focusedHoveredStates = <MaterialState>{MaterialState.focused, MaterialState.hovered}; const Set<MaterialState> focusedHoveredPressedStates = <MaterialState>{MaterialState.focused, MaterialState.hovered, MaterialState.pressed}; bool sameStates(Set<MaterialState> expectedValue, Set<MaterialState> actualValue) { return expectedValue.difference(actualValue).isEmpty && actualValue.difference(expectedValue).isEmpty; } // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(sameStates(focusedStates, backgroundStates), isTrue); expect(sameStates(focusedStates, foregroundStates), isTrue); // Hovered. final Offset center = tester.getCenter(find.byType(ElevatedButton)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(sameStates(focusedHoveredStates, backgroundStates), isTrue); expect(sameStates(focusedHoveredStates, foregroundStates), isTrue); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. expect(sameStates(focusedHoveredPressedStates, backgroundStates), isTrue); expect(sameStates(focusedHoveredPressedStates, foregroundStates), isTrue); focusNode.dispose(); }); testWidgets('Default iconAlignment', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection }) { return MaterialApp( home: Directionality( textDirection: textDirection, child: Center( child: ElevatedButton.icon( onPressed: () {}, icon: const Icon(Icons.add), label: const Text('button'), ), ), ), ); } // Test default iconAlignment when textDirection is ltr. await tester.pumpWidget(buildWidget(textDirection: TextDirection.ltr)); final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); // The icon is aligned to the left of the button. expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); // 16.0 - padding between icon and button edge. // Test default iconAlignment when textDirection is rtl. await tester.pumpWidget(buildWidget(textDirection: TextDirection.rtl)); final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); // The icon is aligned to the right of the button. expect(buttonTopRight.dx, iconTopRight.dx + 16.0); // 16.0 - padding between icon and button edge. }); testWidgets('iconAlignment can be customized', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection, required IconAlignment iconAlignment, }) { return MaterialApp( home: Directionality( textDirection: textDirection, child: Center( child: ElevatedButton.icon( onPressed: () {}, icon: const Icon(Icons.add), label: const Text('button'), iconAlignment: iconAlignment, ), ), ), ); } // Test iconAlignment when textDirection is ltr. await tester.pumpWidget( buildWidget( textDirection: TextDirection.ltr, iconAlignment: IconAlignment.start, ), ); Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); // The icon is aligned to the left of the button. expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); // 16.0 - padding between icon and button edge. // Test iconAlignment when textDirection is ltr. await tester.pumpWidget( buildWidget( textDirection: TextDirection.ltr, iconAlignment: IconAlignment.end, ), ); Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); // The icon is aligned to the right of the button. expect(buttonTopRight.dx, iconTopRight.dx + 24.0); // 24.0 - padding between icon and button edge. // Test iconAlignment when textDirection is rtl. await tester.pumpWidget( buildWidget( textDirection: TextDirection.rtl, iconAlignment: IconAlignment.start, ), ); buttonTopRight = tester.getTopRight(find.byType(Material).last); iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); // The icon is aligned to the right of the button. expect(buttonTopRight.dx, iconTopRight.dx + 16.0); // 16.0 - padding between icon and button edge. // Test iconAlignment when textDirection is rtl. await tester.pumpWidget( buildWidget( textDirection: TextDirection.rtl, iconAlignment: IconAlignment.end, ), ); buttonTopLeft = tester.getTopLeft(find.byType(Material).last); iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); // The icon is aligned to the left of the button. expect(buttonTopLeft.dx, iconTopLeft.dx - 24.0); // 24.0 - padding between icon and button edge. }); } TextStyle _iconStyle(WidgetTester tester, IconData icon) { final RichText iconRichText = tester.widget<RichText>( find.descendant(of: find.byIcon(icon), matching: find.byType(RichText)), ); return iconRichText.text.style!; }
flutter/packages/flutter/test/material/elevated_button_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/elevated_button_test.dart", "repo_id": "flutter", "token_count": 33901 }
713
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) @TestOn('!chrome') library; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; import 'feedback_tester.dart'; void main() { final ThemeData material3Theme = ThemeData(useMaterial3: true); final ThemeData material2Theme = ThemeData(useMaterial3: false); testWidgets('Floating Action Button control test', (WidgetTester tester) async { bool didPressButton = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: FloatingActionButton( onPressed: () { didPressButton = true; }, child: const Icon(Icons.add), ), ), ), ); expect(didPressButton, isFalse); await tester.tap(find.byType(Icon)); expect(didPressButton, isTrue); }); testWidgets('Floating Action Button tooltip', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () {}, tooltip: 'Add', child: const Icon(Icons.add), ), ), ), ); await tester.tap(find.byType(Icon)); expect(find.byTooltip('Add'), findsOneWidget); }); // Regression test for: https://github.com/flutter/flutter/pull/21084 testWidgets('Floating Action Button tooltip (long press button edge)', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () {}, tooltip: 'Add', child: const Icon(Icons.add), ), ), ), ); expect(find.text('Add'), findsNothing); await tester.longPressAt(_rightEdgeOfFab(tester)); await tester.pumpAndSettle(); expect(find.text('Add'), findsOneWidget); }); // Regression test for: https://github.com/flutter/flutter/pull/21084 testWidgets('Floating Action Button tooltip (long press button edge - no child)', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () {}, tooltip: 'Add', ), ), ), ); expect(find.text('Add'), findsNothing); await tester.longPressAt(_rightEdgeOfFab(tester)); await tester.pumpAndSettle(); expect(find.text('Add'), findsOneWidget); }); testWidgets('Floating Action Button tooltip (no child)', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () {}, tooltip: 'Add', ), ), ), ); expect(find.text('Add'), findsNothing); // Test hover for tooltip. final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); addTearDown(() => gesture.removePointer()); await gesture.moveTo(tester.getCenter(find.byType(FloatingActionButton))); await tester.pumpAndSettle(); expect(find.text('Add'), findsOneWidget); await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); expect(find.text('Add'), findsNothing); // Test long press for tooltip. await tester.longPress(find.byType(FloatingActionButton)); await tester.pumpAndSettle(); expect(find.text('Add'), findsOneWidget); }); testWidgets('Floating Action Button tooltip reacts when disabled', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, tooltip: 'Add', ), ), ), ); expect(find.text('Add'), findsNothing); // Test hover for tooltip. final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); addTearDown(() => gesture.removePointer()); await tester.pumpAndSettle(); await gesture.moveTo(tester.getCenter(find.byType(FloatingActionButton))); await tester.pumpAndSettle(); expect(find.text('Add'), findsOneWidget); await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); expect(find.text('Add'), findsNothing); // Test long press for tooltip. await tester.longPress(find.byType(FloatingActionButton)); await tester.pumpAndSettle(); expect(find.text('Add'), findsOneWidget); }); testWidgets('Floating Action Button elevation when highlighted - effect', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: material3Theme, home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, ), ), ), ); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); final TestGesture gesture = await tester.press(find.byType(PhysicalShape)); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, highlightElevation: 20.0, ), ), ), ); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 20.0); await gesture.up(); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 20.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); }); testWidgets('Floating Action Button elevation when disabled - defaults', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, ), ), ), ); // Disabled elevation defaults to regular default elevation. expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); }); testWidgets('Floating Action Button elevation when disabled - override', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, disabledElevation: 0, ), ), ), ); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 0.0); }); testWidgets('Floating Action Button elevation when disabled - effect', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, ), ), ), ); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pumpWidget( const MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, disabledElevation: 3.0, ), ), ), ); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 3.0); await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, disabledElevation: 3.0, ), ), ), ); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 3.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); }); testWidgets('Floating Action Button elevation when disabled while highlighted - effect', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: material3Theme, home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, ), ), ), ); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.press(find.byType(PhysicalShape)); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pumpWidget( MaterialApp( theme: material3Theme, home: const Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, ), ), ), ); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pumpWidget( MaterialApp( theme: material3Theme, home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, ), ), ), ); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); }); testWidgets('Floating Action Button states elevation', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); await tester.pumpWidget( MaterialApp( theme: material3Theme, home: Scaffold( body: FloatingActionButton.extended( label: const Text('tooltip'), onPressed: () {}, focusNode: focusNode, ), ), ), ); final Finder fabFinder = find.byType(PhysicalShape); PhysicalShape getFABWidget(Finder finder) => tester.widget<PhysicalShape>(finder); // Default, not disabled. expect(getFABWidget(fabFinder).elevation, 6); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(getFABWidget(fabFinder).elevation, 6); // Hovered. final Offset center = tester.getCenter(fabFinder); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(getFABWidget(fabFinder).elevation, 8); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. expect(getFABWidget(fabFinder).elevation, 6); focusNode.dispose(); }); testWidgets('FlatActionButton mini size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async { final Key key1 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Theme( data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.padded), child: Scaffold( floatingActionButton: FloatingActionButton( key: key1, mini: true, onPressed: null, ), ), ), ), ); expect(tester.getSize(find.byKey(key1)), const Size(48.0, 48.0)); final Key key2 = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Theme( data: ThemeData(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap), child: Scaffold( floatingActionButton: FloatingActionButton( key: key2, mini: true, onPressed: null, ), ), ), ), ); expect(tester.getSize(find.byKey(key2)), const Size(40.0, 40.0)); }); testWidgets('FloatingActionButton.isExtended', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: material3Theme, home: const Scaffold( floatingActionButton: FloatingActionButton(onPressed: null), ), ), ); final Finder fabFinder = find.byType(FloatingActionButton); FloatingActionButton getFabWidget() { return tester.widget<FloatingActionButton>(fabFinder); } final Finder materialButtonFinder = find.byType(RawMaterialButton); RawMaterialButton getRawMaterialButtonWidget() { return tester.widget<RawMaterialButton>(materialButtonFinder); } expect(getFabWidget().isExtended, false); expect( getRawMaterialButtonWidget().shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))) ); await tester.pumpWidget( const MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton.extended( label: SizedBox( width: 100.0, child: Text('label'), ), icon: Icon(Icons.android), onPressed: null, ), ), ), ); expect(getFabWidget().isExtended, true); expect( getRawMaterialButtonWidget().shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))) ); expect(find.text('label'), findsOneWidget); expect(find.byType(Icon), findsOneWidget); // Verify that the widget's height is 56 and that its internal /// horizontal layout is: 16 icon 8 label 20 expect(tester.getSize(fabFinder).height, 56.0); final double fabLeft = tester.getTopLeft(fabFinder).dx; final double fabRight = tester.getTopRight(fabFinder).dx; final double iconLeft = tester.getTopLeft(find.byType(Icon)).dx; final double iconRight = tester.getTopRight(find.byType(Icon)).dx; final double labelLeft = tester.getTopLeft(find.text('label')).dx; final double labelRight = tester.getTopRight(find.text('label')).dx; expect(iconLeft - fabLeft, 16.0); expect(labelLeft - iconRight, 8.0); expect(fabRight - labelRight, 20.0); // The overall width of the button is: // 168 = 16 + 24(icon) + 8 + 100(label) + 20 expect(tester.getSize(find.byType(Icon)).width, 24.0); expect(tester.getSize(find.text('label')).width, 100.0); expect(tester.getSize(fabFinder).width, 168); }); testWidgets('FloatingActionButton.isExtended (without icon)', (WidgetTester tester) async { final Finder fabFinder = find.byType(FloatingActionButton); FloatingActionButton getFabWidget() { return tester.widget<FloatingActionButton>(fabFinder); } final Finder materialButtonFinder = find.byType(RawMaterialButton); RawMaterialButton getRawMaterialButtonWidget() { return tester.widget<RawMaterialButton>(materialButtonFinder); } await tester.pumpWidget( MaterialApp( theme: material3Theme, home: const Scaffold( floatingActionButton: FloatingActionButton.extended( label: SizedBox( width: 100.0, child: Text('label'), ), onPressed: null, ), ), ), ); expect(getFabWidget().isExtended, true); expect( getRawMaterialButtonWidget().shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))) ); expect(find.text('label'), findsOneWidget); expect(find.byType(Icon), findsNothing); // Verify that the widget's height is 56 and that its internal /// horizontal layout is: 20 label 20 expect(tester.getSize(fabFinder).height, 56.0); final double fabLeft = tester.getTopLeft(fabFinder).dx; final double fabRight = tester.getTopRight(fabFinder).dx; final double labelLeft = tester.getTopLeft(find.text('label')).dx; final double labelRight = tester.getTopRight(find.text('label')).dx; expect(labelLeft - fabLeft, 20.0); expect(fabRight - labelRight, 20.0); // The overall width of the button is: // 140 = 20 + 100(label) + 20 expect(tester.getSize(find.text('label')).width, 100.0); expect(tester.getSize(fabFinder).width, 140); }); testWidgets('Floating Action Button heroTag', (WidgetTester tester) async { late BuildContext theContext; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { theContext = context; return const FloatingActionButton(heroTag: 1, onPressed: null); }, ), floatingActionButton: const FloatingActionButton(heroTag: 2, onPressed: null), ), ), ); Navigator.push(theContext, PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return const Placeholder(); }, )); await tester.pump(); // this would fail if heroTag was the same on both FloatingActionButtons (see below). }); testWidgets('Floating Action Button heroTag - with duplicate', (WidgetTester tester) async { late BuildContext theContext; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { theContext = context; return const FloatingActionButton(onPressed: null); }, ), floatingActionButton: const FloatingActionButton(onPressed: null), ), ), ); Navigator.push(theContext, PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return const Placeholder(); }, )); await tester.pump(); expect(tester.takeException().toString(), contains('FloatingActionButton')); }); testWidgets('Floating Action Button heroTag - with duplicate', (WidgetTester tester) async { late BuildContext theContext; await tester.pumpWidget( MaterialApp( home: Scaffold( body: Builder( builder: (BuildContext context) { theContext = context; return const FloatingActionButton(heroTag: 'xyzzy', onPressed: null); }, ), floatingActionButton: const FloatingActionButton(heroTag: 'xyzzy', onPressed: null), ), ), ); Navigator.push(theContext, PageRouteBuilder<void>( pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return const Placeholder(); }, )); await tester.pump(); expect(tester.takeException().toString(), contains('xyzzy')); }); testWidgets('Floating Action Button semantics (enabled)', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: FloatingActionButton( onPressed: () { }, child: const Icon(Icons.add, semanticLabel: 'Add'), ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( label: 'Add', flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('Floating Action Button semantics (disabled)', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Center( child: FloatingActionButton( onPressed: null, child: Icon(Icons.add, semanticLabel: 'Add'), ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( label: 'Add', flags: <SemanticsFlag>[ SemanticsFlag.isButton, SemanticsFlag.hasEnabledState, ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('Tooltip is used as semantics tooltip', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, tooltip: 'Add Photo', child: const Icon(Icons.add_a_photo), ), ), ), ); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.scopesRoute, ], children: <TestSemantics>[ TestSemantics( tooltip: 'Add Photo', actions: <SemanticsAction>[ SemanticsAction.tap, ], flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreId: true, ignoreRect: true)); semantics.dispose(); }); testWidgets('extended FAB hero transitions succeed', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/18782 await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: Builder( builder: (BuildContext context) { // define context of Navigator.push() return FloatingActionButton.extended( icon: const Icon(Icons.add), label: const Text('A long FAB label'), onPressed: () { Navigator.push(context, MaterialPageRoute<void>( builder: (BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton.extended( icon: const Icon(Icons.add), label: const Text('X'), onPressed: () { }, ), body: Center( child: ElevatedButton( child: const Text('POP'), onPressed: () { Navigator.pop(context); }, ), ), ); }, )); }, ); }, ), body: const Center( child: Text('Hello World'), ), ), ), ); final Finder longFAB = find.text('A long FAB label'); final Finder shortFAB = find.text('X'); final Finder helloWorld = find.text('Hello World'); expect(longFAB, findsOneWidget); expect(shortFAB, findsNothing); expect(helloWorld, findsOneWidget); await tester.tap(longFAB); await tester.pumpAndSettle(); expect(shortFAB, findsOneWidget); expect(longFAB, findsNothing); // Trigger a hero transition from shortFAB to longFAB. await tester.tap(find.text('POP')); await tester.pumpAndSettle(); expect(longFAB, findsOneWidget); expect(shortFAB, findsNothing); expect(helloWorld, findsOneWidget); }); // This test prevents https://github.com/flutter/flutter/issues/20483 testWidgets('Floating Action Button clips ink splash and highlight', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget( MaterialApp( theme: material3Theme, home: Scaffold( body: Center( child: RepaintBoundary( key: key, child: FloatingActionButton( onPressed: () { }, child: const Icon(Icons.add), ), ), ), ), ), ); await tester.press(find.byKey(key)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1000)); await expectLater( find.byKey(key), matchesGoldenFile('floating_action_button_test.clip.png'), ); }); testWidgets('Floating Action Button changes mouse cursor when hovered', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Align( alignment: Alignment.topLeft, child: FloatingActionButton.extended( onPressed: () { }, mouseCursor: SystemMouseCursors.text, label: const Text('label'), icon: const Icon(Icons.android), ), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: tester.getCenter(find.byType(FloatingActionButton))); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Align( alignment: Alignment.topLeft, child: FloatingActionButton( onPressed: () { }, mouseCursor: SystemMouseCursors.text, child: const Icon(Icons.add), ), ), ), ), ); await gesture.moveTo(tester.getCenter(find.byType(FloatingActionButton))); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); // Test default cursor await tester.pumpWidget( MaterialApp( home: Scaffold( body: Align( alignment: Alignment.topLeft, child: FloatingActionButton( onPressed: () { }, child: const Icon(Icons.add), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); // Test default cursor when disabled await tester.pumpWidget( const MaterialApp( home: Scaffold( body: Align( alignment: Alignment.topLeft, child: FloatingActionButton( onPressed: null, child: Icon(Icons.add), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }); testWidgets('Floating Action Button has no clip by default', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: FloatingActionButton( focusNode: focusNode, onPressed: () { /* to make sure the button is enabled */ }, ), ), ); focusNode.unfocus(); await tester.pump(); expect( tester.renderObject(find.byType(FloatingActionButton)), paintsExactlyCountTimes(#clipPath, 0), ); focusNode.dispose(); }); testWidgets('Can find FloatingActionButton semantics', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: FloatingActionButton(onPressed: () {}), )); expect( tester.getSemantics(find.byType(FloatingActionButton)), matchesSemantics( hasTapAction: true, hasEnabledState: true, isButton: true, isEnabled: true, isFocusable: true, ), ); }); testWidgets('Foreground color applies to icon on fab', (WidgetTester tester) async { const Color foregroundColor = Color(0xcafefeed); await tester.pumpWidget(MaterialApp( home: FloatingActionButton( onPressed: () {}, foregroundColor: foregroundColor, child: const Icon(Icons.access_alarm), ), )); final RichText iconRichText = tester.widget<RichText>( find.descendant(of: find.byIcon(Icons.access_alarm), matching: find.byType(RichText)), ); expect(iconRichText.text.style!.color, foregroundColor); }); testWidgets('FloatingActionButton uses custom splash color', (WidgetTester tester) async { const Color splashColor = Color(0xcafefeed); await tester.pumpWidget(MaterialApp( theme: material2Theme, home: FloatingActionButton( onPressed: () {}, splashColor: splashColor, child: const Icon(Icons.access_alarm), ), )); await tester.press(find.byType(FloatingActionButton)); await tester.pumpAndSettle(); expect( find.byType(FloatingActionButton), paints..circle(color: splashColor), ); }); testWidgets('extended FAB does not show label when isExtended is false', (WidgetTester tester) async { const Key iconKey = Key('icon'); const Key labelKey = Key('label'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: FloatingActionButton.extended( isExtended: false, label: const Text('', key: labelKey), icon: const Icon(Icons.add, key: iconKey), onPressed: () {}, ), ), ); // Verify that Icon is present and label is not. expect(find.byKey(iconKey), findsOneWidget); expect(find.byKey(labelKey), findsNothing); }); testWidgets('FloatingActionButton.small configures correct size', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton.small( key: key, materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, onPressed: null, ), ), ), ); expect(tester.getSize(find.byKey(key)), const Size(40.0, 40.0)); }); testWidgets('FloatingActionButton.large configures correct size', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton.large( key: key, onPressed: null, ), ), ), ); expect(tester.getSize(find.byKey(key)), const Size(96.0, 96.0)); }); testWidgets('FloatingActionButton.extended can customize spacing', (WidgetTester tester) async { const Key iconKey = Key('icon'); const Key labelKey = Key('label'); const double spacing = 33.0; const EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(start: 5.0, end: 6.0); await tester.pumpWidget( MaterialApp( home: Scaffold( floatingActionButton: FloatingActionButton.extended( label: const Text('', key: labelKey), icon: const Icon(Icons.add, key: iconKey), extendedIconLabelSpacing: spacing, extendedPadding: padding, onPressed: () {}, ), ), ), ); expect(tester.getTopLeft(find.byKey(labelKey)).dx - tester.getTopRight(find.byKey(iconKey)).dx, spacing); expect(tester.getTopLeft(find.byKey(iconKey)).dx - tester.getTopLeft(find.byType(FloatingActionButton)).dx, padding.start); expect(tester.getTopRight(find.byType(FloatingActionButton)).dx - tester.getTopRight(find.byKey(labelKey)).dx, padding.end); }); testWidgets('FloatingActionButton.extended can customize text style', (WidgetTester tester) async { const Key labelKey = Key('label'); const TextStyle style = TextStyle(letterSpacing: 2.0); await tester.pumpWidget( MaterialApp( theme: material2Theme, home: Scaffold( floatingActionButton: FloatingActionButton.extended( label: const Text('', key: labelKey), icon: const Icon(Icons.add), extendedTextStyle: style, onPressed: () {}, ), ), ), ); final RawMaterialButton rawMaterialButton = tester.widget<RawMaterialButton>( find.descendant( of: find.byType(FloatingActionButton), matching: find.byType(RawMaterialButton), ), ); // The color comes from the default color scheme's onSecondary value. expect(rawMaterialButton.textStyle, style.copyWith(color: const Color(0xffffffff))); }); 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('Floating Action Button elevation when highlighted - effect', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: material2Theme, home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, ), ), ), ); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); final TestGesture gesture = await tester.press(find.byType(PhysicalShape)); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 12.0); await tester.pumpWidget( MaterialApp( theme: material2Theme, home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, highlightElevation: 20.0, ), ), ), ); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 12.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 20.0); await gesture.up(); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 20.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); }); testWidgets('Floating Action Button elevation when disabled while highlighted - effect', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: material2Theme, home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, ), ), ), ); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.press(find.byType(PhysicalShape)); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 12.0); await tester.pumpWidget( MaterialApp( theme: material2Theme, home: const Scaffold( floatingActionButton: FloatingActionButton( onPressed: null, ), ), ), ); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 12.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pumpWidget( MaterialApp( theme: material2Theme, home: Scaffold( floatingActionButton: FloatingActionButton( onPressed: () { }, ), ), ), ); await tester.pump(); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); await tester.pump(const Duration(seconds: 1)); expect(tester.widget<PhysicalShape>(find.byType(PhysicalShape)).elevation, 6.0); }); testWidgets('Floating Action Button states elevation', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); await tester.pumpWidget( MaterialApp( theme: material2Theme, home: Scaffold( body: FloatingActionButton.extended( label: const Text('tooltip'), onPressed: () {}, focusNode: focusNode, ), ), ), ); final Finder fabFinder = find.byType(PhysicalShape); PhysicalShape getFABWidget(Finder finder) => tester.widget<PhysicalShape>(finder); // Default, not disabled. expect(getFABWidget(fabFinder).elevation, 6); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(getFABWidget(fabFinder).elevation, 6); // Hovered. final Offset center = tester.getCenter(fabFinder); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(getFABWidget(fabFinder).elevation, 8); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. expect(getFABWidget(fabFinder).elevation, 12); focusNode.dispose(); }); testWidgets('FloatingActionButton.isExtended', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: material2Theme, home: const Scaffold( floatingActionButton: FloatingActionButton(onPressed: null), ), ), ); final Finder fabFinder = find.byType(FloatingActionButton); FloatingActionButton getFabWidget() { return tester.widget<FloatingActionButton>(fabFinder); } final Finder materialButtonFinder = find.byType(RawMaterialButton); RawMaterialButton getRawMaterialButtonWidget() { return tester.widget<RawMaterialButton>(materialButtonFinder); } expect(getFabWidget().isExtended, false); expect(getRawMaterialButtonWidget().shape, const CircleBorder()); await tester.pumpWidget( MaterialApp( theme: material2Theme, home: const Scaffold( floatingActionButton: FloatingActionButton.extended( label: SizedBox( width: 100.0, child: Text('label'), ), icon: Icon(Icons.android), onPressed: null, ), ), ), ); expect(getFabWidget().isExtended, true); expect(getRawMaterialButtonWidget().shape, const StadiumBorder()); expect(find.text('label'), findsOneWidget); expect(find.byType(Icon), findsOneWidget); // Verify that the widget's height is 48 and that its internal /// horizontal layout is: 16 icon 8 label 20 expect(tester.getSize(fabFinder).height, 48.0); final double fabLeft = tester.getTopLeft(fabFinder).dx; final double fabRight = tester.getTopRight(fabFinder).dx; final double iconLeft = tester.getTopLeft(find.byType(Icon)).dx; final double iconRight = tester.getTopRight(find.byType(Icon)).dx; final double labelLeft = tester.getTopLeft(find.text('label')).dx; final double labelRight = tester.getTopRight(find.text('label')).dx; expect(iconLeft - fabLeft, 16.0); expect(labelLeft - iconRight, 8.0); expect(fabRight - labelRight, 20.0); // The overall width of the button is: // 168 = 16 + 24(icon) + 8 + 100(label) + 20 expect(tester.getSize(find.byType(Icon)).width, 24.0); expect(tester.getSize(find.text('label')).width, 100.0); expect(tester.getSize(fabFinder).width, 168); }); testWidgets('FloatingActionButton.isExtended (without icon)', (WidgetTester tester) async { final Finder fabFinder = find.byType(FloatingActionButton); FloatingActionButton getFabWidget() { return tester.widget<FloatingActionButton>(fabFinder); } final Finder materialButtonFinder = find.byType(RawMaterialButton); RawMaterialButton getRawMaterialButtonWidget() { return tester.widget<RawMaterialButton>(materialButtonFinder); } await tester.pumpWidget( MaterialApp( theme: material2Theme, home: const Scaffold( floatingActionButton: FloatingActionButton.extended( label: SizedBox( width: 100.0, child: Text('label'), ), onPressed: null, ), ), ), ); expect(getFabWidget().isExtended, true); expect(getRawMaterialButtonWidget().shape, const StadiumBorder()); expect(find.text('label'), findsOneWidget); expect(find.byType(Icon), findsNothing); // Verify that the widget's height is 48 and that its internal /// horizontal layout is: 20 label 20 expect(tester.getSize(fabFinder).height, 48.0); final double fabLeft = tester.getTopLeft(fabFinder).dx; final double fabRight = tester.getTopRight(fabFinder).dx; final double labelLeft = tester.getTopLeft(find.text('label')).dx; final double labelRight = tester.getTopRight(find.text('label')).dx; expect(labelLeft - fabLeft, 20.0); expect(fabRight - labelRight, 20.0); // The overall width of the button is: // 140 = 20 + 100(label) + 20 expect(tester.getSize(find.text('label')).width, 100.0); expect(tester.getSize(fabFinder).width, 140); }); // This test prevents https://github.com/flutter/flutter/issues/20483 testWidgets('Floating Action Button clips ink splash and highlight', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget( MaterialApp( theme: material2Theme, home: Scaffold( body: Center( child: RepaintBoundary( key: key, child: FloatingActionButton( onPressed: () { }, child: const Icon(Icons.add), ), ), ), ), ), ); await tester.press(find.byKey(key)); await tester.pump(); await tester.pump(const Duration(milliseconds: 1000)); await expectLater( find.byKey(key), matchesGoldenFile('floating_action_button_test_m2.clip.png'), ); }); }); group('feedback', () { late FeedbackTester feedback; setUp(() { feedback = FeedbackTester(); }); tearDown(() { feedback.dispose(); }); testWidgets('FloatingActionButton with enabled feedback', (WidgetTester tester) async { const bool enableFeedback = true; await tester.pumpWidget(MaterialApp( home: FloatingActionButton( onPressed: () {}, enableFeedback: enableFeedback, child: const Icon(Icons.access_alarm), ), )); await tester.tap(find.byType(RawMaterialButton)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 1); expect(feedback.hapticCount, 0); }); testWidgets('FloatingActionButton with disabled feedback', (WidgetTester tester) async { const bool enableFeedback = false; await tester.pumpWidget(MaterialApp( home: FloatingActionButton( onPressed: () {}, enableFeedback: enableFeedback, child: const Icon(Icons.access_alarm), ), )); await tester.tap(find.byType(RawMaterialButton)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 0); expect(feedback.hapticCount, 0); }); testWidgets('FloatingActionButton with enabled feedback by default', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: FloatingActionButton( onPressed: () {}, child: const Icon(Icons.access_alarm), ), )); await tester.tap(find.byType(RawMaterialButton)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 1); expect(feedback.hapticCount, 0); }); testWidgets('FloatingActionButton with disabled feedback using FloatingActionButtonTheme', (WidgetTester tester) async { const bool enableFeedbackTheme = false; final ThemeData theme = ThemeData( floatingActionButtonTheme: const FloatingActionButtonThemeData( enableFeedback: enableFeedbackTheme, ), ); await tester.pumpWidget(MaterialApp( home: Theme( data: theme, child: FloatingActionButton( onPressed: () {}, child: const Icon(Icons.access_alarm), ), ), )); await tester.tap(find.byType(RawMaterialButton)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 0); expect(feedback.hapticCount, 0); }); testWidgets('FloatingActionButton.enableFeedback is overridden by FloatingActionButtonThemeData.enableFeedback', (WidgetTester tester) async { const bool enableFeedbackTheme = false; const bool enableFeedback = true; final ThemeData theme = ThemeData( floatingActionButtonTheme: const FloatingActionButtonThemeData( enableFeedback: enableFeedbackTheme, ), ); await tester.pumpWidget(MaterialApp( home: Theme( data: theme, child: FloatingActionButton( enableFeedback: enableFeedback, onPressed: () {}, child: const Icon(Icons.access_alarm), ), ), )); await tester.tap(find.byType(RawMaterialButton)); await tester.pump(const Duration(seconds: 1)); expect(feedback.clickSoundCount, 1); expect(feedback.hapticCount, 0); }); }); } Offset _rightEdgeOfFab(WidgetTester tester) { final Finder fab = find.byType(FloatingActionButton); return tester.getRect(fab).centerRight - const Offset(1.0, 0.0); }
flutter/packages/flutter/test/material/floating_action_button_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/floating_action_button_test.dart", "repo_id": "flutter", "token_count": 20442 }
714
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; class TestIcon extends StatefulWidget { const TestIcon({ super.key }); @override TestIconState createState() => TestIconState(); } class TestIconState extends State<TestIcon> { late IconThemeData iconTheme; @override Widget build(BuildContext context) { iconTheme = IconTheme.of(context); return const Icon(Icons.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() { test('ListTileThemeData copyWith, ==, hashCode, basics', () { expect(const ListTileThemeData(), const ListTileThemeData().copyWith()); expect(const ListTileThemeData().hashCode, const ListTileThemeData().copyWith().hashCode); }); test('ListTileThemeData lerp special cases', () { expect(ListTileThemeData.lerp(null, null, 0), null); const ListTileThemeData data = ListTileThemeData(); expect(identical(ListTileThemeData.lerp(data, data, 0.5), data), true); }); test('ListTileThemeData defaults', () { const ListTileThemeData themeData = ListTileThemeData(); expect(themeData.dense, null); expect(themeData.shape, null); expect(themeData.style, null); expect(themeData.selectedColor, null); expect(themeData.iconColor, null); expect(themeData.textColor, null); expect(themeData.titleTextStyle, null); expect(themeData.subtitleTextStyle, null); expect(themeData.leadingAndTrailingTextStyle, null); expect(themeData.contentPadding, null); expect(themeData.tileColor, null); expect(themeData.selectedTileColor, null); expect(themeData.horizontalTitleGap, null); expect(themeData.minVerticalPadding, null); expect(themeData.minLeadingWidth, null); expect(themeData.minTileHeight, null); expect(themeData.enableFeedback, null); expect(themeData.mouseCursor, null); expect(themeData.visualDensity, null); expect(themeData.titleAlignment, null); }); testWidgets('Default ListTileThemeData debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const ListTileThemeData().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('ListTileThemeData implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); const ListTileThemeData( dense: true, shape: StadiumBorder(), style: ListTileStyle.drawer, selectedColor: Color(0x00000001), iconColor: Color(0x00000002), textColor: Color(0x00000003), titleTextStyle: TextStyle(color: Color(0x00000004)), subtitleTextStyle: TextStyle(color: Color(0x00000005)), leadingAndTrailingTextStyle: TextStyle(color: Color(0x00000006)), contentPadding: EdgeInsets.all(100), tileColor: Color(0x00000007), selectedTileColor: Color(0x00000008), horizontalTitleGap: 200, minVerticalPadding: 300, minLeadingWidth: 400, minTileHeight: 30, enableFeedback: true, mouseCursor: MaterialStateMouseCursor.clickable, visualDensity: VisualDensity.comfortable, titleAlignment: ListTileTitleAlignment.top, ).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>[ 'dense: true', 'shape: StadiumBorder(BorderSide(width: 0.0, style: none))', 'style: drawer', 'selectedColor: Color(0x00000001)', 'iconColor: Color(0x00000002)', 'textColor: Color(0x00000003)', 'titleTextStyle: TextStyle(inherit: true, color: Color(0x00000004))', 'subtitleTextStyle: TextStyle(inherit: true, color: Color(0x00000005))', 'leadingAndTrailingTextStyle: TextStyle(inherit: true, color: Color(0x00000006))', 'contentPadding: EdgeInsets.all(100.0)', 'tileColor: Color(0x00000007)', 'selectedTileColor: Color(0x00000008)', 'horizontalTitleGap: 200.0', 'minVerticalPadding: 300.0', 'minLeadingWidth: 400.0', 'minTileHeight: 30.0', 'enableFeedback: true', 'mouseCursor: WidgetStateMouseCursor(clickable)', 'visualDensity: VisualDensity#00000(h: -1.0, v: -1.0)(horizontal: -1.0, vertical: -1.0)', 'titleAlignment: ListTileTitleAlignment.top', ]), ); }); testWidgets('ListTileTheme backwards compatibility constructor', (WidgetTester tester) async { late ListTileThemeData theme; await tester.pumpWidget( MaterialApp( home: Material( child: ListTileTheme( dense: true, shape: const StadiumBorder(), style: ListTileStyle.drawer, selectedColor: const Color(0x00000001), iconColor: const Color(0x00000002), textColor: const Color(0x00000003), contentPadding: const EdgeInsets.all(100), tileColor: const Color(0x00000004), selectedTileColor: const Color(0x00000005), horizontalTitleGap: 200, minVerticalPadding: 300, minLeadingWidth: 400, enableFeedback: true, mouseCursor: MaterialStateMouseCursor.clickable, child: Center( child: Builder( builder: (BuildContext context) { theme = ListTileTheme.of(context); return const Placeholder(); }, ), ), ), ), ), ); expect(theme.dense, true); expect(theme.shape, const StadiumBorder()); expect(theme.style, ListTileStyle.drawer); expect(theme.selectedColor, const Color(0x00000001)); expect(theme.iconColor, const Color(0x00000002)); expect(theme.textColor, const Color(0x00000003)); expect(theme.contentPadding, const EdgeInsets.all(100)); expect(theme.tileColor, const Color(0x00000004)); expect(theme.selectedTileColor, const Color(0x00000005)); expect(theme.horizontalTitleGap, 200); expect(theme.minVerticalPadding, 300); expect(theme.minLeadingWidth, 400); expect(theme.enableFeedback, true); expect(theme.mouseCursor, MaterialStateMouseCursor.clickable); }); testWidgets('ListTileTheme', (WidgetTester tester) async { final Key listTileKey = UniqueKey(); final Key titleKey = UniqueKey(); final Key subtitleKey = UniqueKey(); final Key leadingKey = UniqueKey(); final Key trailingKey = UniqueKey(); late ThemeData theme; Widget buildFrame({ bool enabled = true, bool dense = false, bool selected = false, ShapeBorder? shape, Color? selectedColor, Color? iconColor, Color? textColor, }) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: ListTileTheme( data: ListTileThemeData( dense: dense, shape: shape, selectedColor: selectedColor, iconColor: iconColor, textColor: textColor, minVerticalPadding: 25.0, mouseCursor: MaterialStateProperty.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return SystemMouseCursors.forbidden; } return SystemMouseCursors.click; }), visualDensity: VisualDensity.compact, titleAlignment: ListTileTitleAlignment.bottom, ), child: Builder( builder: (BuildContext context) { theme = Theme.of(context); return ListTile( key: listTileKey, enabled: enabled, selected: selected, leading: TestIcon(key: leadingKey), trailing: TestIcon(key: trailingKey), title: TestText('title', key: titleKey), subtitle: TestText('subtitle', key: subtitleKey), ); }, ), ), ), ), ); } const Color green = Color(0xFF00FF00); const Color red = Color(0xFFFF0000); const ShapeBorder roundedShape = RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4.0)), ); Color iconColor(Key key) => tester.state<TestIconState>(find.byKey(key)).iconTheme.color!; Color textColor(Key key) => tester.state<TestTextState>(find.byKey(key)).textStyle.color!; ShapeBorder inkWellBorder() => tester.widget<InkWell>(find.descendant(of: find.byType(ListTile), matching: find.byType(InkWell))).customBorder!; // A selected ListTile's leading, trailing, and text get the primary color by default await tester.pumpWidget(buildFrame(selected: true)); await tester.pump(const Duration(milliseconds: 300)); // DefaultTextStyle changes animate expect(iconColor(leadingKey), theme.primaryColor); expect(iconColor(trailingKey), theme.primaryColor); expect(textColor(titleKey), theme.primaryColor); expect(textColor(subtitleKey), theme.primaryColor); // A selected ListTile's leading, trailing, and text get the ListTileTheme's selectedColor await tester.pumpWidget(buildFrame(selected: true, selectedColor: green)); await tester.pump(const Duration(milliseconds: 300)); // DefaultTextStyle changes animate expect(iconColor(leadingKey), green); expect(iconColor(trailingKey), green); expect(textColor(titleKey), green); expect(textColor(subtitleKey), green); // An unselected ListTile's leading and trailing get the ListTileTheme's iconColor // An unselected ListTile's title texts get the ListTileTheme's textColor await tester.pumpWidget(buildFrame(iconColor: red, textColor: green)); await tester.pump(const Duration(milliseconds: 300)); // DefaultTextStyle changes animate expect(iconColor(leadingKey), red); expect(iconColor(trailingKey), red); expect(textColor(titleKey), green); expect(textColor(subtitleKey), green); // If the item is disabled it's rendered with the theme's disabled color. await tester.pumpWidget(buildFrame(enabled: false)); await tester.pump(const Duration(milliseconds: 300)); // DefaultTextStyle changes animate expect(iconColor(leadingKey), theme.disabledColor); expect(iconColor(trailingKey), theme.disabledColor); expect(textColor(titleKey), theme.disabledColor); expect(textColor(subtitleKey), theme.disabledColor); // If the item is disabled it's rendered with the theme's disabled color. // Even if it's selected. await tester.pumpWidget(buildFrame(enabled: false, selected: true)); await tester.pump(const Duration(milliseconds: 300)); // DefaultTextStyle changes animate expect(iconColor(leadingKey), theme.disabledColor); expect(iconColor(trailingKey), theme.disabledColor); expect(textColor(titleKey), theme.disabledColor); expect(textColor(subtitleKey), theme.disabledColor); // A selected ListTile's InkWell gets the ListTileTheme's shape await tester.pumpWidget(buildFrame(selected: true, shape: roundedShape)); expect(inkWellBorder(), roundedShape); // Cursor updates when hovering disabled ListTile await tester.pumpWidget(buildFrame(enabled: false)); final Offset listTile = tester.getCenter(find.byKey(titleKey)); 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.forbidden); // VisualDensity is respected final RenderBox box = tester.renderObject(find.byKey(listTileKey)); expect(box.size, equals(const Size(800, 80.0))); // titleAlignment is respected. final Offset titleOffset = tester.getTopLeft(find.text('title')); final Offset leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); final Offset trailingOffset = tester.getTopRight(find.byKey(trailingKey)); expect(leadingOffset.dy - titleOffset.dy, 6); expect(trailingOffset.dy - titleOffset.dy, 6); }); testWidgets('ListTileTheme colors are applied to leading and trailing text widgets', (WidgetTester tester) async { final Key leadingKey = UniqueKey(); final Key trailingKey = UniqueKey(); const Color selectedColor = Colors.orange; const Color defaultColor = Colors.black; late ThemeData theme; Widget buildFrame({ bool enabled = true, bool selected = false, }) { return MaterialApp( home: Material( child: Center( child: ListTileTheme( data: const ListTileThemeData( selectedColor: selectedColor, textColor: defaultColor, ), 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 use ListTileTheme.textColor. expect(textColor(leadingKey), defaultColor); expect(textColor(trailingKey), defaultColor); await tester.pumpWidget(buildFrame(selected: true)); // Wait for text color to animate. await tester.pumpAndSettle(); // Selected color should use ListTileTheme.selectedColor. expect(textColor(leadingKey), selectedColor); expect(textColor(trailingKey), selectedColor); await tester.pumpWidget(buildFrame(enabled: false)); // Wait for text color to animate. await tester.pumpAndSettle(); // Disabled color should be ThemeData.disabledColor. expect(textColor(leadingKey), theme.disabledColor); expect(textColor(trailingKey), theme.disabledColor); }); testWidgets( "Material3 - ListTile respects ListTileTheme's titleTextStyle, subtitleTextStyle & leadingAndTrailingTextStyle", (WidgetTester tester) async { const TextStyle titleTextStyle = TextStyle( fontSize: 23.0, color: Color(0xffff0000), fontStyle: FontStyle.italic, ); const TextStyle subtitleTextStyle = TextStyle( fontSize: 20.0, color: Color(0xff00ff00), fontStyle: FontStyle.italic, ); const TextStyle leadingAndTrailingTextStyle = TextStyle( fontSize: 18.0, color: Color(0xff0000ff), fontStyle: FontStyle.italic, ); final ThemeData theme = ThemeData( useMaterial3: true, listTileTheme: const ListTileThemeData( titleTextStyle: titleTextStyle, subtitleTextStyle: subtitleTextStyle, leadingAndTrailingTextStyle: leadingAndTrailingTextStyle, ), ); Widget buildFrame() { return MaterialApp( theme: theme, home: Material( child: Center( child: Builder( builder: (BuildContext context) { return const ListTile( leading: TestText('leading'), title: TestText('title'), subtitle: TestText('subtitle'), trailing: TestText('trailing'), ); }, ), ), ), ); } await tester.pumpWidget(buildFrame()); final RenderParagraph leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.fontSize, leadingAndTrailingTextStyle.fontSize); expect(leading.text.style!.color, leadingAndTrailingTextStyle.color); expect(leading.text.style!.fontStyle, leadingAndTrailingTextStyle.fontStyle); final RenderParagraph title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.fontSize, titleTextStyle.fontSize); expect(title.text.style!.color, titleTextStyle.color); expect(title.text.style!.fontStyle, titleTextStyle.fontStyle); final RenderParagraph subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.fontSize, subtitleTextStyle.fontSize); expect(subtitle.text.style!.color, subtitleTextStyle.color); expect(subtitle.text.style!.fontStyle, subtitleTextStyle.fontStyle); final RenderParagraph trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.fontSize, leadingAndTrailingTextStyle.fontSize); expect(trailing.text.style!.color, leadingAndTrailingTextStyle.color); expect(trailing.text.style!.fontStyle, leadingAndTrailingTextStyle.fontStyle); }); testWidgets( "Material2 - ListTile respects ListTileTheme's titleTextStyle, subtitleTextStyle & leadingAndTrailingTextStyle", (WidgetTester tester) async { const TextStyle titleTextStyle = TextStyle( fontSize: 23.0, color: Color(0xffff0000), fontStyle: FontStyle.italic, ); const TextStyle subtitleTextStyle = TextStyle( fontSize: 20.0, color: Color(0xff00ff00), fontStyle: FontStyle.italic, ); const TextStyle leadingAndTrailingTextStyle = TextStyle( fontSize: 18.0, color: Color(0xff0000ff), fontStyle: FontStyle.italic, ); final ThemeData theme = ThemeData( useMaterial3: false, listTileTheme: const ListTileThemeData( titleTextStyle: titleTextStyle, subtitleTextStyle: subtitleTextStyle, leadingAndTrailingTextStyle: leadingAndTrailingTextStyle, ), ); Widget buildFrame() { return MaterialApp( theme: theme, home: Material( child: Center( child: Builder( builder: (BuildContext context) { return const ListTile( leading: TestText('leading'), title: TestText('title'), subtitle: TestText('subtitle'), trailing: TestText('trailing'), ); }, ), ), ), ); } await tester.pumpWidget(buildFrame()); final RenderParagraph leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.fontSize, leadingAndTrailingTextStyle.fontSize); expect(leading.text.style!.color, leadingAndTrailingTextStyle.color); expect(leading.text.style!.fontStyle, leadingAndTrailingTextStyle.fontStyle); final RenderParagraph title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.fontSize, titleTextStyle.fontSize); expect(title.text.style!.color, titleTextStyle.color); expect(title.text.style!.fontStyle, titleTextStyle.fontStyle); final RenderParagraph subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.fontSize, subtitleTextStyle.fontSize); expect(subtitle.text.style!.color, subtitleTextStyle.color); expect(subtitle.text.style!.fontStyle, subtitleTextStyle.fontStyle); final RenderParagraph trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.fontSize, leadingAndTrailingTextStyle.fontSize); expect(trailing.text.style!.color, leadingAndTrailingTextStyle.color); expect(trailing.text.style!.fontStyle, leadingAndTrailingTextStyle.fontStyle); }); testWidgets( "Material3 - ListTile's titleTextStyle, subtitleTextStyle & leadingAndTrailingTextStyle are overridden by ListTile properties", (WidgetTester tester) async { final ThemeData theme = ThemeData( useMaterial3: true, listTileTheme: const ListTileThemeData( titleTextStyle: TextStyle(fontSize: 20.0), subtitleTextStyle: TextStyle(fontSize: 17.5), leadingAndTrailingTextStyle: TextStyle(fontSize: 15.0), ), ); const TextStyle titleTextStyle = TextStyle( fontSize: 23.0, color: Color(0xffff0000), fontStyle: FontStyle.italic, ); const TextStyle subtitleTextStyle = TextStyle( fontSize: 20.0, color: Color(0xff00ff00), fontStyle: FontStyle.italic, ); const TextStyle leadingAndTrailingTextStyle = TextStyle( fontSize: 18.0, color: Color(0xff0000ff), fontStyle: FontStyle.italic, ); Widget buildFrame() { return MaterialApp( theme: theme, home: Material( child: Center( child: Builder( builder: (BuildContext context) { return const ListTile( titleTextStyle: titleTextStyle, subtitleTextStyle: subtitleTextStyle, leadingAndTrailingTextStyle: leadingAndTrailingTextStyle, leading: TestText('leading'), title: TestText('title'), subtitle: TestText('subtitle'), trailing: TestText('trailing'), ); }, ), ), ), ); } await tester.pumpWidget(buildFrame()); final RenderParagraph leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.fontSize, leadingAndTrailingTextStyle.fontSize); expect(leading.text.style!.color, leadingAndTrailingTextStyle.color); expect(leading.text.style!.fontStyle, leadingAndTrailingTextStyle.fontStyle); final RenderParagraph title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.fontSize, titleTextStyle.fontSize); expect(title.text.style!.color, titleTextStyle.color); expect(title.text.style!.fontStyle, titleTextStyle.fontStyle); final RenderParagraph subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.fontSize, subtitleTextStyle.fontSize); expect(subtitle.text.style!.color, subtitleTextStyle.color); expect(subtitle.text.style!.fontStyle, subtitleTextStyle.fontStyle); final RenderParagraph trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.fontSize, leadingAndTrailingTextStyle.fontSize); expect(trailing.text.style!.color, leadingAndTrailingTextStyle.color); expect(trailing.text.style!.fontStyle, leadingAndTrailingTextStyle.fontStyle); }); testWidgets( "Material2 - ListTile's titleTextStyle, subtitleTextStyle & leadingAndTrailingTextStyle are overridden by ListTile properties", (WidgetTester tester) async { final ThemeData theme = ThemeData( useMaterial3: false, listTileTheme: const ListTileThemeData( titleTextStyle: TextStyle(fontSize: 20.0), subtitleTextStyle: TextStyle(fontSize: 17.5), leadingAndTrailingTextStyle: TextStyle(fontSize: 15.0), ), ); const TextStyle titleTextStyle = TextStyle( fontSize: 23.0, color: Color(0xffff0000), fontStyle: FontStyle.italic, ); const TextStyle subtitleTextStyle = TextStyle( fontSize: 20.0, color: Color(0xff00ff00), fontStyle: FontStyle.italic, ); const TextStyle leadingAndTrailingTextStyle = TextStyle( fontSize: 18.0, color: Color(0xff0000ff), fontStyle: FontStyle.italic, ); Widget buildFrame() { return MaterialApp( theme: theme, home: Material( child: Center( child: Builder( builder: (BuildContext context) { return const ListTile( titleTextStyle: titleTextStyle, subtitleTextStyle: subtitleTextStyle, leadingAndTrailingTextStyle: leadingAndTrailingTextStyle, leading: TestText('leading'), title: TestText('title'), subtitle: TestText('subtitle'), trailing: TestText('trailing'), ); }, ), ), ), ); } await tester.pumpWidget(buildFrame()); final RenderParagraph leading = _getTextRenderObject(tester, 'leading'); expect(leading.text.style!.fontSize, leadingAndTrailingTextStyle.fontSize); expect(leading.text.style!.color, leadingAndTrailingTextStyle.color); expect(leading.text.style!.fontStyle, leadingAndTrailingTextStyle.fontStyle); final RenderParagraph title = _getTextRenderObject(tester, 'title'); expect(title.text.style!.fontSize, titleTextStyle.fontSize); expect(title.text.style!.color, titleTextStyle.color); expect(title.text.style!.fontStyle, titleTextStyle.fontStyle); final RenderParagraph subtitle = _getTextRenderObject(tester, 'subtitle'); expect(subtitle.text.style!.fontSize, subtitleTextStyle.fontSize); expect(subtitle.text.style!.color, subtitleTextStyle.color); expect(subtitle.text.style!.fontStyle, subtitleTextStyle.fontStyle); final RenderParagraph trailing = _getTextRenderObject(tester, 'trailing'); expect(trailing.text.style!.fontSize, leadingAndTrailingTextStyle.fontSize); expect(trailing.text.style!.color, leadingAndTrailingTextStyle.color); expect(trailing.text.style!.fontStyle, leadingAndTrailingTextStyle.fontStyle); }); testWidgets("ListTile respects ListTileTheme's tileColor & selectedTileColor", (WidgetTester tester) async { late ListTileThemeData theme; bool isSelected = false; await tester.pumpWidget( MaterialApp( home: Material( child: ListTileTheme( data: ListTileThemeData( tileColor: Colors.green.shade500, selectedTileColor: Colors.red.shade500, ), child: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { theme = ListTileTheme.of(context); return ListTile( selected: isSelected, onTap: () { setState(()=> isSelected = !isSelected); }, title: const Text('Title'), ); }, ), ), ), ), ), ); expect(find.byType(Material), paints..rect(color: theme.tileColor)); // Tap on tile to change isSelected. await tester.tap(find.byType(ListTile)); await tester.pumpAndSettle(); expect(find.byType(Material), paints..rect(color: theme.selectedTileColor)); }); testWidgets("ListTileTheme's tileColor & selectedTileColor are overridden by ListTile properties", (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: ListTileTheme( data: const ListTileThemeData( selectedTileColor: Colors.green, tileColor: Colors.red, ), child: Center( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ListTile( tileColor: tileColor, selectedTileColor: selectedTileColor, selected: isSelected, onTap: () { setState(()=> isSelected = !isSelected); }, title: const Text('Title'), ); }, ), ), ), ), ), ); expect(find.byType(Material), paints..rect(color: tileColor)); // Tap on tile to change isSelected. await tester.tap(find.byType(ListTile)); await tester.pumpAndSettle(); expect(find.byType(Material), paints..rect(color: selectedTileColor)); }); testWidgets('ListTile uses ListTileTheme shape in a drawer', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/106303 final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final ShapeBorder shapeBorder = RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)); await tester.pumpWidget(MaterialApp( theme: ThemeData( listTileTheme: ListTileThemeData(shape: shapeBorder), ), home: Scaffold( key: scaffoldKey, drawer: const Drawer( child: ListTile(), ), body: Container(), ), )); await tester.pumpAndSettle(); scaffoldKey.currentState!.openDrawer(); // Start drawer animation. await tester.pump(); final ShapeBorder? inkWellBorder = tester.widget<InkWell>( find.descendant( of: find.byType(ListTile), matching: find.byType(InkWell), )).customBorder; // Test shape. expect(inkWellBorder, shapeBorder); }); testWidgets('ListTile respects MaterialStateColor LisTileTheme.textColor', (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 ThemeData theme = ThemeData( listTileTheme: ListTileThemeData( textColor: MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return disabledColor; } if (states.contains(MaterialState.selected)) { return selectedColor; } return defaultColor; }), ), ); Widget buildFrame() { return MaterialApp( theme: theme, home: Material( child: Center( child: Builder( builder: (BuildContext context) { return ListTile( enabled: enabled, selected: selected, 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 respects MaterialStateColor LisTileTheme.iconColor', (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(); final ThemeData theme = ThemeData( listTileTheme: ListTileThemeData( iconColor: MaterialStateColor.resolveWith((Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return disabledColor; } if (states.contains(MaterialState.selected)) { return selectedColor; } return defaultColor; }), ), ); Widget buildFrame() { return MaterialApp( theme: theme, home: Material( child: Center( child: Builder( builder: (BuildContext context) { return ListTile( enabled: enabled, selected: selected, 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('ListTileThemeData copyWith overrides all properties', (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/119734 const ListTileThemeData original = ListTileThemeData( dense: true, shape: StadiumBorder(), style: ListTileStyle.drawer, selectedColor: Color(0x00000001), iconColor: Color(0x00000002), textColor: Color(0x00000003), titleTextStyle: TextStyle(color: Color(0x00000004)), subtitleTextStyle: TextStyle(color: Color(0x00000005)), leadingAndTrailingTextStyle: TextStyle(color: Color(0x00000006)), contentPadding: EdgeInsets.all(100), tileColor: Color(0x00000007), selectedTileColor: Color(0x00000008), horizontalTitleGap: 200, minVerticalPadding: 300, minLeadingWidth: 400, minTileHeight: 30, enableFeedback: true, titleAlignment: ListTileTitleAlignment.bottom, ); final ListTileThemeData copy = original.copyWith( dense: false, shape: const RoundedRectangleBorder(), style: ListTileStyle.list, selectedColor: const Color(0x00000009), iconColor: const Color(0x0000000A), textColor: const Color(0x0000000B), titleTextStyle: const TextStyle(color: Color(0x0000000C)), subtitleTextStyle: const TextStyle(color: Color(0x0000000D)), leadingAndTrailingTextStyle: const TextStyle(color: Color(0x0000000E)), contentPadding: const EdgeInsets.all(500), tileColor: const Color(0x0000000F), selectedTileColor: const Color(0x00000010), horizontalTitleGap: 600, minVerticalPadding: 700, minLeadingWidth: 800, minTileHeight: 80, enableFeedback: false, titleAlignment: ListTileTitleAlignment.top, ); expect(copy.dense, false); expect(copy.shape, const RoundedRectangleBorder()); expect(copy.style, ListTileStyle.list); expect(copy.selectedColor, const Color(0x00000009)); expect(copy.iconColor, const Color(0x0000000A)); expect(copy.textColor, const Color(0x0000000B)); expect(copy.titleTextStyle, const TextStyle(color: Color(0x0000000C))); expect(copy.subtitleTextStyle, const TextStyle(color: Color(0x0000000D))); expect(copy.leadingAndTrailingTextStyle, const TextStyle(color: Color(0x0000000E))); expect(copy.contentPadding, const EdgeInsets.all(500)); expect(copy.tileColor, const Color(0x0000000F)); expect(copy.selectedTileColor, const Color(0x00000010)); expect(copy.horizontalTitleGap, 600); expect(copy.minVerticalPadding, 700); expect(copy.minLeadingWidth, 800); expect(copy.minTileHeight, 80); expect(copy.enableFeedback, false); expect(copy.titleAlignment, ListTileTitleAlignment.top); }); testWidgets('ListTileTheme.titleAlignment is overridden by ListTile.titleAlignment', (WidgetTester tester) async { final Key leadingKey = GlobalKey(); final Key trailingKey = GlobalKey(); const String titleText = '\nHeadline Text\n'; const String subtitleText = '\nSupporting Text\n'; Widget buildFrame({ ListTileTitleAlignment? alignment }) { return MaterialApp( theme: ThemeData( useMaterial3: true, listTileTheme: const ListTileThemeData( titleAlignment: ListTileTitleAlignment.center, ), ), home: Material( child: Center( child: ListTile( titleAlignment: ListTileTitleAlignment.top, leading: SizedBox(key: leadingKey, width: 24.0, height: 24.0), title: const Text(titleText), subtitle: const Text(subtitleText), trailing: SizedBox(key: trailingKey, width: 24.0, height: 24.0), ), ), ), ); } await tester.pumpWidget(buildFrame()); final Offset tileOffset = tester.getTopLeft(find.byType(ListTile)); final Offset leadingOffset = tester.getTopLeft(find.byKey(leadingKey)); final Offset trailingOffset = tester.getTopRight(find.byKey(trailingKey)); expect(leadingOffset.dy - tileOffset.dy, 8.0); expect(trailingOffset.dy - tileOffset.dy, 8.0); }); testWidgets('ListTileTheme.merge supports all properties', (WidgetTester tester) async { Widget buildFrame() { return MaterialApp( theme: ThemeData( listTileTheme: const ListTileThemeData( dense: true, shape: StadiumBorder(), style: ListTileStyle.drawer, selectedColor: Color(0x00000001), iconColor: Color(0x00000002), textColor: Color(0x00000003), titleTextStyle: TextStyle(color: Color(0x00000004)), subtitleTextStyle: TextStyle(color: Color(0x00000005)), leadingAndTrailingTextStyle: TextStyle(color: Color(0x00000006)), contentPadding: EdgeInsets.all(100), tileColor: Color(0x00000007), selectedTileColor: Color(0x00000008), horizontalTitleGap: 200, minVerticalPadding: 300, minLeadingWidth: 400, minTileHeight: 30, enableFeedback: true, titleAlignment: ListTileTitleAlignment.bottom, mouseCursor: MaterialStateMouseCursor.textable, visualDensity: VisualDensity.comfortable, ), ), home: Material( child: Center( child: Builder( builder: (BuildContext context) { return ListTileTheme.merge( dense: false, shape: const RoundedRectangleBorder(), style: ListTileStyle.list, selectedColor: const Color(0x00000009), iconColor: const Color(0x0000000A), textColor: const Color(0x0000000B), titleTextStyle: const TextStyle(color: Color(0x0000000C)), subtitleTextStyle: const TextStyle(color: Color(0x0000000D)), leadingAndTrailingTextStyle: const TextStyle(color: Color(0x0000000E)), contentPadding: const EdgeInsets.all(500), tileColor: const Color(0x0000000F), selectedTileColor: const Color(0x00000010), horizontalTitleGap: 600, minVerticalPadding: 700, minLeadingWidth: 800, minTileHeight: 80, enableFeedback: false, titleAlignment: ListTileTitleAlignment.top, mouseCursor: MaterialStateMouseCursor.clickable, visualDensity: VisualDensity.compact, child: const ListTile(), ); } ), ), ), ); } await tester.pumpWidget(buildFrame()); final ListTileThemeData theme = ListTileTheme.of(tester.element(find.byType(ListTile))); expect(theme.dense, false); expect(theme.shape, const RoundedRectangleBorder()); expect(theme.style, ListTileStyle.list); expect(theme.selectedColor, const Color(0x00000009)); expect(theme.iconColor, const Color(0x0000000A)); expect(theme.textColor, const Color(0x0000000B)); expect(theme.titleTextStyle, const TextStyle(color: Color(0x0000000C))); expect(theme.subtitleTextStyle, const TextStyle(color: Color(0x0000000D))); expect(theme.leadingAndTrailingTextStyle, const TextStyle(color: Color(0x0000000E))); expect(theme.contentPadding, const EdgeInsets.all(500)); expect(theme.tileColor, const Color(0x0000000F)); expect(theme.selectedTileColor, const Color(0x00000010)); expect(theme.horizontalTitleGap, 600); expect(theme.minVerticalPadding, 700); expect(theme.minLeadingWidth, 800); expect(theme.minTileHeight, 80); expect(theme.enableFeedback, false); expect(theme.titleAlignment, ListTileTitleAlignment.top); expect(theme.mouseCursor, MaterialStateMouseCursor.clickable); expect(theme.visualDensity, VisualDensity.compact); }); } 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_theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/list_tile_theme_test.dart", "repo_id": "flutter", "token_count": 17258 }
715
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Navigation drawer updates destinations when tapped', (WidgetTester tester) async { int mutatedIndex = -1; final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final ThemeData theme = ThemeData(); widgetSetup(tester, 3000, viewHeight: 3000); final Widget widget = _buildWidget( scaffoldKey, NavigationDrawer( children: <Widget>[ Text('Headline', style: theme.textTheme.bodyLarge), NavigationDrawerDestination( icon: Icon(Icons.ac_unit, color: theme.iconTheme.color), label: Text('AC', style: theme.textTheme.bodySmall), ), NavigationDrawerDestination( icon: Icon(Icons.access_alarm, color: theme.iconTheme.color), label: Text('Alarm', style: theme.textTheme.bodySmall), ), ], onDestinationSelected: (int i) { mutatedIndex = i; }, ), ); await tester.pumpWidget(widget); scaffoldKey.currentState!.openDrawer(); await tester.pump(); expect(find.text('Headline'), findsOneWidget); expect(find.text('AC'), findsOneWidget); expect(find.text('Alarm'), findsOneWidget); await tester.pump(const Duration(seconds: 1)); // animation done await tester.tap(find.text('Alarm')); expect(mutatedIndex, 1); await tester.tap(find.text('AC')); expect(mutatedIndex, 0); }); testWidgets('NavigationDrawer can update background color', (WidgetTester tester) async { const Color color = Colors.yellow; final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final ThemeData theme = ThemeData(); await tester.pumpWidget( _buildWidget( scaffoldKey, NavigationDrawer( backgroundColor: color, children: <Widget>[ Text('Headline', style: theme.textTheme.bodyLarge), NavigationDrawerDestination( icon: Icon(Icons.ac_unit, color: theme.iconTheme.color), label: Text('AC', style: theme.textTheme.bodySmall), ), NavigationDrawerDestination( icon: Icon(Icons.access_alarm, color: theme.iconTheme.color), label: Text('Alarm', style: theme.textTheme.bodySmall), ), ], onDestinationSelected: (int i) {}, ), ), ); scaffoldKey.currentState!.openDrawer(); await tester.pump(const Duration(seconds: 1)); // animation done expect(_getMaterial(tester).color, equals(color)); }); testWidgets('NavigationDrawer can update destination background color', (WidgetTester tester) async { const Color color = Colors.yellow; final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final ThemeData theme = ThemeData(); await tester.pumpWidget( _buildWidget( scaffoldKey, NavigationDrawer( children: <Widget>[ Text('Headline', style: theme.textTheme.bodyLarge), NavigationDrawerDestination( icon: Icon(Icons.ac_unit, color: theme.iconTheme.color), label: Text('AC', style: theme.textTheme.bodySmall), backgroundColor: color, ), NavigationDrawerDestination( icon: Icon(Icons.access_alarm, color: theme.iconTheme.color), label: Text('Alarm', style: theme.textTheme.bodySmall), backgroundColor: color, ), ], onDestinationSelected: (int i) {}, ), ), ); scaffoldKey.currentState!.openDrawer(); await tester.pump(const Duration(seconds: 1)); // animation done final Container destinationColor = tester.firstWidget<Container>( find.descendant( of: find.byType(NavigationDrawerDestination), matching: find.byType(Container)), ); expect(destinationColor.color, equals(color)); }); testWidgets('NavigationDrawer can update elevation', (WidgetTester tester) async { const double elevation = 42.0; final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final ThemeData theme = ThemeData(); final NavigationDrawer drawer = NavigationDrawer( elevation: elevation, children: <Widget>[ Text('Headline', style: theme.textTheme.bodyLarge), NavigationDrawerDestination( icon: Icon(Icons.ac_unit, color: theme.iconTheme.color), label: Text('AC', style: theme.textTheme.bodySmall), ), NavigationDrawerDestination( icon: Icon(Icons.access_alarm, color: theme.iconTheme.color), label: Text('Alarm', style: theme.textTheme.bodySmall), ), ], ); await tester.pumpWidget( _buildWidget( scaffoldKey, drawer, ), ); scaffoldKey.currentState!.openDrawer(); await tester.pump(const Duration(seconds: 1)); expect(_getMaterial(tester).elevation, equals(elevation)); }); testWidgets( 'NavigationDrawer uses proper defaults when no parameters are given', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget( _buildWidget( scaffoldKey, NavigationDrawer( children: <Widget>[ Text('Headline', style: theme.textTheme.bodyLarge), const NavigationDrawerDestination( icon: Icon(Icons.ac_unit), label: Text('AC'), ), const NavigationDrawerDestination( icon: Icon(Icons.access_alarm), label: Text('Alarm'), ), ], onDestinationSelected: (int i) {}, ), useMaterial3: theme.useMaterial3, ), ); scaffoldKey.currentState!.openDrawer(); await tester.pump(const Duration(seconds: 1)); // Test drawer Material. expect(_getMaterial(tester).color, theme.colorScheme.surfaceContainerLow); expect(_getMaterial(tester).surfaceTintColor, Colors.transparent); expect(_getMaterial(tester).shadowColor, Colors.transparent); expect(_getMaterial(tester).elevation, 1); // Test indicator decoration. expect(_getIndicatorDecoration(tester)?.color, theme.colorScheme.secondaryContainer); expect(_getIndicatorDecoration(tester)?.shape, const StadiumBorder()); // Test selected and unselected icon colors. expect(_iconStyle(tester, Icons.ac_unit)?.color, theme.colorScheme.onSecondaryContainer); expect(_iconStyle(tester, Icons.access_alarm)?.color, theme.colorScheme.onSurfaceVariant); // Test selected and unselected label colors. expect(_labelStyle(tester, 'AC')?.color, theme.colorScheme.onSecondaryContainer); expect(_labelStyle(tester, 'Alarm')?.color, theme.colorScheme.onSurfaceVariant); // Test that the icon and label are the correct size. RenderBox iconBox = tester.renderObject(find.byIcon(Icons.ac_unit)); expect(iconBox.size, const Size(24.0, 24.0)); iconBox = tester.renderObject(find.byIcon(Icons.access_alarm)); expect(iconBox.size, const Size(24.0, 24.0)); }); testWidgets('Navigation drawer is scrollable', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); widgetSetup(tester, 500, viewHeight: 300); await tester.pumpWidget( _buildWidget( scaffoldKey, NavigationDrawer( children: <Widget>[ for (int i = 0; i < 100; i++) NavigationDrawerDestination( icon: const Icon(Icons.ac_unit), label: Text('Label$i'), ), ], onDestinationSelected: (int i) {}, ), ), ); scaffoldKey.currentState!.openDrawer(); await tester.pump(const Duration(seconds: 1)); expect(find.text('Label0'), findsOneWidget); expect(find.text('Label1'), findsOneWidget); expect(find.text('Label2'), findsOneWidget); expect(find.text('Label3'), findsOneWidget); expect(find.text('Label4'), findsOneWidget); expect(find.text('Label5'), findsOneWidget); expect(find.text('Label6'), findsNothing); expect(find.text('Label7'), findsNothing); expect(find.text('Label8'), findsNothing); await tester.dragFrom(const Offset(0, 200), const Offset(0.0, -200)); await tester.pump(); expect(find.text('Label0'), findsNothing); expect(find.text('Label1'), findsNothing); expect(find.text('Label2'), findsNothing); expect(find.text('Label3'), findsOneWidget); expect(find.text('Label4'), findsOneWidget); expect(find.text('Label5'), findsOneWidget); expect(find.text('Label6'), findsOneWidget); expect(find.text('Label7'), findsOneWidget); expect(find.text('Label8'), findsOneWidget); expect(find.text('Label9'), findsNothing); expect(find.text('Label10'), findsNothing); }); testWidgets('Safe Area test', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); const double viewHeight = 300; widgetSetup(tester, 500, viewHeight: viewHeight); await tester.pumpWidget( MediaQuery( data: const MediaQueryData(padding: EdgeInsets.all(20.0)), child: MaterialApp( useInheritedMediaQuery: true, theme: ThemeData.light(), home: Scaffold( key: scaffoldKey, drawer: NavigationDrawer( children: <Widget>[ for (int i = 0; i < 10; i++) NavigationDrawerDestination( icon: const Icon(Icons.ac_unit), label: Text('Label$i'), ), ], onDestinationSelected: (int i) {}, ), body: Container(), ), ), ), ); scaffoldKey.currentState!.openDrawer(); await tester.pump(); await tester.pump(const Duration(seconds: 1)); // Safe area padding on the top and sides. expect( tester.getTopLeft(find.widgetWithText(NavigationDrawerDestination,'Label0')), const Offset(20.0, 20.0), ); // No Safe area padding at the bottom. expect(tester.getBottomRight(find.widgetWithText(NavigationDrawerDestination,'Label4')).dy, viewHeight); }); testWidgets('Navigation drawer semantics', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final ThemeData theme = ThemeData(); Widget widget({int selectedIndex = 0}) { return _buildWidget( scaffoldKey, NavigationDrawer( selectedIndex: selectedIndex, children: <Widget>[ Text('Headline', style: theme.textTheme.bodyLarge), NavigationDrawerDestination( icon: Icon(Icons.ac_unit, color: theme.iconTheme.color), label: Text('AC', style: theme.textTheme.bodySmall), ), NavigationDrawerDestination( icon: Icon(Icons.access_alarm, color: theme.iconTheme.color), label: Text('Alarm', style: theme.textTheme.bodySmall), ), ], ), ); } await tester.pumpWidget(widget()); scaffoldKey.currentState!.openDrawer(); await tester.pump(const Duration(seconds: 1)); expect( tester.getSemantics(find.text('AC')), matchesSemantics( label: 'AC\nTab 1 of 2', textDirection: TextDirection.ltr, isFocusable: true, isSelected: true, hasTapAction: true, ), ); expect( tester.getSemantics(find.text('Alarm')), matchesSemantics( label: 'Alarm\nTab 2 of 2', textDirection: TextDirection.ltr, isFocusable: true, hasTapAction: true, ), ); await tester.pumpWidget(widget(selectedIndex: 1)); expect( tester.getSemantics(find.text('AC')), matchesSemantics( label: 'AC\nTab 1 of 2', textDirection: TextDirection.ltr, isFocusable: true, hasTapAction: true, ), ); expect( tester.getSemantics(find.text('Alarm')), matchesSemantics( label: 'Alarm\nTab 2 of 2', textDirection: TextDirection.ltr, isFocusable: true, isSelected: true, hasTapAction: true, ), ); }); testWidgets('Navigation destination updates indicator color and shape', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); final ThemeData theme = ThemeData(useMaterial3: true); const Color color = Color(0xff0000ff); const ShapeBorder shape = RoundedRectangleBorder(); Widget buildNavigationDrawer({Color? indicatorColor, ShapeBorder? indicatorShape}) { return MaterialApp( theme: theme, home: Scaffold( key: scaffoldKey, drawer: NavigationDrawer( indicatorColor: indicatorColor, indicatorShape: indicatorShape, children: <Widget>[ Text('Headline', style: theme.textTheme.bodyLarge), const NavigationDrawerDestination( icon: Icon(Icons.ac_unit), label: Text('AC'), ), const NavigationDrawerDestination( icon: Icon(Icons.access_alarm), label: Text('Alarm'), ), ], onDestinationSelected: (int i) { }, ), body: Container(), ), ); } await tester.pumpWidget(buildNavigationDrawer()); scaffoldKey.currentState!.openDrawer(); await tester.pumpAndSettle(); // Test default indicator color and shape. expect(_getIndicatorDecoration(tester)?.color, theme.colorScheme.secondaryContainer); expect(_getIndicatorDecoration(tester)?.shape, const StadiumBorder()); // Test that InkWell for hover, focus and pressed use default shape. expect(_getInkWell(tester)?.customBorder, const StadiumBorder()); await tester.pumpWidget(buildNavigationDrawer(indicatorColor: color, indicatorShape: shape)); // Test custom indicator color and shape. expect(_getIndicatorDecoration(tester)?.color, color); expect(_getIndicatorDecoration(tester)?.shape, shape); // Test that InkWell for hover, focus and pressed use custom shape. expect(_getInkWell(tester)?.customBorder, shape); }); testWidgets('NavigationDrawer.tilePadding defaults to EdgeInsets.symmetric(horizontal: 12.0)', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); widgetSetup(tester, 3000, viewHeight: 3000); final Widget widget = _buildWidget( scaffoldKey, NavigationDrawer( children: const <Widget>[ NavigationDrawerDestination( icon: Icon(Icons.ac_unit), label: Text('AC'), ), ], onDestinationSelected: (int i) {}, ), ); await tester.pumpWidget(widget); scaffoldKey.currentState?.openDrawer(); await tester.pump(); final NavigationDrawer drawer = tester.widget(find.byType(NavigationDrawer)); expect(drawer.tilePadding, const EdgeInsets.symmetric(horizontal: 12.0)); }); testWidgets('Destinations respect their disabled state', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); int selectedIndex = 0; widgetSetup(tester, 800); final Widget widget = _buildWidget( scaffoldKey, NavigationDrawer( children: const <Widget>[ NavigationDrawerDestination( icon: Icon(Icons.ac_unit), label: Text('AC'), ), NavigationDrawerDestination( icon: Icon(Icons.access_alarm), label: Text('Alarm'), ), NavigationDrawerDestination( icon: Icon(Icons.accessible), label: Text('Accessible'), enabled: false, ), ], onDestinationSelected: (int i) { selectedIndex = i; }, ), ); await tester.pumpWidget(widget); scaffoldKey.currentState!.openDrawer(); await tester.pump(); expect(find.text('AC'), findsOneWidget); expect(find.text('Alarm'), findsOneWidget); expect(find.text('Accessible'), findsOneWidget); await tester.pump(const Duration(seconds: 1)); expect(selectedIndex, 0); await tester.tap(find.text('Alarm')); expect(selectedIndex, 1); await tester.tap(find.text('Accessible')); expect(selectedIndex, 1); tester.pumpAndSettle(); }); } Widget _buildWidget(GlobalKey<ScaffoldState> scaffoldKey, Widget child, { bool? useMaterial3 }) { return MaterialApp( theme: ThemeData(useMaterial3: useMaterial3), home: Scaffold( key: scaffoldKey, drawer: child, body: Container(), ), ); } Material _getMaterial(WidgetTester tester) { return tester.firstWidget<Material>( find.descendant( of: find.byType(NavigationDrawer), matching: find.byType(Material)), ); } InkWell? _getInkWell(WidgetTester tester) { return tester.firstWidget<InkWell>( find.descendant( of: find.byType(NavigationDrawer), matching: find.byType(InkWell)), ); } ShapeDecoration? _getIndicatorDecoration(WidgetTester tester) { return tester .firstWidget<Container>( find.descendant( of: find.byType(FadeTransition), matching: find.byType(Container), ), ) .decoration as ShapeDecoration?; } TextStyle? _iconStyle(WidgetTester tester, IconData icon) { final RichText iconRichText = tester.widget<RichText>( find.descendant(of: find.byIcon(icon), matching: find.byType(RichText)), ); return iconRichText.text.style; } TextStyle? _labelStyle(WidgetTester tester, String label) { final RichText labelRichText = tester.widget<RichText>( find.descendant(of: find.text(label), matching: find.byType(RichText)), ); return labelRichText.text.style; } void widgetSetup(WidgetTester tester, double viewWidth, {double viewHeight = 1000}) { tester.view.devicePixelRatio = 2; final double dpi = tester.view.devicePixelRatio; tester.view.physicalSize = Size(viewWidth * dpi, viewHeight * dpi); }
flutter/packages/flutter/test/material/navigation_drawer_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/navigation_drawer_test.dart", "repo_id": "flutter", "token_count": 7688 }
716
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is run as part of a reduced test set in CI on Mac and Windows // machines. @Tags(<String>['reduced-test-set']) library; import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/src/gestures/constants.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; void main() { final ThemeData theme = ThemeData(); testWidgets('Radio control test', (WidgetTester tester) async { final Key key = UniqueKey(); final List<int?> log = <int?>[]; await tester.pumpWidget(Theme( data: theme, child: Material( child: Center( child: Radio<int>( key: key, value: 1, groupValue: 2, onChanged: log.add, ), ), ), )); await tester.tap(find.byKey(key)); expect(log, equals(<int>[1])); log.clear(); await tester.pumpWidget(Theme( data: theme, child: Material( child: Center( child: Radio<int>( key: key, value: 1, groupValue: 1, onChanged: log.add, activeColor: Colors.green[500], ), ), ), )); await tester.tap(find.byKey(key)); expect(log, isEmpty); await tester.pumpWidget(Theme( data: theme, child: Material( child: Center( child: Radio<int>( key: key, value: 1, groupValue: 2, onChanged: null, ), ), ), )); await tester.tap(find.byKey(key)); expect(log, isEmpty); }); testWidgets('Radio can be toggled when toggleable is set', (WidgetTester tester) async { final Key key = UniqueKey(); final List<int?> log = <int?>[]; await tester.pumpWidget(Theme( data: theme, child: 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(Theme( data: theme, child: 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(Theme( data: theme, child: 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('Radio size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async { final Key key1 = UniqueKey(); await tester.pumpWidget( Theme( data: theme.copyWith(materialTapTargetSize: MaterialTapTargetSize.padded), child: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: Radio<bool>( key: key1, groupValue: true, value: true, onChanged: (bool? newValue) { }, ), ), ), ), ), ); expect(tester.getSize(find.byKey(key1)), const Size(48.0, 48.0)); final Key key2 = UniqueKey(); await tester.pumpWidget( Theme( data: theme.copyWith(materialTapTargetSize: MaterialTapTargetSize.shrinkWrap), child: Directionality( textDirection: TextDirection.ltr, child: Material( child: Center( child: Radio<bool>( key: key2, groupValue: true, value: true, onChanged: (bool? newValue) { }, ), ), ), ), ), ); expect(tester.getSize(find.byKey(key2)), const Size(40.0, 40.0)); }); testWidgets('Radio selected semantics - platform adaptive', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(Theme( data: theme, child: Material( child: Radio<int>( value: 1, groupValue: 1, onChanged: (int? i) {}, ), ), )); final bool isApple = defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS; expect( semantics, includesNodeWith( flags: <SemanticsFlag>[ SemanticsFlag.isInMutuallyExclusiveGroup, SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, SemanticsFlag.isChecked, if (isApple) SemanticsFlag.isSelected, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], ), ); semantics.dispose(); }, variant: TargetPlatformVariant.all()); testWidgets('Radio semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(Theme( data: theme, child: Material( child: Radio<int>( value: 1, groupValue: 2, onChanged: (int? i) { }, ), ), )); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.isInMutuallyExclusiveGroup, SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], ), ], ), ignoreRect: true, ignoreTransform: true)); await tester.pumpWidget(Theme( data: theme, child: Material( child: Radio<int>( value: 2, groupValue: 2, onChanged: (int? i) { }, ), ), )); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.isInMutuallyExclusiveGroup, SemanticsFlag.hasCheckedState, SemanticsFlag.isChecked, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], ), ], ), ignoreRect: true, ignoreTransform: true)); await tester.pumpWidget(Theme( data: theme, child: const Material( child: Radio<int>( value: 1, groupValue: 2, onChanged: null, ), ), )); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, SemanticsFlag.isInMutuallyExclusiveGroup, SemanticsFlag.isFocusable, // This flag is delayed by 1 frame. ], ), ], ), ignoreRect: true, ignoreTransform: true)); await tester.pump(); // Now the isFocusable should be gone. expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, SemanticsFlag.isInMutuallyExclusiveGroup, ], ), ], ), ignoreRect: true, ignoreTransform: true)); await tester.pumpWidget(Theme( data: theme, child: const Material( child: Radio<int>( value: 2, groupValue: 2, onChanged: null, ), ), )); expect(semantics, hasSemantics(TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.isChecked, SemanticsFlag.hasEnabledState, SemanticsFlag.isInMutuallyExclusiveGroup, ], ), ], ), ignoreRect: true, ignoreTransform: true)); semantics.dispose(); }); testWidgets('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(Theme( data: theme, child: Material( child: Radio<int>( key: key, value: 1, groupValue: radioValue, onChanged: (int? i) { radioValue = i; }, ), ), )); await tester.tap(find.byKey(key)); 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('Material2 - Radio ink ripple is displayed correctly', (WidgetTester tester) async { final Key painterKey = UniqueKey(); const Key radioKey = Key('radio'); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: RepaintBoundary( key: painterKey, child: Center( child: Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( key: radioKey, value: 1, groupValue: 1, onChanged: (int? value) { }, ), ), ), ), ), )); await tester.press(find.byKey(radioKey)); await tester.pumpAndSettle(); await expectLater( find.byKey(painterKey), matchesGoldenFile('m2_radio.ink_ripple.png'), ); }); testWidgets('Material3 - Radio ink ripple is displayed correctly', (WidgetTester tester) async { final Key painterKey = UniqueKey(); const Key radioKey = Key('radio'); await tester.pumpWidget(MaterialApp( theme: ThemeData(useMaterial3: true), home: Scaffold( body: RepaintBoundary( key: painterKey, child: Center( child: Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( key: radioKey, value: 1, groupValue: 1, onChanged: (int? value) { }, ), ), ), ), ), )); await tester.press(find.byKey(radioKey)); await tester.pumpAndSettle(); await expectLater( find.byKey(painterKey), matchesGoldenFile('m3_radio.ink_ripple.png'), ); }); testWidgets('Radio with splash radius set', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const double splashRadius = 30; Widget buildApp() { return MaterialApp( theme: theme, home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( value: 0, onChanged: (int? newValue) {}, focusColor: Colors.orange[500], autofocus: true, groupValue: 0, splashRadius: splashRadius, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); 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('Material2 - Radio is focusable and has correct focus color', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Radio'); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; int? groupValue = 0; const Key radioKey = Key('radio'); Widget buildApp({bool enabled = true}) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( key: radioKey, value: 0, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, focusColor: Colors.orange[500], autofocus: true, focusNode: focusNode, groupValue: groupValue, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: Colors.orange[500]) ..circle(color: const Color(0xff2196f3)) ..circle(color: const Color(0xff2196f3)), ); // Check when the radio isn't selected. groupValue = 1; await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: Colors.orange[500]) ..circle(color: const Color(0x8a000000), 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(focusNode.hasPrimaryFocus, isFalse); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: const Color(0x61000000)) ..circle(color: const Color(0x61000000)), ); focusNode.dispose(); }); testWidgets('Material3 - Radio is focusable and has correct focus color', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Radio'); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; int? groupValue = 0; const Key radioKey = Key('radio'); final ThemeData theme = ThemeData(useMaterial3: true); Widget buildApp({bool enabled = true}) { return MaterialApp( theme: theme, home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( key: radioKey, value: 0, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, focusColor: Colors.orange[500], autofocus: true, focusNode: focusNode, groupValue: groupValue, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: Colors.orange[500]) ..circle(color: theme.colorScheme.primary) ..circle(color: theme.colorScheme.primary), ); // Check when the radio isn't selected. groupValue = 1; await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byKey(radioKey))), paints..rect()..circle(color: Colors.orange[500])..circle(color: theme.colorScheme.onSurface), ); // Check when the radio is selected, but disabled. groupValue = 0; await tester.pumpWidget(buildApp(enabled: false)); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isFalse); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: theme.colorScheme.onSurface.withOpacity(0.38)) ..circle(color: theme.colorScheme.onSurface.withOpacity(0.38)), ); focusNode.dispose(); }); testWidgets('Material2 - Radio can be hovered and has correct hover color', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; int? groupValue = 0; const Key radioKey = Key('radio'); Widget buildApp({bool enabled = true}) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( key: radioKey, value: 0, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, hoverColor: Colors.orange[500], groupValue: groupValue, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..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.byKey(radioKey))); // 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.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: Colors.orange[500]) ..circle(color: const Color(0x8a000000), style: PaintingStyle.stroke, strokeWidth: 2.0), ); // 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.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: const Color(0x61000000)) ..circle(color: const Color(0x61000000)), ); }); testWidgets('Material3 - Radio can be hovered and has correct hover color', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; int? groupValue = 0; const Key radioKey = Key('radio'); final ThemeData theme = ThemeData(useMaterial3: true); Widget buildApp({bool enabled = true}) { return MaterialApp( theme: theme, home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( key: radioKey, value: 0, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, hoverColor: Colors.orange[500], groupValue: groupValue, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pump(); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..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.byKey(radioKey))); // 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.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: Colors.orange[500]) ..circle(color: theme.colorScheme.onSurface, style: PaintingStyle.stroke, strokeWidth: 2.0), ); // 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.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: theme.colorScheme.onSurface.withOpacity(0.38)) ..circle(color: theme.colorScheme.onSurface.withOpacity(0.38)), ); }); testWidgets('Radio can be controlled by keyboard shortcuts', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; int? groupValue = 1; const Key radioKey0 = Key('radio0'); const Key radioKey1 = Key('radio1'); const Key radioKey2 = Key('radio2'); final FocusNode focusNode2 = FocusNode(debugLabel: 'radio2'); Widget buildApp({bool enabled = true}) { return MaterialApp( theme: theme, home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 200, height: 100, color: Colors.white, child: Row( children: <Widget>[ Radio<int>( key: radioKey0, value: 0, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, hoverColor: Colors.orange[500], groupValue: groupValue, autofocus: true, ), Radio<int>( key: radioKey1, value: 1, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, hoverColor: Colors.orange[500], groupValue: groupValue, ), Radio<int>( key: radioKey2, value: 2, onChanged: enabled ? (int? newValue) { setState(() { groupValue = newValue; }); } : null, hoverColor: Colors.orange[500], groupValue: groupValue, focusNode: focusNode2, ), ], ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.enter); await tester.pumpAndSettle(); // On web, radios don't respond to the enter key. expect(groupValue, kIsWeb ? equals(1) : equals(0)); focusNode2.requestFocus(); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); expect(groupValue, equals(2)); focusNode2.dispose(); }); testWidgets('Radio responds to density changes.', (WidgetTester tester) async { const Key key = Key('test'); Future<void> buildTest(VisualDensity visualDensity) async { return tester.pumpWidget( MaterialApp( theme: theme, home: Material( child: Center( child: Radio<int>( visualDensity: visualDensity, key: key, onChanged: (int? value) {}, value: 0, groupValue: 0, ), ), ), ), ); } await buildTest(VisualDensity.standard); final RenderBox box = tester.renderObject(find.byKey(key)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(48, 48))); await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(60, 60))); await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(36, 36))); await buildTest(const VisualDensity(horizontal: 3.0, vertical: -3.0)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(60, 36))); }); testWidgets('Radio changes mouse cursor when hovered', (WidgetTester tester) async { const Key key = ValueKey<int>(1); // Test Radio() constructor await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: Align( alignment: Alignment.topLeft, child: Material( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: Radio<int>( key: key, 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.byKey(key))); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); // Test default cursor await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: Align( alignment: Alignment.topLeft, child: Material( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: Radio<int>( value: 1, onChanged: (int? v) {}, groupValue: 2, ), ), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); // Test default cursor when disabled await tester.pumpWidget( MaterialApp( theme: theme, home: const Scaffold( body: Align( alignment: Alignment.topLeft, child: Material( child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: Radio<int>( value: 1, onChanged: null, groupValue: 2, ), ), ), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }); testWidgets('Radio button fill color resolves 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; const Key radioKey = Key('radio'); Widget buildApp({required bool enabled}) { return MaterialApp( theme: theme, home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( key: radioKey, 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.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..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.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..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.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..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.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: inactiveDisabledFillColor, style: PaintingStyle.stroke, strokeWidth: 2.0), ); }); testWidgets('Material2 - Radio fill color resolves in hovered/focused states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'radio'); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const Color hoveredFillColor = Color(0xFF000001); const Color focusedFillColor = Color(0xFF000002); Color getFillColor(Set<MaterialState> states) { if (states.contains(MaterialState.hovered)) { return hoveredFillColor; } if (states.contains(MaterialState.focused)) { return focusedFillColor; } return Colors.transparent; } final MaterialStateProperty<Color> fillColor = MaterialStateColor.resolveWith(getFillColor); int? groupValue = 0; const Key radioKey = Key('radio'); final ThemeData theme = ThemeData(useMaterial3: false); Widget buildApp() { return MaterialApp( theme: theme, home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( autofocus: true, focusNode: focusNode, key: radioKey, value: 0, fillColor: fillColor, onChanged: (int? newValue) { setState(() { groupValue = newValue; }); }, groupValue: groupValue, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: Colors.black12) ..circle(color: focusedFillColor), ); // Start hovering final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byKey(radioKey))); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: theme.hoverColor) ..circle(color: hoveredFillColor), ); focusNode.dispose(); }); testWidgets('Material3 - Radio fill color resolves in hovered/focused states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'radio'); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; const Color hoveredFillColor = Color(0xFF000001); const Color focusedFillColor = Color(0xFF000002); Color getFillColor(Set<MaterialState> states) { if (states.contains(MaterialState.hovered)) { return hoveredFillColor; } if (states.contains(MaterialState.focused)) { return focusedFillColor; } return Colors.transparent; } final MaterialStateProperty<Color> fillColor = MaterialStateColor.resolveWith(getFillColor); int? groupValue = 0; const Key radioKey = Key('radio'); final ThemeData theme = ThemeData(useMaterial3: true); Widget buildApp() { return MaterialApp( theme: theme, home: Material( child: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return Container( width: 100, height: 100, color: Colors.white, child: Radio<int>( autofocus: true, focusNode: focusNode, key: radioKey, value: 0, fillColor: fillColor, onChanged: (int? newValue) { setState(() { groupValue = newValue; }); }, groupValue: groupValue, ), ); }), ), ), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byKey(radioKey))), paints..rect()..circle(color: theme.colorScheme.primary.withOpacity(0.1))..circle(color: focusedFillColor), ); // Start hovering final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byKey(radioKey))); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byKey(radioKey))), paints ..rect( color: const Color(0xffffffff), rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), ) ..circle(color: theme.colorScheme.primary.withOpacity(0.08)) ..circle(color: hoveredFillColor), ); focusNode.dispose(); }); testWidgets('Radio overlay color resolves in active/pressed/focused/hovered states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Radio'); 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 focusOverlayColor = Color(0xFF000004); const Color hoverColor = Color(0xFF000005); const Color focusColor = Color(0xFF000006); Color? getOverlayColor(Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { if (states.contains(MaterialState.selected)) { return activePressedOverlayColor; } return inactivePressedOverlayColor; } if (states.contains(MaterialState.hovered)) { return hoverOverlayColor; } if (states.contains(MaterialState.focused)) { return focusOverlayColor; } return null; } const double splashRadius = 24.0; Finder findRadio() { return find.byWidgetPredicate((Widget widget) => widget is Radio<bool>); } MaterialInkController? getRadioMaterial(WidgetTester tester) { return Material.of(tester.element(findRadio())); } Widget buildRadio({bool active = false, bool focused = false, bool useOverlay = true}) { return MaterialApp( theme: theme, home: Scaffold( body: Radio<bool>( focusNode: focusNode, autofocus: focused, value: active, groupValue: true, onChanged: (_) { }, fillColor: const MaterialStatePropertyAll<Color>(fillColor), overlayColor: useOverlay ? MaterialStateProperty.resolveWith(getOverlayColor) : null, hoverColor: hoverColor, focusColor: focusColor, splashRadius: splashRadius, ), ), ); } await tester.pumpWidget(buildRadio(useOverlay: false)); await tester.press(findRadio()); await tester.pumpAndSettle(); expect( getRadioMaterial(tester), paints ..circle( color: fillColor.withAlpha(kRadialReactionAlpha), radius: splashRadius, ), reason: 'Default inactive pressed Radio should have overlay color from fillColor', ); await tester.pumpWidget(buildRadio(active: true, useOverlay: false)); await tester.press(findRadio()); await tester.pumpAndSettle(); expect( getRadioMaterial(tester), paints ..circle( color: fillColor.withAlpha(kRadialReactionAlpha), radius: splashRadius, ), reason: 'Default active pressed Radio should have overlay color from fillColor', ); await tester.pumpWidget(buildRadio()); await tester.press(findRadio()); await tester.pumpAndSettle(); expect( getRadioMaterial(tester), paints ..circle( color: inactivePressedOverlayColor, radius: splashRadius, ), reason: 'Inactive pressed Radio should have overlay color: $inactivePressedOverlayColor', ); await tester.pumpWidget(buildRadio(active: true)); await tester.press(findRadio()); await tester.pumpAndSettle(); expect( getRadioMaterial(tester), paints ..circle( color: activePressedOverlayColor, radius: splashRadius, ), reason: 'Active pressed Radio should have overlay color: $activePressedOverlayColor', ); await tester.pumpWidget(Container()); await tester.pumpWidget(buildRadio(focused: true)); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( getRadioMaterial(tester), paints ..circle( color: focusOverlayColor, radius: splashRadius, ), reason: 'Focused Radio should use overlay color $focusOverlayColor over $focusColor', ); // Start hovering final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(findRadio())); await tester.pumpAndSettle(); expect( getRadioMaterial(tester), paints ..circle( color: hoverOverlayColor, radius: splashRadius, ), reason: 'Hovered Radio should use overlay color $hoverOverlayColor over $hoverColor', ); focusNode.dispose(); }); testWidgets('Do not crash when widget disappears while pointer is down', (WidgetTester tester) async { final Key key = UniqueKey(); Widget buildRadio(bool show) { return MaterialApp( theme: theme, home: Material( child: Center( child: show ? Radio<bool>(key: key, value: true, groupValue: false, onChanged: (_) { }) : Container(), ), ), ); } await tester.pumpWidget(buildRadio(true)); final Offset center = tester.getCenter(find.byKey(key)); // Put a pointer down on the screen. final TestGesture gesture = await tester.startGesture(center); await tester.pump(); // While the pointer is down, the widget disappears. await tester.pumpWidget(buildRadio(false)); expect(find.byKey(key), findsNothing); // Release pointer after widget disappeared. await gesture.up(); }); testWidgets('disabled radio shows tooltip', (WidgetTester tester) async { const String longPressTooltip = 'long press tooltip'; const String tapTooltip = 'tap tooltip'; await tester.pumpWidget( MaterialApp( theme: theme, home: const Material( child: Tooltip( message: longPressTooltip, child: Radio<bool>(value: true, groupValue: false, onChanged: null), ), ), ) ); // Default tooltip shows up after long pressed. final Finder tooltip0 = find.byType(Tooltip); expect(find.text(longPressTooltip), findsNothing); await tester.tap(tooltip0); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(longPressTooltip), findsNothing); final TestGesture gestureLongPress = await tester.startGesture(tester.getCenter(tooltip0)); await tester.pump(); await tester.pump(kLongPressTimeout); await gestureLongPress.up(); await tester.pump(); expect(find.text(longPressTooltip), findsOneWidget); // Tooltip shows up after tapping when set triggerMode to TooltipTriggerMode.tap. await tester.pumpWidget( MaterialApp( theme: theme, home: const Material( child: Tooltip( triggerMode: TooltipTriggerMode.tap, message: tapTooltip, child: Radio<bool>(value: true, groupValue: false, onChanged: null), ), ), ) ); await tester.pump(const Duration(days: 1)); await tester.pumpAndSettle(); expect(find.text(tapTooltip), findsNothing); expect(find.text(longPressTooltip), findsNothing); final Finder tooltip1 = find.byType(Tooltip); await tester.tap(tooltip1); await tester.pump(const Duration(milliseconds: 10)); expect(find.text(tapTooltip), findsOneWidget); }); testWidgets('Material2 - Radio button default colors', (WidgetTester tester) async { Widget buildRadio({bool enabled = true, bool selected = true}) { return MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Radio<bool>( value: true, groupValue: true, onChanged: enabled ? (_) {} : null, ), ) ); } await tester.pumpWidget(buildRadio()); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..circle(color: const Color(0xFF2196F3)) // Outer circle - primary value ..circle(color: const Color(0xFF2196F3))..restore(), // Inner circle - primary value ); await tester.pumpWidget(Container()); await tester.pumpWidget(buildRadio(selected: false)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..save() ..circle(color: const Color(0xFF2196F3)) ..restore(), ); await tester.pumpWidget(Container()); await tester.pumpWidget(buildRadio(enabled: false)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: Colors.black38) ); }); testWidgets('Material3 - Radio button default colors', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: true); Widget buildRadio({bool enabled = true, bool selected = true}) { return MaterialApp( theme: theme, home: Scaffold( body: Radio<bool>( value: true, groupValue: true, onChanged: enabled ? (_) {} : null, ), ) ); } await tester.pumpWidget(buildRadio()); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..circle(color: theme.colorScheme.primary) // Outer circle - primary value ..circle(color: theme.colorScheme.primary)..restore(), // Inner circle - primary value ); await tester.pumpWidget(Container()); await tester.pumpWidget(buildRadio(selected: false)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..save() ..circle(color: theme.colorScheme.primary) ..restore(), ); await tester.pumpWidget(Container()); await tester.pumpWidget(buildRadio(enabled: false)); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints ..circle(color: theme.colorScheme.onSurface.withOpacity(0.38)) ); }); testWidgets('Material2 - Radio button default overlay colors in hover/focus/press states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Radio'); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final ThemeData theme = ThemeData(useMaterial3: false); final ColorScheme colors = theme.colorScheme; Widget buildRadio({bool enabled = true, bool focused = false, bool selected = true}) { return MaterialApp( theme: theme, home: Scaffold( body: Radio<bool>( focusNode: focusNode, autofocus: focused, value: true, groupValue: selected, onChanged: enabled ? (_) {} : null, ), ), ); } // default selected radio await tester.pumpWidget(buildRadio()); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: colors.secondary) ); // selected radio in pressed state await tester.pumpWidget(buildRadio()); final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.byType(Radio<bool>))); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: colors.secondary.withAlpha(0x1F)) ..circle(color: colors.secondary ) ); // unselected radio in pressed state await tester.pumpWidget(buildRadio(selected: false)); final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byType(Radio<bool>))); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: theme.unselectedWidgetColor.withAlpha(0x1F))..circle(color: theme.unselectedWidgetColor) ); // selected radio in focused state await tester.pumpWidget(Container()); // reset test await tester.pumpWidget(buildRadio(focused: true)); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: theme.focusColor)..circle(color: colors.secondary) ); // unselected radio in focused state await tester.pumpWidget(Container()); // reset test await tester.pumpWidget(buildRadio(focused: true, selected: false)); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: theme.focusColor)..circle(color: theme.unselectedWidgetColor) ); // selected radio in hovered state await tester.pumpWidget(Container()); // reset test await tester.pumpWidget(buildRadio()); final TestGesture gesture3 = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture3.addPointer(); await gesture3.moveTo(tester.getCenter(find.byType(Radio<bool>))); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: theme.hoverColor)..circle(color: colors.secondary) ); focusNode.dispose(); // Finish gesture to release resources. await gesture1.up(); await gesture2.up(); await tester.pumpAndSettle(); }); testWidgets('Material3 - Radio button default overlay colors in hover/focus/press states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Radio'); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final ThemeData theme = ThemeData(useMaterial3: true); final ColorScheme colors = theme.colorScheme; Widget buildRadio({bool enabled = true, bool focused = false, bool selected = true}) { return MaterialApp( theme: theme, home: Scaffold( body: Radio<bool>( focusNode: focusNode, autofocus: focused, value: true, groupValue: selected, onChanged: enabled ? (_) {} : null, ), ), ); } // default selected radio await tester.pumpWidget(buildRadio()); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: colors.primary.withOpacity(1)) ); // selected radio in pressed state await tester.pumpWidget(buildRadio()); final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.byType(Radio<bool>))); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: colors.onSurface.withOpacity(0.1)) ..circle(color: colors.primary.withOpacity(1)) ); // unselected radio in pressed state await tester.pumpWidget(buildRadio(selected: false)); final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byType(Radio<bool>))); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: colors.primary.withOpacity(0.1))..circle(color: colors.onSurfaceVariant.withOpacity(1)) ); // selected radio in focused state await tester.pumpWidget(Container()); // reset test await tester.pumpWidget(buildRadio(focused: true)); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: colors.primary.withOpacity(0.1))..circle(color: colors.primary.withOpacity(1)) ); // unselected radio in focused state await tester.pumpWidget(Container()); // reset test await tester.pumpWidget(buildRadio(focused: true, selected: false)); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: colors.onSurface.withOpacity(0.1))..circle(color: colors.onSurface.withOpacity(1)) ); // selected radio in hovered state await tester.pumpWidget(Container()); // reset test await tester.pumpWidget(buildRadio()); final TestGesture gesture3 = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture3.addPointer(); await gesture3.moveTo(tester.getCenter(find.byType(Radio<bool>))); await tester.pumpAndSettle(); expect( Material.of(tester.element(find.byType(Radio<bool>))), paints..circle(color: colors.primary.withOpacity(0.08))..circle(color: colors.primary.withOpacity(1)) ); focusNode.dispose(); // Finish gesture to release resources. await gesture1.up(); await gesture2.up(); await tester.pumpAndSettle(); }); testWidgets('Radio.adaptive shows the correct platform widget', (WidgetTester tester) async { Widget buildApp(TargetPlatform platform) { return MaterialApp( theme: ThemeData(platform: platform), home: Material( child: Center( child: Radio<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); } }); testWidgets('Material2 - Radio default overlayColor and fillColor resolves pressed state', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Radio'); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final ThemeData theme = ThemeData(useMaterial3: false); Finder findRadio() { return find.byWidgetPredicate((Widget widget) => widget is Radio<bool>); } MaterialInkController? getRadioMaterial(WidgetTester tester) { return Material.of(tester.element(findRadio())); } await tester.pumpWidget(MaterialApp( theme: theme, home: Scaffold( body: Radio<bool>( focusNode: focusNode, value: true, groupValue: true, onChanged: (_) { }, ), ), )); // Hover final Offset center = tester.getCenter(find.byType(Radio<bool>)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(getRadioMaterial(tester), paints ..circle(color: theme.hoverColor) ..circle(color: theme.colorScheme.secondary) ); // Highlighted (pressed). await gesture.down(center); await tester.pumpAndSettle(); expect(getRadioMaterial(tester), paints ..circle(color: theme.colorScheme.secondary.withAlpha(kRadialReactionAlpha)) ..circle(color: theme.colorScheme.secondary) ); // Remove pressed and hovered states await gesture.up(); await tester.pumpAndSettle(); await gesture.moveTo(const Offset(0, 50)); await tester.pumpAndSettle(); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(getRadioMaterial(tester), paints ..circle(color: theme.focusColor) ..circle(color: theme.colorScheme.secondary) ); focusNode.dispose(); }); testWidgets('Material3 - Radio default overlayColor and fillColor resolves pressed state', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(debugLabel: 'Radio'); tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; final ThemeData theme = ThemeData(useMaterial3: true); Finder findRadio() { return find.byWidgetPredicate((Widget widget) => widget is Radio<bool>); } MaterialInkController? getRadioMaterial(WidgetTester tester) { return Material.of(tester.element(findRadio())); } await tester.pumpWidget(MaterialApp( theme: theme, home: Scaffold( body: Radio<bool>( focusNode: focusNode, value: true, groupValue: true, onChanged: (_) { }, ), ), )); // Hover final Offset center = tester.getCenter(find.byType(Radio<bool>)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(getRadioMaterial(tester), paints ..circle(color: theme.colorScheme.primary.withOpacity(0.08)) ..circle(color: theme.colorScheme.primary) ); // Highlighted (pressed). await gesture.down(center); await tester.pumpAndSettle(); expect(getRadioMaterial(tester), paints ..circle(color: theme.colorScheme.onSurface.withOpacity(0.1)) ..circle(color: theme.colorScheme.primary) ); // Remove pressed and hovered states await gesture.up(); await tester.pumpAndSettle(); await gesture.moveTo(const Offset(0, 50)); await tester.pumpAndSettle(); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(getRadioMaterial(tester), paints ..circle(color: theme.colorScheme.primary.withOpacity(0.1)) ..circle(color: theme.colorScheme.primary) ); focusNode.dispose(); }); }
flutter/packages/flutter/test/material/radio_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/radio_test.dart", "repo_id": "flutter", "token_count": 27971 }
717
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/process_text_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); } void main() { testWidgets('SelectionArea uses correct selection controls', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp( home: SelectionArea( child: Text('abc'), ), )); final SelectableRegion region = tester.widget<SelectableRegion>(find.byType(SelectableRegion)); switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: expect(region.selectionControls, materialTextSelectionHandleControls); case TargetPlatform.iOS: expect(region.selectionControls, cupertinoTextSelectionHandleControls); case TargetPlatform.linux: case TargetPlatform.windows: expect(region.selectionControls, desktopTextSelectionHandleControls); case TargetPlatform.macOS: expect(region.selectionControls, cupertinoDesktopTextSelectionHandleControls); } }, variant: TargetPlatformVariant.all()); testWidgets('Does not crash when long pressing on padding after dragging', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/123378 await tester.pumpWidget( const MaterialApp( color: Color(0xFF2196F3), title: 'Demo', home: Scaffold( body: SelectionArea( child: Padding( padding: EdgeInsets.all(100.0), child: Text('Hello World'), ), ), ), ), ); final TestGesture dragging = await tester.startGesture(const Offset(10, 10)); addTearDown(dragging.removePointer); await tester.pump(const Duration(milliseconds: 500)); await dragging.moveTo(const Offset(90, 90)); await dragging.up(); final TestGesture longpress = await tester.startGesture(const Offset(20,20)); addTearDown(longpress.removePointer); await tester.pump(const Duration(milliseconds: 500)); await longpress.up(); expect(tester.takeException(), isNull); }); // Regression test for https://github.com/flutter/flutter/issues/111370 testWidgets('Handle is correctly transformed when the text is inside of a FittedBox ',(WidgetTester tester) async { final Key textKey = UniqueKey(); await tester.pumpWidget( MaterialApp( color: const Color(0xFF2196F3), home: Scaffold( body: SelectionArea( child: SizedBox( height: 100, child: FittedBox( fit: BoxFit.fill, child: Text('test', key: textKey), ), ), ), ), ), ); final TestGesture longpress = await tester.startGesture(tester.getCenter(find.byType(Text))); addTearDown(longpress.removePointer); await tester.pump(const Duration(milliseconds: 500)); await longpress.up(); // Text box is scaled by 5. final RenderBox textBox = tester.firstRenderObject(find.byKey(textKey)); expect(textBox.size.height, 20.0); final Offset textPoint = textBox.localToGlobal(const Offset(0, 20)); expect(textPoint, equals(const Offset(0, 100))); // Find handles and verify their sizes. expect(find.byType(Overlay), findsOneWidget); expect(find.descendant(of: find.byType(Overlay),matching: find.byType(CustomPaint),),findsNWidgets(2)); final Iterable<RenderBox> handles = tester.renderObjectList(find.descendant( of: find.byType(Overlay), matching: find.byType(CustomPaint), )); // The handle height is determined by the formula: // textLineHeight + _kSelectionHandleRadius * 2 - _kSelectionHandleOverlap . // The text line height will be the value of the fontSize. // The constant _kSelectionHandleRadius has the value of 6. // The constant _kSelectionHandleOverlap has the value of 1.5. // The handle height before scaling is 20.0 + 6 * 2 - 1.5 = 30.5. final double handleHeightBeforeScaling = handles.first.size.height; expect(handleHeightBeforeScaling, 30.5); final Offset handleHeightAfterScaling = handles.first.localToGlobal(const Offset(0, 30.5)) - handles.first.localToGlobal(Offset.zero); // The handle height after scaling is 30.5 * 5 = 152.5 expect(handleHeightAfterScaling, equals(const Offset(0.0, 152.5))); }, skip: isBrowser, // [intended] variant: const TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS}), ); testWidgets('builds the default context menu by default', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectionArea( focusNode: focusNode, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); // Show the toolbar by longpressing. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 6)); // at the 'r' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); // `are` is selected. expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); await gesture.up(); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); }, skip: kIsWeb, // [intended] ); testWidgets('builds a custom context menu if provided', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectionArea( focusNode: focusNode, contextMenuBuilder: ( BuildContext context, SelectableRegionState selectableRegionState, ) { return Placeholder(key: key); }, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); expect(find.byKey(key), findsNothing); // Show the toolbar by longpressing. final RenderParagraph paragraph1 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph1, 6)); // at the 'r' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); // `are` is selected. expect(paragraph1.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); await gesture.up(); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); expect(find.byKey(key), findsOneWidget); }, skip: kIsWeb, // [intended] ); testWidgets('Text processing actions are added to the toolbar', (WidgetTester tester) async { final MockProcessTextHandler mockProcessTextHandler = MockProcessTextHandler(); TestWidgetsFlutterBinding.ensureInitialized().defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.processText, mockProcessTextHandler.handleMethodCall); addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.processText, null)); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); await tester.pumpWidget( MaterialApp( home: SelectionArea( focusNode: focusNode, child: const Text('How are you?'), ), ), ); await tester.pumpAndSettle(); expect(find.byType(AdaptiveTextSelectionToolbar), findsNothing); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>( find.descendant( of: find.text('How are you?'), matching: find.byType(RichText), ), ); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 6)); // at the 'r' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); // `are` is selected. expect(paragraph.selections[0], const TextSelection(baseOffset: 4, extentOffset: 7)); await gesture.up(); await tester.pumpAndSettle(); // The toolbar is visible. expect(find.byType(AdaptiveTextSelectionToolbar), findsOneWidget); // The text processing actions are visible on Android only. final bool areTextActionsSupported = defaultTargetPlatform == TargetPlatform.android; expect(find.text(fakeAction1Label), areTextActionsSupported ? findsOneWidget : findsNothing); expect(find.text(fakeAction2Label), areTextActionsSupported ? findsOneWidget : findsNothing); }, variant: TargetPlatformVariant.all(), skip: kIsWeb, // [intended] ); testWidgets('onSelectionChange is called when the selection changes', (WidgetTester tester) async { SelectedContent? content; await tester.pumpWidget(MaterialApp( home: SelectionArea( child: const Text('How are you'), onSelectionChanged: (SelectedContent? selectedContent) => content = selectedContent, ), )); final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('How are you'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph, 4), kind: PointerDeviceKind.mouse); expect(content, isNull); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 7)); await gesture.up(); await tester.pump(); expect(content, isNotNull); expect(content!.plainText, 'are'); // Backwards selection. await gesture.down(textOffsetToPosition(paragraph, 3)); await tester.pump(); await gesture.up(); await tester.pumpAndSettle(kDoubleTapTimeout); expect(content, isNotNull); expect(content!.plainText, ''); await gesture.down(textOffsetToPosition(paragraph, 3)); await tester.pump(); await gesture.moveTo(textOffsetToPosition(paragraph, 0)); await gesture.up(); await tester.pump(); expect(content, isNotNull); expect(content!.plainText, 'How'); }); testWidgets('stopping drag of end handle will show the toolbar', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); // Regression test for https://github.com/flutter/flutter/issues/119314 await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Padding( padding: const EdgeInsets.only(top: 64), child: Column( children: <Widget>[ const Text('How are you?'), SelectionArea( focusNode: focusNode, child: const Text('Good, and you?'), ), const Text('Fine, thank you.'), ], ), ), ), ), ); await tester.pumpAndSettle(); final RenderParagraph paragraph2 = tester.renderObject<RenderParagraph>(find.descendant(of: find.text('Good, and you?'), matching: find.byType(RichText))); final TestGesture gesture = await tester.startGesture(textOffsetToPosition(paragraph2, 7)); // at the 'a' addTearDown(gesture.removePointer); await tester.pump(const Duration(milliseconds: 500)); await gesture.up(); final List<TextBox> boxes = paragraph2.getBoxesForSelection(paragraph2.selections[0]); expect(boxes.length, 1); await tester.pumpAndSettle(); // There is a selection now. // We check the presence of the copy button to make sure the selection toolbar // is showing. expect(find.text('Copy'), findsOneWidget); // This is the position of the selection handle displayed at the end. final Offset handlePos = paragraph2.localToGlobal(boxes[0].toRect().bottomRight); await gesture.down(handlePos); await gesture.moveTo(textOffsetToPosition(paragraph2, 11) + Offset(0, paragraph2.size.height / 2)); await tester.pump(); await gesture.up(); await tester.pump(); // After lifting the finger up, the selection toolbar should be showing again. expect(find.text('Copy'), findsOneWidget); }, variant: TargetPlatformVariant.all(), skip: kIsWeb, // [intended] ); }
flutter/packages/flutter/test/material/selection_area_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/selection_area_test.dart", "repo_id": "flutter", "token_count": 4989 }
718
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import '../widgets/semantics_tester.dart'; void main() { testWidgets('TextButton, TextButton.icon defaults', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); final ThemeData theme = ThemeData.from(colorScheme: colorScheme); final bool material3 = theme.useMaterial3; // Enabled TextButton await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: TextButton( onPressed: () { }, child: const Text('button'), ), ), ), ); final Finder buttonMaterial = find.descendant( of: find.byType(TextButton), matching: find.byType(Material), ); Material material = tester.widget<Material>(buttonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderOnForeground, true); expect(material.borderRadius, null); expect(material.clipBehavior, Clip.none); expect(material.color, Colors.transparent); expect(material.elevation, 0.0); expect(material.shadowColor, material3 ? Colors.transparent : const Color(0xff000000)); expect(material.shape, material3 ? const StadiumBorder() : const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))); expect(material.textStyle!.color, colorScheme.primary); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(material.type, MaterialType.button); final Align align = tester.firstWidget<Align>(find.ancestor(of: find.text('button'), matching: find.byType(Align))); expect(align.alignment, Alignment.center); final Offset center = tester.getCenter(find.byType(TextButton)); final TestGesture gesture = await tester.startGesture(center); await tester.pump(); // start the splash animation await tester.pump(const Duration(milliseconds: 100)); // splash is underway // Material 3 uses the InkSparkle which uses a shader, so we can't capture // the effect with paint methods. if (!material3) { final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..circle(color: colorScheme.primary.withOpacity(0.12))); } await gesture.up(); await tester.pumpAndSettle(); material = tester.widget<Material>(buttonMaterial); // No change vs enabled and not pressed. expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderOnForeground, true); expect(material.borderRadius, null); expect(material.clipBehavior, Clip.none); expect(material.color, Colors.transparent); expect(material.elevation, 0.0); expect(material.shadowColor, material3 ? Colors.transparent : const Color(0xff000000)); expect(material.shape, material3 ? const StadiumBorder() : const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))); expect(material.textStyle!.color, colorScheme.primary); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(material.type, MaterialType.button); // Enabled TextButton.icon final Key iconButtonKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: TextButton.icon( key: iconButtonKey, onPressed: () { }, icon: const Icon(Icons.add), label: const Text('label'), ), ), ), ); final Finder iconButtonMaterial = find.descendant( of: find.byKey(iconButtonKey), matching: find.byType(Material), ); material = tester.widget<Material>(iconButtonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderOnForeground, true); expect(material.borderRadius, null); expect(material.clipBehavior, Clip.none); expect(material.color, Colors.transparent); expect(material.elevation, 0.0); expect(material.shadowColor, material3 ? Colors.transparent : const Color(0xff000000)); expect(material.shape, material3 ? const StadiumBorder() : const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))); expect(material.textStyle!.color, colorScheme.primary); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(material.type, MaterialType.button); // Disabled TextButton await tester.pumpWidget( MaterialApp( theme: theme, home: const Center( child: TextButton( onPressed: null, child: Text('button'), ), ), ), ); material = tester.widget<Material>(buttonMaterial); expect(material.animationDuration, const Duration(milliseconds: 200)); expect(material.borderOnForeground, true); expect(material.borderRadius, null); expect(material.clipBehavior, Clip.none); expect(material.color, Colors.transparent); expect(material.elevation, 0.0); expect(material.shadowColor, material3 ? Colors.transparent : const Color(0xff000000)); expect(material.shape, material3 ? const StadiumBorder() : const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4)))); expect(material.textStyle!.color, colorScheme.onSurface.withOpacity(0.38)); expect(material.textStyle!.fontFamily, 'Roboto'); expect(material.textStyle!.fontSize, 14); expect(material.textStyle!.fontWeight, FontWeight.w500); expect(material.type, MaterialType.button); }); testWidgets('TextButton.icon produces the correct widgets when icon is null', (WidgetTester tester) async { const ColorScheme colorScheme = ColorScheme.light(); final ThemeData theme = ThemeData.from(colorScheme: colorScheme); final Key iconButtonKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: TextButton.icon( key: iconButtonKey, onPressed: () { }, icon: const Icon(Icons.add), label: const Text('label'), ), ), ), ); expect(find.byIcon(Icons.add), findsOneWidget); expect(find.text('label'), findsOneWidget); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: TextButton.icon( key: iconButtonKey, onPressed: () { }, // No icon specified. label: const Text('label'), ), ), ), ); expect(find.byIcon(Icons.add), findsNothing); expect(find.text('label'), findsOneWidget); }); testWidgets('Default TextButton meets a11y contrast guidelines', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light()), home: Scaffold( body: Center( child: TextButton( onPressed: () { }, focusNode: focusNode, child: const Text('TextButton'), ), ), ), ), ); // Default, not disabled. await expectLater(tester, meetsGuideline(textContrastGuideline)); // Hovered. final Offset center = tester.getCenter(find.byType(TextButton)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); await expectLater(tester, meetsGuideline(textContrastGuideline)); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. await expectLater(tester, meetsGuideline(textContrastGuideline)); await gesture.removePointer(); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); await expectLater(tester, meetsGuideline(textContrastGuideline)); focusNode.dispose(); }, skip: isBrowser, // https://github.com/flutter/flutter/issues/44115 ); testWidgets('TextButton with colored theme meets a11y contrast guidelines', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); Color getTextColor(Set<MaterialState> states) { final Set<MaterialState> interactiveStates = <MaterialState>{ MaterialState.pressed, MaterialState.hovered, MaterialState.focused, }; if (states.any(interactiveStates.contains)) { return Colors.blue[900]!; } return Colors.blue[800]!; } await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: TextButtonTheme( data: TextButtonThemeData( style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith<Color>(getTextColor), ), ), child: Builder( builder: (BuildContext context) { return TextButton( onPressed: () {}, focusNode: focusNode, child: const Text('TextButton'), ); }, ), ), ), ), ), ); // Default, not disabled. await expectLater(tester, meetsGuideline(textContrastGuideline)); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); await expectLater(tester, meetsGuideline(textContrastGuideline)); // Hovered. final Offset center = tester.getCenter(find.byType(TextButton)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); await expectLater(tester, meetsGuideline(textContrastGuideline)); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. await expectLater(tester, meetsGuideline(textContrastGuideline)); focusNode.dispose(); }, skip: isBrowser, // https://github.com/flutter/flutter/issues/44115 ); testWidgets('TextButton default overlayColor resolves pressed state', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: Center( child: Builder( builder: (BuildContext context) { return TextButton( onPressed: () {}, focusNode: focusNode, child: const Text('TextButton'), ); }, ), ), ), ), ); RenderObject overlayColor() { return tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); } // Hovered. final Offset center = tester.getCenter(find.byType(TextButton)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(overlayColor(), paints..rect(color: theme.colorScheme.primary.withOpacity(0.08))); // Highlighted (pressed). await gesture.down(center); await tester.pumpAndSettle(); expect(overlayColor(), paints..rect()..rect(color: theme.colorScheme.primary.withOpacity(0.1))); // Remove pressed and hovered states await gesture.up(); await tester.pumpAndSettle(); await gesture.moveTo(const Offset(0, 50)); await tester.pumpAndSettle(); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(overlayColor(), paints..rect(color: theme.colorScheme.primary.withOpacity(0.1))); focusNode.dispose(); }); testWidgets('TextButton uses stateful color for text color in different states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); Color getTextColor(Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return pressedColor; } if (states.contains(MaterialState.hovered)) { return hoverColor; } if (states.contains(MaterialState.focused)) { return focusedColor; } return defaultColor; } await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith<Color>(getTextColor), ), onPressed: () {}, focusNode: focusNode, child: const Text('TextButton'), ), ), ), ), ); Color? textColor() { return tester.renderObject<RenderParagraph>(find.text('TextButton')).text.style?.color; } // Default, not disabled. expect(textColor(), equals(defaultColor)); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(textColor(), focusedColor); // Hovered. final Offset center = tester.getCenter(find.byType(TextButton)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(textColor(), hoverColor); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. expect(textColor(), pressedColor); focusNode.dispose(); }); testWidgets('TextButton uses stateful color for icon color in different states', (WidgetTester tester) async { final FocusNode focusNode = FocusNode(); final Key buttonKey = UniqueKey(); const Color pressedColor = Color(0x00000001); const Color hoverColor = Color(0x00000002); const Color focusedColor = Color(0x00000003); const Color defaultColor = Color(0x00000004); Color getTextColor(Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return pressedColor; } if (states.contains(MaterialState.hovered)) { return hoverColor; } if (states.contains(MaterialState.focused)) { return focusedColor; } return defaultColor; } await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: TextButton.icon( style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith<Color>(getTextColor), ), key: buttonKey, icon: const Icon(Icons.add), label: const Text('TextButton'), onPressed: () {}, focusNode: focusNode, ), ), ), ), ); Color? iconColor() => _iconStyle(tester, Icons.add)?.color; // Default, not disabled. expect(iconColor(), equals(defaultColor)); // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(iconColor(), focusedColor); // Hovered. final Offset center = tester.getCenter(find.byKey(buttonKey)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(iconColor(), hoverColor); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. expect(iconColor(), pressedColor); focusNode.dispose(); }); testWidgets('TextButton has no clip by default', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( child: Container(), onPressed: () { /* to make sure the button is enabled */ }, ), ), ); expect( tester.renderObject(find.byType(TextButton)), paintsExactlyCountTimes(#clipPath, 0), ); }); testWidgets('Does TextButton work with hover', (WidgetTester tester) async { const Color hoverColor = Color(0xff001122); Color? getOverlayColor(Set<MaterialState> states) { return states.contains(MaterialState.hovered) ? hoverColor : null; } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color?>(getOverlayColor), ), child: Container(), onPressed: () { /* to make sure the button is enabled */ }, ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(TextButton))); await tester.pumpAndSettle(); final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..rect(color: hoverColor)); }); testWidgets('Does TextButton work with focus', (WidgetTester tester) async { const Color focusColor = Color(0xff001122); Color? getOverlayColor(Set<MaterialState> states) { return states.contains(MaterialState.focused) ? focusColor : null; } final FocusNode focusNode = FocusNode(debugLabel: 'TextButton Node'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( style: ButtonStyle( overlayColor: MaterialStateProperty.resolveWith<Color?>(getOverlayColor), ), focusNode: focusNode, onPressed: () { }, child: const Text('button'), ), ), ); WidgetsBinding.instance.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; focusNode.requestFocus(); await tester.pumpAndSettle(); final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures'); expect(inkFeatures, paints..rect(color: focusColor)); focusNode.dispose(); }); testWidgets('Does TextButton contribute semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Center( child: TextButton( style: const ButtonStyle( // Specifying minimumSize to mimic the original minimumSize for // RaisedButton so that the semantics tree's rect and transform // match the original version of this test. minimumSize: MaterialStatePropertyAll<Size>(Size(88, 36)), ), onPressed: () { }, child: const Text('ABC'), ), ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( actions: <SemanticsAction>[ SemanticsAction.tap, ], label: 'ABC', rect: const Rect.fromLTRB(0.0, 0.0, 88.0, 48.0), transform: Matrix4.translationValues(356.0, 276.0, 0.0), flags: <SemanticsFlag>[ SemanticsFlag.hasEnabledState, SemanticsFlag.isButton, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], ), ], ), ignoreId: true, )); semantics.dispose(); }); testWidgets('Does TextButton scale with font scale changes', (WidgetTester tester) async { await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Center( child: TextButton( onPressed: () { }, child: const Text('ABC'), ), ), ), ), ), ); expect(tester.getSize(find.byType(TextButton)), equals(const Size(64.0, 48.0))); expect(tester.getSize(find.byType(Text)), equals(const Size(42.0, 14.0))); // textScaleFactor expands text, but not button. await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery.withClampedTextScaling( minScaleFactor: 1.25, maxScaleFactor: 1.25, child: Center( child: TextButton( onPressed: () { }, child: const Text('ABC'), ), ), ), ), ), ); const Size textButtonSize = Size(68.5, 48.0); const Size textSize = Size(52.5, 18.0); expect(tester.getSize(find.byType(TextButton)), textButtonSize); expect(tester.getSize(find.byType(Text)), textSize); // Set text scale large enough to expand text and button. await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Directionality( textDirection: TextDirection.ltr, child: MediaQuery.withClampedTextScaling( minScaleFactor: 3.0, maxScaleFactor: 3.0, child: Center( child: TextButton( onPressed: () { }, child: const Text('ABC'), ), ), ), ), ), ); expect(tester.getSize(find.byType(TextButton)), const Size(134.0, 48.0)); expect(tester.getSize(find.byType(Text)), const Size(126.0, 42.0)); }, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/61016 testWidgets('TextButton size is configurable by ThemeData.materialTapTargetSize', (WidgetTester tester) async { Widget buildFrame(MaterialTapTargetSize tapTargetSize, Key key) { return Theme( data: ThemeData(useMaterial3: false, materialTapTargetSize: tapTargetSize), child: Directionality( textDirection: TextDirection.ltr, child: Center( child: TextButton( key: key, style: TextButton.styleFrom(minimumSize: const Size(64, 36)), child: const SizedBox(width: 50.0, height: 8.0), onPressed: () { }, ), ), ), ); } final Key key1 = UniqueKey(); await tester.pumpWidget(buildFrame(MaterialTapTargetSize.padded, key1)); expect(tester.getSize(find.byKey(key1)), const Size(66.0, 48.0)); final Key key2 = UniqueKey(); await tester.pumpWidget(buildFrame(MaterialTapTargetSize.shrinkWrap, key2)); expect(tester.getSize(find.byKey(key2)), const Size(66.0, 36.0)); }); testWidgets('TextButton onPressed and onLongPress callbacks are correctly called when non-null', (WidgetTester tester) async { bool wasPressed; Finder textButton; Widget buildFrame({ VoidCallback? onPressed, VoidCallback? onLongPress }) { return Directionality( textDirection: TextDirection.ltr, child: TextButton( onPressed: onPressed, onLongPress: onLongPress, child: const Text('button'), ), ); } // onPressed not null, onLongPress null. wasPressed = false; await tester.pumpWidget( buildFrame(onPressed: () { wasPressed = true; }), ); textButton = find.byType(TextButton); expect(tester.widget<TextButton>(textButton).enabled, true); await tester.tap(textButton); expect(wasPressed, true); // onPressed null, onLongPress not null. wasPressed = false; await tester.pumpWidget( buildFrame(onLongPress: () { wasPressed = true; }), ); textButton = find.byType(TextButton); expect(tester.widget<TextButton>(textButton).enabled, true); await tester.longPress(textButton); expect(wasPressed, true); // onPressed null, onLongPress null. await tester.pumpWidget( buildFrame(), ); textButton = find.byType(TextButton); expect(tester.widget<TextButton>(textButton).enabled, false); }); testWidgets('TextButton onPressed and onLongPress callbacks are distinctly recognized', (WidgetTester tester) async { bool didPressButton = false; bool didLongPressButton = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( onPressed: () { didPressButton = true; }, onLongPress: () { didLongPressButton = true; }, child: const Text('button'), ), ), ); final Finder textButton = find.byType(TextButton); expect(tester.widget<TextButton>(textButton).enabled, true); expect(didPressButton, isFalse); await tester.tap(textButton); expect(didPressButton, isTrue); expect(didLongPressButton, isFalse); await tester.longPress(textButton); expect(didLongPressButton, isTrue); }); testWidgets("TextButton response doesn't hover when disabled", (WidgetTester tester) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch; final FocusNode focusNode = FocusNode(debugLabel: 'TextButton Focus'); final GlobalKey childKey = GlobalKey(); bool hovering = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 100, height: 100, child: TextButton( autofocus: true, onPressed: () {}, onLongPress: () {}, onHover: (bool value) { hovering = value; }, focusNode: focusNode, child: SizedBox(key: childKey), ), ), ), ); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isTrue); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byKey(childKey))); await tester.pumpAndSettle(); expect(hovering, isTrue); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SizedBox( width: 100, height: 100, child: TextButton( focusNode: focusNode, onHover: (bool value) { hovering = value; }, onPressed: null, child: SizedBox(key: childKey), ), ), ), ); await tester.pumpAndSettle(); expect(focusNode.hasPrimaryFocus, isFalse); focusNode.dispose(); }); testWidgets('disabled and hovered TextButton responds to mouse-exit', (WidgetTester tester) async { int onHoverCount = 0; late bool hover; Widget buildFrame({ required bool enabled }) { return Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( width: 100, height: 100, child: TextButton( onPressed: enabled ? () { } : null, onHover: (bool value) { onHoverCount += 1; hover = value; }, child: const Text('TextButton'), ), ), ), ); } await tester.pumpWidget(buildFrame(enabled: true)); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(TextButton))); await tester.pumpAndSettle(); expect(onHoverCount, 1); expect(hover, true); await tester.pumpWidget(buildFrame(enabled: false)); await tester.pumpAndSettle(); await gesture.moveTo(Offset.zero); // Even though the TextButton has been disabled, the mouse-exit still // causes onHover(false) to be called. expect(onHoverCount, 2); expect(hover, false); await gesture.moveTo(tester.getCenter(find.byType(TextButton))); await tester.pumpAndSettle(); // We no longer see hover events because the TextButton is disabled // and it's no longer in the "hovering" state. expect(onHoverCount, 2); expect(hover, false); await tester.pumpWidget(buildFrame(enabled: true)); await tester.pumpAndSettle(); // The TextButton was enabled while it contained the mouse, however // we do not call onHover() because it may call setState(). expect(onHoverCount, 2); expect(hover, false); await gesture.moveTo(tester.getCenter(find.byType(TextButton)) - const Offset(1, 1)); await tester.pumpAndSettle(); // Moving the mouse a little within the TextButton doesn't change anything. expect(onHoverCount, 2); expect(hover, false); }); testWidgets('Can set TextButton focus and Can set unFocus.', (WidgetTester tester) async { final FocusNode node = FocusNode(debugLabel: 'TextButton Focus'); bool gotFocus = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( focusNode: node, onFocusChange: (bool focused) => gotFocus = focused, onPressed: () { }, child: const SizedBox(), ), ), ); 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('When TextButton disable, Can not set TextButton focus.', (WidgetTester tester) async { final FocusNode node = FocusNode(debugLabel: 'TextButton Focus'); bool gotFocus = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( focusNode: node, onFocusChange: (bool focused) => gotFocus = focused, onPressed: null, child: const SizedBox(), ), ), ); node.requestFocus(); await tester.pump(); expect(gotFocus, isFalse); expect(node.hasFocus, isFalse); node.dispose(); }); testWidgets('TextButton responds to density changes.', (WidgetTester tester) async { const Key key = Key('test'); const Key childKey = Key('test child'); Future<void> buildTest(VisualDensity visualDensity, { bool useText = false }) async { return tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Directionality( textDirection: TextDirection.rtl, child: Center( child: TextButton( style: ButtonStyle( visualDensity: visualDensity, ), key: key, onPressed: () {}, child: useText ? const Text('Text', key: childKey) : Container(key: childKey, width: 100, height: 100, color: const Color(0xffff0000)), ), ), ), ), ); } await buildTest(VisualDensity.standard); final RenderBox box = tester.renderObject(find.byKey(key)); Rect childRect = tester.getRect(find.byKey(childKey)); await tester.pumpAndSettle(); expect(box.size, equals(const Size(116, 116))); expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350))); await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0)); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(140, 140))); expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350))); await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0)); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(116, 100))); expect(childRect, equals(const Rect.fromLTRB(350, 250, 450, 350))); await buildTest(VisualDensity.standard, useText: true); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(72, 48))); expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0))); await buildTest(const VisualDensity(horizontal: 3.0, vertical: 3.0), useText: true); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(96, 60))); expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0))); await buildTest(const VisualDensity(horizontal: -3.0, vertical: -3.0), useText: true); await tester.pumpAndSettle(); childRect = tester.getRect(find.byKey(childKey)); expect(box.size, equals(const Size(72, 36))); expect(childRect, equals(const Rect.fromLTRB(372.0, 293.0, 428.0, 307.0))); }); group('Default TextButton padding for textScaleFactor, textDirection', () { const ValueKey<String> buttonKey = ValueKey<String>('button'); const ValueKey<String> labelKey = ValueKey<String>('label'); const ValueKey<String> iconKey = ValueKey<String>('icon'); const List<double> textScaleFactorOptions = <double>[0.5, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0, 4.0]; const List<TextDirection> textDirectionOptions = <TextDirection>[TextDirection.ltr, TextDirection.rtl]; const List<Widget?> iconOptions = <Widget?>[null, Icon(Icons.add, size: 18, key: iconKey)]; // Expected values for each textScaleFactor. final Map<double, double> paddingVertical = <double, double>{ 0.5: 8, 1: 8, 1.25: 6, 1.5: 4, 2: 0, 2.5: 0, 3: 0, 4: 0, }; final Map<double, double> paddingWithIconGap = <double, double>{ 0.5: 8, 1: 8, 1.25: 7, 1.5: 6, 2: 4, 2.5: 4, 3: 4, 4: 4, }; final Map<double, double> textPaddingWithoutIconHorizontal = <double, double>{ 0.5: 8, 1: 8, 1.25: 8, 1.5: 8, 2: 8, 2.5: 6, 3: 4, 4: 4, }; final Map<double, double> textPaddingWithIconHorizontal = <double, double>{ 0.5: 8, 1: 8, 1.25: 7, 1.5: 6, 2: 4, 2.5: 4, 3: 4, 4: 4, }; Rect globalBounds(RenderBox renderBox) { final Offset topLeft = renderBox.localToGlobal(Offset.zero); return topLeft & renderBox.size; } /// Computes the padding between two [Rect]s, one inside the other. EdgeInsets paddingBetween({ required Rect parent, required Rect child }) { assert (parent.intersect(child) == child); return EdgeInsets.fromLTRB( child.left - parent.left, child.top - parent.top, parent.right - child.right, parent.bottom - child.bottom, ); } for (final double textScaleFactor in textScaleFactorOptions) { for (final TextDirection textDirection in textDirectionOptions) { for (final Widget? icon in iconOptions) { final String testName = <String>[ 'TextButton, text scale $textScaleFactor', if (icon != null) 'with icon', if (textDirection == TextDirection.rtl) 'RTL', ].join(', '); testWidgets(testName, (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData( useMaterial3: false, colorScheme: const ColorScheme.light(), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom(minimumSize: const Size(64, 36)), ), ), home: Builder( builder: (BuildContext context) { return MediaQuery.withClampedTextScaling( minScaleFactor: textScaleFactor, maxScaleFactor: textScaleFactor, child: Directionality( textDirection: textDirection, child: Scaffold( body: Center( child: icon == null ? TextButton( key: buttonKey, onPressed: () {}, child: const Text('button', key: labelKey), ) : TextButton.icon( key: buttonKey, onPressed: () {}, icon: icon, label: const Text('button', key: labelKey), ), ), ), ), ); }, ), ), ); final Element paddingElement = tester.element( find.descendant( of: find.byKey(buttonKey), matching: find.byType(Padding), ), ); expect(Directionality.of(paddingElement), textDirection); final Padding paddingWidget = paddingElement.widget as Padding; // Compute expected padding, and check. final double expectedPaddingTop = paddingVertical[textScaleFactor]!; final double expectedPaddingBottom = paddingVertical[textScaleFactor]!; final double expectedPaddingStart = icon != null ? textPaddingWithIconHorizontal[textScaleFactor]! : textPaddingWithoutIconHorizontal[textScaleFactor]!; final double expectedPaddingEnd = expectedPaddingStart; final EdgeInsets expectedPadding = EdgeInsetsDirectional.fromSTEB( expectedPaddingStart, expectedPaddingTop, expectedPaddingEnd, expectedPaddingBottom, ).resolve(textDirection); expect(paddingWidget.padding.resolve(textDirection), expectedPadding); // Measure padding in terms of the difference between the button and its label child // and check that. final RenderBox labelRenderBox = tester.renderObject<RenderBox>(find.byKey(labelKey)); final Rect labelBounds = globalBounds(labelRenderBox); final RenderBox? iconRenderBox = icon == null ? null : tester.renderObject<RenderBox>(find.byKey(iconKey)); final Rect? iconBounds = icon == null ? null : globalBounds(iconRenderBox!); final Rect childBounds = icon == null ? labelBounds : labelBounds.expandToInclude(iconBounds!); // We measure the `InkResponse` descendant of the button // element, because the button has a larger `RenderBox` // which accommodates the minimum tap target with a height // of 48. final RenderBox buttonRenderBox = tester.renderObject<RenderBox>( find.descendant( of: find.byKey(buttonKey), matching: find.byWidgetPredicate( (Widget widget) => widget is InkResponse, ), ), ); final Rect buttonBounds = globalBounds(buttonRenderBox); final EdgeInsets visuallyMeasuredPadding = paddingBetween( parent: buttonBounds, child: childBounds, ); // Since there is a requirement of a minimum width of 64 // and a minimum height of 36 on material buttons, the visual // padding of smaller buttons may not match their settings. // Therefore, we only test buttons that are large enough. if (buttonBounds.width > 64) { expect( visuallyMeasuredPadding.left, expectedPadding.left, ); expect( visuallyMeasuredPadding.right, expectedPadding.right, ); } if (buttonBounds.height > 36) { expect( visuallyMeasuredPadding.top, expectedPadding.top, ); expect( visuallyMeasuredPadding.bottom, expectedPadding.bottom, ); } // Check the gap between the icon and the label if (icon != null) { final double gapWidth = textDirection == TextDirection.ltr ? labelBounds.left - iconBounds!.right : iconBounds!.left - labelBounds.right; expect(gapWidth, paddingWithIconGap[textScaleFactor]); } // Check the text's height - should be consistent with the textScaleFactor. final RenderBox textRenderObject = tester.renderObject<RenderBox>( find.descendant( of: find.byKey(labelKey), matching: find.byElementPredicate( (Element element) => element.widget is RichText, ), ), ); final double textHeight = textRenderObject.paintBounds.size.height; final double expectedTextHeight = 14 * textScaleFactor; expect(textHeight, moreOrLessEquals(expectedTextHeight, epsilon: 0.5)); }); } } } }); testWidgets('Override TextButton default padding', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light()), home: Builder( builder: (BuildContext context) { return MediaQuery.withClampedTextScaling( minScaleFactor: 2, maxScaleFactor: 2, child: Scaffold( body: Center( child: TextButton( style: TextButton.styleFrom(padding: const EdgeInsets.all(22)), onPressed: () {}, child: const Text('TextButton'), ), ), ), ); }, ), ), ); final Padding paddingWidget = tester.widget<Padding>( find.descendant( of: find.byType(TextButton), matching: find.byType(Padding), ), ); expect(paddingWidget.padding, const EdgeInsets.all(22)); }); testWidgets('Override theme fontSize changes padding', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData.from( colorScheme: const ColorScheme.light(), textTheme: const TextTheme(labelLarge: TextStyle(fontSize: 28.0)), ), home: Builder( builder: (BuildContext context) { return Scaffold( body: Center( child: TextButton( onPressed: () {}, child: const Text('text'), ), ), ); }, ), ), ); final Padding paddingWidget = tester.widget<Padding>( find.descendant( of: find.byType(TextButton), matching: find.byType(Padding), ), ); expect(paddingWidget.padding, const EdgeInsets.symmetric(horizontal: 8)); }); testWidgets('M3 TextButton has correct default padding', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true), home: Scaffold( body: Center( child: TextButton( key: key, onPressed: () {}, child: const Text('TextButton'), ), ), ), ), ); final Padding paddingWidget = tester.widget<Padding>( find.descendant( of: find.byKey(key), matching: find.byType(Padding), ), ); expect(paddingWidget.padding, const EdgeInsets.symmetric(horizontal: 12,vertical: 8)); }); testWidgets('M3 TextButton.icon has correct default padding', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true), home: Scaffold( body: Center( child: TextButton.icon( key: key, onPressed: () {}, icon: const Icon(Icons.add), label: const Text('TextButton'), ), ), ), ), ); final Padding paddingWidget = tester.widget<Padding>( find.descendant( of: find.byKey(key), matching: find.byType(Padding), ), ); expect(paddingWidget.padding, const EdgeInsetsDirectional.fromSTEB(12, 8, 16, 8)); }); testWidgets('Fixed size TextButtons', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ TextButton( style: TextButton.styleFrom(fixedSize: const Size(100, 100)), onPressed: () {}, child: const Text('100x100'), ), TextButton( style: TextButton.styleFrom(fixedSize: const Size.fromWidth(200)), onPressed: () {}, child: const Text('200xh'), ), TextButton( style: TextButton.styleFrom(fixedSize: const Size.fromHeight(200)), onPressed: () {}, child: const Text('wx200'), ), ], ), ), ), ); expect(tester.getSize(find.widgetWithText(TextButton, '100x100')), const Size(100, 100)); expect(tester.getSize(find.widgetWithText(TextButton, '200xh')).width, 200); expect(tester.getSize(find.widgetWithText(TextButton, 'wx200')).height, 200); }); testWidgets('TextButton with NoSplash splashFactory paints nothing', (WidgetTester tester) async { Widget buildFrame({ InteractiveInkFeatureFactory? splashFactory }) { return MaterialApp( home: Scaffold( body: Center( child: TextButton( style: TextButton.styleFrom( splashFactory: splashFactory, ), onPressed: () { }, child: const Text('test'), ), ), ), ); } // NoSplash.splashFactory, no splash circles drawn await tester.pumpWidget(buildFrame(splashFactory: NoSplash.splashFactory)); { final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('test'))); final MaterialInkController material = Material.of(tester.element(find.text('test'))); await tester.pump(const Duration(milliseconds: 200)); expect(material, paintsExactlyCountTimes(#drawCircle, 0)); await gesture.up(); await tester.pumpAndSettle(); } // InkRipple.splashFactory, one splash circle drawn. await tester.pumpWidget(buildFrame(splashFactory: InkRipple.splashFactory)); { final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('test'))); final MaterialInkController material = Material.of(tester.element(find.text('test'))); await tester.pump(const Duration(milliseconds: 200)); expect(material, paintsExactlyCountTimes(#drawCircle, 1)); await gesture.up(); await tester.pumpAndSettle(); } }); testWidgets('TextButton uses InkSparkle only for Android non-web when useMaterial3 is true', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: true); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: TextButton( onPressed: () { }, child: const Text('button'), ), ), ), ); final InkWell buttonInkWell = tester.widget<InkWell>(find.descendant( of: find.byType(TextButton), matching: find.byType(InkWell), )); if (debugDefaultTargetPlatformOverride! == TargetPlatform.android && !kIsWeb) { expect(buttonInkWell.splashFactory, equals(InkSparkle.splashFactory)); } else { expect(buttonInkWell.splashFactory, equals(InkRipple.splashFactory)); } }, variant: TargetPlatformVariant.all()); testWidgets('TextButton uses InkRipple when useMaterial3 is false', (WidgetTester tester) async { final ThemeData theme = ThemeData(useMaterial3: false); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: TextButton( onPressed: () { }, child: const Text('button'), ), ), ), ); final InkWell buttonInkWell = tester.widget<InkWell>(find.descendant( of: find.byType(TextButton), matching: find.byType(InkWell), )); expect(buttonInkWell.splashFactory, equals(InkRipple.splashFactory)); }, variant: TargetPlatformVariant.all()); testWidgets('TextButton.icon does not overflow', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/77815 await tester.pumpWidget( MaterialApp( home: Scaffold( body: SizedBox( width: 200, child: TextButton.icon( onPressed: () {}, icon: const Icon(Icons.add), label: const Text( // Much wider than 200 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut a euismod nibh. Morbi laoreet purus.', ), ), ), ), ), ); expect(tester.takeException(), null); }); testWidgets('TextButton.icon icon,label layout', (WidgetTester tester) async { final Key buttonKey = UniqueKey(); final Key iconKey = UniqueKey(); final Key labelKey = UniqueKey(); final ButtonStyle style = TextButton.styleFrom( padding: EdgeInsets.zero, visualDensity: VisualDensity.standard, // dx=0, dy=0 ); await tester.pumpWidget( MaterialApp( home: Scaffold( body: SizedBox( width: 200, child: TextButton.icon( key: buttonKey, style: style, onPressed: () {}, icon: SizedBox(key: iconKey, width: 50, height: 100), label: SizedBox(key: labelKey, width: 50, height: 100), ), ), ), ), ); // The button's label and icon are separated by a gap of 8: // 46 [icon 50] 8 [label 50] 46 // The overall button width is 200. So: // icon.x = 46 // label.x = 46 + 50 + 8 = 104 expect(tester.getRect(find.byKey(buttonKey)), const Rect.fromLTRB(0.0, 0.0, 200.0, 100.0)); expect(tester.getRect(find.byKey(iconKey)), const Rect.fromLTRB(46.0, 0.0, 96.0, 100.0)); expect(tester.getRect(find.byKey(labelKey)), const Rect.fromLTRB(104.0, 0.0, 154.0, 100.0)); }); testWidgets('TextButton maximumSize', (WidgetTester tester) async { final Key key0 = UniqueKey(); final Key key1 = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), home: Scaffold( body: Center( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ TextButton( key: key0, style: TextButton.styleFrom( minimumSize: const Size(24, 36), maximumSize: const Size.fromWidth(64), ), onPressed: () { }, child: const Text('A B C D E F G H I J K L M N O P'), ), TextButton.icon( key: key1, style: TextButton.styleFrom( minimumSize: const Size(24, 36), maximumSize: const Size.fromWidth(104), ), onPressed: () {}, icon: Container(color: Colors.red, width: 32, height: 32), label: const Text('A B C D E F G H I J K L M N O P'), ), ], ), ), ), ), ); expect(tester.getSize(find.byKey(key0)), const Size(64.0, 128.0)); expect(tester.getSize(find.byKey(key1)), const Size(104.0, 128.0)); }); testWidgets('Fixed size TextButton, same as minimumSize == maximumSize', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ TextButton( style: TextButton.styleFrom(fixedSize: const Size(200, 200)), onPressed: () { }, child: const Text('200x200'), ), TextButton( style: TextButton.styleFrom( minimumSize: const Size(200, 200), maximumSize: const Size(200, 200), ), onPressed: () { }, child: const Text('200,200'), ), ], ), ), ), ); expect(tester.getSize(find.widgetWithText(TextButton, '200x200')), const Size(200, 200)); expect(tester.getSize(find.widgetWithText(TextButton, '200,200')), const Size(200, 200)); }); testWidgets('TextButton changes mouse cursor when hovered', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextButton( style: TextButton.styleFrom( enabledMouseCursor: SystemMouseCursors.text, disabledMouseCursor: SystemMouseCursors.grab, ), onPressed: () {}, child: const Text('button'), ), ), ), ); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: Offset.zero); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text); // Test cursor when disabled await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextButton( style: TextButton.styleFrom( enabledMouseCursor: SystemMouseCursors.text, disabledMouseCursor: SystemMouseCursors.grab, ), onPressed: null, child: const Text('button'), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grab); // Test default cursor await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextButton( onPressed: () {}, child: const Text('button'), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); // Test default cursor when disabled await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: MouseRegion( cursor: SystemMouseCursors.forbidden, child: TextButton( onPressed: null, child: Text('button'), ), ), ), ); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic); }); testWidgets('TextButton in SelectionArea changes mouse cursor when hovered', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/104595. await tester.pumpWidget(MaterialApp( home: SelectionArea( child: TextButton( style: TextButton.styleFrom( enabledMouseCursor: SystemMouseCursors.click, disabledMouseCursor: SystemMouseCursors.grab, ), onPressed: () {}, child: const Text('button'), ), ), )); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: tester.getCenter(find.byType(Text))); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click); }); testWidgets('TextButton.styleFrom can be used to set foreground and background colors', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: Scaffold( body: TextButton( style: TextButton.styleFrom( foregroundColor: Colors.white, backgroundColor: Colors.purple, ), onPressed: () {}, child: const Text('button'), ), ), ), ); final Material material = tester.widget<Material>(find.descendant( of: find.byType(TextButton), matching: find.byType(Material), )); expect(material.color, Colors.purple); expect(material.textStyle!.color, Colors.white); }); Future<void> testStatesController(Widget? icon, WidgetTester tester) async { int count = 0; void valueChanged() { count += 1; } final MaterialStatesController controller = MaterialStatesController(); addTearDown(controller.dispose); controller.addListener(valueChanged); await tester.pumpWidget( MaterialApp( home: Center( child: icon == null ? TextButton( statesController: controller, onPressed: () { }, child: const Text('button'), ) : TextButton.icon( statesController: controller, onPressed: () { }, icon: icon, label: const Text('button'), ), ), ), ); expect(controller.value, <MaterialState>{}); expect(count, 0); final Offset center = tester.getCenter(find.byType(Text)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered}); expect(count, 1); await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{}); expect(count, 2); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered}); expect(count, 3); await gesture.down(center); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed}); expect(count, 4); await gesture.up(); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered}); expect(count, 5); await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{}); expect(count, 6); await gesture.down(center); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.pressed}); expect(count, 8); // adds hovered and pressed - two changes // If the button is rebuilt disabled, then the pressed state is // removed. await tester.pumpWidget( MaterialApp( home: Center( child: icon == null ? TextButton( statesController: controller, onPressed: null, child: const Text('button'), ) : TextButton.icon( statesController: controller, onPressed: null, icon: icon, label: const Text('button'), ), ), ), ); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.hovered, MaterialState.disabled}); expect(count, 10); // removes pressed and adds disabled - two changes await gesture.moveTo(Offset.zero); await tester.pumpAndSettle(); expect(controller.value, <MaterialState>{MaterialState.disabled}); expect(count, 11); await gesture.removePointer(); } testWidgets('TextButton statesController', (WidgetTester tester) async { testStatesController(null, tester); }); testWidgets('TextButton.icon statesController', (WidgetTester tester) async { testStatesController(const Icon(Icons.add), tester); }); testWidgets('Disabled TextButton statesController', (WidgetTester tester) async { int count = 0; void valueChanged() { count += 1; } final MaterialStatesController controller = MaterialStatesController(); addTearDown(controller.dispose); controller.addListener(valueChanged); await tester.pumpWidget( MaterialApp( home: Center( child: TextButton( statesController: controller, onPressed: null, child: const Text('button'), ), ), ), ); expect(controller.value, <MaterialState>{MaterialState.disabled}); expect(count, 1); }); testWidgets('icon color can be different from the text color', (WidgetTester tester) async { final Key iconButtonKey = UniqueKey(); const ColorScheme colorScheme = ColorScheme.light(); final ThemeData theme = ThemeData.from(colorScheme: colorScheme); await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: TextButton.icon( key: iconButtonKey, style: TextButton.styleFrom(iconColor: Colors.red), icon: const Icon(Icons.add), onPressed: () {}, label: const Text('button'), ), ), ), ); Finder buttonMaterial = find.descendant( of: find.byKey(iconButtonKey), matching: find.byType(Material), ); Material material = tester.widget<Material>(buttonMaterial); expect(material.textStyle!.color, colorScheme.primary); Color? iconColor() => _iconStyle(tester, Icons.add)?.color; expect(iconColor(), equals(Colors.red)); // disabled button await tester.pumpWidget( MaterialApp( theme: theme, home: Center( child: TextButton.icon( key: iconButtonKey, style: TextButton.styleFrom(iconColor: Colors.red, disabledIconColor: Colors.blue), icon: const Icon(Icons.add), onPressed: null, label: const Text('button'), ), ), ), ); buttonMaterial = find.descendant( of: find.byKey(iconButtonKey), matching: find.byType(Material), ); material = tester.widget<Material>(buttonMaterial); expect(material.textStyle!.color, colorScheme.onSurface.withOpacity(0.38)); expect(iconColor(), equals(Colors.blue)); }); testWidgets("TextButton.styleFrom doesn't throw exception on passing only one cursor", (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/118071. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( style: TextButton.styleFrom( enabledMouseCursor: SystemMouseCursors.text, ), onPressed: () {}, child: const Text('button'), ), ), ); expect(tester.takeException(), isNull); }); testWidgets('TextButton backgroundBuilder and foregroundBuilder', (WidgetTester tester) async { const Color backgroundColor = Color(0xFF000011); const Color foregroundColor = Color(0xFF000022); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( style: TextButton.styleFrom( backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return DecoratedBox( decoration: const BoxDecoration( color: backgroundColor, ), child: child, ); }, foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return DecoratedBox( decoration: const BoxDecoration( color: foregroundColor, ), child: child, ); }, ), onPressed: () { }, child: const Text('button'), ), ), ); BoxDecoration boxDecorationOf(Finder finder) { return tester.widget<DecoratedBox>(finder).decoration as BoxDecoration; } final Finder decorations = find.descendant( of: find.byType(TextButton), matching: find.byType(DecoratedBox), ); expect(boxDecorationOf(decorations.at(0)).color, backgroundColor); expect(boxDecorationOf(decorations.at(1)).color, foregroundColor); Text textChildOf(Finder finder) { return tester.widget<Text>( find.descendant( of: finder, matching: find.byType(Text), ), ); } expect(textChildOf(decorations.at(0)).data, 'button'); expect(textChildOf(decorations.at(1)).data, 'button'); }); testWidgets('TextButton backgroundBuilder drops button child and foregroundBuilder return value', (WidgetTester tester) async { const Color backgroundColor = Color(0xFF000011); const Color foregroundColor = Color(0xFF000022); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( style: TextButton.styleFrom( backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return const DecoratedBox( decoration: BoxDecoration( color: backgroundColor, ), ); }, foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return const DecoratedBox( decoration: BoxDecoration( color: foregroundColor, ), ); }, ), onPressed: () { }, child: const Text('button'), ), ), ); final Finder background = find.descendant( of: find.byType(TextButton), matching: find.byType(DecoratedBox), ); expect(background, findsOneWidget); expect(find.text('button'), findsNothing); }); testWidgets('TextButton foregroundBuilder drops button child', (WidgetTester tester) async { const Color foregroundColor = Color(0xFF000022); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: TextButton( style: TextButton.styleFrom( foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { return const DecoratedBox( decoration: BoxDecoration( color: foregroundColor, ), ); }, ), onPressed: () { }, child: const Text('button'), ), ), ); final Finder foreground = find.descendant( of: find.byType(TextButton), matching: find.byType(DecoratedBox), ); expect(foreground, findsOneWidget); expect(find.text('button'), findsNothing); }); testWidgets('TextButton foreground and background builders are applied to the correct states', (WidgetTester tester) async { Set<MaterialState> foregroundStates = <MaterialState>{}; Set<MaterialState> backgroundStates = <MaterialState>{}; final FocusNode focusNode = FocusNode(); await tester.pumpWidget( MaterialApp( home: Scaffold( body: Center( child: TextButton( style: ButtonStyle( backgroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { backgroundStates = states; return child!; }, foregroundBuilder: (BuildContext context, Set<MaterialState> states, Widget? child) { foregroundStates = states; return child!; }, ), onPressed: () {}, focusNode: focusNode, child: const Text('button'), ), ), ), ), ); // Default. expect(backgroundStates.isEmpty, isTrue); expect(foregroundStates.isEmpty, isTrue); const Set<MaterialState> focusedStates = <MaterialState>{MaterialState.focused}; const Set<MaterialState> focusedHoveredStates = <MaterialState>{MaterialState.focused, MaterialState.hovered}; const Set<MaterialState> focusedHoveredPressedStates = <MaterialState>{MaterialState.focused, MaterialState.hovered, MaterialState.pressed}; bool sameStates(Set<MaterialState> expectedValue, Set<MaterialState> actualValue) { return expectedValue.difference(actualValue).isEmpty && actualValue.difference(expectedValue).isEmpty; } // Focused. focusNode.requestFocus(); await tester.pumpAndSettle(); expect(sameStates(focusedStates, backgroundStates), isTrue); expect(sameStates(focusedStates, foregroundStates), isTrue); // Hovered. final Offset center = tester.getCenter(find.byType(TextButton)); final TestGesture gesture = await tester.createGesture( kind: PointerDeviceKind.mouse, ); await gesture.addPointer(); await gesture.moveTo(center); await tester.pumpAndSettle(); expect(sameStates(focusedHoveredStates, backgroundStates), isTrue); expect(sameStates(focusedHoveredStates, foregroundStates), isTrue); // Highlighted (pressed). await gesture.down(center); await tester.pump(); // Start the splash and highlight animations. await tester.pump(const Duration(milliseconds: 800)); // Wait for splash and highlight to be well under way. expect(sameStates(focusedHoveredPressedStates, backgroundStates), isTrue); expect(sameStates(focusedHoveredPressedStates, foregroundStates), isTrue); focusNode.dispose(); }); testWidgets('TextButton styleFrom backgroundColor special case', (WidgetTester tester) async { // Regression test for an internal Google issue: b/323399158 const Color backgroundColor = Color(0xFF000022); Widget buildFrame({ VoidCallback? onPressed }) { return Directionality( textDirection: TextDirection.ltr, child: TextButton( style: TextButton.styleFrom( backgroundColor: backgroundColor, ), onPressed: () { }, child: const Text('button'), ), ); } await tester.pumpWidget(buildFrame(onPressed: () { })); // enabled final Material material = tester.widget<Material>(find.descendant( of: find.byType(TextButton), matching: find.byType(Material), )); expect(material.color, backgroundColor); await tester.pumpWidget(buildFrame()); // onPressed: null - disabled expect(material.color, backgroundColor); }); testWidgets('Default iconAlignment', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection }) { return MaterialApp( home: Directionality( textDirection: textDirection, child: Center( child: TextButton.icon( onPressed: () {}, icon: const Icon(Icons.add), label: const Text('button'), ), ), ), ); } // Test default iconAlignment when textDirection is ltr. await tester.pumpWidget(buildWidget(textDirection: TextDirection.ltr)); final Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); final Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); // The icon is aligned to the left of the button. expect(buttonTopLeft.dx, iconTopLeft.dx - 12.0); // 12.0 - padding between icon and button edge. // Test default iconAlignment when textDirection is rtl. await tester.pumpWidget(buildWidget(textDirection: TextDirection.rtl)); final Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); final Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); // The icon is aligned to the right of the button. expect(buttonTopRight.dx, iconTopRight.dx + 12.0); // 12.0 - padding between icon and button edge. }); testWidgets('iconAlignment can be customized', (WidgetTester tester) async { Widget buildWidget({ required TextDirection textDirection, required IconAlignment iconAlignment, }) { return MaterialApp( home: Directionality( textDirection: textDirection, child: Center( child: TextButton.icon( onPressed: () {}, icon: const Icon(Icons.add), label: const Text('button'), iconAlignment: iconAlignment, ), ), ), ); } // Test iconAlignment when textDirection is ltr. await tester.pumpWidget( buildWidget( textDirection: TextDirection.ltr, iconAlignment: IconAlignment.start, ), ); Offset buttonTopLeft = tester.getTopLeft(find.byType(Material).last); Offset iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); // The icon is aligned to the left of the button. expect(buttonTopLeft.dx, iconTopLeft.dx - 12.0); // 12.0 - padding between icon and button edge. // Test iconAlignment when textDirection is ltr. await tester.pumpWidget( buildWidget( textDirection: TextDirection.ltr, iconAlignment: IconAlignment.end, ), ); Offset buttonTopRight = tester.getTopRight(find.byType(Material).last); Offset iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); // The icon is aligned to the right of the button. expect(buttonTopRight.dx, iconTopRight.dx + 16.0); // 16.0 - padding between icon and button edge. // Test iconAlignment when textDirection is rtl. await tester.pumpWidget( buildWidget( textDirection: TextDirection.rtl, iconAlignment: IconAlignment.start, ), ); buttonTopRight = tester.getTopRight(find.byType(Material).last); iconTopRight = tester.getTopRight(find.byIcon(Icons.add)); // The icon is aligned to the right of the button. expect(buttonTopRight.dx, iconTopRight.dx + 12.0); // 12.0 - padding between icon and button edge. // Test iconAlignment when textDirection is rtl. await tester.pumpWidget( buildWidget( textDirection: TextDirection.rtl, iconAlignment: IconAlignment.end, ), ); buttonTopLeft = tester.getTopLeft(find.byType(Material).last); iconTopLeft = tester.getTopLeft(find.byIcon(Icons.add)); // The icon is aligned to the left of the button. expect(buttonTopLeft.dx, iconTopLeft.dx - 16.0); // 16.0 - padding between icon and button edge. }); } TextStyle? _iconStyle(WidgetTester tester, IconData icon) { final RichText iconRichText = tester.widget<RichText>( find.descendant(of: find.byIcon(icon), matching: find.byType(RichText)), ); return iconRichText.text.style; }
flutter/packages/flutter/test/material/text_button_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/text_button_test.dart", "repo_id": "flutter", "token_count": 33468 }
719
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' as ui; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { const TextTheme defaultGeometryTheme = Typography.englishLike2014; const TextTheme defaultGeometryThemeM3 = Typography.englishLike2021; test('ThemeDataTween control test', () { final ThemeData light = ThemeData.light(); final ThemeData dark = ThemeData.dark(); final ThemeDataTween tween = ThemeDataTween(begin: light, end: dark); expect(tween.lerp(0.25), equals(ThemeData.lerp(light, dark, 0.25))); }); testWidgets('PopupMenu inherits app theme', (WidgetTester tester) async { final Key popupMenuButtonKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(brightness: Brightness.dark), home: Scaffold( appBar: AppBar( actions: <Widget>[ PopupMenuButton<String>( key: popupMenuButtonKey, itemBuilder: (BuildContext context) { return <PopupMenuItem<String>>[ const PopupMenuItem<String>(child: Text('menuItem')), ]; }, ), ], ), ), ), ); await tester.tap(find.byKey(popupMenuButtonKey)); await tester.pump(const Duration(seconds: 1)); expect(Theme.of(tester.element(find.text('menuItem'))).brightness, equals(Brightness.dark)); }); testWidgets('Theme overrides selection style', (WidgetTester tester) async { final Key key = UniqueKey(); const Color defaultSelectionColor = Color(0x11111111); const Color defaultCursorColor = Color(0x22222222); const Color themeSelectionColor = Color(0x33333333); const Color themeCursorColor = Color(0x44444444); await tester.pumpWidget( MaterialApp( theme: ThemeData(brightness: Brightness.dark), home: Scaffold( body: DefaultSelectionStyle( selectionColor: defaultSelectionColor, cursorColor: defaultCursorColor, child: Theme( data: ThemeData( textSelectionTheme: const TextSelectionThemeData( selectionColor: themeSelectionColor, cursorColor: themeCursorColor, ), ), child: TextField( key: key, ), ) ), ), ), ); // Finds RenderEditable. final RenderObject root = tester.renderObject(find.byType(EditableText)); late RenderEditable renderEditable; void recursiveFinder(RenderObject child) { if (child is RenderEditable) { renderEditable = child; return; } child.visitChildren(recursiveFinder); } root.visitChildren(recursiveFinder); // Focus text field so it has a selection color. The selection color is null // on an unfocused text field. await tester.tap(find.byKey(key)); await tester.pump(); expect(renderEditable.selectionColor, themeSelectionColor); expect(tester.widget<EditableText>(find.byType(EditableText)).cursorColor, themeCursorColor); }); testWidgets('Material2 - Fallback theme', (WidgetTester tester) async { late BuildContext capturedContext; await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: false), child: Builder( builder: (BuildContext context) { capturedContext = context; return Container(); }, ), ), ); expect(Theme.of(capturedContext), equals(ThemeData.localize(ThemeData.fallback(useMaterial3: false), defaultGeometryTheme))); }); testWidgets('Material3 - Fallback theme', (WidgetTester tester) async { late BuildContext capturedContextM3; await tester.pumpWidget( Theme( data: ThemeData(useMaterial3: true), child: Builder( builder: (BuildContext context) { capturedContextM3 = context; return Container(); }, ), ), ); expect(Theme.of(capturedContextM3), equals(ThemeData.localize(ThemeData.fallback(useMaterial3: true), defaultGeometryThemeM3))); }); testWidgets('ThemeData.localize memoizes the result', (WidgetTester tester) async { final ThemeData light = ThemeData.light(); final ThemeData dark = ThemeData.dark(); // Same input, same output. expect( ThemeData.localize(light, defaultGeometryTheme), same(ThemeData.localize(light, defaultGeometryTheme)), ); // Different text geometry, different output. expect( ThemeData.localize(light, defaultGeometryTheme), isNot(same(ThemeData.localize(light, Typography.tall2014))), ); // Different base theme, different output. expect( ThemeData.localize(light, defaultGeometryTheme), isNot(same(ThemeData.localize(dark, defaultGeometryTheme))), ); }); testWidgets('Material2 - ThemeData with null typography uses proper defaults', (WidgetTester tester) async { final ThemeData m2Theme = ThemeData(useMaterial3: false); expect(m2Theme.typography, Typography.material2014()); }); testWidgets('Material3 - ThemeData with null typography uses proper defaults', (WidgetTester tester) async { final ThemeData m3Theme = ThemeData(useMaterial3: true); expect(m3Theme.typography, Typography.material2021(colorScheme: m3Theme.colorScheme)); }); testWidgets('PopupMenu inherits shadowed app theme', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/5572 final Key popupMenuButtonKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(brightness: Brightness.dark), home: Theme( data: ThemeData(brightness: Brightness.light), child: Scaffold( appBar: AppBar( actions: <Widget>[ PopupMenuButton<String>( key: popupMenuButtonKey, itemBuilder: (BuildContext context) { return <PopupMenuItem<String>>[ const PopupMenuItem<String>(child: Text('menuItem')), ]; }, ), ], ), ), ), ), ); await tester.tap(find.byKey(popupMenuButtonKey)); await tester.pump(const Duration(seconds: 1)); expect(Theme.of(tester.element(find.text('menuItem'))).brightness, equals(Brightness.light)); }); testWidgets('DropdownMenu inherits shadowed app theme', (WidgetTester tester) async { final Key dropdownMenuButtonKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(brightness: Brightness.dark), home: Theme( data: ThemeData(brightness: Brightness.light), child: Scaffold( appBar: AppBar( actions: <Widget>[ DropdownButton<String>( key: dropdownMenuButtonKey, onChanged: (String? newValue) { }, value: 'menuItem', items: const <DropdownMenuItem<String>>[ DropdownMenuItem<String>( value: 'menuItem', child: Text('menuItem'), ), ], ), ], ), ), ), ), ); await tester.tap(find.byKey(dropdownMenuButtonKey)); await tester.pump(const Duration(seconds: 1)); for (final Element item in tester.elementList(find.text('menuItem'))) { expect(Theme.of(item).brightness, equals(Brightness.light)); } }); testWidgets('ModalBottomSheet inherits shadowed app theme', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(brightness: Brightness.dark), home: Theme( data: ThemeData(brightness: Brightness.light), child: Scaffold( body: Center( child: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showModalBottomSheet<void>( context: context, builder: (BuildContext context) => const Text('bottomSheet'), ); }, child: const Text('SHOW'), ); }, ), ), ), ), ), ); await tester.tap(find.text('SHOW')); await tester.pump(); // start animation await tester.pump(const Duration(seconds: 1)); // end animation expect(Theme.of(tester.element(find.text('bottomSheet'))).brightness, equals(Brightness.light)); }); testWidgets('Dialog inherits shadowed app theme', (WidgetTester tester) async { final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>(); await tester.pumpWidget( MaterialApp( theme: ThemeData(brightness: Brightness.dark), home: Theme( data: ThemeData(brightness: Brightness.light), child: Scaffold( key: scaffoldKey, body: Center( child: Builder( builder: (BuildContext context) { return ElevatedButton( onPressed: () { showDialog<void>( context: context, builder: (BuildContext context) => const Text('dialog'), ); }, child: const Text('SHOW'), ); }, ), ), ), ), ), ); await tester.tap(find.text('SHOW')); await tester.pump(const Duration(seconds: 1)); expect(Theme.of(tester.element(find.text('dialog'))).brightness, equals(Brightness.light)); }); testWidgets("Scaffold inherits theme's scaffoldBackgroundColor", (WidgetTester tester) async { const Color green = Color(0xFF00FF00); await tester.pumpWidget( MaterialApp( theme: ThemeData(scaffoldBackgroundColor: green), home: Scaffold( body: Center( child: Builder( builder: (BuildContext context) { return GestureDetector( onTap: () { showDialog<void>( context: context, builder: (BuildContext context) { return const Scaffold( body: SizedBox( width: 200.0, height: 200.0, ), ); }, ); }, child: const Text('SHOW'), ); }, ), ), ), ), ); await tester.tap(find.text('SHOW')); await tester.pump(const Duration(seconds: 1)); final List<Material> materials = tester.widgetList<Material>(find.byType(Material)).toList(); expect(materials.length, equals(2)); expect(materials[0].color, green); // app scaffold expect(materials[1].color, green); // dialog scaffold }); testWidgets('IconThemes are applied', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( theme: ThemeData(iconTheme: const IconThemeData(color: Colors.green, size: 10.0)), home: const Icon(Icons.computer), ), ); RenderParagraph glyphText = tester.renderObject(find.byType(RichText)); expect(glyphText.text.style!.color, Colors.green); expect(glyphText.text.style!.fontSize, 10.0); await tester.pumpWidget( MaterialApp( theme: ThemeData(iconTheme: const IconThemeData(color: Colors.orange, size: 20.0)), home: const Icon(Icons.computer), ), ); await tester.pump(const Duration(milliseconds: 100)); // Halfway through the theme transition glyphText = tester.renderObject(find.byType(RichText)); expect(glyphText.text.style!.color, Color.lerp(Colors.green, Colors.orange, 0.5)); expect(glyphText.text.style!.fontSize, 15.0); await tester.pump(const Duration(milliseconds: 100)); // Finish the transition glyphText = tester.renderObject(find.byType(RichText)); expect(glyphText.text.style!.color, Colors.orange); expect(glyphText.text.style!.fontSize, 20.0); }); testWidgets( 'Same ThemeData reapplied does not trigger descendants rebuilds', (WidgetTester tester) async { testBuildCalled = 0; ThemeData themeData = ThemeData(primaryColor: const Color(0xFF000000)); Widget buildTheme() { return Theme( data: themeData, child: const Test(), ); } await tester.pumpWidget(buildTheme()); expect(testBuildCalled, 1); // Pump the same widgets again. await tester.pumpWidget(buildTheme()); // No repeated build calls to the child since it's the same theme data. expect(testBuildCalled, 1); // New instance of theme data but still the same content. themeData = ThemeData(primaryColor: const Color(0xFF000000)); await tester.pumpWidget(buildTheme()); // Still no repeated calls. expect(testBuildCalled, 1); // Different now. themeData = ThemeData(primaryColor: const Color(0xFF222222)); await tester.pumpWidget(buildTheme()); // Should call build again. expect(testBuildCalled, 2); }, ); testWidgets('Text geometry set in Theme has higher precedence than that of Localizations', (WidgetTester tester) async { const double kMagicFontSize = 4321.0; final ThemeData fallback = ThemeData.fallback(); final ThemeData customTheme = fallback.copyWith( primaryTextTheme: fallback.primaryTextTheme.copyWith( bodyMedium: fallback.primaryTextTheme.bodyMedium!.copyWith( fontSize: kMagicFontSize, ), ), ); expect(customTheme.primaryTextTheme.bodyMedium!.fontSize, kMagicFontSize); late double actualFontSize; await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Theme( data: customTheme, child: Builder(builder: (BuildContext context) { final ThemeData theme = Theme.of(context); actualFontSize = theme.primaryTextTheme.bodyMedium!.fontSize!; return Text( 'A', style: theme.primaryTextTheme.bodyMedium, ); }), ), )); expect(actualFontSize, kMagicFontSize); }); testWidgets('Material2 - Default Theme provides all basic TextStyle properties', (WidgetTester tester) async { late ThemeData theme; await tester.pumpWidget(Theme( data: ThemeData(useMaterial3: false), child: Directionality( textDirection: TextDirection.ltr, child: Builder( builder: (BuildContext context) { theme = Theme.of(context); return const Text('A'); }, ), ), )); List<TextStyle> extractStyles(TextTheme textTheme) { return <TextStyle>[ textTheme.displayLarge!, textTheme.displayMedium!, textTheme.displaySmall!, textTheme.headlineLarge!, textTheme.headlineMedium!, textTheme.headlineSmall!, textTheme.titleLarge!, textTheme.titleMedium!, textTheme.bodyLarge!, textTheme.bodyMedium!, textTheme.bodySmall!, textTheme.labelLarge!, textTheme.labelMedium!, // textTheme.labelSmall!, ]; } for (final TextTheme textTheme in <TextTheme>[theme.textTheme, theme.primaryTextTheme]) { for (final TextStyle style in extractStyles(textTheme).map<TextStyle>((TextStyle style) => _TextStyleProxy(style))) { expect(style.inherit, false); expect(style.color, isNotNull); expect(style.fontFamily, isNotNull); expect(style.fontSize, isNotNull); expect(style.fontWeight, isNotNull); expect(style.fontStyle, null); expect(style.letterSpacing, null); expect(style.wordSpacing, null); expect(style.textBaseline, isNotNull); expect(style.height, null); expect(style.decoration, TextDecoration.none); expect(style.decorationColor, null); expect(style.decorationStyle, null); expect(style.debugLabel, isNotNull); expect(style.locale, null); expect(style.background, null); } } expect(theme.textTheme.displayLarge!.debugLabel, '(englishLike displayLarge 2014).merge(blackMountainView displayLarge)'); }); testWidgets('Material3 - Default Theme provides all basic TextStyle properties', (WidgetTester tester) async { late ThemeData theme; await tester.pumpWidget(Theme( data: ThemeData(useMaterial3: true), child: Directionality( textDirection: TextDirection.ltr, child: Builder( builder: (BuildContext context) { theme = Theme.of(context); return const Text('A'); }, ), ), )); List<TextStyle> extractStyles(TextTheme textTheme) { return <TextStyle>[ textTheme.displayLarge!, textTheme.displayMedium!, textTheme.displaySmall!, textTheme.headlineLarge!, textTheme.headlineMedium!, textTheme.headlineSmall!, textTheme.titleLarge!, textTheme.titleMedium!, textTheme.bodyLarge!, textTheme.bodyMedium!, textTheme.bodySmall!, textTheme.labelLarge!, textTheme.labelMedium!, ]; } for (final TextTheme textTheme in <TextTheme>[theme.textTheme, theme.primaryTextTheme]) { for (final TextStyle style in extractStyles(textTheme).map<TextStyle>((TextStyle style) => _TextStyleProxy(style))) { expect(style.inherit, false); expect(style.color, isNotNull); expect(style.fontFamily, isNotNull); expect(style.fontSize, isNotNull); expect(style.fontWeight, isNotNull); expect(style.fontStyle, null); expect(style.letterSpacing, isNotNull); expect(style.wordSpacing, null); expect(style.textBaseline, isNotNull); expect(style.height, isNotNull); expect(style.decoration, TextDecoration.none); expect(style.decorationColor, isNotNull); expect(style.decorationStyle, null); expect(style.debugLabel, isNotNull); expect(style.locale, null); expect(style.background, null); } } expect(theme.textTheme.displayLarge!.debugLabel, '(englishLike displayLarge 2021).merge((blackMountainView displayLarge).apply)'); }); group('Cupertino theme', () { late int buildCount; CupertinoThemeData? actualTheme; IconThemeData? actualIconTheme; BuildContext? context; final Widget singletonThemeSubtree = Builder( builder: (BuildContext localContext) { buildCount++; actualTheme = CupertinoTheme.of(localContext); actualIconTheme = IconTheme.of(localContext); context = localContext; return const Placeholder(); }, ); Future<CupertinoThemeData> testTheme(WidgetTester tester, ThemeData theme) async { await tester.pumpWidget(Theme(data: theme, child: singletonThemeSubtree)); return actualTheme!; } setUp(() { buildCount = 0; actualTheme = null; actualIconTheme = null; context = null; }); testWidgets('Material2 - Default light theme has defaults', (WidgetTester tester) async { final CupertinoThemeData themeM2 = await testTheme(tester, ThemeData(useMaterial3: false)); expect(themeM2.brightness, Brightness.light); expect(themeM2.primaryColor, Colors.blue); expect(themeM2.scaffoldBackgroundColor, Colors.grey[50]); expect(themeM2.primaryContrastingColor, Colors.white); expect(themeM2.textTheme.textStyle.fontFamily, 'CupertinoSystemText'); expect(themeM2.textTheme.textStyle.fontSize, 17.0); }); testWidgets('Material3 - Default light theme has defaults', (WidgetTester tester) async { final CupertinoThemeData themeM3 = await testTheme(tester, ThemeData(useMaterial3: true)); expect(themeM3.brightness, Brightness.light); expect(themeM3.primaryColor, const Color(0xff6750a4)); expect(themeM3.scaffoldBackgroundColor, const Color(0xfffef7ff)); // ColorScheme.background expect(themeM3.primaryContrastingColor, Colors.white); expect(themeM3.textTheme.textStyle.fontFamily, 'CupertinoSystemText'); expect(themeM3.textTheme.textStyle.fontSize, 17.0); }); testWidgets('Material2 - Dark theme has defaults', (WidgetTester tester) async { final CupertinoThemeData themeM2 = await testTheme(tester, ThemeData.dark(useMaterial3: false)); expect(themeM2.brightness, Brightness.dark); expect(themeM2.primaryColor, Colors.blue); expect(themeM2.primaryContrastingColor, Colors.white); expect(themeM2.scaffoldBackgroundColor, Colors.grey[850]); expect(themeM2.textTheme.textStyle.fontFamily, 'CupertinoSystemText'); expect(themeM2.textTheme.textStyle.fontSize, 17.0); }); testWidgets('Material3 - Dark theme has defaults', (WidgetTester tester) async { final CupertinoThemeData themeM3 = await testTheme(tester, ThemeData.dark(useMaterial3: true)); expect(themeM3.brightness, Brightness.dark); expect(themeM3.primaryColor, const Color(0xffd0bcff)); expect(themeM3.primaryContrastingColor, const Color(0xff381e72)); expect(themeM3.scaffoldBackgroundColor, const Color(0xff141218)); expect(themeM3.textTheme.textStyle.fontFamily, 'CupertinoSystemText'); expect(themeM3.textTheme.textStyle.fontSize, 17.0); }); testWidgets('MaterialTheme overrides the brightness', (WidgetTester tester) async { await testTheme(tester, ThemeData.dark()); expect(CupertinoTheme.brightnessOf(context!), Brightness.dark); await testTheme(tester, ThemeData.light()); expect(CupertinoTheme.brightnessOf(context!), Brightness.light); // Overridable by cupertinoOverrideTheme. await testTheme(tester, ThemeData( brightness: Brightness.light, cupertinoOverrideTheme: const CupertinoThemeData(brightness: Brightness.dark), )); expect(CupertinoTheme.brightnessOf(context!), Brightness.dark); await testTheme(tester, ThemeData( brightness: Brightness.dark, cupertinoOverrideTheme: const CupertinoThemeData(brightness: Brightness.light), )); expect(CupertinoTheme.brightnessOf(context!), Brightness.light); }); testWidgets('Material2 - Can override material theme', (WidgetTester tester) async { final CupertinoThemeData themeM2 = await testTheme(tester, ThemeData( cupertinoOverrideTheme: const CupertinoThemeData( scaffoldBackgroundColor: CupertinoColors.lightBackgroundGray, ), useMaterial3: false, )); expect(themeM2.brightness, Brightness.light); // We took the scaffold background override but the rest are still cascaded // to the material themeM2. expect(themeM2.primaryColor, Colors.blue); expect(themeM2.primaryContrastingColor, Colors.white); expect(themeM2.scaffoldBackgroundColor, CupertinoColors.lightBackgroundGray); expect(themeM2.textTheme.textStyle.fontFamily, 'CupertinoSystemText'); expect(themeM2.textTheme.textStyle.fontSize, 17.0); }); testWidgets('Material3 - Can override material theme', (WidgetTester tester) async { final CupertinoThemeData themeM3 = await testTheme(tester, ThemeData( cupertinoOverrideTheme: const CupertinoThemeData( scaffoldBackgroundColor: CupertinoColors.lightBackgroundGray, ), useMaterial3: true, )); expect(themeM3.brightness, Brightness.light); // We took the scaffold background override but the rest are still cascaded // to the material themeM3. expect(themeM3.primaryColor, const Color(0xff6750a4)); expect(themeM3.primaryContrastingColor, Colors.white); expect(themeM3.scaffoldBackgroundColor, CupertinoColors.lightBackgroundGray); expect(themeM3.textTheme.textStyle.fontFamily, 'CupertinoSystemText'); expect(themeM3.textTheme.textStyle.fontSize, 17.0); }); testWidgets('Material2 - Can override properties that are independent of material', (WidgetTester tester) async { final CupertinoThemeData themeM2 = await testTheme(tester, ThemeData( cupertinoOverrideTheme: const CupertinoThemeData( // The bar colors ignore all things material except brightness. barBackgroundColor: CupertinoColors.black, ), useMaterial3: false, )); expect(themeM2.primaryColor, Colors.blue); // MaterialBasedCupertinoThemeData should also function like a normal CupertinoThemeData. expect(themeM2.barBackgroundColor, CupertinoColors.black); }); testWidgets('Material3 - Can override properties that are independent of material', (WidgetTester tester) async { final CupertinoThemeData themeM3 = await testTheme(tester, ThemeData( cupertinoOverrideTheme: const CupertinoThemeData( // The bar colors ignore all things material except brightness. barBackgroundColor: CupertinoColors.black, ), useMaterial3: true )); expect(themeM3.primaryColor, const Color(0xff6750a4)); // MaterialBasedCupertinoThemeData should also function like a normal CupertinoThemeData. expect(themeM3.barBackgroundColor, CupertinoColors.black); }); testWidgets('Material2 - Changing material theme triggers rebuilds', (WidgetTester tester) async { CupertinoThemeData themeM2 = await testTheme(tester, ThemeData( useMaterial3: false, primarySwatch: Colors.red, )); expect(buildCount, 1); expect(themeM2.primaryColor, Colors.red); themeM2 = await testTheme(tester, ThemeData( useMaterial3: false, primarySwatch: Colors.orange, )); expect(buildCount, 2); expect(themeM2.primaryColor, Colors.orange); }); testWidgets('Material3 - Changing material theme triggers rebuilds', (WidgetTester tester) async { CupertinoThemeData themeM3 = await testTheme(tester, ThemeData( useMaterial3: true, colorScheme: const ColorScheme.light( primary: Colors.red ), )); expect(buildCount, 1); expect(themeM3.primaryColor, Colors.red); themeM3 = await testTheme(tester, ThemeData( useMaterial3: true, colorScheme: const ColorScheme.light( primary: Colors.orange ), )); expect(buildCount, 2); expect(themeM3.primaryColor, Colors.orange); }); testWidgets( "CupertinoThemeData does not override material theme's icon theme", (WidgetTester tester) async { const Color materialIconColor = Colors.blue; const Color cupertinoIconColor = Colors.black; await testTheme(tester, ThemeData( iconTheme: const IconThemeData(color: materialIconColor), cupertinoOverrideTheme: const CupertinoThemeData(primaryColor: cupertinoIconColor), )); expect(buildCount, 1); expect(actualIconTheme!.color, materialIconColor); }, ); testWidgets( 'Changing cupertino theme override triggers rebuilds', (WidgetTester tester) async { CupertinoThemeData theme = await testTheme(tester, ThemeData( primarySwatch: Colors.purple, cupertinoOverrideTheme: const CupertinoThemeData( primaryColor: CupertinoColors.activeOrange, ), )); expect(buildCount, 1); expect(theme.primaryColor, CupertinoColors.activeOrange); theme = await testTheme(tester, ThemeData( primarySwatch: Colors.purple, cupertinoOverrideTheme: const CupertinoThemeData( primaryColor: CupertinoColors.activeGreen, ), )); expect(buildCount, 2); expect(theme.primaryColor, CupertinoColors.activeGreen); }, ); testWidgets( 'Cupertino theme override blocks derivative changes', (WidgetTester tester) async { CupertinoThemeData theme = await testTheme(tester, ThemeData( primarySwatch: Colors.purple, cupertinoOverrideTheme: const CupertinoThemeData( primaryColor: CupertinoColors.activeOrange, ), )); expect(buildCount, 1); expect(theme.primaryColor, CupertinoColors.activeOrange); // Change the upstream material primary color. theme = await testTheme(tester, ThemeData( primarySwatch: Colors.blue, cupertinoOverrideTheme: const CupertinoThemeData( // But the primary material color is preempted by the override. primaryColor: CupertinoColors.systemRed, ), )); expect(buildCount, 2); expect(theme.primaryColor, CupertinoColors.systemRed); }, ); testWidgets( 'Material2 - Cupertino overrides do not block derivatives triggering rebuilds when derivatives are not overridden', (WidgetTester tester) async { CupertinoThemeData theme = await testTheme(tester, ThemeData( useMaterial3: false, primarySwatch: Colors.purple, cupertinoOverrideTheme: const CupertinoThemeData( primaryContrastingColor: CupertinoColors.destructiveRed, ), )); expect(buildCount, 1); expect(theme.textTheme.actionTextStyle.color, Colors.purple); expect(theme.primaryContrastingColor, CupertinoColors.destructiveRed); theme = await testTheme(tester, ThemeData( useMaterial3: false, primarySwatch: Colors.green, cupertinoOverrideTheme: const CupertinoThemeData( primaryContrastingColor: CupertinoColors.destructiveRed, ), )); expect(buildCount, 2); expect(theme.textTheme.actionTextStyle.color, Colors.green); expect(theme.primaryContrastingColor, CupertinoColors.destructiveRed); }, ); testWidgets( 'Material3 - Cupertino overrides do not block derivatives triggering rebuilds when derivatives are not overridden', (WidgetTester tester) async { CupertinoThemeData theme = await testTheme(tester, ThemeData( useMaterial3: true, colorScheme: const ColorScheme.light( primary: Colors.purple, ), cupertinoOverrideTheme: const CupertinoThemeData( primaryContrastingColor: CupertinoColors.destructiveRed, ), )); expect(buildCount, 1); expect(theme.textTheme.actionTextStyle.color, Colors.purple); expect(theme.primaryContrastingColor, CupertinoColors.destructiveRed); theme = await testTheme(tester, ThemeData( useMaterial3: true, colorScheme: const ColorScheme.light( primary: Colors.green, ), cupertinoOverrideTheme: const CupertinoThemeData( primaryContrastingColor: CupertinoColors.destructiveRed, ), )); expect(buildCount, 2); expect(theme.textTheme.actionTextStyle.color, Colors.green); expect(theme.primaryContrastingColor, CupertinoColors.destructiveRed); }, ); testWidgets( 'Material2 - copyWith only copies the overrides, not the material or cupertino derivatives', (WidgetTester tester) async { final CupertinoThemeData originalTheme = await testTheme(tester, ThemeData( useMaterial3: false, primarySwatch: Colors.purple, cupertinoOverrideTheme: const CupertinoThemeData( primaryContrastingColor: CupertinoColors.activeOrange, ), )); final CupertinoThemeData copiedTheme = originalTheme.copyWith( barBackgroundColor: CupertinoColors.destructiveRed, ); final CupertinoThemeData theme = await testTheme(tester, ThemeData( useMaterial3: false, primarySwatch: Colors.blue, cupertinoOverrideTheme: copiedTheme, )); expect(theme.primaryColor, Colors.blue); expect(theme.primaryContrastingColor, CupertinoColors.activeOrange); expect(theme.barBackgroundColor, CupertinoColors.destructiveRed); }, ); testWidgets( 'Material3 - copyWith only copies the overrides, not the material or cupertino derivatives', (WidgetTester tester) async { final CupertinoThemeData originalTheme = await testTheme(tester, ThemeData( useMaterial3: true, colorScheme: const ColorScheme.light(primary: Colors.purple), cupertinoOverrideTheme: const CupertinoThemeData( primaryContrastingColor: CupertinoColors.activeOrange, ), )); final CupertinoThemeData copiedTheme = originalTheme.copyWith( barBackgroundColor: CupertinoColors.destructiveRed, ); final CupertinoThemeData theme = await testTheme(tester, ThemeData( useMaterial3: true, colorScheme: const ColorScheme.light(primary: Colors.blue), cupertinoOverrideTheme: copiedTheme, )); expect(theme.primaryColor, Colors.blue); expect(theme.primaryContrastingColor, CupertinoColors.activeOrange); expect(theme.barBackgroundColor, CupertinoColors.destructiveRed); }, ); testWidgets( "Material2 - Material themes with no cupertino overrides can also be copyWith'ed", (WidgetTester tester) async { final CupertinoThemeData originalTheme = await testTheme(tester, ThemeData( useMaterial3: false, primarySwatch: Colors.purple, )); final CupertinoThemeData copiedTheme = originalTheme.copyWith( primaryContrastingColor: CupertinoColors.destructiveRed, ); final CupertinoThemeData theme = await testTheme(tester, ThemeData( useMaterial3: false, primarySwatch: Colors.blue, cupertinoOverrideTheme: copiedTheme, )); expect(theme.primaryColor, Colors.blue); expect(theme.primaryContrastingColor, CupertinoColors.destructiveRed); }, ); testWidgets( "Material3 - Material themes with no cupertino overrides can also be copyWith'ed", (WidgetTester tester) async { final CupertinoThemeData originalTheme = await testTheme(tester, ThemeData( useMaterial3: true, colorScheme: const ColorScheme.light(primary: Colors.purple), )); final CupertinoThemeData copiedTheme = originalTheme.copyWith( primaryContrastingColor: CupertinoColors.destructiveRed, ); final CupertinoThemeData theme = await testTheme(tester, ThemeData( useMaterial3: true, colorScheme: const ColorScheme.light(primary: Colors.blue), cupertinoOverrideTheme: copiedTheme, )); expect(theme.primaryColor, Colors.blue); expect(theme.primaryContrastingColor, CupertinoColors.destructiveRed); }, ); }); } int testBuildCalled = 0; class Test extends StatelessWidget { const Test({ super.key }); @override Widget build(BuildContext context) { testBuildCalled += 1; return Container( decoration: BoxDecoration( color: Theme.of(context).primaryColor, ), ); } } /// This class exists only to make sure that we test all the properties of the /// [TextStyle] class. If a property is added/removed/renamed, the analyzer will /// complain that this class has incorrect overrides. class _TextStyleProxy implements TextStyle { _TextStyleProxy(this._delegate); final TextStyle _delegate; // Do make sure that all the properties correctly forward to the _delegate. @override Color? get color => _delegate.color; @override Color? get backgroundColor => _delegate.backgroundColor; @override String? get debugLabel => _delegate.debugLabel; @override TextDecoration? get decoration => _delegate.decoration; @override Color? get decorationColor => _delegate.decorationColor; @override TextDecorationStyle? get decorationStyle => _delegate.decorationStyle; @override double? get decorationThickness => _delegate.decorationThickness; @override String? get fontFamily => _delegate.fontFamily; @override List<String>? get fontFamilyFallback => _delegate.fontFamilyFallback; @override double? get fontSize => _delegate.fontSize; @override FontStyle? get fontStyle => _delegate.fontStyle; @override FontWeight? get fontWeight => _delegate.fontWeight; @override double? get height => _delegate.height; @override TextLeadingDistribution? get leadingDistribution => _delegate.leadingDistribution; @override Locale? get locale => _delegate.locale; @override ui.Paint? get foreground => _delegate.foreground; @override ui.Paint? get background => _delegate.background; @override bool get inherit => _delegate.inherit; @override double? get letterSpacing => _delegate.letterSpacing; @override TextBaseline? get textBaseline => _delegate.textBaseline; @override double? get wordSpacing => _delegate.wordSpacing; @override List<Shadow>? get shadows => _delegate.shadows; @override List<ui.FontFeature>? get fontFeatures => _delegate.fontFeatures; @override List<ui.FontVariation>? get fontVariations => _delegate.fontVariations; @override TextOverflow? get overflow => _delegate.overflow; @override String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) => super.toString(); @override DiagnosticsNode toDiagnosticsNode({ String? name, DiagnosticsTreeStyle? style }) { throw UnimplementedError(); } @override String toStringShort() { throw UnimplementedError(); } @override TextStyle apply({ Color? color, Color? backgroundColor, TextDecoration? decoration, Color? decorationColor, TextDecorationStyle? decorationStyle, double decorationThicknessFactor = 1.0, double decorationThicknessDelta = 0.0, String? fontFamily, List<String>? fontFamilyFallback, double fontSizeFactor = 1.0, double fontSizeDelta = 0.0, int fontWeightDelta = 0, FontStyle? fontStyle, double letterSpacingFactor = 1.0, double letterSpacingDelta = 0.0, double wordSpacingFactor = 1.0, double wordSpacingDelta = 0.0, double heightFactor = 1.0, double heightDelta = 0.0, TextLeadingDistribution? leadingDistribution, TextBaseline? textBaseline, Locale? locale, List<ui.Shadow>? shadows, List<ui.FontFeature>? fontFeatures, List<ui.FontVariation>? fontVariations, TextOverflow? overflow, String? package, }) { throw UnimplementedError(); } @override RenderComparison compareTo(TextStyle other) { throw UnimplementedError(); } @override TextStyle copyWith({ bool? inherit, Color? color, Color? backgroundColor, String? fontFamily, List<String>? fontFamilyFallback, double? fontSize, FontWeight? fontWeight, FontStyle? fontStyle, double? letterSpacing, double? wordSpacing, TextBaseline? textBaseline, double? height, TextLeadingDistribution? leadingDistribution, Locale? locale, ui.Paint? foreground, ui.Paint? background, List<Shadow>? shadows, List<ui.FontFeature>? fontFeatures, List<ui.FontVariation>? fontVariations, TextDecoration? decoration, Color? decorationColor, TextDecorationStyle? decorationStyle, double? decorationThickness, String? debugLabel, TextOverflow? overflow, String? package, }) { throw UnimplementedError(); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties, { String prefix = '' }) { throw UnimplementedError(); } @override ui.ParagraphStyle getParagraphStyle({ TextAlign? textAlign, TextDirection? textDirection, double textScaleFactor = 1.0, TextScaler textScaler = TextScaler.noScaling, String? ellipsis, int? maxLines, ui.TextHeightBehavior? textHeightBehavior, Locale? locale, String? fontFamily, double? fontSize, FontWeight? fontWeight, FontStyle? fontStyle, double? height, StrutStyle? strutStyle, }) { throw UnimplementedError(); } @override ui.TextStyle getTextStyle({ double textScaleFactor = 1.0, TextScaler textScaler = TextScaler.noScaling }) { throw UnimplementedError(); } @override TextStyle merge(TextStyle? other) { throw UnimplementedError(); } }
flutter/packages/flutter/test/material/theme_test.dart/0
{ "file_path": "flutter/packages/flutter/test/material/theme_test.dart", "repo_id": "flutter", "token_count": 16644 }
720
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/painting.dart'; import 'package:flutter_test/flutter_test.dart'; void approxExpect(Alignment a, Alignment b) { expect(a.x, moreOrLessEquals(b.x)); expect(a.y, moreOrLessEquals(b.y)); } void main() { test('Alignment control test', () { const Alignment alignment = Alignment(0.5, 0.25); expect(alignment, hasOneLineDescription); expect(alignment.hashCode, equals(const Alignment(0.5, 0.25).hashCode)); expect(alignment / 2.0, const Alignment(0.25, 0.125)); expect(alignment ~/ 2.0, Alignment.center); expect(alignment % 5.0, const Alignment(0.5, 0.25)); }); test('Alignment.lerp()', () { const Alignment a = Alignment.topLeft; const Alignment b = Alignment.topCenter; expect(Alignment.lerp(a, b, 0.25), equals(const Alignment(-0.75, -1.0))); expect(Alignment.lerp(null, null, 0.25), isNull); expect(Alignment.lerp(null, b, 0.25), equals(const Alignment(0.0, -0.25))); expect(Alignment.lerp(a, null, 0.25), equals(const Alignment(-0.75, -0.75))); }); test('Alignment.lerp identical a,b', () { expect(Alignment.lerp(null, null, 0), null); const Alignment alignment = Alignment.topLeft; expect(identical(Alignment.lerp(alignment, alignment, 0.5), alignment), true); }); test('AlignmentGeometry.lerp identical a,b', () { expect(AlignmentGeometry.lerp(null, null, 0), null); const AlignmentGeometry alignment = Alignment.topLeft; expect(identical(AlignmentGeometry.lerp(alignment, alignment, 0.5), alignment), true); }); test('AlignmentDirectional.lerp identical a,b', () { expect(AlignmentDirectional.lerp(null, null, 0), null); const AlignmentDirectional alignment = AlignmentDirectional.topStart; expect(identical(AlignmentDirectional.lerp(alignment, alignment, 0.5), alignment), true); }); test('AlignmentGeometry invariants', () { const AlignmentDirectional topStart = AlignmentDirectional.topStart; const AlignmentDirectional topEnd = AlignmentDirectional.topEnd; const Alignment center = Alignment.center; const Alignment topLeft = Alignment.topLeft; const Alignment topRight = Alignment.topRight; final List<double> numbers = <double>[0.0, 1.0, -1.0, 2.0, 0.25, 0.5, 100.0, -999.75]; expect((topEnd * 0.0).add(topRight * 0.0), center); expect(topEnd.add(topRight) * 0.0, (topEnd * 0.0).add(topRight * 0.0)); expect(topStart.add(topLeft), topLeft.add(topStart)); expect(topStart.add(topLeft).resolve(TextDirection.ltr), (topStart.resolve(TextDirection.ltr)) + topLeft); expect(topStart.add(topLeft).resolve(TextDirection.rtl), (topStart.resolve(TextDirection.rtl)) + topLeft); expect(topStart.add(topLeft).resolve(TextDirection.ltr), topStart.resolve(TextDirection.ltr).add(topLeft)); expect(topStart.add(topLeft).resolve(TextDirection.rtl), topStart.resolve(TextDirection.rtl).add(topLeft)); expect(topStart.resolve(TextDirection.ltr), topLeft); expect(topStart.resolve(TextDirection.rtl), topRight); expect(topEnd * 0.0, center); expect(topLeft * 0.0, center); expect(topStart * 1.0, topStart); expect(topEnd * 1.0, topEnd); expect(topLeft * 1.0, topLeft); expect(topRight * 1.0, topRight); for (final double n in numbers) { expect((topStart * n).add(topStart), topStart * (n + 1.0)); expect((topEnd * n).add(topEnd), topEnd * (n + 1.0)); for (final double m in numbers) { expect((topStart * n).add(topStart * m), topStart * (n + m)); } } expect(topStart + topStart + topStart, topStart * 3.0); // without using "add" for (final TextDirection x in TextDirection.values) { expect((topEnd * 0.0).add(topRight * 0.0).resolve(x), center.add(center).resolve(x)); expect((topEnd * 0.0).add(topLeft).resolve(x), center.add(topLeft).resolve(x)); expect((topEnd * 0.0).resolve(x).add(topLeft.resolve(x)), center.resolve(x).add(topLeft.resolve(x))); expect((topEnd * 0.0).resolve(x).add(topLeft), center.resolve(x).add(topLeft)); expect((topEnd * 0.0).resolve(x), center.resolve(x)); } expect(topStart, isNot(topLeft)); expect(topEnd, isNot(topLeft)); expect(topStart, isNot(topRight)); expect(topEnd, isNot(topRight)); expect(topStart.add(topLeft), isNot(topLeft)); expect(topStart.add(topLeft), isNot(topStart)); }); test('AlignmentGeometry.resolve()', () { expect(const AlignmentDirectional(0.25, 0.3).resolve(TextDirection.ltr), const Alignment(0.25, 0.3)); expect(const AlignmentDirectional(0.25, 0.3).resolve(TextDirection.rtl), const Alignment(-0.25, 0.3)); expect(const AlignmentDirectional(-0.25, 0.3).resolve(TextDirection.ltr), const Alignment(-0.25, 0.3)); expect(const AlignmentDirectional(-0.25, 0.3).resolve(TextDirection.rtl), const Alignment(0.25, 0.3)); expect(const AlignmentDirectional(1.25, 0.3).resolve(TextDirection.ltr), const Alignment(1.25, 0.3)); expect(const AlignmentDirectional(1.25, 0.3).resolve(TextDirection.rtl), const Alignment(-1.25, 0.3)); expect(const AlignmentDirectional(0.5, -0.3).resolve(TextDirection.ltr), const Alignment(0.5, -0.3)); expect(const AlignmentDirectional(0.5, -0.3).resolve(TextDirection.rtl), const Alignment(-0.5, -0.3)); expect(AlignmentDirectional.center.resolve(TextDirection.ltr), Alignment.center); expect(AlignmentDirectional.center.resolve(TextDirection.rtl), Alignment.center); expect(AlignmentDirectional.bottomEnd.resolve(TextDirection.ltr), Alignment.bottomRight); expect(AlignmentDirectional.bottomEnd.resolve(TextDirection.rtl), Alignment.bottomLeft); expect(AlignmentDirectional(nonconst(1.0), 2.0), AlignmentDirectional(nonconst(1.0), 2.0)); expect(const AlignmentDirectional(1.0, 2.0), isNot(const AlignmentDirectional(2.0, 1.0))); expect( AlignmentDirectional.centerStart.resolve(TextDirection.ltr), AlignmentDirectional.centerEnd.resolve(TextDirection.rtl), ); expect( AlignmentDirectional.centerStart.resolve(TextDirection.ltr), isNot(AlignmentDirectional.centerEnd.resolve(TextDirection.ltr)), ); expect( AlignmentDirectional.centerEnd.resolve(TextDirection.ltr), isNot(AlignmentDirectional.centerEnd.resolve(TextDirection.rtl)), ); }); test('AlignmentGeometry.lerp ad hoc tests', () { final AlignmentGeometry mixed1 = const Alignment(10.0, 20.0).add(const AlignmentDirectional(30.0, 50.0)); final AlignmentGeometry mixed2 = const Alignment(70.0, 110.0).add(const AlignmentDirectional(130.0, 170.0)); final AlignmentGeometry mixed3 = const Alignment(25.0, 42.5).add(const AlignmentDirectional(55.0, 80.0)); for (final TextDirection direction in TextDirection.values) { expect(AlignmentGeometry.lerp(mixed1, mixed2, 0.0)!.resolve(direction), mixed1.resolve(direction)); expect(AlignmentGeometry.lerp(mixed1, mixed2, 1.0)!.resolve(direction), mixed2.resolve(direction)); expect(AlignmentGeometry.lerp(mixed1, mixed2, 0.25)!.resolve(direction), mixed3.resolve(direction)); } }); test('lerp commutes with resolve', () { final List<AlignmentGeometry?> offsets = <AlignmentGeometry?>[ Alignment.topLeft, Alignment.topCenter, Alignment.topRight, AlignmentDirectional.topStart, AlignmentDirectional.topCenter, AlignmentDirectional.topEnd, Alignment.centerLeft, Alignment.center, Alignment.centerRight, AlignmentDirectional.centerStart, AlignmentDirectional.center, AlignmentDirectional.centerEnd, Alignment.bottomLeft, Alignment.bottomCenter, Alignment.bottomRight, AlignmentDirectional.bottomStart, AlignmentDirectional.bottomCenter, AlignmentDirectional.bottomEnd, const Alignment(-1.0, 0.65), const AlignmentDirectional(-1.0, 0.45), const AlignmentDirectional(0.125, 0.625), const Alignment(0.25, 0.875), const Alignment(0.0625, 0.5625).add(const AlignmentDirectional(0.1875, 0.6875)), const AlignmentDirectional(2.0, 3.0), const Alignment(2.0, 3.0), const Alignment(2.0, 3.0).add(const AlignmentDirectional(5.0, 3.0)), const Alignment(10.0, 20.0).add(const AlignmentDirectional(30.0, 50.0)), const Alignment(70.0, 110.0).add(const AlignmentDirectional(130.0, 170.0)), const Alignment(25.0, 42.5).add(const AlignmentDirectional(55.0, 80.0)), null, ]; final List<double> times = <double>[ 0.25, 0.5, 0.75 ]; for (final TextDirection direction in TextDirection.values) { final Alignment defaultValue = AlignmentDirectional.center.resolve(direction); for (final AlignmentGeometry? a in offsets) { final Alignment resolvedA = a?.resolve(direction) ?? defaultValue; for (final AlignmentGeometry? b in offsets) { final Alignment resolvedB = b?.resolve(direction) ?? defaultValue; approxExpect(Alignment.lerp(resolvedA, resolvedB, 0.0)!, resolvedA); approxExpect(Alignment.lerp(resolvedA, resolvedB, 1.0)!, resolvedB); approxExpect((AlignmentGeometry.lerp(a, b, 0.0) ?? defaultValue).resolve(direction), resolvedA); approxExpect((AlignmentGeometry.lerp(a, b, 1.0) ?? defaultValue).resolve(direction), resolvedB); for (final double t in times) { assert(t > 0.0); assert(t < 1.0); final Alignment value = (AlignmentGeometry.lerp(a, b, t) ?? defaultValue).resolve(direction); approxExpect(value, Alignment.lerp(resolvedA, resolvedB, t)!); final double minDX = math.min(resolvedA.x, resolvedB.x); final double maxDX = math.max(resolvedA.x, resolvedB.x); final double minDY = math.min(resolvedA.y, resolvedB.y); final double maxDY = math.max(resolvedA.y, resolvedB.y); expect(value.x, inInclusiveRange(minDX, maxDX)); expect(value.y, inInclusiveRange(minDY, maxDY)); } } } } }); test('AlignmentGeometry add/subtract', () { const AlignmentGeometry directional = AlignmentDirectional(1.0, 2.0); const AlignmentGeometry normal = Alignment(3.0, 5.0); expect(directional.add(normal).resolve(TextDirection.ltr), const Alignment(4.0, 7.0)); expect(directional.add(normal).resolve(TextDirection.rtl), const Alignment(2.0, 7.0)); expect(normal.add(normal), normal * 2.0); expect(directional.add(directional), directional * 2.0); }); test('AlignmentGeometry operators', () { expect(const AlignmentDirectional(1.0, 2.0) * 2.0, const AlignmentDirectional(2.0, 4.0)); expect(const AlignmentDirectional(1.0, 2.0) / 2.0, const AlignmentDirectional(0.5, 1.0)); expect(const AlignmentDirectional(1.0, 2.0) % 2.0, AlignmentDirectional.centerEnd); expect(const AlignmentDirectional(1.0, 2.0) ~/ 2.0, AlignmentDirectional.bottomCenter); for (final TextDirection direction in TextDirection.values) { expect(Alignment.center.add(const AlignmentDirectional(1.0, 2.0) * 2.0).resolve(direction), const AlignmentDirectional(2.0, 4.0).resolve(direction)); expect(Alignment.center.add(const AlignmentDirectional(1.0, 2.0) / 2.0).resolve(direction), const AlignmentDirectional(0.5, 1.0).resolve(direction)); expect(Alignment.center.add(const AlignmentDirectional(1.0, 2.0) % 2.0).resolve(direction), AlignmentDirectional.centerEnd.resolve(direction)); expect(Alignment.center.add(const AlignmentDirectional(1.0, 2.0) ~/ 2.0).resolve(direction), AlignmentDirectional.bottomCenter.resolve(direction)); } expect(const Alignment(1.0, 2.0) * 2.0, const Alignment(2.0, 4.0)); expect(const Alignment(1.0, 2.0) / 2.0, const Alignment(0.5, 1.0)); expect(const Alignment(1.0, 2.0) % 2.0, Alignment.centerRight); expect(const Alignment(1.0, 2.0) ~/ 2.0, Alignment.bottomCenter); }); test('AlignmentGeometry operators', () { expect(const Alignment(1.0, 2.0) + const Alignment(3.0, 5.0), const Alignment(4.0, 7.0)); expect(const Alignment(1.0, 2.0) - const Alignment(3.0, 5.0), const Alignment(-2.0, -3.0)); expect(const AlignmentDirectional(1.0, 2.0) + const AlignmentDirectional(3.0, 5.0), const AlignmentDirectional(4.0, 7.0)); expect(const AlignmentDirectional(1.0, 2.0) - const AlignmentDirectional(3.0, 5.0), const AlignmentDirectional(-2.0, -3.0)); }); test('AlignmentGeometry toString', () { expect(const Alignment(1.0001, 2.0001).toString(), 'Alignment(1.0, 2.0)'); expect(Alignment.center.toString(), 'Alignment.center'); expect(Alignment.bottomLeft.add(AlignmentDirectional.centerEnd).toString(), 'Alignment.bottomLeft + AlignmentDirectional.centerEnd'); expect(const Alignment(0.0001, 0.0001).toString(), 'Alignment(0.0, 0.0)'); expect(Alignment.center.toString(), 'Alignment.center'); expect(AlignmentDirectional.center.toString(), 'AlignmentDirectional.center'); expect(Alignment.bottomRight.add(AlignmentDirectional.bottomEnd).toString(), 'Alignment(1.0, 2.0) + AlignmentDirectional.centerEnd'); }); }
flutter/packages/flutter/test/painting/alignment_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/alignment_test.dart", "repo_id": "flutter", "token_count": 5223 }
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/painting.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('EdgeInsets constructors', () { // fromLTRB final EdgeInsets ltrbLtr = const EdgeInsets.fromLTRB(10, 20, 30, 40).resolve(TextDirection.ltr); expect(ltrbLtr.left, 10); expect(ltrbLtr.top, 20); expect(ltrbLtr.right, 30); expect(ltrbLtr.bottom, 40); final EdgeInsets ltrbRtl = const EdgeInsets.fromLTRB(10, 20, 30, 40).resolve(TextDirection.rtl); expect(ltrbRtl.left, 10); expect(ltrbRtl.top, 20); expect(ltrbRtl.right, 30); expect(ltrbRtl.bottom, 40); // all const EdgeInsets all = EdgeInsets.all(10); expect(all.resolve(TextDirection.ltr), equals(const EdgeInsets.fromLTRB(10, 10, 10, 10))); expect(all.resolve(TextDirection.rtl), equals(const EdgeInsets.fromLTRB(10, 10, 10, 10))); // only const EdgeInsets only = EdgeInsets.only(left: 10, top: 20, right: 30, bottom: 40); expect(only.resolve(TextDirection.ltr), equals(const EdgeInsets.fromLTRB(10, 20, 30, 40))); expect(only.resolve(TextDirection.rtl), equals(const EdgeInsets.fromLTRB(10, 20, 30, 40))); // symmetric const EdgeInsets symmetric = EdgeInsets.symmetric(horizontal: 10, vertical: 20); expect(symmetric.resolve(TextDirection.ltr), equals(const EdgeInsets.fromLTRB(10, 20, 10, 20))); expect(symmetric.resolve(TextDirection.rtl), equals(const EdgeInsets.fromLTRB(10, 20, 10, 20))); }); test('EdgeInsetsDirectional constructors', () { // fromSTEB final EdgeInsets stebLtr = const EdgeInsetsDirectional.fromSTEB(10, 20, 30, 40).resolve(TextDirection.ltr); expect(stebLtr.left, 10); expect(stebLtr.top, 20); expect(stebLtr.right, 30); expect(stebLtr.bottom, 40); final EdgeInsets stebRtl = const EdgeInsetsDirectional.fromSTEB(10, 20, 30, 40).resolve(TextDirection.rtl); expect(stebRtl.left, 30); expect(stebRtl.top, 20); expect(stebRtl.right, 10); expect(stebRtl.bottom, 40); // all const EdgeInsetsDirectional all = EdgeInsetsDirectional.all(10); expect(all.resolve(TextDirection.ltr), equals(const EdgeInsets.fromLTRB(10, 10, 10, 10))); expect(all.resolve(TextDirection.rtl), equals(const EdgeInsets.fromLTRB(10, 10, 10, 10))); // only const EdgeInsetsDirectional directional = EdgeInsetsDirectional.only(start: 10, top: 20, end: 30, bottom: 40); expect(directional.resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(10, 20, 30, 40)); expect(directional.resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(30, 20, 10, 40)); // symmetric const EdgeInsetsDirectional symmetric = EdgeInsetsDirectional.symmetric(horizontal: 10, vertical: 20); expect(symmetric.resolve(TextDirection.ltr), equals(const EdgeInsets.fromLTRB(10, 20, 10, 20))); expect(symmetric.resolve(TextDirection.rtl), equals(const EdgeInsets.fromLTRB(10, 20, 10, 20))); }); test('EdgeInsets control test', () { const EdgeInsets insets = EdgeInsets.fromLTRB(5.0, 7.0, 11.0, 13.0); expect(insets, hasOneLineDescription); expect(insets.hashCode, equals(const EdgeInsets.fromLTRB(5.0, 7.0, 11.0, 13.0).hashCode)); expect(insets.topLeft, const Offset(5.0, 7.0)); expect(insets.topRight, const Offset(-11.0, 7.0)); expect(insets.bottomLeft, const Offset(5.0, -13.0)); expect(insets.bottomRight, const Offset(-11.0, -13.0)); expect(insets.collapsedSize, const Size(16.0, 20.0)); expect(insets.flipped, const EdgeInsets.fromLTRB(11.0, 13.0, 5.0, 7.0)); expect(insets.along(Axis.horizontal), equals(16.0)); expect(insets.along(Axis.vertical), equals(20.0)); expect( insets.inflateRect(const Rect.fromLTRB(23.0, 32.0, 124.0, 143.0)), const Rect.fromLTRB(18.0, 25.0, 135.0, 156.0), ); expect( insets.deflateRect(const Rect.fromLTRB(23.0, 32.0, 124.0, 143.0)), const Rect.fromLTRB(28.0, 39.0, 113.0, 130.0), ); expect(insets.inflateSize(const Size(100.0, 125.0)), const Size(116.0, 145.0)); expect(insets.deflateSize(const Size(100.0, 125.0)), const Size(84.0, 105.0)); expect(insets / 2.0, const EdgeInsets.fromLTRB(2.5, 3.5, 5.5, 6.5)); expect(insets ~/ 2.0, const EdgeInsets.fromLTRB(2.0, 3.0, 5.0, 6.0)); expect(insets % 5.0, const EdgeInsets.fromLTRB(0.0, 2.0, 1.0, 3.0)); }); test('EdgeInsets.lerp()', () { const EdgeInsets a = EdgeInsets.all(10.0); const EdgeInsets b = EdgeInsets.all(20.0); expect(EdgeInsets.lerp(a, b, 0.25), equals(a * 1.25)); expect(EdgeInsets.lerp(a, b, 0.25), equals(b * 0.625)); expect(EdgeInsets.lerp(a, b, 0.25), equals(a + const EdgeInsets.all(2.5))); expect(EdgeInsets.lerp(a, b, 0.25), equals(b - const EdgeInsets.all(7.5))); expect(EdgeInsets.lerp(null, null, 0.25), isNull); expect(EdgeInsets.lerp(null, b, 0.25), equals(b * 0.25)); expect(EdgeInsets.lerp(a, null, 0.25), equals(a * 0.75)); }); test('EdgeInsets.lerp identical a,b', () { expect(EdgeInsets.lerp(null, null, 0), null); const EdgeInsets insets = EdgeInsets.zero; expect(identical(EdgeInsets.lerp(insets, insets, 0.5), insets), true); }); test('EdgeInsets.resolve()', () { expect(const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(10.0, 20.0, 30.0, 40.0)); expect(const EdgeInsetsDirectional.fromSTEB(99.0, 98.0, 97.0, 96.0).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(97.0, 98.0, 99.0, 96.0)); expect(const EdgeInsetsDirectional.all(50.0).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(50.0, 50.0, 50.0, 50.0)); expect(const EdgeInsetsDirectional.all(50.0).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(50.0, 50.0, 50.0, 50.0)); expect(const EdgeInsetsDirectional.only(start: 963.25).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(963.25, 0.0, 0.0, 0.0)); expect(const EdgeInsetsDirectional.only(top: 963.25).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(0.0, 963.25, 0.0, 0.0)); expect(const EdgeInsetsDirectional.only(end: 963.25).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(0.0, 0.0, 963.25, 0.0)); expect(const EdgeInsetsDirectional.only(bottom: 963.25).resolve(TextDirection.ltr), const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 963.25)); expect(const EdgeInsetsDirectional.only(start: 963.25).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(0.0, 0.0, 963.25, 0.0)); expect(const EdgeInsetsDirectional.only(top: 963.25).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(0.0, 963.25, 0.0, 0.0)); expect(const EdgeInsetsDirectional.only(end: 963.25).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(963.25, 0.0, 0.0, 0.0)); expect(const EdgeInsetsDirectional.only(bottom: 963.25).resolve(TextDirection.rtl), const EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 963.25)); expect(EdgeInsetsDirectional.only(), EdgeInsetsDirectional.only()); // ignore: prefer_const_constructors expect(const EdgeInsetsDirectional.only(top: 1.0), isNot(const EdgeInsetsDirectional.only(bottom: 1.0))); expect( const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.ltr), const EdgeInsetsDirectional.fromSTEB(30.0, 20.0, 10.0, 40.0).resolve(TextDirection.rtl), ); expect( const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.ltr), isNot(const EdgeInsetsDirectional.fromSTEB(30.0, 20.0, 10.0, 40.0).resolve(TextDirection.ltr)), ); expect( const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.ltr), isNot(const EdgeInsetsDirectional.fromSTEB(10.0, 20.0, 30.0, 40.0).resolve(TextDirection.rtl)), ); }); test('EdgeInsets equality', () { final double $5 = nonconst(5.0); expect(EdgeInsetsDirectional.only(top: $5, bottom: 7.0), EdgeInsetsDirectional.only(top: $5, bottom: 7.0)); expect(EdgeInsets.only(top: $5, bottom: 7.0), EdgeInsetsDirectional.only(top: $5, bottom: 7.0)); expect(EdgeInsetsDirectional.only(top: $5, bottom: 7.0), EdgeInsets.only(top: $5, bottom: 7.0)); expect(EdgeInsets.only(top: $5, bottom: 7.0), EdgeInsets.only(top: $5, bottom: 7.0)); expect(EdgeInsetsDirectional.only(start: $5), EdgeInsetsDirectional.only(start: $5)); expect(const EdgeInsets.only(left: 5.0), isNot(const EdgeInsetsDirectional.only(start: 5.0))); expect(const EdgeInsetsDirectional.only(start: 5.0), isNot(const EdgeInsets.only(left: 5.0))); expect(EdgeInsets.only(left: $5), EdgeInsets.only(left: $5)); expect(EdgeInsetsDirectional.only(end: $5), EdgeInsetsDirectional.only(end: $5)); expect(const EdgeInsets.only(right: 5.0), isNot(const EdgeInsetsDirectional.only(end: 5.0))); expect(const EdgeInsetsDirectional.only(end: 5.0), isNot(const EdgeInsets.only(right: 5.0))); expect(EdgeInsets.only(right: $5), EdgeInsets.only(right: $5)); expect(const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(right: 5.0)), const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(right: 5.0))); expect(const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(right: 5.0)), isNot(const EdgeInsetsDirectional.only(end: 5.0).add(const EdgeInsets.only(left: 5.0)))); expect(const EdgeInsetsDirectional.only(top: 1.0).add(const EdgeInsets.only(top: 2.0)), const EdgeInsetsDirectional.only(top: 3.0)); expect(const EdgeInsetsDirectional.only(top: 1.0).add(const EdgeInsets.only(top: 2.0)), const EdgeInsets.only(top: 3.0)); }); test('EdgeInsets copyWith', () { const EdgeInsets sourceEdgeInsets = EdgeInsets.only(left: 1.0, top: 2.0, bottom: 3.0, right: 4.0); final EdgeInsets copy = sourceEdgeInsets.copyWith(left: 5.0, top: 6.0); expect(copy, const EdgeInsets.only(left: 5.0, top: 6.0, bottom: 3.0, right: 4.0)); }); test('EdgeInsetsGeometry.lerp(...)', () { expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(end: 10.0), null, 0.5), const EdgeInsetsDirectional.only(end: 5.0)); expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(start: 10.0), null, 0.5), const EdgeInsetsDirectional.only(start: 5.0)); expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(top: 10.0), null, 0.5), const EdgeInsetsDirectional.only(top: 5.0)); expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 10.0), null, 0.5), const EdgeInsetsDirectional.only(bottom: 5.0)); expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 10.0), EdgeInsetsDirectional.zero, 0.5), const EdgeInsetsDirectional.only(bottom: 5.0)); expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 10.0), EdgeInsets.zero, 0.5), const EdgeInsetsDirectional.only(bottom: 5.0)); expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(start: 10.0), const EdgeInsets.only(left: 20.0), 0.5), const EdgeInsetsDirectional.only(start: 5.0).add(const EdgeInsets.only(left: 10.0))); expect(EdgeInsetsGeometry.lerp(const EdgeInsetsDirectional.only(bottom: 1.0), const EdgeInsetsDirectional.only(start: 1.0, bottom: 1.0).add(const EdgeInsets.only(right: 2.0)), 0.5), const EdgeInsetsDirectional.only(start: 0.5).add(const EdgeInsets.only(right: 1.0, bottom: 1.0))); expect(EdgeInsetsGeometry.lerp(const EdgeInsets.only(bottom: 1.0), const EdgeInsetsDirectional.only(end: 1.0, bottom: 1.0).add(const EdgeInsets.only(right: 2.0)), 0.5), const EdgeInsetsDirectional.only(end: 0.5).add(const EdgeInsets.only(right: 1.0, bottom: 1.0))); }); test('EdgeInsetsGeometry.lerp identical a,b', () { expect(EdgeInsetsGeometry.lerp(null, null, 0), null); const EdgeInsetsGeometry insets = EdgeInsets.zero; expect(identical(EdgeInsetsGeometry.lerp(insets, insets, 0.5), insets), true); }); test('EdgeInsetsDirectional.lerp identical a,b', () { expect(EdgeInsetsDirectional.lerp(null, null, 0), null); const EdgeInsetsDirectional insets = EdgeInsetsDirectional.zero; expect(identical(EdgeInsetsDirectional.lerp(insets, insets, 0.5), insets), true); }); test('EdgeInsetsGeometry.lerp(normal, ...)', () { const EdgeInsets a = EdgeInsets.all(10.0); const EdgeInsets b = EdgeInsets.all(20.0); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(a * 1.25)); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(b * 0.625)); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(a + const EdgeInsets.all(2.5))); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(b - const EdgeInsets.all(7.5))); expect(EdgeInsetsGeometry.lerp(null, null, 0.25), isNull); expect(EdgeInsetsGeometry.lerp(null, b, 0.25), equals(b * 0.25)); expect(EdgeInsetsGeometry.lerp(a, null, 0.25), equals(a * 0.75)); }); test('EdgeInsetsGeometry.lerp(directional, ...)', () { const EdgeInsetsDirectional a = EdgeInsetsDirectional.only(start: 10.0, end: 10.0); const EdgeInsetsDirectional b = EdgeInsetsDirectional.only(start: 20.0, end: 20.0); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(a * 1.25)); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(b * 0.625)); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(a + const EdgeInsetsDirectional.only(start: 2.5, end: 2.5))); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(b - const EdgeInsetsDirectional.only(start: 7.5, end: 7.5))); expect(EdgeInsetsGeometry.lerp(null, null, 0.25), isNull); expect(EdgeInsetsGeometry.lerp(null, b, 0.25), equals(b * 0.25)); expect(EdgeInsetsGeometry.lerp(a, null, 0.25), equals(a * 0.75)); }); test('EdgeInsetsGeometry.lerp(mixed, ...)', () { final EdgeInsetsGeometry a = const EdgeInsetsDirectional.only(start: 10.0, end: 10.0).add(const EdgeInsets.all(1.0)); final EdgeInsetsGeometry b = const EdgeInsetsDirectional.only(start: 20.0, end: 20.0).add(const EdgeInsets.all(2.0)); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(a * 1.25)); expect(EdgeInsetsGeometry.lerp(a, b, 0.25), equals(b * 0.625)); expect(EdgeInsetsGeometry.lerp(null, null, 0.25), isNull); expect(EdgeInsetsGeometry.lerp(null, b, 0.25), equals(b * 0.25)); expect(EdgeInsetsGeometry.lerp(a, null, 0.25), equals(a * 0.75)); }); test('EdgeInsets operators', () { const EdgeInsets a = EdgeInsets.fromLTRB(1.0, 2.0, 3.0, 5.0); expect(a * 2.0, const EdgeInsets.fromLTRB(2.0, 4.0, 6.0, 10.0)); expect(a / 2.0, const EdgeInsets.fromLTRB(0.5, 1.0, 1.5, 2.5)); expect(a % 2.0, const EdgeInsets.fromLTRB(1.0, 0.0, 1.0, 1.0)); expect(a ~/ 2.0, const EdgeInsets.fromLTRB(0.0, 1.0, 1.0, 2.0)); expect(a + a, a * 2.0); expect(a - a, EdgeInsets.zero); expect(a.add(a), a * 2.0); expect(a.subtract(a), EdgeInsets.zero); }); test('EdgeInsetsDirectional operators', () { const EdgeInsetsDirectional a = EdgeInsetsDirectional.fromSTEB(1.0, 2.0, 3.0, 5.0); expect(a * 2.0, const EdgeInsetsDirectional.fromSTEB(2.0, 4.0, 6.0, 10.0)); expect(a / 2.0, const EdgeInsetsDirectional.fromSTEB(0.5, 1.0, 1.5, 2.5)); expect(a % 2.0, const EdgeInsetsDirectional.fromSTEB(1.0, 0.0, 1.0, 1.0)); expect(a ~/ 2.0, const EdgeInsetsDirectional.fromSTEB(0.0, 1.0, 1.0, 2.0)); expect(a + a, a * 2.0); expect(a - a, EdgeInsetsDirectional.zero); expect(a.add(a), a * 2.0); expect(a.subtract(a), EdgeInsetsDirectional.zero); }); test('EdgeInsetsGeometry operators', () { final EdgeInsetsGeometry a = const EdgeInsetsDirectional.fromSTEB(1.0, 2.0, 3.0, 5.0).add(EdgeInsets.zero); expect(a, isNot(isA<EdgeInsetsDirectional>())); expect(a * 2.0, const EdgeInsetsDirectional.fromSTEB(2.0, 4.0, 6.0, 10.0)); expect(a / 2.0, const EdgeInsetsDirectional.fromSTEB(0.5, 1.0, 1.5, 2.5)); expect(a % 2.0, const EdgeInsetsDirectional.fromSTEB(1.0, 0.0, 1.0, 1.0)); expect(a ~/ 2.0, const EdgeInsetsDirectional.fromSTEB(0.0, 1.0, 1.0, 2.0)); expect(a.add(a), a * 2.0); expect(a.subtract(a), EdgeInsetsDirectional.zero); expect(a.subtract(a), EdgeInsets.zero); }); test('EdgeInsetsGeometry toString', () { expect(EdgeInsets.zero.toString(), 'EdgeInsets.zero'); expect(const EdgeInsets.only(top: 1.01, left: 1.01, right: 1.01, bottom: 1.01).toString(), 'EdgeInsets.all(1.0)'); expect(const EdgeInsetsDirectional.only(start: 1.01, end: 1.01, top: 1.01, bottom: 1.01).toString(), 'EdgeInsetsDirectional(1.0, 1.0, 1.0, 1.0)'); expect(const EdgeInsetsDirectional.only(start: 4.0).add(const EdgeInsets.only(top: 3.0)).toString(), 'EdgeInsetsDirectional(4.0, 3.0, 0.0, 0.0)'); expect(const EdgeInsetsDirectional.only(top: 4.0).add(const EdgeInsets.only(right: 3.0)).toString(), 'EdgeInsets(0.0, 4.0, 3.0, 0.0)'); expect(const EdgeInsetsDirectional.only(start: 4.0).add(const EdgeInsets.only(left: 3.0)).toString(), 'EdgeInsets(3.0, 0.0, 0.0, 0.0) + EdgeInsetsDirectional(4.0, 0.0, 0.0, 0.0)'); }); test('EdgeInsetsDirectional copyWith', () { const EdgeInsetsDirectional sourceEdgeInsets = EdgeInsetsDirectional.only(start: 1.0, top: 2.0, bottom: 3.0, end: 4.0); final EdgeInsetsDirectional copy = sourceEdgeInsets.copyWith(start: 5.0, top: 6.0); expect(copy, const EdgeInsetsDirectional.only(start: 5.0, top: 6.0, bottom: 3.0, end: 4.0)); }); }
flutter/packages/flutter/test/painting/edge_insets_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/edge_insets_test.dart", "repo_id": "flutter", "token_count": 7367 }
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 'dart:async'; import 'dart:io'; import 'dart:ui'; import 'package:file/memory.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import '../image_data.dart'; import '../rendering/rendering_tester.dart'; import 'mocks_for_image_cache.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); FlutterExceptionHandler? oldError; setUp(() { oldError = FlutterError.onError; }); tearDown(() { FlutterError.onError = oldError; PaintingBinding.instance.imageCache.clear(); PaintingBinding.instance.imageCache.clearLiveImages(); }); test('obtainKey errors will be caught', () async { final ImageProvider imageProvider = ObtainKeyErrorImageProvider(); final Completer<bool> caughtError = Completer<bool>(); FlutterError.onError = (FlutterErrorDetails details) { caughtError.complete(false); }; final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty); stream.addListener(ImageStreamListener((ImageInfo info, bool syncCall) { caughtError.complete(false); }, onError: (dynamic error, StackTrace? stackTrace) { caughtError.complete(true); })); expect(await caughtError.future, true); }); test('obtainKey errors will be caught - check location', () async { final ImageProvider imageProvider = ObtainKeyErrorImageProvider(); final Completer<bool> caughtError = Completer<bool>(); FlutterError.onError = (FlutterErrorDetails details) { caughtError.complete(true); }; await imageProvider.obtainCacheStatus(configuration: ImageConfiguration.empty); expect(await caughtError.future, true); }); test('File image with empty file throws expected error and evicts from cache', () async { final Completer<StateError> error = Completer<StateError>(); FlutterError.onError = (FlutterErrorDetails details) { error.complete(details.exception as StateError); }; final MemoryFileSystem fs = MemoryFileSystem(); final File file = fs.file('/empty.png')..createSync(recursive: true); final FileImage provider = FileImage(file); expect(imageCache.statusForKey(provider).untracked, true); expect(imageCache.pendingImageCount, 0); provider.resolve(ImageConfiguration.empty); expect(imageCache.statusForKey(provider).pending, true); expect(imageCache.pendingImageCount, 1); expect(await error.future, isStateError); expect(imageCache.statusForKey(provider).untracked, true); expect(imageCache.pendingImageCount, 0); }); test('File image with empty file throws expected error (load)', () async { final Completer<StateError> error = Completer<StateError>(); FlutterError.onError = (FlutterErrorDetails details) { error.complete(details.exception as StateError); }; final MemoryFileSystem fs = MemoryFileSystem(); final File file = fs.file('/empty.png')..createSync(recursive: true); final FileImage provider = FileImage(file); expect(provider.loadBuffer(provider, (ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) async { return Future<Codec>.value(FakeCodec()); }), isA<MultiFrameImageStreamCompleter>()); expect(await error.future, isStateError); }); Future<Codec> decoder(ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) async { return FakeCodec(); } test('File image sets tag', () async { final MemoryFileSystem fs = MemoryFileSystem(); final File file = fs.file('/blue.png')..createSync(recursive: true)..writeAsBytesSync(kBlueSquarePng); final FileImage provider = FileImage(file); final MultiFrameImageStreamCompleter completer = provider.loadBuffer(provider, decoder) as MultiFrameImageStreamCompleter; expect(completer.debugLabel, file.path); }); test('Memory image sets tag', () async { final Uint8List bytes = Uint8List.fromList(kBlueSquarePng); final MemoryImage provider = MemoryImage(bytes); final MultiFrameImageStreamCompleter completer = provider.loadBuffer(provider, decoder) as MultiFrameImageStreamCompleter; expect(completer.debugLabel, 'MemoryImage(${describeIdentity(bytes)})'); }); test('Asset image sets tag', () async { const String asset = 'images/blue.png'; final ExactAssetImage provider = ExactAssetImage(asset, bundle: _TestAssetBundle()); final AssetBundleImageKey key = await provider.obtainKey(ImageConfiguration.empty); final MultiFrameImageStreamCompleter completer = provider.loadBuffer(key, decoder) as MultiFrameImageStreamCompleter; expect(completer.debugLabel, asset); }); test('Resize image sets tag', () async { final Uint8List bytes = Uint8List.fromList(kBlueSquarePng); final ResizeImage provider = ResizeImage(MemoryImage(bytes), width: 40, height: 40); final MultiFrameImageStreamCompleter completer = provider.loadBuffer( await provider.obtainKey(ImageConfiguration.empty), decoder, ) as MultiFrameImageStreamCompleter; expect(completer.debugLabel, 'MemoryImage(${describeIdentity(bytes)}) - Resized(40×40)'); }); test('File image throws error when given a real but non-image file', () async { final Completer<Exception> error = Completer<Exception>(); FlutterError.onError = (FlutterErrorDetails details) { error.complete(details.exception as Exception); }; final FileImage provider = FileImage(File('pubspec.yaml')); expect(imageCache.statusForKey(provider).untracked, true); expect(imageCache.pendingImageCount, 0); provider.resolve(ImageConfiguration.empty); expect(imageCache.statusForKey(provider).pending, true); expect(imageCache.pendingImageCount, 1); expect(await error.future, isException .having((Exception exception) => exception.toString(), 'toString', contains('Invalid image data'))); // Invalid images are marked as pending so that we do not attempt to reload them. expect(imageCache.statusForKey(provider).untracked, false); expect(imageCache.pendingImageCount, 1); }, skip: kIsWeb); // [intended] The web cannot load files. test('ImageProvider toStrings', () async { expect(const NetworkImage('test', scale: 1.21).toString(), 'NetworkImage("test", scale: 1.2)'); expect(const ExactAssetImage('test', scale: 1.21).toString(), 'ExactAssetImage(name: "test", scale: 1.2, bundle: null)'); expect(MemoryImage(Uint8List(0), scale: 1.21).toString(), equalsIgnoringHashCodes('MemoryImage(Uint8List#00000, scale: 1.2)')); }); } class FakeCodec implements Codec { @override void dispose() {} @override int get frameCount => throw UnimplementedError(); @override Future<FrameInfo> getNextFrame() { throw UnimplementedError(); } @override int get repetitionCount => throw UnimplementedError(); } class _TestAssetBundle extends CachingAssetBundle { @override Future<ByteData> load(String key) async { return Uint8List.fromList(kBlueSquarePng).buffer.asByteData(); } }
flutter/packages/flutter/test/painting/image_provider_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/image_provider_test.dart", "repo_id": "flutter", "token_count": 2353 }
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/painting.dart'; import 'package:flutter_test/flutter_test.dart'; import 'common_matchers.dart'; void main() { test('StadiumBorder defaults', () { const StadiumBorder border = StadiumBorder(); expect(border.side, BorderSide.none); }); test('StadiumBorder copyWith, ==, hashCode', () { expect(const StadiumBorder(), const StadiumBorder().copyWith()); expect(const StadiumBorder().hashCode, const StadiumBorder().copyWith().hashCode); const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456)); expect(const StadiumBorder().copyWith(side: side), const StadiumBorder(side: side)); }); test('StadiumBorder', () { const StadiumBorder c10 = StadiumBorder(side: BorderSide(width: 10.0)); const StadiumBorder c15 = StadiumBorder(side: BorderSide(width: 15.0)); const StadiumBorder c20 = StadiumBorder(side: BorderSide(width: 20.0)); expect(c10.dimensions, const EdgeInsets.all(10.0)); expect(c10.scale(2.0), c20); expect(c20.scale(0.5), c10); expect(ShapeBorder.lerp(c10, c20, 0.0), c10); expect(ShapeBorder.lerp(c10, c20, 0.5), c15); expect(ShapeBorder.lerp(c10, c20, 1.0), c20); const StadiumBorder c1 = StadiumBorder(side: BorderSide()); expect(c1.getOuterPath(Rect.fromCircle(center: Offset.zero, radius: 1.0)), isUnitCircle); const StadiumBorder c2 = StadiumBorder(side: BorderSide()); expect(c2.getInnerPath(Rect.fromCircle(center: Offset.zero, radius: 2.0)), isUnitCircle); const Rect rect = Rect.fromLTRB(10.0, 20.0, 100.0, 200.0); expect( (Canvas canvas) => c10.paint(canvas, rect), paints ..rrect( rrect: RRect.fromRectAndRadius(rect.deflate(5.0), Radius.circular(rect.shortestSide / 2.0 - 5.0)), strokeWidth: 10.0, ), ); }); test('StadiumBorder with StrokeAlign', () { const StadiumBorder center = StadiumBorder(side: BorderSide(width: 10.0, strokeAlign: BorderSide.strokeAlignCenter)); const StadiumBorder outside = StadiumBorder(side: BorderSide(width: 10.0, strokeAlign: BorderSide.strokeAlignOutside)); expect(center.dimensions, const EdgeInsets.all(5.0)); expect(outside.dimensions, EdgeInsets.zero); const Rect rect = Rect.fromLTRB(10.0, 20.0, 100.0, 200.0); expect( (Canvas canvas) => center.paint(canvas, rect), paints ..rrect( rrect: RRect.fromRectAndRadius(rect, Radius.circular(rect.shortestSide / 2.0)), strokeWidth: 10.0, ), ); expect( (Canvas canvas) => outside.paint(canvas, rect), paints ..rrect( rrect: RRect.fromRectAndRadius(rect, Radius.circular(rect.shortestSide / 2.0)).inflate(5.0), strokeWidth: 10.0, ), ); }); test('StadiumBorder and CircleBorder', () { const StadiumBorder stadium = StadiumBorder(); const CircleBorder circle = CircleBorder(); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0); final Matcher looksLikeS = isPathThat( includes: const <Offset>[ Offset(30.0, 10.0), Offset(50.0, 10.0), ], excludes: const <Offset>[ Offset(1.0, 1.0), Offset(99.0, 19.0), ], ); final Matcher looksLikeC = 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(stadium.getOuterPath(rect), looksLikeS); expect(circle.getOuterPath(rect), looksLikeC); expect(ShapeBorder.lerp(stadium, circle, 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(stadium, circle, 0.9)!.getOuterPath(rect), looksLikeC); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.9), stadium, 0.1)!.getOuterPath(rect), looksLikeC); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.9), stadium, 0.9)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), circle, 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), circle, 0.9)!.getOuterPath(rect), looksLikeC); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), ShapeBorder.lerp(stadium, circle, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), ShapeBorder.lerp(stadium, circle, 0.9), 0.9)!.getOuterPath(rect), looksLikeC); expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, circle, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, circle, 0.9), 0.9)!.getOuterPath(rect), looksLikeC); expect(ShapeBorder.lerp(circle, ShapeBorder.lerp(stadium, circle, 0.1), 0.1)!.getOuterPath(rect), looksLikeC); expect(ShapeBorder.lerp(circle, ShapeBorder.lerp(stadium, circle, 0.1), 0.9)!.getOuterPath(rect), looksLikeS); expect( ShapeBorder.lerp(stadium, circle, 0.1).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), 10.0% of the way to being a CircleBorder)', ); expect( ShapeBorder.lerp(stadium, circle, 0.2).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), 20.0% of the way to being a CircleBorder)', ); expect( ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.1), ShapeBorder.lerp(stadium, circle, 0.9), 0.9).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), 82.0% of the way to being a CircleBorder)', ); expect( ShapeBorder.lerp(circle, stadium, 0.9).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), 10.0% of the way to being a CircleBorder)', ); expect( ShapeBorder.lerp(circle, stadium, 0.8).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), 20.0% of the way to being a CircleBorder)', ); expect( ShapeBorder.lerp(ShapeBorder.lerp(stadium, circle, 0.9), ShapeBorder.lerp(stadium, circle, 0.1), 0.1).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), 82.0% of the way to being a CircleBorder)', ); expect(ShapeBorder.lerp(stadium, circle, 0.1), ShapeBorder.lerp(stadium, circle, 0.1)); expect(ShapeBorder.lerp(stadium, circle, 0.1).hashCode, ShapeBorder.lerp(stadium, circle, 0.1).hashCode); final ShapeBorder direct50 = ShapeBorder.lerp(stadium, circle, 0.5)!; final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(circle, stadium, 0.1), ShapeBorder.lerp(circle, stadium, 0.9), 0.5)!; expect(direct50, indirect50); expect(direct50.hashCode, indirect50.hashCode); expect(direct50.toString(), indirect50.toString()); }); test('StadiumBorder and RoundedRectBorder with BorderRadius.zero', () { const StadiumBorder stadium = StadiumBorder(); const RoundedRectangleBorder rrect = RoundedRectangleBorder(); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 50.0); final Matcher looksLikeS = isPathThat( includes: const <Offset>[ Offset(25.0, 25.0), Offset(50.0, 25.0), Offset(7.33, 7.33), ], excludes: const <Offset>[ Offset(0.001, 0.001), Offset(99.999, 0.001), Offset(99.999, 49.999), Offset(0.001, 49.999), ], ); final Matcher looksLikeR = isPathThat( includes: const <Offset>[ Offset(25.0, 25.0), Offset(50.0, 25.0), Offset(7.33, 7.33), Offset(4.0, 4.0), Offset(96.0, 4.0), Offset(96.0, 46.0), Offset(4.0, 46.0), ], ); expect(stadium.getOuterPath(rect), looksLikeS); expect(rrect.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(stadium, rrect, 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(stadium, rrect, 0.9)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.1)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.9)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.9)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.9)!.getOuterPath(rect), looksLikeS); expect( ShapeBorder.lerp(stadium, rrect, 0.1).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.zero, 10.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(stadium, rrect, 0.2).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.zero, 20.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.zero, 82.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(rrect, stadium, 0.9).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.zero, 10.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(rrect, stadium, 0.8).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.zero, 20.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), ShapeBorder.lerp(stadium, rrect, 0.1), 0.1).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.zero, 82.0% of the way to being a RoundedRectangleBorder)', ); expect(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.1)); expect(ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, ShapeBorder.lerp(stadium, rrect, 0.1).hashCode); final ShapeBorder direct50 = ShapeBorder.lerp(stadium, rrect, 0.5)!; final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(rrect, stadium, 0.1), ShapeBorder.lerp(rrect, stadium, 0.9), 0.5)!; expect(direct50, indirect50); expect(direct50.hashCode, indirect50.hashCode); expect(direct50.toString(), indirect50.toString()); }); test('StadiumBorder and RoundedRectBorder with circular BorderRadius', () { const StadiumBorder stadium = StadiumBorder(); const RoundedRectangleBorder rrect = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10))); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 50.0); final Matcher looksLikeS = isPathThat( includes: const <Offset>[ Offset(25.0, 25.0), Offset(50.0, 25.0), Offset(7.33, 7.33), ], excludes: const <Offset>[ Offset(0.001, 0.001), Offset(99.999, 0.001), Offset(99.999, 49.999), Offset(0.001, 49.999), ], ); final Matcher looksLikeR = isPathThat( includes: const <Offset>[ Offset(25.0, 25.0), Offset(50.0, 25.0), Offset(7.33, 7.33), Offset(4.0, 4.0), Offset(96.0, 4.0), Offset(96.0, 46.0), Offset(4.0, 46.0), ], ); expect(stadium.getOuterPath(rect), looksLikeS); expect(rrect.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(stadium, rrect, 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(stadium, rrect, 0.9)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.1)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.9)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.9)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect), looksLikeR); expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.1)!.getOuterPath(rect), looksLikeS); expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.9)!.getOuterPath(rect), looksLikeS); expect( ShapeBorder.lerp(stadium, rrect, 0.1).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.circular(10.0), 10.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(stadium, rrect, 0.2).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.circular(10.0), 20.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.circular(10.0), 82.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(rrect, stadium, 0.9).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.circular(10.0), 10.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(rrect, stadium, 0.8).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.circular(10.0), 20.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), ShapeBorder.lerp(stadium, rrect, 0.1), 0.1).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadius.circular(10.0), 82.0% of the way to being a RoundedRectangleBorder)', ); expect(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.1)); expect(ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, ShapeBorder.lerp(stadium, rrect, 0.1).hashCode); final ShapeBorder direct50 = ShapeBorder.lerp(stadium, rrect, 0.5)!; final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(rrect, stadium, 0.1), ShapeBorder.lerp(rrect, stadium, 0.9), 0.5)!; expect(direct50, indirect50); expect(direct50.hashCode, indirect50.hashCode); expect(direct50.toString(), indirect50.toString()); }); test('StadiumBorder and RoundedRectBorder with BorderRadiusDirectional', () { const StadiumBorder stadium = StadiumBorder(); const RoundedRectangleBorder rrect = RoundedRectangleBorder( borderRadius: BorderRadiusDirectional.only( topStart: Radius.circular(10), bottomEnd: Radius.circular(10), ), ); const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 50.0); final Matcher looksLikeS = isPathThat( includes: const <Offset>[ Offset(25.0, 25.0), Offset(50.0, 25.0), Offset(7.33, 7.33), ], excludes: const <Offset>[ Offset(0.001, 0.001), Offset(99.999, 0.001), Offset(99.999, 49.999), Offset(0.001, 49.999), ], ); final Matcher looksLikeR = isPathThat( includes: const <Offset>[ Offset(25.0, 25.0), Offset(50.0, 25.0), Offset(7.33, 7.33), Offset(4.0, 4.0), Offset(96.0, 4.0), Offset(96.0, 46.0), Offset(4.0, 46.0), ], ); expect(stadium.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect(rrect.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); expect(ShapeBorder.lerp(stadium, rrect, 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect(ShapeBorder.lerp(stadium, rrect, 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), stadium, 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), rrect, 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect(ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect(ShapeBorder.lerp(stadium, ShapeBorder.lerp(stadium, rrect, 0.9), 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeR); expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.1)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect(ShapeBorder.lerp(rrect, ShapeBorder.lerp(stadium, rrect, 0.1), 0.9)!.getOuterPath(rect, textDirection: TextDirection.rtl), looksLikeS); expect( ShapeBorder.lerp(stadium, rrect, 0.1).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadiusDirectional.only(topStart: Radius.circular(10.0), ' 'bottomEnd: Radius.circular(10.0)), 10.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(stadium, rrect, 0.2).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadiusDirectional.only(topStart: Radius.circular(10.0), ' 'bottomEnd: Radius.circular(10.0)), 20.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.9), 0.9).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadiusDirectional.only(topStart: Radius.circular(10.0), ' 'bottomEnd: Radius.circular(10.0)), 82.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(rrect, stadium, 0.9).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadiusDirectional.only(topStart: Radius.circular(10.0), ' 'bottomEnd: Radius.circular(10.0)), 10.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(rrect, stadium, 0.8).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadiusDirectional.only(topStart: Radius.circular(10.0), ' 'bottomEnd: Radius.circular(10.0)), 20.0% of the way to being a RoundedRectangleBorder)', ); expect( ShapeBorder.lerp(ShapeBorder.lerp(stadium, rrect, 0.9), ShapeBorder.lerp(stadium, rrect, 0.1), 0.1).toString(), 'StadiumBorder(BorderSide(width: 0.0, style: none), ' 'BorderRadiusDirectional.only(topStart: Radius.circular(10.0), ' 'bottomEnd: Radius.circular(10.0)), 82.0% of the way to being a RoundedRectangleBorder)', ); expect(ShapeBorder.lerp(stadium, rrect, 0.1), ShapeBorder.lerp(stadium, rrect, 0.1)); expect(ShapeBorder.lerp(stadium, rrect, 0.1).hashCode, ShapeBorder.lerp(stadium, rrect, 0.1).hashCode); final ShapeBorder direct50 = ShapeBorder.lerp(stadium, rrect, 0.5)!; final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(rrect, stadium, 0.1), ShapeBorder.lerp(rrect, stadium, 0.9), 0.5)!; expect(direct50, indirect50); expect(direct50.hashCode, indirect50.hashCode); expect(direct50.toString(), indirect50.toString()); }); }
flutter/packages/flutter/test/painting/stadium_border_test.dart/0
{ "file_path": "flutter/packages/flutter/test/painting/stadium_border_test.dart", "repo_id": "flutter", "token_count": 8720 }
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/physics.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('nearEquals', () { expect(nearEqual(double.infinity, double.infinity, 0.1), isTrue); expect(nearEqual(double.negativeInfinity, double.negativeInfinity, 0.1), isTrue); expect(nearEqual(double.infinity, double.negativeInfinity, 0.1), isFalse); expect(nearEqual(0.1, 0.11, 0.001), isFalse); expect(nearEqual(0.1, 0.11, 0.1), isTrue); expect(nearEqual(0.1, 0.1, 0.0000001), isTrue); }); }
flutter/packages/flutter/test/physics/utils_test.dart/0
{ "file_path": "flutter/packages/flutter/test/physics/utils_test.dart", "repo_id": "flutter", "token_count": 255 }
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:math' as math; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/src/services/text_input.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; double _caretMarginOf(RenderEditable renderEditable) { return renderEditable.cursorWidth + 1.0; } void _applyParentData(List<RenderBox> inlineRenderBoxes, InlineSpan span) { int index = 0; RenderBox? previousBox; span.visitChildren((InlineSpan span) { if (span is! WidgetSpan) { return true; } final RenderBox box = inlineRenderBoxes[index]; box.parentData = TextParentData() ..span = span ..previousSibling = previousBox; (previousBox?.parentData as TextParentData?)?.nextSibling = box; index += 1; previousBox = box; return true; }); } 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) { } } void main() { TestRenderingFlutterBinding.ensureInitialized(); test('RenderEditable respects clipBehavior', () { const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 1.0); final String longString = 'a' * 10000; for (final Clip? clip in <Clip?>[null, ...Clip.values]) { final TestClipPaintingContext context = TestClipPaintingContext(); final RenderEditable editable; switch (clip) { case Clip.none: case Clip.hardEdge: case Clip.antiAlias: case Clip.antiAliasWithSaveLayer: editable = RenderEditable( text: TextSpan(text: longString), textDirection: TextDirection.ltr, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), offset: ViewportOffset.zero(), textSelectionDelegate: _FakeEditableTextState(), selection: const TextSelection(baseOffset: 0, extentOffset: 0), clipBehavior: clip!, ); case null: editable = RenderEditable( text: TextSpan(text: longString), textDirection: TextDirection.ltr, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), offset: ViewportOffset.zero(), textSelectionDelegate: _FakeEditableTextState(), selection: const TextSelection(baseOffset: 0, extentOffset: 0), ); } layout(editable, constraints: viewport, phase: EnginePhase.composite, onErrors: expectNoFlutterErrors); context.paintChild(editable, Offset.zero); // By default, clipBehavior is Clip.hardEdge. expect(context.clipBehavior, equals(clip ?? Clip.hardEdge), reason: 'for $clip'); } }); test('Reports the real height when maxLines is 1', () { const InlineSpan tallSpan = TextSpan( style: TextStyle(fontSize: 10), children: <InlineSpan>[TextSpan(text: 'TALL', style: TextStyle(fontSize: 100))], ); final BoxConstraints constraints = BoxConstraints.loose(const Size(600, 600)); final RenderEditable editable = RenderEditable( textDirection: TextDirection.ltr, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), offset: ViewportOffset.zero(), textSelectionDelegate: _FakeEditableTextState(), text: tallSpan, ); layout(editable, constraints: constraints); expect(editable.size.height, 100); }); test('Reports the height of the first line when maxLines is 1', () { final InlineSpan multilineSpan = TextSpan( text: 'liiiiines\n' * 10, style: const TextStyle(fontSize: 10), ); final BoxConstraints constraints = BoxConstraints.loose(const Size(600, 600)); final RenderEditable editable = RenderEditable( textDirection: TextDirection.ltr, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), offset: ViewportOffset.zero(), textSelectionDelegate: _FakeEditableTextState(), text: multilineSpan, ); layout(editable, constraints: constraints); expect(editable.size.height, 10); }); test('Editable respect clipBehavior in describeApproximatePaintClip', () { final String longString = 'a' * 10000; final RenderEditable editable = RenderEditable( text: TextSpan(text: longString), textDirection: TextDirection.ltr, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), offset: ViewportOffset.zero(), textSelectionDelegate: _FakeEditableTextState(), selection: const TextSelection(baseOffset: 0, extentOffset: 0), clipBehavior: Clip.none, ); layout(editable); bool visited = false; editable.visitChildren((RenderObject child) { visited = true; expect(editable.describeApproximatePaintClip(child), null); }); expect(visited, true); }); test('RenderEditable.paint respects offset argument', () { const BoxConstraints viewport = BoxConstraints(maxHeight: 1000.0, maxWidth: 1000.0); final TestPushLayerPaintingContext context = TestPushLayerPaintingContext(); const Offset paintOffset = Offset(100, 200); const double fontSize = 20.0; const Offset endpoint = Offset(0.0, fontSize); final RenderEditable editable = RenderEditable( text: const TextSpan( text: 'text', style: TextStyle( fontSize: fontSize, height: 1.0, ), ), textDirection: TextDirection.ltr, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), offset: ViewportOffset.zero(), textSelectionDelegate: _FakeEditableTextState(), selection: const TextSelection(baseOffset: 0, extentOffset: 0), ); layout(editable, constraints: viewport, phase: EnginePhase.composite); editable.paint(context, paintOffset); final List<LeaderLayer> leaderLayers = context.pushedLayers.whereType<LeaderLayer>().toList(); expect(leaderLayers, hasLength(1), reason: '_paintHandleLayers will paint a LeaderLayer'); expect(leaderLayers.single.offset, endpoint + paintOffset, reason: 'offset should respect paintOffset'); }); // Test that clipping will be used even when the text fits within the visible // region if the start position of the text is offset (e.g. during scrolling // animation). test('correct clipping', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), text: 'A', ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, locale: const Locale('en', 'US'), offset: ViewportOffset.fixed(10.0), textSelectionDelegate: delegate, selection: const TextSelection.collapsed( offset: 0, ), ); layout(editable, constraints: BoxConstraints.loose(const Size(500.0, 500.0))); // Prepare for painting after layout. pumpFrame(phase: EnginePhase.compositingBits); expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), paints..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 500.0, 10.0)), ); }); test('Can change cursor color, radius, visibility', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final ValueNotifier<bool> showCursor = ValueNotifier<bool>(true); EditableText.debugDeterministicCursor = true; final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, textDirection: TextDirection.ltr, cursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), offset: ViewportOffset.zero(), textSelectionDelegate: delegate, text: const TextSpan( text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed( offset: 4, affinity: TextAffinity.upstream, ), ); layout(editable); editable.layout(BoxConstraints.loose(const Size(100, 100))); // Prepare for painting after layout. pumpFrame(phase: EnginePhase.compositingBits); expect( editable, // Draw no cursor by default. paintsExactlyCountTimes(#drawRect, 0), ); editable.showCursor = showCursor; pumpFrame(phase: EnginePhase.compositingBits); expect(editable, paints..rect( color: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), rect: const Rect.fromLTWH(40, 0, 1, 10), )); // Now change to a rounded caret. editable.cursorColor = const Color.fromARGB(0xFF, 0x00, 0x00, 0xFF); editable.cursorWidth = 4; editable.cursorRadius = const Radius.circular(3); pumpFrame(phase: EnginePhase.compositingBits); expect(editable, paints..rrect( color: const Color.fromARGB(0xFF, 0x00, 0x00, 0xFF), rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(40, 0, 4, 10), const Radius.circular(3), ), )); editable.textScaler = const TextScaler.linear(2.0); pumpFrame(phase: EnginePhase.compositingBits); // Now the caret height is much bigger due to the bigger font scale. expect(editable, paints..rrect( color: const Color.fromARGB(0xFF, 0x00, 0x00, 0xFF), rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(80, 0, 4, 20), const Radius.circular(3), ), )); // Can turn off caret. showCursor.value = false; pumpFrame(phase: EnginePhase.compositingBits); expect(editable, paintsExactlyCountTimes(#drawRRect, 0)); }); test('Can change textAlign', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( textDirection: TextDirection.ltr, offset: ViewportOffset.zero(), textSelectionDelegate: delegate, text: const TextSpan(text: 'test'), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), ); layout(editable); editable.layout(BoxConstraints.loose(const Size(100, 100))); expect(editable.textAlign, TextAlign.start); expect(editable.debugNeedsLayout, isFalse); editable.textAlign = TextAlign.center; expect(editable.textAlign, TextAlign.center); expect(editable.debugNeedsLayout, isTrue); }); test('Can read plain text', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( maxLines: null, textDirection: TextDirection.ltr, offset: ViewportOffset.zero(), textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), ); expect(editable.plainText, ''); editable.text = const TextSpan(text: '123'); expect(editable.plainText, '123'); editable.text = const TextSpan( children: <TextSpan>[ TextSpan(text: 'abc', style: TextStyle(fontSize: 12)), TextSpan(text: 'def', style: TextStyle(fontSize: 10)), ], ); expect(editable.plainText, 'abcdef'); editable.layout(const BoxConstraints.tightFor(width: 200)); expect(editable.plainText, 'abcdef'); }); test('Cursor with ideographic script', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final ValueNotifier<bool> showCursor = ValueNotifier<bool>(true); EditableText.debugDeterministicCursor = true; final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, textDirection: TextDirection.ltr, cursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), offset: ViewportOffset.zero(), textSelectionDelegate: delegate, text: const TextSpan( text: '中文测试文本是否正确', style: TextStyle(fontSize: 10.0, fontFamily: 'FlutterTest'), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed( offset: 4, affinity: TextAffinity.upstream, ), ); layout(editable, constraints: BoxConstraints.loose(const Size(100, 100))); pumpFrame(phase: EnginePhase.compositingBits); expect( editable, // Draw no cursor by default. paintsExactlyCountTimes(#drawRect, 0), ); editable.showCursor = showCursor; pumpFrame(phase: EnginePhase.compositingBits); expect(editable, paints..rect( color: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), rect: const Rect.fromLTWH(40, 0, 1, 10), )); // Now change to a rounded caret. editable.cursorColor = const Color.fromARGB(0xFF, 0x00, 0x00, 0xFF); editable.cursorWidth = 4; editable.cursorRadius = const Radius.circular(3); pumpFrame(phase: EnginePhase.compositingBits); expect(editable, paints..rrect( color: const Color.fromARGB(0xFF, 0x00, 0x00, 0xFF), rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(40, 0, 4, 10), const Radius.circular(3), ), )); editable.textScaler = const TextScaler.linear(2.0); pumpFrame(phase: EnginePhase.compositingBits); // Now the caret height is much bigger due to the bigger font scale. expect(editable, paints..rrect( color: const Color.fromARGB(0xFF, 0x00, 0x00, 0xFF), rrect: RRect.fromRectAndRadius( const Rect.fromLTWH(80, 0, 4, 20), const Radius.circular(3), ), )); // Can turn off caret. showCursor.value = false; pumpFrame(phase: EnginePhase.compositingBits); expect(editable, paintsExactlyCountTimes(#drawRRect, 0)); // TODO(yjbanov): ahem.ttf doesn't have Chinese glyphs, making this test // sensitive to browser/OS when running in web mode: }, skip: kIsWeb); // https://github.com/flutter/flutter/issues/83129 test('text is painted above selection', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: ViewportOffset.zero(), textSelectionDelegate: delegate, text: const TextSpan( text: 'test', style: TextStyle( height: 1.0, fontSize: 10.0, ), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection( baseOffset: 0, extentOffset: 3, affinity: TextAffinity.upstream, ), ); layout(editable); expect( editable, paints // Check that it's the black selection box, not the red cursor. ..rect(color: Colors.black) ..paragraph(), ); // There is exactly one rect paint (1 selection, 0 cursor). expect(editable, paintsExactlyCountTimes(#drawRect, 1)); }); test('cursor can paint above or below the text', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final ValueNotifier<bool> showCursor = ValueNotifier<bool>(true); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, paintCursorAboveText: true, textDirection: TextDirection.ltr, cursorColor: Colors.red, showCursor: showCursor, offset: ViewportOffset.zero(), textSelectionDelegate: delegate, text: const TextSpan( text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed( offset: 2, affinity: TextAffinity.upstream, ), ); layout(editable); expect( editable, paints ..paragraph() // Red collapsed cursor is painted, not a selection box. ..rect(color: Colors.red[500]), ); // There is exactly one rect paint (0 selection, 1 cursor). expect(editable, paintsExactlyCountTimes(#drawRect, 1)); editable.paintCursorAboveText = false; pumpFrame(phase: EnginePhase.compositingBits); expect( editable, // The paint order is now flipped. paints ..rect(color: Colors.red[500]) ..paragraph(), ); expect(editable, paintsExactlyCountTimes(#drawRect, 1)); }); test('does not paint the caret when selection is null or invalid', () async { final TextSelectionDelegate delegate = _FakeEditableTextState(); final ValueNotifier<bool> showCursor = ValueNotifier<bool>(true); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, paintCursorAboveText: true, textDirection: TextDirection.ltr, cursorColor: Colors.red, showCursor: showCursor, offset: ViewportOffset.zero(), textSelectionDelegate: delegate, text: const TextSpan( text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed( offset: 2, affinity: TextAffinity.upstream, ), ); layout(editable); expect( editable, paints ..paragraph() // Red collapsed cursor is painted, not a selection box. ..rect(color: Colors.red[500]), ); // Let the RenderEditable paint again. Setting the selection to null should // prevent the caret from being painted. editable.selection = null; // Still paints the paragraph. expect(editable, paints..paragraph()); // No longer paints the caret. expect(editable, isNot(paints..rect(color: Colors.red[500]))); // Reset. editable.selection = const TextSelection.collapsed(offset: 0); expect(editable, paints..paragraph()); expect(editable, paints..rect(color: Colors.red[500])); // Invalid cursor position. editable.selection = const TextSelection.collapsed(offset: -1); // Still paints the paragraph. expect(editable, paints..paragraph()); // No longer paints the caret. expect(editable, isNot(paints..rect(color: Colors.red[500]))); }); test('selects correct place with offsets', () { const String text = 'test\ntest'; final _FakeEditableTextState delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue(text: text); final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, // This makes the scroll axis vertical. maxLines: 2, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: const TextSpan( text: text, style: TextStyle(height: 1.0, fontSize: 10.0), ), selection: const TextSelection.collapsed( offset: 4, ), ); layout(editable); expect( editable, paints..paragraph(offset: Offset.zero), ); editable.selectPositionAt(from: const Offset(0, 2), cause: SelectionChangedCause.tap); pumpFrame(); expect(delegate.selection!.isCollapsed, true); expect(delegate.selection!.baseOffset, 0); viewportOffset.correctBy(10); pumpFrame(phase: EnginePhase.compositingBits); expect( editable, paints..paragraph(offset: const Offset(0, -10)), ); // Tap the same place. But because the offset is scrolled up, the second line // gets tapped instead. editable.selectPositionAt(from: const Offset(0, 2), cause: SelectionChangedCause.tap); pumpFrame(); expect(delegate.selection!.isCollapsed, true); expect(delegate.selection!.baseOffset, 5); // Test the other selection methods. // Move over by one character. editable.handleTapDown(TapDownDetails(globalPosition: const Offset(10, 2))); pumpFrame(); editable.selectPosition(cause:SelectionChangedCause.tap); pumpFrame(); expect(delegate.selection!.isCollapsed, true); expect(delegate.selection!.baseOffset, 6); editable.handleTapDown(TapDownDetails(globalPosition: const Offset(20, 2))); pumpFrame(); editable.selectWord(cause:SelectionChangedCause.longPress); pumpFrame(); expect(delegate.selection!.isCollapsed, false); expect(delegate.selection!.baseOffset, 5); expect(delegate.selection!.extentOffset, 9); // Select one more character down but since it's still part of the same // word, the same word is selected. editable.selectWordsInRange(from: const Offset(30, 2), cause:SelectionChangedCause.longPress); pumpFrame(); expect(delegate.selection!.isCollapsed, false); expect(delegate.selection!.baseOffset, 5); expect(delegate.selection!.extentOffset, 9); }); test('selects readonly renderEditable matches native behavior for android', () { // Regression test for https://github.com/flutter/flutter/issues/79166. final TargetPlatform? previousPlatform = debugDefaultTargetPlatformOverride; debugDefaultTargetPlatformOverride = TargetPlatform.android; const String text = ' test'; final _FakeEditableTextState delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue(text: text); final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, readOnly: true, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: const TextSpan( text: text, style: TextStyle(height: 1.0, fontSize: 10.0), ), selection: const TextSelection.collapsed( offset: 4, ), ); layout(editable); // Select the second white space, where the text position = 1. editable.selectWordsInRange(from: const Offset(10, 2), cause:SelectionChangedCause.longPress); pumpFrame(); expect(delegate.selection!.isCollapsed, false); expect(delegate.selection!.baseOffset, 1); expect(delegate.selection!.extentOffset, 2); debugDefaultTargetPlatformOverride = previousPlatform; }); test('selects renderEditable matches native behavior for iOS case 1', () { // Regression test for https://github.com/flutter/flutter/issues/79166. final TargetPlatform? previousPlatform = debugDefaultTargetPlatformOverride; debugDefaultTargetPlatformOverride = TargetPlatform.iOS; const String text = ' test'; final _FakeEditableTextState delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue(text: text); final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: const TextSpan( text: text, style: TextStyle(height: 1.0, fontSize: 10.0), ), selection: const TextSelection.collapsed( offset: 4, ), ); layout(editable); // Select the second white space, where the text position = 1. editable.selectWordsInRange(from: const Offset(10, 2), cause:SelectionChangedCause.longPress); pumpFrame(); expect(delegate.selection!.isCollapsed, false); expect(delegate.selection!.baseOffset, 1); expect(delegate.selection!.extentOffset, 6); debugDefaultTargetPlatformOverride = previousPlatform; }); test('selects renderEditable matches native behavior for iOS case 2', () { // Regression test for https://github.com/flutter/flutter/issues/79166. final TargetPlatform? previousPlatform = debugDefaultTargetPlatformOverride; debugDefaultTargetPlatformOverride = TargetPlatform.iOS; const String text = ' '; final _FakeEditableTextState delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue(text: text); final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: const TextSpan( text: text, style: TextStyle(height: 1.0, fontSize: 10.0), ), selection: const TextSelection.collapsed( offset: 4, ), ); layout(editable); // Select the second white space, where the text position = 1. editable.selectWordsInRange(from: const Offset(10, 2), cause:SelectionChangedCause.longPress); pumpFrame(); expect(delegate.selection!.isCollapsed, true); expect(delegate.selection!.baseOffset, 1); expect(delegate.selection!.extentOffset, 1); debugDefaultTargetPlatformOverride = previousPlatform; }); test('selects correct place when offsets are flipped', () { const String text = 'abc def ghi'; final _FakeEditableTextState delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue(text: text); final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, text: const TextSpan( text: text, style: TextStyle(height: 1.0, fontSize: 10.0), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), ); layout(editable); editable.selectPositionAt(from: const Offset(30, 2), to: const Offset(10, 2), cause: SelectionChangedCause.drag); pumpFrame(); expect(delegate.selection!.isCollapsed, isFalse); expect(delegate.selection!.baseOffset, 3); expect(delegate.selection!.extentOffset, 1); }); test('promptRect disappears when promptRectColor is set to null', () { const Color promptRectColor = Color(0x12345678); final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), text: 'ABCDEFG', ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, locale: const Locale('en', 'US'), offset: ViewportOffset.fixed(10.0), textSelectionDelegate: delegate, selection: const TextSelection.collapsed(offset: 0), promptRectColor: promptRectColor, promptRectRange: const TextRange(start: 0, end: 1), ); layout(editable, constraints: BoxConstraints.loose(const Size(1000.0, 1000.0))); pumpFrame(phase: EnginePhase.compositingBits); expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), paints..rect(color: promptRectColor), ); editable.promptRectColor = null; editable.layout(BoxConstraints.loose(const Size(1000.0, 1000.0))); pumpFrame(phase: EnginePhase.compositingBits); expect(editable.promptRectColor, null); expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), isNot(paints..rect(color: promptRectColor)), ); }); test('editable hasFocus correctly initialized', () { // Regression test for https://github.com/flutter/flutter/issues/21640 final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), text: '12345', ), textDirection: TextDirection.ltr, locale: const Locale('en', 'US'), offset: ViewportOffset.zero(), textSelectionDelegate: delegate, hasFocus: true, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), ); expect(editable.hasFocus, true); editable.hasFocus = false; expect(editable.hasFocus, false); }); test('has correct maxScrollExtent', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); EditableText.debugDeterministicCursor = true; final RenderEditable editable = RenderEditable( maxLines: 2, backgroundCursorColor: Colors.grey, textDirection: TextDirection.ltr, cursorColor: const Color.fromARGB(0xFF, 0xFF, 0x00, 0x00), offset: ViewportOffset.zero(), textSelectionDelegate: delegate, text: const TextSpan( text: '撒地方加咖啡哈金凤凰卡号方式剪坏算法发挥福建垃\nasfjafjajfjaslfjaskjflasjfksajf撒分开建安路口附近拉设\n计费可使肌肤撒附近埃里克圾房卡设计费"', style: TextStyle( height: 1.0, fontSize: 10.0, fontFamily: 'Roboto', ), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed( offset: 4, affinity: TextAffinity.upstream, ), ); editable.layout(BoxConstraints.loose(const Size(100.0, 1000.0))); expect(editable.size, equals(const Size(100, 20))); expect(editable.maxLines, equals(2)); expect(editable.maxScrollExtent, equals(90)); editable.layout(BoxConstraints.loose(const Size(150.0, 1000.0))); expect(editable.maxScrollExtent, equals(50)); editable.layout(BoxConstraints.loose(const Size(200.0, 1000.0))); expect(editable.maxScrollExtent, equals(40)); editable.layout(BoxConstraints.loose(const Size(500.0, 1000.0))); expect(editable.maxScrollExtent, equals(10)); editable.layout(BoxConstraints.loose(const Size(1000.0, 1000.0))); expect(editable.maxScrollExtent, equals(10)); // TODO(yjbanov): This test is failing in the Dart HHH-web bot and // needs additional investigation before it can be reenabled. }, skip: const bool.fromEnvironment('DART_HHH_BOT')); // https://github.com/flutter/flutter/issues/93691 test('getEndpointsForSelection handles empty characters', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( // This is a Unicode left-to-right mark character that will not render // any glyphs. text: const TextSpan(text: '\u200e'), textDirection: TextDirection.ltr, offset: ViewportOffset.zero(), textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), ); editable.layout(BoxConstraints.loose(const Size(100, 100))); final List<TextSelectionPoint> endpoints = editable.getEndpointsForSelection( const TextSelection(baseOffset: 0, extentOffset: 1), ); expect(endpoints[0].point.dx, 0); }); test('TextSelectionPoint can compare', () { // ignore: prefer_const_constructors final TextSelectionPoint first = TextSelectionPoint(Offset(1, 2), TextDirection.ltr); // ignore: prefer_const_constructors final TextSelectionPoint second = TextSelectionPoint(Offset(1, 2), TextDirection.ltr); expect(first == second, isTrue); expect(first.hashCode == second.hashCode, isTrue); // ignore: prefer_const_constructors final TextSelectionPoint different = TextSelectionPoint(Offset(2, 2), TextDirection.ltr); expect(first == different, isFalse); expect(first.hashCode == different.hashCode, isFalse); }); group('getRectForComposingRange', () { const TextSpan emptyTextSpan = TextSpan(text: '\u200e'); final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( maxLines: null, textDirection: TextDirection.ltr, offset: ViewportOffset.zero(), textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), ); test('returns null when no composing range', () { editable.text = const TextSpan(text: '123'); editable.layout(const BoxConstraints.tightFor(width: 200)); // Invalid range. expect(editable.getRectForComposingRange(const TextRange(start: -1, end: 2)), isNull); // Collapsed range. expect(editable.getRectForComposingRange(const TextRange.collapsed(2)), isNull); // Empty Editable. editable.text = emptyTextSpan; editable.layout(const BoxConstraints.tightFor(width: 200)); expect( editable.getRectForComposingRange(const TextRange(start: 0, end: 1)), // On web this evaluates to a zero-width Rect. anyOf(isNull, (Rect rect) => rect.width == 0), ); }); test('more than 1 run on the same line', () { const TextStyle tinyText = TextStyle(fontSize: 1); const TextStyle normalText = TextStyle(fontSize: 10); editable.text = TextSpan( children: <TextSpan>[ const TextSpan(text: 'A', style: tinyText), TextSpan(text: 'A' * 20, style: normalText), const TextSpan(text: 'A', style: tinyText), ], ); // Give it a width that forces the editable to wrap. editable.layout(const BoxConstraints.tightFor(width: 200)); final Rect composingRect = editable.getRectForComposingRange(const TextRange(start: 0, end: 20 + 2))!; // Since the range covers an entire line, the Rect should also be almost // as wide as the entire paragraph (give or take 1 character). expect(composingRect.width, greaterThan(200 - 10)); }); }); group('custom painters', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final _TestRenderEditable editable = _TestRenderEditable( textDirection: TextDirection.ltr, offset: ViewportOffset.zero(), textSelectionDelegate: delegate, text: const TextSpan( text: 'test', style: TextStyle( height: 1.0, fontSize: 10.0, ), ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed( offset: 4, affinity: TextAffinity.upstream, ), ); setUp(() { EditableText.debugDeterministicCursor = true; }); tearDown(() { EditableText.debugDeterministicCursor = false; editable.foregroundPainter = null; editable.painter = null; editable.paintCount = 0; final RenderObject? parent = editable.parent; if (parent is RenderConstrainedBox) { parent.child = null; } }); test('paints in the correct order', () { layout(editable, constraints: BoxConstraints.loose(const Size(100, 100))); // Prepare for painting after layout. // Foreground painter. editable.foregroundPainter = _TestRenderEditablePainter(); pumpFrame(phase: EnginePhase.compositingBits); expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), paints ..paragraph() ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: const Color(0x12345678)), ); // Background painter. editable.foregroundPainter = null; editable.painter = _TestRenderEditablePainter(); expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), paints ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: const Color(0x12345678)) ..paragraph(), ); editable.foregroundPainter = _TestRenderEditablePainter(); editable.painter = _TestRenderEditablePainter(); expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), paints ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: const Color(0x12345678)) ..paragraph() ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: const Color(0x12345678)), ); }); test('changing foreground painter', () { layout(editable, constraints: BoxConstraints.loose(const Size(100, 100))); // Prepare for painting after layout. _TestRenderEditablePainter currentPainter = _TestRenderEditablePainter(); // Foreground painter. editable.foregroundPainter = currentPainter; pumpFrame(phase: EnginePhase.paint); expect(currentPainter.paintCount, 1); editable.foregroundPainter = (currentPainter = _TestRenderEditablePainter()..repaint = false); pumpFrame(phase: EnginePhase.paint); expect(currentPainter.paintCount, 0); editable.foregroundPainter = (currentPainter = _TestRenderEditablePainter()..repaint = true); pumpFrame(phase: EnginePhase.paint); expect(currentPainter.paintCount, 1); }); test('changing background painter', () { layout(editable, constraints: BoxConstraints.loose(const Size(100, 100))); // Prepare for painting after layout. _TestRenderEditablePainter currentPainter = _TestRenderEditablePainter(); // Foreground painter. editable.painter = currentPainter; pumpFrame(phase: EnginePhase.paint); expect(currentPainter.paintCount, 1); editable.painter = (currentPainter = _TestRenderEditablePainter()..repaint = false); pumpFrame(phase: EnginePhase.paint); expect(currentPainter.paintCount, 0); editable.painter = (currentPainter = _TestRenderEditablePainter()..repaint = true); pumpFrame(phase: EnginePhase.paint); expect(currentPainter.paintCount, 1); }); test('swapping painters', () { layout(editable, constraints: BoxConstraints.loose(const Size(100, 100))); final _TestRenderEditablePainter painter1 = _TestRenderEditablePainter(color: const Color(0x01234567)); final _TestRenderEditablePainter painter2 = _TestRenderEditablePainter(color: const Color(0x76543210)); editable.painter = painter1; editable.foregroundPainter = painter2; expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), paints ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: painter1.color) ..paragraph() ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: painter2.color), ); editable.painter = painter2; editable.foregroundPainter = painter1; expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), paints ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: painter2.color) ..paragraph() ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: painter1.color), ); }); test('reusing the same painter', () { layout(editable, constraints: BoxConstraints.loose(const Size(100, 100))); final _TestRenderEditablePainter painter = _TestRenderEditablePainter(); FlutterErrorDetails? errorDetails; editable.painter = painter; editable.foregroundPainter = painter; pumpFrame(phase: EnginePhase.paint, onErrors: () { errorDetails = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails(); }); expect(errorDetails, isNull); expect(painter.paintCount, 2); expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), paints ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: const Color(0x12345678)) ..paragraph() ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: const Color(0x12345678)), ); }); test('does not repaint the render editable when custom painters need repaint', () { layout(editable, constraints: BoxConstraints.loose(const Size(100, 100))); final _TestRenderEditablePainter painter = _TestRenderEditablePainter(); editable.painter = painter; pumpFrame(phase: EnginePhase.paint); editable.paintCount = 0; painter.paintCount = 0; painter.markNeedsPaint(); pumpFrame(phase: EnginePhase.paint); expect(editable.paintCount, 0); expect(painter.paintCount, 1); }); test('repaints when its RenderEditable repaints', () { layout(editable, constraints: BoxConstraints.loose(const Size(100, 100))); final _TestRenderEditablePainter painter = _TestRenderEditablePainter(); editable.painter = painter; pumpFrame(phase: EnginePhase.paint); editable.paintCount = 0; painter.paintCount = 0; editable.markNeedsPaint(); pumpFrame(phase: EnginePhase.paint); expect(editable.paintCount, 1); expect(painter.paintCount, 1); }); test('correct coordinate space', () { layout(editable, constraints: BoxConstraints.loose(const Size(100, 100))); final _TestRenderEditablePainter painter = _TestRenderEditablePainter(); editable.painter = painter; editable.offset = ViewportOffset.fixed(1000); pumpFrame(phase: EnginePhase.compositingBits); expect( (Canvas canvas) => editable.paint(TestRecordingPaintingContext(canvas), Offset.zero), paints ..rect(rect: const Rect.fromLTRB(1, 1, 1, 1), color: const Color(0x12345678)) ..paragraph(), ); }); group('hit testing', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); test('Basic TextSpan Hit testing', () { final TextSpan textSpanA = TextSpan(text: 'A' * 10); const TextSpan textSpanBC = TextSpan(text: 'BC', style: TextStyle(letterSpacing: 26.0)); final TextSpan text = TextSpan( text: '', style: const TextStyle(fontSize: 10.0), children: <InlineSpan>[textSpanA, textSpanBC], ); final RenderEditable renderEditable = RenderEditable( text: text, maxLines: null, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, offset: ViewportOffset.fixed(0.0), textSelectionDelegate: delegate, selection: const TextSelection.collapsed(offset: 0), ); layout(renderEditable, constraints: BoxConstraints.tightFor(width: 100.0 + _caretMarginOf(renderEditable))); BoxHitTestResult result; // Hit-testing the first line // First A expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(5.0, 5.0)), isTrue); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[textSpanA]); // The last A. expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(95.0, 5.0)), isTrue); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[textSpanA]); // Far away from the line. expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(200.0, 5.0)), isFalse); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[]); // Hit-testing the second line // Tapping on B (startX = letter-spacing / 2 = 13.0). expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(18.0, 15.0)), isTrue); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[textSpanBC]); // Between B and C, with large letter-spacing. expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(31.0, 15.0)), isTrue); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[textSpanBC]); // On C. expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(54.0, 15.0)), isTrue); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[textSpanBC]); // After C. expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(100.0, 15.0)), isTrue); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[]); // Not even remotely close. expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(9999.0, 9999.0)), isFalse); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[]); }); test('TextSpan Hit testing with text justification', () { const TextSpan textSpanA = TextSpan(text: 'A '); // The space is a word break. const TextSpan textSpanB = TextSpan(text: 'B\u200B'); // The zero-width space is used as a line break. final TextSpan textSpanC = TextSpan(text: 'C' * 10); // The third span starts a new line since it's too long for the first line. // The text should look like: // A B // CCCCCCCCCC final TextSpan text = TextSpan( text: '', style: const TextStyle(fontSize: 10.0), children: <InlineSpan>[textSpanA, textSpanB, textSpanC], ); final RenderEditable renderEditable = RenderEditable( text: text, maxLines: null, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, textAlign: TextAlign.justify, offset: ViewportOffset.fixed(0.0), textSelectionDelegate: delegate, selection: const TextSelection.collapsed(offset: 0), ); layout(renderEditable, constraints: BoxConstraints.tightFor(width: 100.0 + _caretMarginOf(renderEditable))); BoxHitTestResult result; // Tapping on A. expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(5.0, 5.0)), isTrue); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[textSpanA]); // Between A and B. expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(50.0, 5.0)), isTrue); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[textSpanA]); // On B. expect(renderEditable.hitTest(result = BoxHitTestResult(), position: const Offset(95.0, 5.0)), isTrue); expect(result.path.map((HitTestEntry<HitTestTarget> entry) => entry.target).whereType<TextSpan>(), <TextSpan>[textSpanB]); }); test('hits correct TextSpan when not scrolled', () { final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ TextSpan(text: 'A'), TextSpan(text: 'B'), ], ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, offset: ViewportOffset.fixed(0.0), textSelectionDelegate: delegate, selection: const TextSelection.collapsed( offset: 0, ), ); layout(editable, constraints: BoxConstraints.loose(const Size(500.0, 500.0))); // Prepare for painting after layout. pumpFrame(phase: EnginePhase.compositingBits); BoxHitTestResult result = BoxHitTestResult(); editable.hitTest(result, position: Offset.zero); // We expect two hit test entries in the path because the RenderEditable // will add itself as well. expect(result.path, hasLength(2)); HitTestTarget target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'A'); // Only testing the RenderEditable entry here once, not anymore below. expect(result.path.last.target, isA<RenderEditable>()); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(15.0, 0.0)); expect(result.path, hasLength(2)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'B'); }); test('hits correct TextSpan when scrolled vertically', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ TextSpan(text: 'A'), TextSpan(text: 'B\n'), TextSpan(text: 'C'), ], ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, // Given maxLines of null and an offset of 5, the editable will be // scrolled vertically by 5 pixels. maxLines: null, offset: ViewportOffset.fixed(5.0), textSelectionDelegate: delegate, selection: const TextSelection.collapsed( offset: 0, ), ); layout(editable, constraints: BoxConstraints.loose(const Size(500.0, 500.0))); // Prepare for painting after layout. pumpFrame(phase: EnginePhase.compositingBits); BoxHitTestResult result = BoxHitTestResult(); editable.hitTest(result, position: Offset.zero); expect(result.path, hasLength(2)); HitTestTarget target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'A'); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(15.0, 0.0)); expect(result.path, hasLength(2)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'B\n'); result = BoxHitTestResult(); // When we hit at y=6 and are scrolled by -5 vertically, we expect "C" // to be hit because the font size is 10. editable.hitTest(result, position: const Offset(0.0, 6.0)); expect(result.path, hasLength(2)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'C'); }); test('hits correct TextSpan when scrolled horizontally', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ TextSpan(text: 'A'), TextSpan(text: 'B'), ], ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, // Given maxLines of 1 and an offset of 5, the editable will be // scrolled by 5 pixels to the left. offset: ViewportOffset.fixed(5.0), textSelectionDelegate: delegate, selection: const TextSelection.collapsed( offset: 0, ), ); layout(editable, constraints: BoxConstraints.loose(const Size(500.0, 500.0))); // Prepare for painting after layout. pumpFrame(phase: EnginePhase.compositingBits); final BoxHitTestResult result = BoxHitTestResult(); // At x=6, we should hit "B" as we are scrolled to the left by 6 // pixels. editable.hitTest(result, position: const Offset(6.0, 0)); expect(result.path, hasLength(2)); final HitTestTarget target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'B'); }); }); }); group('WidgetSpan support', () { test('able to render basic WidgetSpan', () async { final TextSelectionDelegate delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue( text: 'test', selection: TextSelection.collapsed(offset: 3), ); final List<RenderBox> renderBoxes = <RenderBox>[ RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), ]; final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: TextSpan( style: const TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ const TextSpan(text: 'test'), WidgetSpan(child: Container(width: 10, height: 10, color: Colors.blue)), ], ), selection: const TextSelection.collapsed(offset: 3), children: renderBoxes, ); _applyParentData(renderBoxes, editable.text!); layout(editable); editable.hasFocus = true; pumpFrame(); final Rect composingRect = editable.getRectForComposingRange(const TextRange(start: 4, end: 5))!; expect(composingRect, const Rect.fromLTRB(40.0, 0.0, 54.0, 14.0)); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61021 test('able to render multiple WidgetSpans', () async { final TextSelectionDelegate delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue( text: 'test', selection: TextSelection.collapsed(offset: 3), ); final List<RenderBox> renderBoxes = <RenderBox>[ RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'c'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'd'), textDirection: TextDirection.ltr), ]; final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: TextSpan( style: const TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ const TextSpan(text: 'test'), WidgetSpan(child: Container(width: 10, height: 10, color: Colors.blue)), WidgetSpan(child: Container(width: 10, height: 10, color: Colors.blue)), WidgetSpan(child: Container(width: 10, height: 10, color: Colors.blue)), ], ), selection: const TextSelection.collapsed(offset: 3), children: renderBoxes, ); _applyParentData(renderBoxes, editable.text!); layout(editable); editable.hasFocus = true; pumpFrame(); final Rect composingRect = editable.getRectForComposingRange(const TextRange(start: 4, end: 7))!; expect(composingRect, const Rect.fromLTRB(40.0, 0.0, 82.0, 14.0)); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61021 test('able to render WidgetSpans with line wrap', () async { final TextSelectionDelegate delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue( text: 'test', selection: TextSelection.collapsed(offset: 3), ); final List<RenderBox> renderBoxes = <RenderBox>[ RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'c'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'd'), textDirection: TextDirection.ltr), ]; final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ TextSpan(text: 'test'), WidgetSpan(child: Text('b')), WidgetSpan(child: Text('c')), WidgetSpan(child: Text('d')), ], ), selection: const TextSelection.collapsed(offset: 3), maxLines: 2, minLines: 2, children: renderBoxes, ); // Force a line wrap _applyParentData(renderBoxes, editable.text!); layout(editable, constraints: const BoxConstraints(maxWidth: 75)); editable.hasFocus = true; pumpFrame(); Rect composingRect = editable.getRectForComposingRange(const TextRange(start: 4, end: 6))!; expect(composingRect, const Rect.fromLTRB(40.0, 0.0, 68.0, 14.0)); composingRect = editable.getRectForComposingRange(const TextRange(start: 6, end: 7))!; expect(composingRect, const Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61021 test('able to render WidgetSpans with line wrap alternating spans', () async { final TextSelectionDelegate delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue( text: 'test', selection: TextSelection.collapsed(offset: 3), ); final List<RenderBox> renderBoxes = <RenderBox>[ RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'c'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'd'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'e'), textDirection: TextDirection.ltr), ]; final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ TextSpan(text: 'test'), WidgetSpan(child: Text('b')), WidgetSpan(child: Text('c')), WidgetSpan(child: Text('d')), TextSpan(text: 'HI'), WidgetSpan(child: Text('e')), ], ), selection: const TextSelection.collapsed(offset: 3), maxLines: 2, minLines: 2, children: renderBoxes, ); // Force a line wrap _applyParentData(renderBoxes, editable.text!); layout(editable, constraints: const BoxConstraints(maxWidth: 75)); editable.hasFocus = true; pumpFrame(); Rect composingRect = editable.getRectForComposingRange(const TextRange(start: 4, end: 6))!; expect(composingRect, const Rect.fromLTRB(40.0, 0.0, 68.0, 14.0)); composingRect = editable.getRectForComposingRange(const TextRange(start: 6, end: 7))!; expect(composingRect, const Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)); composingRect = editable.getRectForComposingRange(const TextRange(start: 7, end: 8))!; // H expect(composingRect, const Rect.fromLTRB(14.0, 18.0, 24.0, 28.0)); composingRect = editable.getRectForComposingRange(const TextRange(start: 8, end: 9))!; // I expect(composingRect, const Rect.fromLTRB(24.0, 18.0, 34.0, 28.0)); composingRect = editable.getRectForComposingRange(const TextRange(start: 9, end: 10))!; expect(composingRect, const Rect.fromLTRB(34.0, 14.0, 48.0, 28.0)); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61021 test('able to render WidgetSpans nested spans', () async { final TextSelectionDelegate delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue( text: 'test', selection: TextSelection.collapsed(offset: 3), ); final List<RenderBox> renderBoxes = <RenderBox>[ RenderParagraph(const TextSpan(text: 'a'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'c'), textDirection: TextDirection.ltr), ]; final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ TextSpan(text: 'test'), WidgetSpan(child: Text('a')), TextSpan(children: <InlineSpan>[ WidgetSpan(child: Text('b')), WidgetSpan(child: Text('c')), ], ), ], ), selection: const TextSelection.collapsed(offset: 3), maxLines: 2, minLines: 2, children: renderBoxes, ); _applyParentData(renderBoxes, editable.text!); // Force a line wrap layout(editable, constraints: const BoxConstraints(maxWidth: 75)); editable.hasFocus = true; pumpFrame(); Rect? composingRect = editable.getRectForComposingRange(const TextRange(start: 4, end: 5)); expect(composingRect, const Rect.fromLTRB(40.0, 0.0, 54.0, 14.0)); composingRect = editable.getRectForComposingRange(const TextRange(start: 5, end: 6)); expect(composingRect, const Rect.fromLTRB(54.0, 0.0, 68.0, 14.0)); composingRect = editable.getRectForComposingRange(const TextRange(start: 6, end: 7)); expect(composingRect, const Rect.fromLTRB(0.0, 14.0, 14.0, 28.0)); composingRect = editable.getRectForComposingRange(const TextRange(start: 7, end: 8)); expect(composingRect, null); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61021 test('WidgetSpan render box is painted at correct offset when scrolled', () async { final TextSelectionDelegate delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue( text: 'test', selection: TextSelection.collapsed(offset: 3), ); final List<RenderBox> renderBoxes = <RenderBox>[ RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), ]; final ViewportOffset viewportOffset = ViewportOffset.fixed(100.0); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), maxLines: null, text: TextSpan( style: const TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ const TextSpan(text: 'test'), WidgetSpan(child: Container(width: 10, height: 10, color: Colors.blue)), ], ), selection: const TextSelection.collapsed(offset: 3), children: renderBoxes, ); _applyParentData(renderBoxes, editable.text!); layout(editable); editable.hasFocus = true; pumpFrame(); final Rect composingRect = editable.getRectForComposingRange(const TextRange(start: 4, end: 5))!; expect(composingRect, const Rect.fromLTRB(40.0, -100.0, 54.0, -86.0)); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61021 test('can compute IntrinsicWidth for WidgetSpans', () { // Regression test for https://github.com/flutter/flutter/issues/59316 const double screenWidth = 1000.0; const double fixedHeight = 1000.0; const String sentence = 'one two'; final TextSelectionDelegate delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue( text: 'test', selection: TextSelection.collapsed(offset: 3), ); final List<RenderBox> renderBoxes = <RenderBox>[ RenderParagraph(const TextSpan(text: sentence), textDirection: TextDirection.ltr), ]; final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, cursorWidth: 0.0, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ TextSpan(text: 'test'), WidgetSpan(child: Text('a')), ], ), selection: const TextSelection.collapsed(offset: 3), maxLines: 2, minLines: 2, textScaler: const TextScaler.linear(2.0), children: renderBoxes, ); _applyParentData(renderBoxes, editable.text!); // Intrinsics can be computed without doing layout. expect(editable.computeMaxIntrinsicWidth(fixedHeight), 2.0 * 10.0 * 4 + 14.0 * 7 + 1.0, reason: "intrinsic width = scale factor * width of 'test' + width of 'one two' + _caretMargin", ); expect(editable.computeMinIntrinsicWidth(fixedHeight), math.max(math.max(2.0 * 10.0 * 4, 14.0 * 3), 14.0 * 3), reason: "intrinsic width = max(scale factor * width of 'test', width of 'one', width of 'two')", ); expect(editable.computeMaxIntrinsicHeight(fixedHeight), 40.0); expect(editable.computeMinIntrinsicHeight(fixedHeight), 40.0); layout(editable, constraints: const BoxConstraints(maxWidth: screenWidth)); // Intrinsics can be computed after layout. expect(editable.computeMaxIntrinsicWidth(fixedHeight), 2.0 * 10.0 * 4 + 14.0 * 7 + 1.0, reason: "intrinsic width = scale factor * width of 'test' + width of 'one two' + _caretMargin", ); }); test('hits correct WidgetSpan when not scrolled', () { final TextSelectionDelegate delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue( text: 'test', selection: TextSelection.collapsed(offset: 3), ); final List<RenderBox> renderBoxes = <RenderBox>[ RenderParagraph(const TextSpan(text: 'a'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'c'), textDirection: TextDirection.ltr), ]; final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ TextSpan(text: 'test'), WidgetSpan(child: Text('a')), TextSpan(children: <InlineSpan>[ WidgetSpan(child: Text('b')), WidgetSpan(child: Text('c')), ], ), ], ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, offset: ViewportOffset.fixed(0.0), textSelectionDelegate: delegate, selection: const TextSelection.collapsed( offset: 0, ), children: renderBoxes, ); _applyParentData(renderBoxes, editable.text!); layout(editable, constraints: BoxConstraints.loose(const Size(500.0, 500.0))); // Prepare for painting after layout. pumpFrame(phase: EnginePhase.compositingBits); BoxHitTestResult result = BoxHitTestResult(); // The WidgetSpans have a height of 14.0, so "test" has a y offset of 4.0. editable.hitTest(result, position: const Offset(1.0, 5.0)); // We expect two hit test entries in the path because the RenderEditable // will add itself as well. expect(result.path, hasLength(2)); HitTestTarget target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'test'); // Only testing the RenderEditable entry here once, not anymore below. expect(result.path.last.target, isA<RenderEditable>()); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(15.0, 5.0)); expect(result.path, hasLength(2)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'test'); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(41.0, 0.0)); expect(result.path, hasLength(3)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'a'); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(55.0, 0.0)); expect(result.path, hasLength(3)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'b'); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(69.0, 5.0)); expect(result.path, hasLength(3)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'c'); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(5.0, 15.0)); expect(result.path, hasLength(0)); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61020 test('hits correct WidgetSpan when scrolled', () { final String text = '${"\n" * 10}test'; final TextSelectionDelegate delegate = _FakeEditableTextState() ..textEditingValue = TextEditingValue( text: text, selection: const TextSelection.collapsed(offset: 13), ); final List<RenderBox> renderBoxes = <RenderBox>[ RenderParagraph(const TextSpan(text: 'a'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'b'), textDirection: TextDirection.ltr), RenderParagraph(const TextSpan(text: 'c'), textDirection: TextDirection.ltr), ]; final RenderEditable editable = RenderEditable( maxLines: null, text: TextSpan( style: const TextStyle(height: 1.0, fontSize: 10.0), children: <InlineSpan>[ TextSpan(text: text), const WidgetSpan(child: Text('a')), const TextSpan(children: <InlineSpan>[ WidgetSpan(child: Text('b')), WidgetSpan(child: Text('c')), ], ), ], ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, offset: ViewportOffset.fixed(100.0), // equal to the height of the 10 empty lines textSelectionDelegate: delegate, selection: const TextSelection.collapsed( offset: 0, ), children: renderBoxes, ); _applyParentData(renderBoxes, editable.text!); layout(editable, constraints: BoxConstraints.loose(const Size(500.0, 500.0))); // Prepare for painting after layout. pumpFrame(phase: EnginePhase.compositingBits); BoxHitTestResult result = BoxHitTestResult(); // The WidgetSpans have a height of 14.0, so "test" has a y offset of 4.0. editable.hitTest(result, position: const Offset(0.0, 4.0)); // We expect two hit test entries in the path because the RenderEditable // will add itself as well. expect(result.path, hasLength(2)); HitTestTarget target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, text); // Only testing the RenderEditable entry here once, not anymore below. expect(result.path.last.target, isA<RenderEditable>()); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(15.0, 4.0)); expect(result.path, hasLength(2)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, text); result = BoxHitTestResult(); // "test" is 40 pixel wide. editable.hitTest(result, position: const Offset(41.0, 0.0)); expect(result.path, hasLength(3)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'a'); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(55.0, 0.0)); expect(result.path, hasLength(3)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'b'); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(69.0, 5.0)); expect(result.path, hasLength(3)); target = result.path.first.target; expect(target, isA<TextSpan>()); expect((target as TextSpan).text, 'c'); result = BoxHitTestResult(); editable.hitTest(result, position: const Offset(5.0, 15.0)); expect(result.path, hasLength(1)); // Only the RenderEditable. }, skip: isBrowser); // https://github.com/flutter/flutter/issues/61020 }); test('does not skip TextPainter.layout because of invalid cache', () { // Regression test for https://github.com/flutter/flutter/issues/84896. final TextSelectionDelegate delegate = _FakeEditableTextState(); const BoxConstraints constraints = BoxConstraints(minWidth: 100, maxWidth: 500); final RenderEditable editable = RenderEditable( text: const TextSpan( style: TextStyle(height: 1.0, fontSize: 10.0), text: 'A', ), startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), textDirection: TextDirection.ltr, locale: const Locale('en', 'US'), offset: ViewportOffset.fixed(10.0), textSelectionDelegate: delegate, selection: const TextSelection.collapsed(offset: 0), cursorColor: const Color(0xFFFFFFFF), showCursor: ValueNotifier<bool>(true), ); layout(editable, constraints: constraints); // ignore: invalid_use_of_protected_member final double initialWidth = editable.computeDryLayout(constraints).width; expect(initialWidth, 500); // Turn off forceLine. Now the width should be significantly smaller. editable.forceLine = false; // ignore: invalid_use_of_protected_member expect(editable.computeDryLayout(constraints).width, lessThan(initialWidth)); }); test('Floating cursor position is independent of viewport offset', () { final TextSelectionDelegate delegate = _FakeEditableTextState(); final ValueNotifier<bool> showCursor = ValueNotifier<bool>(true); EditableText.debugDeterministicCursor = true; const Color cursorColor = Color.fromARGB(0xFF, 0xFF, 0x00, 0x00); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, textDirection: TextDirection.ltr, cursorColor: cursorColor, offset: ViewportOffset.zero(), textSelectionDelegate: delegate, text: const TextSpan( text: 'test', style: TextStyle(height: 1.0, fontSize: 10.0), ), maxLines: 3, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), selection: const TextSelection.collapsed( offset: 4, affinity: TextAffinity.upstream, ), ); layout(editable); editable.layout(BoxConstraints.loose(const Size(100, 100))); // Prepare for painting after layout. pumpFrame(phase: EnginePhase.compositingBits); expect( editable, // Draw no cursor by default. paintsExactlyCountTimes(#drawRect, 0), ); editable.showCursor = showCursor; editable.setFloatingCursor(FloatingCursorDragState.Start, const Offset(50, 50), const TextPosition( offset: 4, affinity: TextAffinity.upstream, )); pumpFrame(phase: EnginePhase.compositingBits); final RRect expectedRRect = RRect.fromRectAndRadius( const Rect.fromLTWH(49.5, 51, 2, 8), const Radius.circular(1) ); expect(editable, paints..rrect( color: cursorColor.withOpacity(0.75), rrect: expectedRRect )); // Change the text viewport offset. editable.offset = ViewportOffset.fixed(200); // Floating cursor should be drawn in the same position. editable.setFloatingCursor(FloatingCursorDragState.Start, const Offset(50, 50), const TextPosition( offset: 4, affinity: TextAffinity.upstream, )); pumpFrame(phase: EnginePhase.compositingBits); expect(editable, paints..rrect( color: cursorColor.withOpacity(0.75), rrect: expectedRRect )); }); test('getWordAtOffset with a negative position', () { const String text = 'abc'; final _FakeEditableTextState delegate = _FakeEditableTextState() ..textEditingValue = const TextEditingValue(text: text); final ViewportOffset viewportOffset = ViewportOffset.zero(); final RenderEditable editable = RenderEditable( backgroundCursorColor: Colors.grey, selectionColor: Colors.black, textDirection: TextDirection.ltr, cursorColor: Colors.red, offset: viewportOffset, textSelectionDelegate: delegate, startHandleLayerLink: LayerLink(), endHandleLayerLink: LayerLink(), text: const TextSpan( text: text, style: TextStyle(height: 1.0, fontSize: 10.0), ), ); layout(editable, onErrors: expectNoFlutterErrors); // Cause text metrics to be computed. editable.computeDistanceToActualBaseline(TextBaseline.alphabetic); final TextSelection selection; try { selection = editable.getWordAtOffset(const TextPosition( offset: -1, affinity: TextAffinity.upstream, )); } catch (error) { // In debug mode, negative offsets are caught by an assertion. expect(error, isA<AssertionError>()); return; } // Web's Paragraph.getWordBoundary behaves differently for a negative // position. if (kIsWeb) { expect(selection, const TextSelection.collapsed(offset: 0)); } else { expect(selection, const TextSelection.collapsed(offset: text.length)); } }); } class _TestRenderEditable extends RenderEditable { _TestRenderEditable({ required super.textDirection, required super.offset, required super.textSelectionDelegate, TextSpan? super.text, required super.startHandleLayerLink, required super.endHandleLayerLink, super.selection, }); int paintCount = 0; @override void paint(PaintingContext context, Offset offset) { super.paint(context, offset); paintCount += 1; } } class _TestRenderEditablePainter extends RenderEditablePainter { _TestRenderEditablePainter({this.color = const Color(0x12345678)}); final Color color; bool repaint = true; int paintCount = 0; @override void paint(Canvas canvas, Size size, RenderEditable renderEditable) { paintCount += 1; canvas.drawRect(const Rect.fromLTRB(1, 1, 1, 1), Paint()..color = color); } @override bool shouldRepaint(RenderEditablePainter? oldDelegate) => repaint; void markNeedsPaint() { notifyListeners(); } @override String toString() => '_TestRenderEditablePainter#${shortHash(this)}'; }
flutter/packages/flutter/test/rendering/editable_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/editable_test.dart", "repo_id": "flutter", "token_count": 32526 }
726
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final RendererBinding binding = RenderingFlutterBinding.ensureInitialized(); test('Adding/removing renderviews updates renderViews getter', () { final FlutterView flutterView = FakeFlutterView(); final RenderView view = RenderView(view: flutterView); expect(binding.renderViews, isEmpty); binding.addRenderView(view); expect(binding.renderViews, contains(view)); expect(view.configuration.devicePixelRatio, flutterView.devicePixelRatio); expect(view.configuration.logicalConstraints, BoxConstraints.tight(flutterView.physicalSize) / flutterView.devicePixelRatio); binding.removeRenderView(view); expect(binding.renderViews, isEmpty); }); test('illegal add/remove renderviews', () { final FlutterView flutterView = FakeFlutterView(); final RenderView view1 = RenderView(view: flutterView); final RenderView view2 = RenderView(view: flutterView); final RenderView view3 = RenderView(view: FakeFlutterView(viewId: 200)); expect(binding.renderViews, isEmpty); binding.addRenderView(view1); expect(binding.renderViews, contains(view1)); expect(() => binding.addRenderView(view1), throwsAssertionError); expect(() => binding.addRenderView(view2), throwsAssertionError); expect(() => binding.removeRenderView(view2), throwsAssertionError); expect(() => binding.removeRenderView(view3), throwsAssertionError); expect(binding.renderViews, contains(view1)); binding.removeRenderView(view1); expect(binding.renderViews, isEmpty); expect(() => binding.removeRenderView(view1), throwsAssertionError); expect(() => binding.removeRenderView(view2), throwsAssertionError); }); test('changing metrics updates configuration', () { final FakeFlutterView flutterView = FakeFlutterView(); final RenderView view = RenderView(view: flutterView); binding.addRenderView(view); expect(view.configuration.devicePixelRatio, 2.5); expect(view.configuration.logicalConstraints.isTight, isTrue); expect(view.configuration.logicalConstraints.minWidth, 160.0); expect(view.configuration.logicalConstraints.minHeight, 240.0); flutterView.devicePixelRatio = 3.0; flutterView.physicalSize = const Size(300, 300); binding.handleMetricsChanged(); expect(view.configuration.devicePixelRatio, 3.0); expect(view.configuration.logicalConstraints.isTight, isTrue); expect(view.configuration.logicalConstraints.minWidth, 100.0); expect(view.configuration.logicalConstraints.minHeight, 100.0); binding.removeRenderView(view); }); test('semantics actions are performed on the right view', () { final FakeFlutterView flutterView1 = FakeFlutterView(viewId: 1); final FakeFlutterView flutterView2 = FakeFlutterView(viewId: 2); final RenderView renderView1 = RenderView(view: flutterView1); final RenderView renderView2 = RenderView(view: flutterView2); final PipelineOwnerSpy owner1 = PipelineOwnerSpy() ..rootNode = renderView1; final PipelineOwnerSpy owner2 = PipelineOwnerSpy() ..rootNode = renderView2; binding.addRenderView(renderView1); binding.addRenderView(renderView2); binding.performSemanticsAction( const SemanticsActionEvent(type: SemanticsAction.copy, viewId: 1, nodeId: 11), ); expect(owner1.semanticsOwner.performedActions.single, (11, SemanticsAction.copy, null)); expect(owner2.semanticsOwner.performedActions, isEmpty); owner1.semanticsOwner.performedActions.clear(); binding.performSemanticsAction( const SemanticsActionEvent(type: SemanticsAction.tap, viewId: 2, nodeId: 22), ); expect(owner1.semanticsOwner.performedActions, isEmpty); expect(owner2.semanticsOwner.performedActions.single, (22, SemanticsAction.tap, null)); owner2.semanticsOwner.performedActions.clear(); binding.performSemanticsAction( const SemanticsActionEvent(type: SemanticsAction.tap, viewId: 3, nodeId: 22), ); expect(owner1.semanticsOwner.performedActions, isEmpty); expect(owner2.semanticsOwner.performedActions, isEmpty); binding.removeRenderView(renderView1); binding.removeRenderView(renderView2); }); test('all registered renderviews are asked to composite frame', () { final FakeFlutterView flutterView1 = FakeFlutterView(viewId: 1); final FakeFlutterView flutterView2 = FakeFlutterView(viewId: 2); final RenderView renderView1 = RenderView(view: flutterView1); final RenderView renderView2 = RenderView(view: flutterView2); final PipelineOwner owner1 = PipelineOwner()..rootNode = renderView1; final PipelineOwner owner2 = PipelineOwner()..rootNode = renderView2; binding.rootPipelineOwner.adoptChild(owner1); binding.rootPipelineOwner.adoptChild(owner2); binding.addRenderView(renderView1); binding.addRenderView(renderView2); renderView1.prepareInitialFrame(); renderView2.prepareInitialFrame(); expect(flutterView1.renderedScenes, isEmpty); expect(flutterView2.renderedScenes, isEmpty); binding.handleBeginFrame(Duration.zero); binding.handleDrawFrame(); expect(flutterView1.renderedScenes, hasLength(1)); expect(flutterView2.renderedScenes, hasLength(1)); binding.removeRenderView(renderView1); binding.handleBeginFrame(Duration.zero); binding.handleDrawFrame(); expect(flutterView1.renderedScenes, hasLength(1)); expect(flutterView2.renderedScenes, hasLength(2)); binding.removeRenderView(renderView2); binding.handleBeginFrame(Duration.zero); binding.handleDrawFrame(); expect(flutterView1.renderedScenes, hasLength(1)); expect(flutterView2.renderedScenes, hasLength(2)); }); test('hit-testing reaches the right view', () { final FakeFlutterView flutterView1 = FakeFlutterView(viewId: 1); final FakeFlutterView flutterView2 = FakeFlutterView(viewId: 2); final RenderView renderView1 = RenderView(view: flutterView1); final RenderView renderView2 = RenderView(view: flutterView2); binding.addRenderView(renderView1); binding.addRenderView(renderView2); HitTestResult result = HitTestResult(); binding.hitTestInView(result, Offset.zero, 1); expect(result.path, hasLength(2)); expect(result.path.first.target, renderView1); expect(result.path.last.target, binding); result = HitTestResult(); binding.hitTestInView(result, Offset.zero, 2); expect(result.path, hasLength(2)); expect(result.path.first.target, renderView2); expect(result.path.last.target, binding); result = HitTestResult(); binding.hitTestInView(result, Offset.zero, 3); expect(result.path.single.target, binding); binding.removeRenderView(renderView1); binding.removeRenderView(renderView2); }); } class FakeFlutterView extends Fake implements FlutterView { FakeFlutterView({ this.viewId = 100, this.devicePixelRatio = 2.5, this.physicalSize = const Size(400,600), this.padding = FakeViewPadding.zero, }); @override final int viewId; @override double devicePixelRatio; @override Size physicalSize; @override ViewConstraints get physicalConstraints => ViewConstraints.tight(physicalSize); @override ViewPadding padding; List<Scene> renderedScenes = <Scene>[]; @override void render(Scene scene, {Size? size}) { renderedScenes.add(scene); } } class PipelineOwnerSpy extends PipelineOwner { @override final SemanticsOwnerSpy semanticsOwner = SemanticsOwnerSpy(); } class SemanticsOwnerSpy extends Fake implements SemanticsOwner { final List<(int, SemanticsAction, Object?)> performedActions = <(int, SemanticsAction, Object?)>[]; @override void performAction(int id, SemanticsAction action, [ Object? args ]) { performedActions.add((id, action, args)); } }
flutter/packages/flutter/test/rendering/multi_view_binding_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/multi_view_binding_test.dart", "repo_id": "flutter", "token_count": 2685 }
727
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'rendering_tester.dart'; void main() { TestRenderingFlutterBinding.ensureInitialized(); test('RenderSliverOpacity does not composite if it is transparent', () { final RenderSliverOpacity renderSliverOpacity = RenderSliverOpacity( opacity: 0.0, sliver: RenderSliverToBoxAdapter( child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter ), ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), cacheExtent: 250.0, children: <RenderSliver>[renderSliverOpacity], ); layout(root, phase: EnginePhase.composite); expect(renderSliverOpacity.needsCompositing, false); }); test('RenderSliverOpacity does composite if it is opaque', () { final RenderSliverOpacity renderSliverOpacity = RenderSliverOpacity( sliver: RenderSliverToBoxAdapter( child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter ), ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), cacheExtent: 250.0, children: <RenderSliver>[renderSliverOpacity], ); layout(root, phase: EnginePhase.composite); expect(renderSliverOpacity.needsCompositing, true); }); test('RenderSliverOpacity reuses its layer', () { final RenderSliverOpacity renderSliverOpacity = RenderSliverOpacity( opacity: 0.5, sliver: RenderSliverToBoxAdapter( child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter ), ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), cacheExtent: 250.0, children: <RenderSliver>[renderSliverOpacity], ); expect(renderSliverOpacity.debugLayer, null); layout(root, phase: EnginePhase.paint, constraints: BoxConstraints.tight(const Size(10, 10))); final ContainerLayer layer = renderSliverOpacity.debugLayer!; expect(layer, isNotNull); // Mark for repaint otherwise pumpFrame is a noop. renderSliverOpacity.markNeedsPaint(); expect(renderSliverOpacity.debugNeedsPaint, true); pumpFrame(phase: EnginePhase.paint); expect(renderSliverOpacity.debugNeedsPaint, false); expect(renderSliverOpacity.debugLayer, same(layer)); }); test('RenderSliverAnimatedOpacity does not composite if it is transparent', () async { final Animation<double> opacityAnimation = AnimationController( vsync: FakeTickerProvider(), )..value = 0.0; final RenderSliverAnimatedOpacity renderSliverAnimatedOpacity = RenderSliverAnimatedOpacity( opacity: opacityAnimation, sliver: RenderSliverToBoxAdapter( child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter ), ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), cacheExtent: 250.0, children: <RenderSliver>[renderSliverAnimatedOpacity], ); layout(root, phase: EnginePhase.composite); expect(renderSliverAnimatedOpacity.needsCompositing, false); }); test('RenderSliverAnimatedOpacity does composite if it is partially opaque', () { final Animation<double> opacityAnimation = AnimationController( vsync: FakeTickerProvider(), )..value = 0.5; final RenderSliverAnimatedOpacity renderSliverAnimatedOpacity = RenderSliverAnimatedOpacity( opacity: opacityAnimation, sliver: RenderSliverToBoxAdapter( child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter ), ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), cacheExtent: 250.0, children: <RenderSliver>[renderSliverAnimatedOpacity], ); layout(root, phase: EnginePhase.composite); expect(renderSliverAnimatedOpacity.needsCompositing, true); }); test('RenderSliverAnimatedOpacity does composite if it is opaque', () { final Animation<double> opacityAnimation = AnimationController( vsync: FakeTickerProvider(), )..value = 1.0; final RenderSliverAnimatedOpacity renderSliverAnimatedOpacity = RenderSliverAnimatedOpacity( opacity: opacityAnimation, sliver: RenderSliverToBoxAdapter( child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter ), ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), cacheExtent: 250.0, children: <RenderSliver>[renderSliverAnimatedOpacity], ); layout(root, phase: EnginePhase.composite); expect(renderSliverAnimatedOpacity.needsCompositing, true); }); test('RenderSliverAnimatedOpacity reuses its layer', () { final Animation<double> opacityAnimation = AnimationController( vsync: FakeTickerProvider(), )..value = 0.5; // must not be 0 or 1.0. Otherwise, it won't create a layer final RenderSliverAnimatedOpacity renderSliverAnimatedOpacity = RenderSliverAnimatedOpacity( opacity: opacityAnimation, sliver: RenderSliverToBoxAdapter( child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter ), ); final RenderViewport root = RenderViewport( crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(), cacheExtent: 250.0, children: <RenderSliver>[renderSliverAnimatedOpacity], ); expect(renderSliverAnimatedOpacity.debugLayer, null); layout(root, phase: EnginePhase.paint, constraints: BoxConstraints.tight(const Size(10, 10))); final ContainerLayer layer = renderSliverAnimatedOpacity.debugLayer!; expect(layer, isNotNull); // Mark for repaint otherwise pumpFrame is a noop. renderSliverAnimatedOpacity.markNeedsPaint(); expect(renderSliverAnimatedOpacity.debugNeedsPaint, true); pumpFrame(phase: EnginePhase.paint); expect(renderSliverAnimatedOpacity.debugNeedsPaint, false); expect(renderSliverAnimatedOpacity.debugLayer, same(layer)); }); }
flutter/packages/flutter/test/rendering/proxy_sliver_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/proxy_sliver_test.dart", "repo_id": "flutter", "token_count": 2291 }
728
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('applyGrowthDirectionToAxisDirection produces expected AxisDirection', () { expect(AxisDirection.values.length, 4); for (final AxisDirection axisDirection in AxisDirection.values) { expect(applyGrowthDirectionToAxisDirection(axisDirection, GrowthDirection.forward), axisDirection); } expect(applyGrowthDirectionToAxisDirection(AxisDirection.up, GrowthDirection.reverse), AxisDirection.down); expect(applyGrowthDirectionToAxisDirection(AxisDirection.down, GrowthDirection.reverse), AxisDirection.up); expect(applyGrowthDirectionToAxisDirection(AxisDirection.left, GrowthDirection.reverse), AxisDirection.right); expect(applyGrowthDirectionToAxisDirection(AxisDirection.right, GrowthDirection.reverse), AxisDirection.left); }); test('SliverConstraints are the same when copied', () { const SliverConstraints original = SliverConstraints( axisDirection: AxisDirection.down, growthDirection: GrowthDirection.forward, userScrollDirection: ScrollDirection.idle, scrollOffset: 0.0, precedingScrollExtent: 0.0, overlap: 0.0, remainingPaintExtent: 0.0, crossAxisExtent: 0.0, crossAxisDirection: AxisDirection.right, viewportMainAxisExtent: 0.0, cacheOrigin: 0.0, remainingCacheExtent: 0.0, ); final SliverConstraints copy = original.copyWith(); expect(original, equals(copy)); expect(original.hashCode, equals(copy.hashCode)); expect(original.toString(), equals(copy.toString())); expect(original, hasOneLineDescription); expect(original.normalizedGrowthDirection, equals(GrowthDirection.forward)); }); test('SliverConstraints normalizedGrowthDirection is inferred from AxisDirection and GrowthDirection', () { const SliverConstraints a = SliverConstraints( axisDirection: AxisDirection.down, growthDirection: GrowthDirection.forward, userScrollDirection: ScrollDirection.idle, scrollOffset: 0.0, precedingScrollExtent: 0.0, overlap: 0.0, remainingPaintExtent: 0.0, crossAxisExtent: 0.0, crossAxisDirection: AxisDirection.right, viewportMainAxisExtent: 0.0, cacheOrigin: 0.0, remainingCacheExtent: 0.0, ); final SliverConstraints c = a.copyWith( axisDirection: AxisDirection.up, growthDirection: GrowthDirection.reverse, userScrollDirection: ScrollDirection.forward, scrollOffset: 10.0, overlap: 20.0, remainingPaintExtent: 30.0, crossAxisExtent: 40.0, viewportMainAxisExtent: 30.0, ); const SliverConstraints d = SliverConstraints( axisDirection: AxisDirection.up, growthDirection: GrowthDirection.reverse, userScrollDirection: ScrollDirection.forward, scrollOffset: 10.0, precedingScrollExtent: 0.0, overlap: 20.0, remainingPaintExtent: 30.0, crossAxisExtent: 40.0, crossAxisDirection: AxisDirection.right, viewportMainAxisExtent: 30.0, cacheOrigin: 0.0, remainingCacheExtent: 0.0, ); expect(c, equals(d)); expect(c.normalizedGrowthDirection, equals(GrowthDirection.forward)); expect(d.normalizedGrowthDirection, equals(GrowthDirection.forward)); final SliverConstraints e = d.copyWith(axisDirection: AxisDirection.right); expect(e.normalizedGrowthDirection, equals(GrowthDirection.reverse)); final SliverConstraints f = d.copyWith(axisDirection: AxisDirection.left); expect(f.normalizedGrowthDirection, equals(GrowthDirection.forward)); final SliverConstraints g = d.copyWith(growthDirection: GrowthDirection.forward); expect(g.normalizedGrowthDirection, equals(GrowthDirection.reverse)); }); test('SliverGeometry with no arguments is valid', () { expect(SliverGeometry.zero.debugAssertIsValid(), isTrue); }); test('SliverGeometry throws error when layoutExtent exceeds paintExtent', () { expect(() { const SliverGeometry(layoutExtent: 10.0, paintExtent: 9.0).debugAssertIsValid(); }, throwsFlutterError); }); test('SliverGeometry throws error when maxPaintExtent is less than paintExtent', () { expect(() { const SliverGeometry(paintExtent: 9.0, maxPaintExtent: 8.0).debugAssertIsValid(); }, throwsFlutterError); }); }
flutter/packages/flutter/test/rendering/slivers_helpers_test.dart/0
{ "file_path": "flutter/packages/flutter/test/rendering/slivers_helpers_test.dart", "repo_id": "flutter", "token_count": 1665 }
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/scheduler.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { test('debugAssertAllSchedulerVarsUnset control test', () { expect(() { debugAssertAllSchedulerVarsUnset('Example test'); }, isNot(throwsFlutterError)); debugPrintBeginFrameBanner = true; expect(() { debugAssertAllSchedulerVarsUnset('Example test'); }, throwsFlutterError); debugPrintBeginFrameBanner = false; debugPrintEndFrameBanner = true; expect(() { debugAssertAllSchedulerVarsUnset('Example test'); }, throwsFlutterError); debugPrintEndFrameBanner = false; expect(() { debugAssertAllSchedulerVarsUnset('Example test'); }, isNot(throwsFlutterError)); }); }
flutter/packages/flutter/test/scheduler/debug_test.dart/0
{ "file_path": "flutter/packages/flutter/test/scheduler/debug_test.dart", "repo_id": "flutter", "token_count": 322 }
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:convert'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; class TestAssetBundle extends AssetBundle { static const Map<String, List<Object>> _binManifestData = <String, List<Object>>{ 'assets/foo.png': <Object>[ <String, Object>{ 'asset': 'assets/foo.png', }, <String, Object>{ 'asset': 'assets/2x/foo.png', 'dpr': 2.0 }, ], 'assets/bar.png': <Object>[ <String, Object>{ 'asset': 'assets/bar.png', }, ], }; @override Future<ByteData> load(String key) async { if (key == 'AssetManifest.bin') { final ByteData data = const StandardMessageCodec().encodeMessage(_binManifestData)!; return data; } if (key == 'AssetManifest.bin.json') { // Encode the manifest data that will be used by the app final ByteData data = const StandardMessageCodec().encodeMessage(_binManifestData)!; // 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) ) ) ) ); } throw ArgumentError('Unexpected key'); } @override Future<T> loadStructuredData<T>(String key, Future<T> Function(String value) parser) async { return parser(await loadString(key)); } } void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('loadFromBundle correctly parses a binary asset manifest', () async { final AssetManifest manifest = await AssetManifest.loadFromAssetBundle(TestAssetBundle()); expect(manifest.listAssets(), unorderedEquals(<String>['assets/foo.png', 'assets/bar.png'])); final List<AssetMetadata> fooVariants = manifest.getAssetVariants('assets/foo.png')!; expect(fooVariants.length, 2); final AssetMetadata firstFooVariant = fooVariants[0]; expect(firstFooVariant.key, 'assets/foo.png'); expect(firstFooVariant.targetDevicePixelRatio, null); expect(firstFooVariant.main, true); final AssetMetadata secondFooVariant = fooVariants[1]; expect(secondFooVariant.key, 'assets/2x/foo.png'); expect(secondFooVariant.targetDevicePixelRatio, 2.0); expect(secondFooVariant.main, false); final List<AssetMetadata> barVariants = manifest.getAssetVariants('assets/bar.png')!; expect(barVariants.length, 1); final AssetMetadata firstBarVariant = barVariants[0]; expect(firstBarVariant.key, 'assets/bar.png'); expect(firstBarVariant.targetDevicePixelRatio, null); expect(firstBarVariant.main, true); }); test('getAssetVariants returns null if the key not contained in the asset manifest', () async { final AssetManifest manifest = await AssetManifest.loadFromAssetBundle(TestAssetBundle()); expect(manifest.getAssetVariants('invalid asset key'), isNull); }); }
flutter/packages/flutter/test/services/asset_manifest_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/asset_manifest_test.dart", "repo_id": "flutter", "token_count": 1199 }
731
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('initialLifecycleState is used to init state paused', (WidgetTester tester) async { final TestWidgetsFlutterBinding binding = tester.binding; binding.resetInternalState(); // Use paused as the initial state. binding.platformDispatcher.initialLifecycleStateTestValue = 'AppLifecycleState.paused'; binding.readTestInitialLifecycleStateFromNativeWindow(); // Re-attempt the initialization. // The lifecycleState should now be the state we passed above, // even though no lifecycle event was fired from the platform. expect(binding.lifecycleState.toString(), equals('AppLifecycleState.paused')); }); testWidgets('Handles all of the allowed states of AppLifecycleState', (WidgetTester tester) async { final TestWidgetsFlutterBinding binding = tester.binding; for (final AppLifecycleState state in AppLifecycleState.values) { binding.resetInternalState(); binding.platformDispatcher.initialLifecycleStateTestValue = state.toString(); binding.readTestInitialLifecycleStateFromNativeWindow(); expect(ServicesBinding.instance.lifecycleState.toString(), equals(state.toString())); } }); test('AppLifecycleState values are in the right order for the state machine to be correct', () { expect( AppLifecycleState.values, equals( <AppLifecycleState>[ AppLifecycleState.detached, AppLifecycleState.resumed, AppLifecycleState.inactive, AppLifecycleState.hidden, AppLifecycleState.paused, ], ), ); }); }
flutter/packages/flutter/test/services/lifecycle_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/lifecycle_test.dart", "repo_id": "flutter", "token_count": 632 }
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/services.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); test('System sound control test', () async { final List<MethodCall> log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { log.add(methodCall); return null; }); await SystemSound.play(SystemSoundType.click); expect(log, hasLength(1)); expect(log.single, isMethodCall('SystemSound.play', arguments: 'SystemSoundType.click')); }); }
flutter/packages/flutter/test/services/system_sound_test.dart/0
{ "file_path": "flutter/packages/flutter/test/services/system_sound_test.dart", "repo_id": "flutter", "token_count": 255 }
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/src/foundation/diagnostics.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { // Regression test for https://github.com/flutter/flutter/issues/100451 testWidgets('SliverAnimatedList.builder respects findChildIndexCallback', (WidgetTester tester) async { bool finderCalled = false; int itemCount = 7; late StateSetter stateSetter; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { stateSetter = setState; return CustomScrollView( slivers: <Widget>[ SliverAnimatedList( initialItemCount: itemCount, itemBuilder: (BuildContext context, int index, Animation<double> animation) => Container( key: Key('$index'), height: 2000.0, ), findChildIndexCallback: (Key key) { finderCalled = true; return null; }, ), ], ); }, ), ) ); expect(finderCalled, false); // Trigger update. stateSetter(() => itemCount = 77); await tester.pump(); expect(finderCalled, true); }); testWidgets('AnimatedList', (WidgetTester tester) async { Widget builder(BuildContext context, int index, Animation<double> animation) { return SizedBox( height: 100.0, child: Center( child: Text('item $index'), ), ); } final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: AnimatedList( key: listKey, initialItemCount: 2, itemBuilder: builder, ), ), ); expect(find.byWidgetPredicate((Widget widget) { return widget is SliverAnimatedList && widget.initialItemCount == 2 && widget.itemBuilder == builder; }), findsOneWidget); listKey.currentState!.insertItem(0); await tester.pump(); expect(find.text('item 2'), findsOneWidget); listKey.currentState!.removeItem( 2, (BuildContext context, Animation<double> animation) { return const SizedBox( height: 100.0, child: Center(child: Text('removing item')), ); }, duration: const Duration(milliseconds: 100), ); await tester.pump(); expect(find.text('removing item'), findsOneWidget); expect(find.text('item 2'), findsNothing); await tester.pumpAndSettle(); expect(find.text('removing item'), findsNothing); // Test for insertAllItems listKey.currentState!.insertAllItems(0, 2); await tester.pump(); expect(find.text('item 2'), findsOneWidget); expect(find.text('item 3'), findsOneWidget); // Test for removeAllItems listKey.currentState!.removeAllItems( (BuildContext context, Animation<double> animation) { return const SizedBox( height: 100.0, child: Center(child: Text('removing item')), ); }, duration: const Duration(milliseconds: 100), ); await tester.pump(); expect(find.text('removing item'), findsWidgets); expect(find.text('item 0'), findsNothing); expect(find.text('item 1'), findsNothing); expect(find.text('item 2'), findsNothing); expect(find.text('item 3'), findsNothing); await tester.pumpAndSettle(); expect(find.text('removing item'), findsNothing); }); group('SliverAnimatedList', () { testWidgets('initialItemCount', (WidgetTester tester) async { final Map<int, Animation<double>> animations = <int, Animation<double>>{}; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverAnimatedList( initialItemCount: 2, itemBuilder: (BuildContext context, int index, Animation<double> animation) { animations[index] = animation; return SizedBox( height: 100.0, child: Center( child: Text('item $index'), ), ); }, ), ], ), ), ); expect(find.text('item 0'), findsOneWidget); expect(find.text('item 1'), findsOneWidget); expect(animations.containsKey(0), true); expect(animations.containsKey(1), true); expect(animations[0]!.value, 1.0); expect(animations[1]!.value, 1.0); }); testWidgets('insert', (WidgetTester tester) async { final GlobalKey<SliverAnimatedListState> listKey = GlobalKey<SliverAnimatedListState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverAnimatedList( key: listKey, itemBuilder: (BuildContext context, int index, Animation<double> animation) { return SizeTransition( key: ValueKey<int>(index), sizeFactor: animation, child: SizedBox( height: 100.0, child: Center(child: Text('item $index')), ), ); }, ), ], ), ), ); double itemHeight(int index) => tester.getSize(find.byKey(ValueKey<int>(index), skipOffstage: false)).height; double itemTop(int index) => tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; double itemBottom(int index) => tester.getBottomLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; listKey.currentState!.insertItem( 0, duration: const Duration(milliseconds: 100), ); await tester.pump(); // Newly inserted item 0's height should animate from 0 to 100 expect(itemHeight(0), 0.0); await tester.pump(const Duration(milliseconds: 50)); expect(itemHeight(0), 50.0); await tester.pump(const Duration(milliseconds: 50)); expect(itemHeight(0), 100.0); // The list now contains one fully expanded item at the top: expect(find.text('item 0'), findsOneWidget); expect(itemTop(0), 0.0); expect(itemBottom(0), 100.0); listKey.currentState!.insertItem( 0, duration: const Duration(milliseconds: 100), ); listKey.currentState!.insertItem( 0, duration: const Duration(milliseconds: 100), ); await tester.pump(); // The height of the newly inserted items at index 0 and 1 should animate // from 0 to 100. // The height of the original item, now at index 2, should remain 100. expect(itemHeight(0), 0.0); expect(itemHeight(1), 0.0); expect(itemHeight(2), 100.0); await tester.pump(const Duration(milliseconds: 50)); expect(itemHeight(0), 50.0); expect(itemHeight(1), 50.0); expect(itemHeight(2), 100.0); await tester.pump(const Duration(milliseconds: 50)); expect(itemHeight(0), 100.0); expect(itemHeight(1), 100.0); expect(itemHeight(2), 100.0); // The newly inserted "item 1" and "item 2" appear above "item 0" expect(find.text('item 0'), findsOneWidget); expect(find.text('item 1'), findsOneWidget); expect(find.text('item 2'), findsOneWidget); expect(itemTop(0), 0.0); expect(itemBottom(0), 100.0); expect(itemTop(1), 100.0); expect(itemBottom(1), 200.0); expect(itemTop(2), 200.0); expect(itemBottom(2), 300.0); }); // Test for insertAllItems with SliverAnimatedList testWidgets('insertAll', (WidgetTester tester) async { final GlobalKey<SliverAnimatedListState> listKey = GlobalKey<SliverAnimatedListState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverAnimatedList( key: listKey, itemBuilder: (BuildContext context, int index, Animation<double> animation) { return SizeTransition( key: ValueKey<int>(index), sizeFactor: animation, child: SizedBox( height: 100.0, child: Center(child: Text('item $index')), ), ); }, ), ], ), ), ); double itemHeight(int index) => tester.getSize(find.byKey(ValueKey<int>(index), skipOffstage: false)).height; double itemTop(int index) => tester.getTopLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; double itemBottom(int index) => tester.getBottomLeft(find.byKey(ValueKey<int>(index), skipOffstage: false)).dy; listKey.currentState!.insertAllItems( 0, 2, duration: const Duration(milliseconds: 100), ); await tester.pump(); // Newly inserted item 0 & 1's height should animate from 0 to 100 expect(itemHeight(0), 0.0); expect(itemHeight(1), 0.0); await tester.pump(const Duration(milliseconds: 50)); expect(itemHeight(0), 50.0); expect(itemHeight(1), 50.0); await tester.pump(const Duration(milliseconds: 50)); expect(itemHeight(0), 100.0); expect(itemHeight(1), 100.0); // The list now contains two fully expanded items at the top: expect(find.text('item 0'), findsOneWidget); expect(find.text('item 1'), findsOneWidget); expect(itemTop(0), 0.0); expect(itemBottom(0), 100.0); expect(itemTop(1), 100.0); expect(itemBottom(1), 200.0); }); // Test for removeAllItems with SliverAnimatedList testWidgets('remove', (WidgetTester tester) async { final GlobalKey<SliverAnimatedListState> listKey = GlobalKey<SliverAnimatedListState>(); final List<int> items = <int>[0, 1, 2]; Widget buildItem(BuildContext context, int item, Animation<double> animation) { return SizeTransition( key: ValueKey<int>(item), sizeFactor: animation, child: SizedBox( height: 100.0, child: Center( child: Text('item $item', textDirection: TextDirection.ltr), ), ), ); } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverAnimatedList( key: listKey, initialItemCount: 3, itemBuilder: (BuildContext context, int index, Animation<double> animation) { return buildItem(context, items[index], animation); }, ), ], ), ), ); double itemTop(int index) => tester.getTopLeft(find.byKey(ValueKey<int>(index))).dy; double itemBottom(int index) => tester.getBottomLeft(find.byKey(ValueKey<int>(index))).dy; expect(find.text('item 0'), findsOneWidget); expect(find.text('item 1'), findsOneWidget); expect(find.text('item 2'), findsOneWidget); items.removeAt(0); listKey.currentState!.removeItem( 0, (BuildContext context, Animation<double> animation) => buildItem(context, 0, animation), duration: const Duration(milliseconds: 100), ); // Items 0, 1, 2 at 0, 100, 200. All heights 100. expect(itemTop(0), 0.0); expect(itemBottom(0), 100.0); expect(itemTop(1), 100.0); expect(itemBottom(1), 200.0); expect(itemTop(2), 200.0); expect(itemBottom(2), 300.0); // Newly removed item 0's height should animate from 100 to 0 over 100ms // Items 0, 1, 2 at 0, 50, 150. Item 0's height is 50. await tester.pump(); await tester.pump(const Duration(milliseconds: 50)); expect(itemTop(0), 0.0); expect(itemBottom(0), 50.0); expect(itemTop(1), 50.0); expect(itemBottom(1), 150.0); expect(itemTop(2), 150.0); expect(itemBottom(2), 250.0); // Items 1, 2 at 0, 100. await tester.pumpAndSettle(); expect(itemTop(1), 0.0); expect(itemBottom(1), 100.0); expect(itemTop(2), 100.0); expect(itemBottom(2), 200.0); }); // Test for removeAllItems with SliverAnimatedList testWidgets('removeAll', (WidgetTester tester) async { final GlobalKey<SliverAnimatedListState> listKey = GlobalKey<SliverAnimatedListState>(); final List<int> items = <int>[0, 1, 2]; Widget buildItem(BuildContext context, int item, Animation<double> animation) { return SizeTransition( key: ValueKey<int>(item), sizeFactor: animation, child: SizedBox( height: 100.0, child: Center( child: Text('item $item', textDirection: TextDirection.ltr), ), ), ); } await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverAnimatedList( key: listKey, initialItemCount: 3, itemBuilder: (BuildContext context, int index, Animation<double> animation) { return buildItem(context, items[index], animation); }, ), ], ), ), ); expect(find.text('item 0'), findsOneWidget); expect(find.text('item 1'), findsOneWidget); expect(find.text('item 2'), findsOneWidget); items.clear(); listKey.currentState!.removeAllItems((BuildContext context, Animation<double> animation) => buildItem(context, 0, animation), duration: const Duration(milliseconds: 100), ); await tester.pumpAndSettle(); expect(find.text('item 0'), findsNothing); expect(find.text('item 1'), findsNothing); expect(find.text('item 2'), findsNothing); }); testWidgets('works in combination with other slivers', (WidgetTester tester) async { final GlobalKey<SliverAnimatedListState> listKey = GlobalKey<SliverAnimatedListState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(<Widget>[ const SizedBox(height: 100), const SizedBox(height: 100), ]), ), SliverAnimatedList( key: listKey, initialItemCount: 3, itemBuilder: (BuildContext context, int index, Animation<double> animation) { return SizedBox( height: 100, child: Text('item $index'), ); }, ), ], ), ), ); expect(tester.getTopLeft(find.text('item 0')).dy, 200); expect(tester.getTopLeft(find.text('item 1')).dy, 300); listKey.currentState!.insertItem(3); await tester.pumpAndSettle(); expect(tester.getTopLeft(find.text('item 3')).dy, 500); listKey.currentState!.removeItem(0, (BuildContext context, Animation<double> animation) { return SizeTransition( sizeFactor: animation, key: const ObjectKey('removing'), child: const SizedBox( height: 100, child: Text('removing'), ), ); }, duration: const Duration(seconds: 1), ); await tester.pump(); expect(find.text('item 3'), findsNothing); await tester.pump(const Duration(milliseconds: 500)); expect( tester.getSize(find.byKey(const ObjectKey('removing'))).height, 50, ); expect(tester.getTopLeft(find.text('item 0')).dy, 250); await tester.pumpAndSettle(); expect(find.text('removing'), findsNothing); expect(tester.getTopLeft(find.text('item 0')).dy, 200); }); testWidgets('passes correctly derived index of findChildIndexCallback to the inner SliverChildBuilderDelegate', (WidgetTester tester) async { final List<int> items = <int>[0, 1, 2, 3]; final GlobalKey<SliverAnimatedListState> listKey = GlobalKey<SliverAnimatedListState>(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverAnimatedList( key: listKey, initialItemCount: items.length, itemBuilder: (BuildContext context, int index, Animation<double> animation) { return _StatefulListItem( key: ValueKey<int>(items[index]), index: index, ); }, findChildIndexCallback: (Key key) { final int index = items.indexOf((key as ValueKey<int>).value); return index == -1 ? null : index; }, ), ], ), ), ); // get all list entries in order final List<Text> listEntries = find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); // check that the list is rendered in the correct order expect(listEntries[0].data, equals('item 0')); expect(listEntries[1].data, equals('item 1')); expect(listEntries[2].data, equals('item 2')); expect(listEntries[3].data, equals('item 3')); // delete one item listKey.currentState?.removeItem(0, (BuildContext context, Animation<double> animation) { return Container(); }); // delete from list items.removeAt(0); // reorder list items.insert(0, items.removeLast()); // render with new list order await tester.pumpAndSettle(); // get all list entries in order final List<Text> reorderedListEntries = find.byType(Text).evaluate().map((Element e) => e.widget as Text).toList(); // check that the stateful items of the list are rendered in the order provided by findChildIndexCallback expect(reorderedListEntries[0].data, equals('item 3')); expect(reorderedListEntries[1].data, equals('item 1')); expect(reorderedListEntries[2].data, equals('item 2')); }); }); testWidgets( 'AnimatedList.of() and maybeOf called with a context that does not contain AnimatedList', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(Container(key: key)); late FlutterError error; expect(AnimatedList.maybeOf(key.currentContext!), isNull); try { AnimatedList.of(key.currentContext!); } on FlutterError catch (e) { error = e; } expect(error.diagnostics.length, 4); expect(error.diagnostics[2].level, DiagnosticLevel.hint); expect( error.diagnostics[2].toStringDeep(), equalsIgnoringHashCodes( 'This can happen when the context provided is from the same\n' 'StatefulWidget that built the AnimatedList. Please see the\n' 'AnimatedList documentation for examples of how to refer to an\n' 'AnimatedListState object:\n' ' https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html\n', ), ); expect(error.diagnostics[3], isA<DiagnosticsProperty<Element>>()); expect( error.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' AnimatedList.of() called with a context that does not contain an\n' ' AnimatedList.\n' ' No AnimatedList ancestor could be found starting from the context\n' ' that was passed to AnimatedList.of().\n' ' This can happen when the context provided is from the same\n' ' StatefulWidget that built the AnimatedList. Please see the\n' ' AnimatedList documentation for examples of how to refer to an\n' ' AnimatedListState object:\n' ' https://api.flutter.dev/flutter/widgets/AnimatedListState-class.html\n' ' The context used was:\n' ' Container-[GlobalKey#32cc6]\n', ), ); }, ); testWidgets('AnimatedList.clipBehavior is forwarded to its inner CustomScrollView', (WidgetTester tester) async { const Clip clipBehavior = Clip.none; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: AnimatedList( initialItemCount: 2, clipBehavior: clipBehavior, itemBuilder: (BuildContext context, int index, Animation<double> _) { return SizedBox( height: 100.0, child: Center( child: Text('item $index'), ), ); }, ), ), ); expect(tester.widget<CustomScrollView>(find.byType(CustomScrollView)).clipBehavior, clipBehavior); }); testWidgets('AnimatedList.shrinkwrap is forwarded to its inner CustomScrollView', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/115040 final ScrollController controller = ScrollController(); addTearDown(controller.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: AnimatedList( controller: controller, initialItemCount: 2, shrinkWrap: true, itemBuilder: (BuildContext context, int index, Animation<double> _) { return SizedBox( height: 100.0, child: Center( child: Text('Item $index'), ), ); }, ), ), ); expect(tester.widget<CustomScrollView>(find.byType(CustomScrollView)).shrinkWrap, true); }); testWidgets('AnimatedList applies MediaQuery padding', (WidgetTester tester) async { const EdgeInsets padding = EdgeInsets.all(30.0); EdgeInsets? innerMediaQueryPadding; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData( padding: EdgeInsets.all(30.0), ), child: AnimatedList( initialItemCount: 3, itemBuilder: (BuildContext context, int index, Animation<double> animation) { innerMediaQueryPadding = MediaQuery.paddingOf(context); return const Placeholder(); }, ), ), ), ); final Offset topLeft = tester.getTopLeft(find.byType(Placeholder).first); // Automatically apply the top padding into sliver. expect(topLeft, Offset(0.0, padding.top)); // Scroll to the bottom. await tester.drag(find.byType(AnimatedList), const Offset(0.0, -1000.0)); await tester.pumpAndSettle(); final Offset bottomLeft = tester.getBottomLeft(find.byType(Placeholder).last); // Automatically apply the bottom padding into sliver. expect(bottomLeft, Offset(0.0, 600.0 - padding.bottom)); // Verify that the left/right padding is not applied. expect(innerMediaQueryPadding, const EdgeInsets.symmetric(horizontal: 30.0)); }); } class _StatefulListItem extends StatefulWidget { const _StatefulListItem({ super.key, required this.index, }); final int index; @override _StatefulListItemState createState() => _StatefulListItemState(); } class _StatefulListItemState extends State<_StatefulListItem> { late final int number = widget.index; @override Widget build(BuildContext context) { return Text('item $number'); } }
flutter/packages/flutter/test/widgets/animated_list_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/animated_list_test.dart", "repo_id": "flutter", "token_count": 10856 }
734
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; final Matcher _matchesCommit = isMethodCall('TextInput.finishAutofillContext', arguments: true); final Matcher _matchesCancel = isMethodCall('TextInput.finishAutofillContext', arguments: false); void main() { testWidgets('AutofillGroup has the right clients', (WidgetTester tester) async { const Key outerKey = Key('outer'); const Key innerKey = Key('inner'); const TextField client1 = TextField(autofillHints: <String>['1']); const TextField client2 = TextField(autofillHints: <String>['2']); await tester.pumpWidget( const MaterialApp( home: Scaffold( body: AutofillGroup( key: outerKey, child: Column(children: <Widget>[ client1, AutofillGroup( key: innerKey, child: Column(children: <Widget>[client2, TextField(autofillHints: null)]), ), ]), ), ), ), ); final AutofillGroupState innerState = tester.state<AutofillGroupState>(find.byKey(innerKey)); final AutofillGroupState outerState = tester.state<AutofillGroupState>(find.byKey(outerKey)); final State<TextField> clientState1 = tester.state<State<TextField>>(find.byWidget(client1)); final State<TextField> clientState2 = tester.state<State<TextField>>(find.byWidget(client2)); expect(outerState.autofillClients.toList(), <State<TextField>>[clientState1]); // The second TextField in the AutofillGroup doesn't have autofill enabled. expect(innerState.autofillClients.toList(), <State<TextField>>[clientState2]); }); testWidgets('new clients can be added & removed to a scope', (WidgetTester tester) async { const Key scopeKey = Key('scope'); const TextField client1 = TextField(autofillHints: <String>['1']); TextField client2 = const TextField(autofillHints: null); late StateSetter setState; await tester.pumpWidget( MaterialApp( home: Scaffold( body: AutofillGroup( key: scopeKey, child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return Column(children: <Widget>[client1, client2]); }, ), ), ), ), ); final AutofillGroupState scopeState = tester.state<AutofillGroupState>(find.byKey(scopeKey)); final State<TextField> clientState1 = tester.state<State<TextField>>(find.byWidget(client1)); final State<TextField> clientState2 = tester.state<State<TextField>>(find.byWidget(client2)); expect(scopeState.autofillClients.toList(), <State<TextField>>[clientState1]); // Add to scope. setState(() { client2 = const TextField(autofillHints: <String>['2']); }); await tester.pump(); expect(scopeState.autofillClients, contains(clientState1)); expect(scopeState.autofillClients, contains(clientState2)); expect(scopeState.autofillClients.length, 2); // Remove from scope again. setState(() { client2 = const TextField(autofillHints: null); }); await tester.pump(); expect(scopeState.autofillClients, <State<TextField>>[clientState1]); }); testWidgets('AutofillGroup has the right clients after reparenting', (WidgetTester tester) async { const Key outerKey = Key('outer'); const Key innerKey = Key('inner'); final GlobalKey keyClient3 = GlobalKey(); const TextField client1 = TextField(autofillHints: <String>['1']); const TextField client2 = TextField(autofillHints: <String>['2']); await tester.pumpWidget( MaterialApp( home: Scaffold( body: AutofillGroup( key: outerKey, child: Column(children: <Widget>[ client1, AutofillGroup( key: innerKey, child: Column(children: <Widget>[ client2, TextField(key: keyClient3, autofillHints: const <String>['3']), ]), ), ]), ), ), ), ); final AutofillGroupState innerState = tester.state<AutofillGroupState>(find.byKey(innerKey)); final AutofillGroupState outerState = tester.state<AutofillGroupState>(find.byKey(outerKey)); final State<TextField> clientState1 = tester.state<State<TextField>>(find.byWidget(client1)); final State<TextField> clientState2 = tester.state<State<TextField>>(find.byWidget(client2)); final State<TextField> clientState3 = tester.state<State<TextField>>(find.byKey(keyClient3)); await tester.pumpWidget( MaterialApp( home: Scaffold( body: AutofillGroup( key: outerKey, child: Column(children: <Widget>[ client1, TextField(key: keyClient3, autofillHints: const <String>['3']), const AutofillGroup( key: innerKey, child: Column(children: <Widget>[client2]), ), ]), ), ), ), ); expect(outerState.autofillClients.length, 2); expect(outerState.autofillClients, contains(clientState1)); expect(outerState.autofillClients, contains(clientState3)); expect(innerState.autofillClients, <State<TextField>>[clientState2]); }); testWidgets('disposing AutofillGroups', (WidgetTester tester) async { late StateSetter setState; const Key group1 = Key('group1'); const Key group2 = Key('group2'); const Key group3 = Key('group3'); const TextField placeholder = TextField(autofillHints: <String>[AutofillHints.name]); List<Widget> children = const <Widget> [ AutofillGroup( key: group1, child: AutofillGroup(child: placeholder), ), AutofillGroup(key: group2, onDisposeAction: AutofillContextAction.cancel, child: placeholder), AutofillGroup( key: group3, child: AutofillGroup(child: placeholder), ), ]; await tester.pumpWidget( MaterialApp( home: Scaffold( body: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return Column(children: children); }, ), ), ), ); expect( tester.testTextInput.log, isNot(contains(_matchesCommit)), ); tester.testTextInput.log.clear(); // Remove the first topmost group group1. Should commit. setState(() { children = const <Widget> [ AutofillGroup(key: group2, onDisposeAction: AutofillContextAction.cancel, child: placeholder), AutofillGroup( key: group3, child: AutofillGroup(child: placeholder), ), ]; }); await tester.pump(); expect( tester.testTextInput.log.single, _matchesCommit, ); tester.testTextInput.log.clear(); // Remove the topmost group group2. Should cancel. setState(() { children = const <Widget> [ AutofillGroup( key: group3, child: AutofillGroup(child: placeholder), ), ]; }); await tester.pump(); expect( tester.testTextInput.log.single, _matchesCancel, ); tester.testTextInput.log.clear(); // Remove the inner group within group3. No action. setState(() { children = const <Widget> [ AutofillGroup( key: group3, child: placeholder, ), ]; }); await tester.pump(); expect( tester.testTextInput.log, isNot(contains('TextInput.finishAutofillContext')), ); tester.testTextInput.log.clear(); // Remove the topmosts group group3. Should commit. setState(() { children = const <Widget> []; }); await tester.pump(); expect( tester.testTextInput.log.single, _matchesCommit, ); }); }
flutter/packages/flutter/test/widgets/autofill_group_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/autofill_group_test.dart", "repo_id": "flutter", "token_count": 3444 }
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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('StatefulWidget BuildContext.mounted', (WidgetTester tester) async { late BuildContext capturedContext; await tester.pumpWidget(TestStatefulWidget( onBuild: (BuildContext context) { capturedContext = context; } )); expect(capturedContext.mounted, isTrue); await tester.pumpWidget(Container()); expect(capturedContext.mounted, isFalse); }); testWidgets('StatelessWidget BuildContext.mounted', (WidgetTester tester) async { late BuildContext capturedContext; await tester.pumpWidget(TestStatelessWidget( onBuild: (BuildContext context) { capturedContext = context; } )); expect(capturedContext.mounted, isTrue); await tester.pumpWidget(Container()); expect(capturedContext.mounted, isFalse); }); } typedef BuildCallback = void Function(BuildContext context); class TestStatelessWidget extends StatelessWidget { const TestStatelessWidget({super.key, required this.onBuild}); final BuildCallback onBuild; @override Widget build(BuildContext context) { onBuild(context); return Container(); } } class TestStatefulWidget extends StatefulWidget { const TestStatefulWidget({super.key, required this.onBuild}); final BuildCallback onBuild; @override State<TestStatefulWidget> createState() => _TestStatefulWidgetState(); } class _TestStatefulWidgetState extends State<TestStatefulWidget> { @override Widget build(BuildContext context) { widget.onBuild(context); return Container(); } }
flutter/packages/flutter/test/widgets/build_context_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/build_context_test.dart", "repo_id": "flutter", "token_count": 576 }
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/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { group(CustomPainter, () { setUp(() { debugResetSemanticsIdCounter(); _PainterWithSemantics.shouldRebuildSemanticsCallCount = 0; _PainterWithSemantics.buildSemanticsCallCount = 0; _PainterWithSemantics.semanticsBuilderCallCount = 0; }); _defineTests(); }); } void _defineTests() { testWidgets('builds no semantics by default', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(CustomPaint( painter: _PainterWithoutSemantics(), )); expect(semanticsTester, hasSemantics( TestSemantics.root(), )); semanticsTester.dispose(); }); testWidgets('provides foreground semantics', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(CustomPaint( foregroundPainter: _PainterWithSemantics( semantics: const CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), properties: SemanticsProperties( label: 'foreground', textDirection: TextDirection.rtl, ), ), ), )); expect(semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, rect: TestSemantics.fullScreen, children: <TestSemantics>[ TestSemantics( id: 2, label: 'foreground', rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), ), ], ), ], ), )); semanticsTester.dispose(); }); testWidgets('provides background semantics', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(CustomPaint( painter: _PainterWithSemantics( semantics: const CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), properties: SemanticsProperties( label: 'background', textDirection: TextDirection.rtl, ), ), ), )); expect(semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, rect: TestSemantics.fullScreen, children: <TestSemantics>[ TestSemantics( id: 2, label: 'background', rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), ), ], ), ], ), )); semanticsTester.dispose(); }); testWidgets('combines background, child and foreground semantics', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(CustomPaint( painter: _PainterWithSemantics( semantics: const CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), properties: SemanticsProperties( label: 'background', textDirection: TextDirection.rtl, ), ), ), foregroundPainter: _PainterWithSemantics( semantics: const CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), properties: SemanticsProperties( label: 'foreground', textDirection: TextDirection.rtl, ), ), ), child: Semantics( container: true, child: const Text('Hello', textDirection: TextDirection.ltr), ), )); expect(semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, rect: TestSemantics.fullScreen, children: <TestSemantics>[ TestSemantics( id: 3, label: 'background', rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), ), TestSemantics( id: 2, label: 'Hello', rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0), ), TestSemantics( id: 4, label: 'foreground', rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), ), ], ), ], ), )); semanticsTester.dispose(); }); testWidgets('applies $SemanticsProperties', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(CustomPaint( painter: _PainterWithSemantics( semantics: const CustomPainterSemantics( key: ValueKey<int>(1), rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), properties: SemanticsProperties( checked: false, selected: false, button: false, label: 'label-before', value: 'value-before', increasedValue: 'increase-before', decreasedValue: 'decrease-before', hint: 'hint-before', textDirection: TextDirection.rtl, ), ), ), )); expect(semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, rect: TestSemantics.fullScreen, children: <TestSemantics>[ TestSemantics( rect: const Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), id: 2, flags: 1, label: 'label-before', value: 'value-before', increasedValue: 'increase-before', decreasedValue: 'decrease-before', hint: 'hint-before', textDirection: TextDirection.rtl, ), ], ), ], ), )); await tester.pumpWidget(CustomPaint( painter: _PainterWithSemantics( semantics: CustomPainterSemantics( key: const ValueKey<int>(1), rect: const Rect.fromLTRB(5.0, 6.0, 7.0, 8.0), properties: SemanticsProperties( checked: true, selected: true, button: true, label: 'label-after', value: 'value-after', increasedValue: 'increase-after', decreasedValue: 'decrease-after', hint: 'hint-after', textDirection: TextDirection.ltr, onScrollDown: () { }, onLongPress: () { }, onDecrease: () { }, onIncrease: () { }, onScrollLeft: () { }, onScrollRight: () { }, onScrollUp: () { }, onTap: () { }, ), ), ), )); expect(semanticsTester, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, rect: TestSemantics.fullScreen, children: <TestSemantics>[ TestSemantics( rect: const Rect.fromLTRB(5.0, 6.0, 7.0, 8.0), actions: 255, id: 2, flags: 15, label: 'label-after', value: 'value-after', increasedValue: 'increase-after', decreasedValue: 'decrease-after', hint: 'hint-after', textDirection: TextDirection.ltr, ), ], ), ], ), )); semanticsTester.dispose(); }); testWidgets('Can toggle semantics on, off, on without crash', (WidgetTester tester) async { await tester.pumpWidget(CustomPaint( painter: _PainterWithSemantics( semantics: const CustomPainterSemantics( key: ValueKey<int>(1), rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), properties: SemanticsProperties( checked: false, selected: false, button: false, label: 'label-before', value: 'value-before', increasedValue: 'increase-before', decreasedValue: 'decrease-before', hint: 'hint-before', textDirection: TextDirection.rtl, ), ), ), )); // Start with semantics off. expect(tester.binding.pipelineOwner.semanticsOwner, isNull); // Semantics on SemanticsTester semantics = SemanticsTester(tester); await tester.pumpAndSettle(); expect(tester.binding.pipelineOwner.semanticsOwner, isNotNull); // Semantics off semantics.dispose(); await tester.pumpAndSettle(); expect(tester.binding.pipelineOwner.semanticsOwner, isNull); // Semantics on semantics = SemanticsTester(tester); await tester.pumpAndSettle(); expect(tester.binding.pipelineOwner.semanticsOwner, isNotNull); semantics.dispose(); }, semanticsEnabled: false); testWidgets('Supports all actions', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); final List<SemanticsAction> performedActions = <SemanticsAction>[]; await tester.pumpWidget(CustomPaint( painter: _PainterWithSemantics( semantics: CustomPainterSemantics( key: const ValueKey<int>(1), rect: const Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), properties: SemanticsProperties( onDismiss: () => performedActions.add(SemanticsAction.dismiss), onTap: () => performedActions.add(SemanticsAction.tap), onLongPress: () => performedActions.add(SemanticsAction.longPress), onScrollLeft: () => performedActions.add(SemanticsAction.scrollLeft), onScrollRight: () => performedActions.add(SemanticsAction.scrollRight), onScrollUp: () => performedActions.add(SemanticsAction.scrollUp), onScrollDown: () => performedActions.add(SemanticsAction.scrollDown), onIncrease: () => performedActions.add(SemanticsAction.increase), onDecrease: () => performedActions.add(SemanticsAction.decrease), onCopy: () => performedActions.add(SemanticsAction.copy), onCut: () => performedActions.add(SemanticsAction.cut), onPaste: () => performedActions.add(SemanticsAction.paste), onMoveCursorForwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByCharacter), onMoveCursorBackwardByCharacter: (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByCharacter), onMoveCursorForwardByWord: (bool _) => performedActions.add(SemanticsAction.moveCursorForwardByWord), onMoveCursorBackwardByWord: (bool _) => performedActions.add(SemanticsAction.moveCursorBackwardByWord), onSetSelection: (TextSelection _) => performedActions.add(SemanticsAction.setSelection), onSetText: (String text) => performedActions.add(SemanticsAction.setText), onDidGainAccessibilityFocus: () => performedActions.add(SemanticsAction.didGainAccessibilityFocus), onDidLoseAccessibilityFocus: () => performedActions.add(SemanticsAction.didLoseAccessibilityFocus), ), ), ), )); final Set<SemanticsAction> allActions = SemanticsAction.values.toSet() ..remove(SemanticsAction.customAction) // customAction is not user-exposed. ..remove(SemanticsAction.showOnScreen); // showOnScreen is not user-exposed const int expectedId = 2; final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, children: <TestSemantics>[ TestSemantics.rootChild( id: expectedId, rect: TestSemantics.fullScreen, actions: allActions.fold<int>(0, (int previous, SemanticsAction action) => previous | action.index), ), ], ), ], ); expect(semantics, hasSemantics(expectedSemantics, ignoreRect: true, ignoreTransform: true)); // Do the actions work? final SemanticsOwner semanticsOwner = tester.binding.pipelineOwner.semanticsOwner!; int expectedLength = 1; for (final SemanticsAction action in allActions) { switch (action) { case SemanticsAction.moveCursorBackwardByCharacter: case SemanticsAction.moveCursorForwardByCharacter: case SemanticsAction.moveCursorBackwardByWord: case SemanticsAction.moveCursorForwardByWord: semanticsOwner.performAction(expectedId, action, true); case SemanticsAction.setSelection: semanticsOwner.performAction(expectedId, action, <String, int>{ 'base': 4, 'extent': 5, }); case SemanticsAction.setText: semanticsOwner.performAction(expectedId, action, 'text'); case SemanticsAction.copy: case SemanticsAction.customAction: case SemanticsAction.cut: case SemanticsAction.decrease: case SemanticsAction.didGainAccessibilityFocus: case SemanticsAction.didLoseAccessibilityFocus: case SemanticsAction.dismiss: case SemanticsAction.increase: case SemanticsAction.longPress: case SemanticsAction.paste: case SemanticsAction.scrollDown: case SemanticsAction.scrollLeft: case SemanticsAction.scrollRight: case SemanticsAction.scrollUp: case SemanticsAction.showOnScreen: case SemanticsAction.tap: semanticsOwner.performAction(expectedId, action); } expect(performedActions.length, expectedLength); expect(performedActions.last, action); expectedLength += 1; } semantics.dispose(); }); testWidgets('Supports all flags', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); // checked state and toggled state are mutually exclusive. await tester.pumpWidget(CustomPaint( painter: _PainterWithSemantics( semantics: const CustomPainterSemantics( key: ValueKey<int>(1), rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), properties: SemanticsProperties( enabled: true, checked: true, selected: true, hidden: true, button: true, slider: true, keyboardKey: true, link: true, textField: true, readOnly: true, focused: true, focusable: true, inMutuallyExclusiveGroup: true, header: true, obscured: true, multiline: true, scopesRoute: true, namesRoute: true, image: true, liveRegion: true, toggled: true, expanded: true, ), ), ), )); List<SemanticsFlag> flags = SemanticsFlag.values.toList(); // [SemanticsFlag.hasImplicitScrolling] isn't part of [SemanticsProperties] // therefore it has to be removed. flags ..remove(SemanticsFlag.hasImplicitScrolling) ..remove(SemanticsFlag.isCheckStateMixed); TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, children: <TestSemantics>[ TestSemantics.rootChild( id: 2, rect: TestSemantics.fullScreen, flags: flags, ), ], ), ], ); expect(semantics, hasSemantics(expectedSemantics, ignoreRect: true, ignoreTransform: true)); await tester.pumpWidget(CustomPaint( painter: _PainterWithSemantics( semantics: const CustomPainterSemantics( key: ValueKey<int>(1), rect: Rect.fromLTRB(1.0, 2.0, 3.0, 4.0), properties: SemanticsProperties( enabled: true, checked: false, mixed: true, toggled: true, selected: true, hidden: true, button: true, slider: true, keyboardKey: true, link: true, textField: true, readOnly: true, focused: true, focusable: true, inMutuallyExclusiveGroup: true, header: true, obscured: true, multiline: true, scopesRoute: true, namesRoute: true, image: true, liveRegion: true, expanded: true, ), ), ), )); flags = SemanticsFlag.values.toList(); // [SemanticsFlag.hasImplicitScrolling] isn't part of [SemanticsProperties] // therefore it has to be removed. flags ..remove(SemanticsFlag.hasImplicitScrolling) ..remove(SemanticsFlag.isChecked); expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, children: <TestSemantics>[ TestSemantics.rootChild( id: 2, rect: TestSemantics.fullScreen, flags: flags, ), ], ), ], ); expect(semantics, hasSemantics(expectedSemantics, ignoreRect: true, ignoreTransform: true)); semantics.dispose(); }); group('diffing', () { testWidgets('complains about duplicate keys', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); await tester.pumpWidget(CustomPaint( painter: _SemanticsDiffTest(<String>[ 'a-k', 'a-k', ]), )); expect(tester.takeException(), isFlutterError); semanticsTester.dispose(); }); _testDiff('adds one item to an empty list', (_DiffTester tester) async { await tester.diff( from: <String>[], to: <String>['a'], ); }); _testDiff('removes the last item from the list', (_DiffTester tester) async { await tester.diff( from: <String>['a'], to: <String>[], ); }); _testDiff('appends one item at the end of a non-empty list', (_DiffTester tester) async { await tester.diff( from: <String>['a'], to: <String>['a', 'b'], ); }); _testDiff('prepends one item at the beginning of a non-empty list', (_DiffTester tester) async { await tester.diff( from: <String>['b'], to: <String>['a', 'b'], ); }); _testDiff('inserts one item in the middle of a list', (_DiffTester tester) async { await tester.diff( from: <String>[ 'a-k', 'c-k', ], to: <String>[ 'a-k', 'b-k', 'c-k', ], ); }); _testDiff('removes one item from the middle of a list', (_DiffTester tester) async { await tester.diff( from: <String>[ 'a-k', 'b-k', 'c-k', ], to: <String>[ 'a-k', 'c-k', ], ); }); _testDiff('swaps two items', (_DiffTester tester) async { await tester.diff( from: <String>[ 'a-k', 'b-k', ], to: <String>[ 'b-k', 'a-k', ], ); }); _testDiff('finds and moved one keyed item', (_DiffTester tester) async { await tester.diff( from: <String>[ 'a-k', 'b', 'c', ], to: <String>[ 'b', 'c', 'a-k', ], ); }); }); testWidgets('rebuilds semantics upon resize', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); final _PainterWithSemantics painter = _PainterWithSemantics( semantics: const CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), properties: SemanticsProperties( label: 'background', textDirection: TextDirection.rtl, ), ), ); final CustomPaint paint = CustomPaint(painter: painter); await tester.pumpWidget(SizedBox( height: 20.0, width: 20.0, child: paint, )); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); await tester.pumpWidget(SizedBox( height: 20.0, width: 20.0, child: paint, )); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); await tester.pumpWidget(SizedBox( height: 40.0, width: 40.0, child: paint, )); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0); expect(_PainterWithSemantics.buildSemanticsCallCount, 2); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); semanticsTester.dispose(); }); testWidgets('does not rebuild when shouldRebuildSemantics is false', (WidgetTester tester) async { final SemanticsTester semanticsTester = SemanticsTester(tester); const CustomPainterSemantics testSemantics = CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), properties: SemanticsProperties( label: 'background', textDirection: TextDirection.rtl, ), ); await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics( semantics: testSemantics, ))); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 0); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics( semantics: testSemantics, ))); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 1); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); const CustomPainterSemantics testSemantics2 = CustomPainterSemantics( rect: Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), properties: SemanticsProperties( label: 'background', textDirection: TextDirection.rtl, ), ); await tester.pumpWidget(CustomPaint(painter: _PainterWithSemantics( semantics: testSemantics2, ))); expect(_PainterWithSemantics.shouldRebuildSemanticsCallCount, 2); expect(_PainterWithSemantics.buildSemanticsCallCount, 1); expect(_PainterWithSemantics.semanticsBuilderCallCount, 4); semanticsTester.dispose(); }); } void _testDiff(String description, Future<void> Function(_DiffTester tester) testFunction) { testWidgets(description, (WidgetTester tester) async { await testFunction(_DiffTester(tester)); }); } class _DiffTester { _DiffTester(this.tester); final WidgetTester tester; /// Creates an initial semantics list using the `from` list, then updates the /// list to the `to` list. This causes [RenderCustomPaint] to diff the two /// lists and apply the changes. This method asserts the changes were /// applied correctly, specifically: /// /// - checks that initial and final configurations are in the desired states. /// - checks that keyed nodes have stable IDs. Future<void> diff({ required List<String> from, required List<String> to }) async { final SemanticsTester semanticsTester = SemanticsTester(tester); TestSemantics createExpectations(List<String> labels) { return TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( rect: TestSemantics.fullScreen, children: <TestSemantics>[ for (final String label in labels) TestSemantics( rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), label: label, ), ], ), ], ); } await tester.pumpWidget(CustomPaint( painter: _SemanticsDiffTest(from), )); expect(semanticsTester, hasSemantics(createExpectations(from), ignoreId: true)); SemanticsNode root = RendererBinding.instance.renderView.debugSemantics!; final Map<Key, int> idAssignments = <Key, int>{}; root.visitChildren((SemanticsNode firstChild) { firstChild.visitChildren((SemanticsNode node) { if (node.key != null) { idAssignments[node.key!] = node.id; } return true; }); return true; }); await tester.pumpWidget(CustomPaint( painter: _SemanticsDiffTest(to), )); await tester.pumpAndSettle(); expect(semanticsTester, hasSemantics(createExpectations(to), ignoreId: true)); root = RendererBinding.instance.renderView.debugSemantics!; root.visitChildren((SemanticsNode firstChild) { firstChild.visitChildren((SemanticsNode node) { if (node.key != null && idAssignments[node.key] != null) { expect(idAssignments[node.key], node.id, reason: 'Node with key ${node.key} was previously assigned ID ${idAssignments[node.key]}. ' 'After diffing the child list, its ID changed to ${node.id}. IDs must be stable.', ); } return true; }); return true; }); semanticsTester.dispose(); } } class _SemanticsDiffTest extends CustomPainter { _SemanticsDiffTest(this.data); final List<String> data; @override void paint(Canvas canvas, Size size) { // We don't test painting. } @override SemanticsBuilderCallback get semanticsBuilder => buildSemantics; List<CustomPainterSemantics> buildSemantics(Size size) { final List<CustomPainterSemantics> semantics = <CustomPainterSemantics>[]; for (final String label in data) { Key? key; if (label.endsWith('-k')) { key = ValueKey<String>(label); } semantics.add( CustomPainterSemantics( rect: const Rect.fromLTRB(1.0, 1.0, 2.0, 2.0), key: key, properties: SemanticsProperties( label: label, textDirection: TextDirection.rtl, ), ), ); } return semantics; } @override bool shouldRepaint(_SemanticsDiffTest oldPainter) => true; } class _PainterWithSemantics extends CustomPainter { _PainterWithSemantics({ required this.semantics }); final CustomPainterSemantics semantics; static int semanticsBuilderCallCount = 0; static int buildSemanticsCallCount = 0; static int shouldRebuildSemanticsCallCount = 0; @override void paint(Canvas canvas, Size size) { // We don't test painting. } @override SemanticsBuilderCallback get semanticsBuilder { semanticsBuilderCallCount += 1; return buildSemantics; } List<CustomPainterSemantics> buildSemantics(Size size) { buildSemanticsCallCount += 1; return <CustomPainterSemantics>[semantics]; } @override bool shouldRepaint(_PainterWithSemantics oldPainter) { return true; } @override bool shouldRebuildSemantics(_PainterWithSemantics oldPainter) { shouldRebuildSemanticsCallCount += 1; return !identical(oldPainter.semantics, semantics); } } class _PainterWithoutSemantics extends CustomPainter { _PainterWithoutSemantics(); @override void paint(Canvas canvas, Size size) { // We don't test painting. } @override bool shouldRepaint(_PainterWithSemantics oldPainter) => true; }
flutter/packages/flutter/test/widgets/custom_painter_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/custom_painter_test.dart", "repo_id": "flutter", "token_count": 12521 }
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. // TODO(gspencergoog): Remove this tag once this test's state leaks/test // dependencies have been fixed. // https://github.com/flutter/flutter/issues/85160 // Fails with "flutter test --test-randomize-ordering-seed=123" @Tags(<String>['no-shuffle']) library; 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 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; import 'semantics_tester.dart'; void main() { testWidgets('Drag and drop - control test', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; int dragStartedCount = 0; int moveCount = 0; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragStarted: () { ++dragStartedCount; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onMove: (_) => moveCount++, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(dragStartedCount, 0); expect(moveCount, 0); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(dragStartedCount, 1); expect(moveCount, 0); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(dragStartedCount, 1); expect(moveCount, 1); await gesture.up(); await tester.pump(); expect(accepted, equals(<int>[1])); expect(acceptedDetails, hasLength(1)); expect(acceptedDetails.first.offset, const Offset(256.0, 74.0)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(dragStartedCount, 1); expect(moveCount, 1); }); // Regression test for https://github.com/flutter/flutter/issues/76825 testWidgets('Drag and drop - onLeave callback fires correctly with generic parameter', (WidgetTester tester) async { final Map<String,int> leftBehind = <String,int>{ 'Target 1': 0, 'Target 2': 0, }; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target 1')); }, onLeave: (int? data) { if (data != null) { leftBehind['Target 1'] = leftBehind['Target 1']! + data; } }, ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target 2')); }, onLeave: (int? data) { if (data != null) { leftBehind['Target 2'] = leftBehind['Target 2']! + data; } }, ), ], ), )); expect(leftBehind['Target 1'], equals(0)); expect(leftBehind['Target 2'], equals(0)); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(leftBehind['Target 1'], equals(0)); expect(leftBehind['Target 2'], equals(0)); final Offset secondLocation = tester.getCenter(find.text('Target 1')); await gesture.moveTo(secondLocation); await tester.pump(); expect(leftBehind['Target 1'], equals(0)); expect(leftBehind['Target 2'], equals(0)); final Offset thirdLocation = tester.getCenter(find.text('Target 2')); await gesture.moveTo(thirdLocation); await tester.pump(); expect(leftBehind['Target 1'], equals(1)); expect(leftBehind['Target 2'], equals(0)); await gesture.moveTo(secondLocation); await tester.pump(); expect(leftBehind['Target 1'], equals(1)); expect(leftBehind['Target 2'], equals(1)); await gesture.up(); await tester.pump(); expect(leftBehind['Target 1'], equals(1)); expect(leftBehind['Target 2'], equals(1)); }); testWidgets('Drag and drop - onLeave callback fires correctly', (WidgetTester tester) async { final Map<String,int> leftBehind = <String,int>{ 'Target 1': 0, 'Target 2': 0, }; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target 1')); }, onLeave: (Object? data) { if (data is int) { leftBehind['Target 1'] = leftBehind['Target 1']! + data; } }, ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target 2')); }, onLeave: (Object? data) { if (data is int) { leftBehind['Target 2'] = leftBehind['Target 2']! + data; } }, ), ], ), )); expect(leftBehind['Target 1'], equals(0)); expect(leftBehind['Target 2'], equals(0)); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(leftBehind['Target 1'], equals(0)); expect(leftBehind['Target 2'], equals(0)); final Offset secondLocation = tester.getCenter(find.text('Target 1')); await gesture.moveTo(secondLocation); await tester.pump(); expect(leftBehind['Target 1'], equals(0)); expect(leftBehind['Target 2'], equals(0)); final Offset thirdLocation = tester.getCenter(find.text('Target 2')); await gesture.moveTo(thirdLocation); await tester.pump(); expect(leftBehind['Target 1'], equals(1)); expect(leftBehind['Target 2'], equals(0)); await gesture.moveTo(secondLocation); await tester.pump(); expect(leftBehind['Target 1'], equals(1)); expect(leftBehind['Target 2'], equals(1)); await gesture.up(); await tester.pump(); expect(leftBehind['Target 1'], equals(1)); expect(leftBehind['Target 2'], equals(1)); }); // Regression test for https://github.com/flutter/flutter/issues/76825 testWidgets('Drag and drop - onMove callback fires correctly with generic parameter', (WidgetTester tester) async { final Map<String,int> targetMoveCount = <String,int>{ 'Target 1': 0, 'Target 2': 0, }; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target 1')); }, onMove: (DragTargetDetails<int> details) { targetMoveCount['Target 1'] = targetMoveCount['Target 1']! + details.data; }, ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target 2')); }, onMove: (DragTargetDetails<int> details) { targetMoveCount['Target 2'] = targetMoveCount['Target 2']! + details.data; }, ), ], ), )); expect(targetMoveCount['Target 1'], equals(0)); expect(targetMoveCount['Target 2'], equals(0)); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(targetMoveCount['Target 1'], equals(0)); expect(targetMoveCount['Target 2'], equals(0)); final Offset secondLocation = tester.getCenter(find.text('Target 1')); await gesture.moveTo(secondLocation); await tester.pump(); expect(targetMoveCount['Target 1'], equals(1)); expect(targetMoveCount['Target 2'], equals(0)); final Offset thirdLocation = tester.getCenter(find.text('Target 2')); await gesture.moveTo(thirdLocation); await tester.pump(); expect(targetMoveCount['Target 1'], equals(1)); expect(targetMoveCount['Target 2'], equals(1)); await gesture.moveTo(secondLocation); await tester.pump(); expect(targetMoveCount['Target 1'], equals(2)); expect(targetMoveCount['Target 2'], equals(1)); await gesture.up(); await tester.pump(); expect(targetMoveCount['Target 1'], equals(2)); expect(targetMoveCount['Target 2'], equals(1)); }); testWidgets('Drag and drop - onMove callback fires correctly', (WidgetTester tester) async { final Map<String,int> targetMoveCount = <String,int>{ 'Target 1': 0, 'Target 2': 0, }; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target 1')); }, onMove: (DragTargetDetails<dynamic> details) { if (details.data is int) { targetMoveCount['Target 1'] = targetMoveCount['Target 1']! + (details.data as int); } }, ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target 2')); }, onMove: (DragTargetDetails<dynamic> details) { if (details.data is int) { targetMoveCount['Target 2'] = targetMoveCount['Target 2']! + (details.data as int); } }, ), ], ), )); expect(targetMoveCount['Target 1'], equals(0)); expect(targetMoveCount['Target 2'], equals(0)); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(targetMoveCount['Target 1'], equals(0)); expect(targetMoveCount['Target 2'], equals(0)); final Offset secondLocation = tester.getCenter(find.text('Target 1')); await gesture.moveTo(secondLocation); await tester.pump(); expect(targetMoveCount['Target 1'], equals(1)); expect(targetMoveCount['Target 2'], equals(0)); final Offset thirdLocation = tester.getCenter(find.text('Target 2')); await gesture.moveTo(thirdLocation); await tester.pump(); expect(targetMoveCount['Target 1'], equals(1)); expect(targetMoveCount['Target 2'], equals(1)); await gesture.moveTo(secondLocation); await tester.pump(); expect(targetMoveCount['Target 1'], equals(2)); expect(targetMoveCount['Target 2'], equals(1)); await gesture.up(); await tester.pump(); expect(targetMoveCount['Target 1'], equals(2)); expect(targetMoveCount['Target 2'], equals(1)); }); testWidgets('Drag and drop - onMove is not called if moved with null data', (WidgetTester tester) async { bool onMoveCalled = false; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onMove: (DragTargetDetails<dynamic> details) { onMoveCalled = true; }, ), ], ), )); expect(onMoveCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(onMoveCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(onMoveCalled, isFalse); await gesture.up(); await tester.pump(); expect(onMoveCalled, isFalse); }); testWidgets('Drag and drop - dragging over button', (WidgetTester tester) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), Stack( children: <Widget>[ GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { events.add('tap'); }, child: const Text('Button'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const IgnorePointer( child: Text('Target'), ); }, onAccept: (int? data) { events.add('drop'); }, onAcceptWithDetails: (DragTargetDetails<int> _) { events.add('details'); }, ), ], ), ], ), )); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(find.text('Button'), findsOneWidget); // taps (we check both to make sure the test is consistent) expect(events, isEmpty); await tester.tap(find.text('Button')); expect(events, equals(<String>['tap'])); events.clear(); expect(events, isEmpty); await tester.tap(find.text('Target'), warnIfMissed: false); // (inside IgnorePointer) expect(events, equals(<String>['tap'])); events.clear(); // drag and drop firstLocation = tester.getCenter(find.text('Source')); TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(events, isEmpty); await gesture.up(); await tester.pump(); expect(events, equals(<String>['drop', 'details'])); events.clear(); // drag and tap and drop firstLocation = tester.getCenter(find.text('Source')); gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(events, isEmpty); await tester.tap(find.text('Button')); await tester.tap(find.text('Target'), warnIfMissed: false); // (inside IgnorePointer) await gesture.up(); await tester.pump(); expect(events, equals(<String>['tap', 'tap', 'drop', 'details'])); events.clear(); }); testWidgets('Drag and drop - tapping button', (WidgetTester tester) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { events.add('tap'); }, child: const Text('Button'), ), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const Text('Target'); }, onAccept: (int? data) { events.add('drop'); }, onAcceptWithDetails: (DragTargetDetails<int> _) { events.add('details'); }, ), ], ), )); expect(events, isEmpty); expect(find.text('Button'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(events, isEmpty); await tester.tap(find.text('Button')); expect(events, equals(<String>['tap'])); events.clear(); firstLocation = tester.getCenter(find.text('Button')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(events, isEmpty); await gesture.up(); await tester.pump(); expect(events, equals(<String>['drop', 'details'])); events.clear(); }); testWidgets('Drag and drop - long press draggable, short press', (WidgetTester tester) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const LongPressDraggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const Text('Target'); }, onAccept: (int? data) { events.add('drop'); }, onAcceptWithDetails: (DragTargetDetails<int> _) { events.add('details'); }, ), ], ), )); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(events, isEmpty); await tester.tap(find.text('Source')); expect(events, isEmpty); firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(events, isEmpty); await gesture.up(); await tester.pump(); expect(events, isEmpty); }); testWidgets('Drag and drop - long press draggable, long press', (WidgetTester tester) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const Text('Target'); }, onAccept: (int? data) { events.add('drop'); }, onAcceptWithDetails: (DragTargetDetails<int> _) { events.add('details'); }, ), ], ), )); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(events, isEmpty); await tester.tap(find.text('Source')); expect(events, isEmpty); firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await tester.pump(const Duration(seconds: 20)); secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(events, isEmpty); await gesture.up(); await tester.pump(); expect(events, equals(<String>['drop', 'details'])); }); testWidgets('Drag and drop - horizontal and vertical draggables in vertical block', (WidgetTester tester) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation, thirdLocation; await tester.pumpWidget(MaterialApp( home: ListView( dragStartBehavior: DragStartBehavior.down, children: <Widget>[ DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const Text('Target'); }, onAccept: (int? data) { events.add('drop $data'); }, onAcceptWithDetails: (DragTargetDetails<int> _) { events.add('details'); }, ), Container(height: 400.0), const Draggable<int>( data: 1, feedback: Text('Dragging'), affinity: Axis.horizontal, child: Text('H'), ), const Draggable<int>( data: 2, feedback: Text('Dragging'), affinity: Axis.vertical, child: Text('V'), ), Container(height: 500.0), Container(height: 500.0), Container(height: 500.0), Container(height: 500.0), ], ), )); expect(events, isEmpty); expect(find.text('Target'), findsOneWidget); expect(find.text('H'), findsOneWidget); expect(find.text('V'), findsOneWidget); // vertical draggable drags vertically expect(events, isEmpty); firstLocation = tester.getCenter(find.text('V')); secondLocation = tester.getCenter(find.text('Target')); TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(events, equals(<String>['drop 2', 'details'])); expect(tester.getCenter(find.text('Target')).dy, greaterThan(0.0)); events.clear(); // horizontal draggable drags horizontally expect(events, isEmpty); firstLocation = tester.getTopLeft(find.text('H')); secondLocation = tester.getTopRight(find.text('H')); thirdLocation = tester.getCenter(find.text('Target')); gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); await gesture.moveTo(thirdLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(events, equals(<String>['drop 1', 'details'])); expect(tester.getCenter(find.text('Target')).dy, greaterThan(0.0)); events.clear(); // vertical draggable drags horizontally when there's no competition // from other gesture detectors expect(events, isEmpty); firstLocation = tester.getTopLeft(find.text('V')); secondLocation = tester.getTopRight(find.text('V')); thirdLocation = tester.getCenter(find.text('Target')); gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); await gesture.moveTo(thirdLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(events, equals(<String>['drop 2', 'details'])); expect(tester.getCenter(find.text('Target')).dy, greaterThan(0.0)); events.clear(); // horizontal draggable doesn't drag vertically when there is competition // for vertical gestures expect(events, isEmpty); firstLocation = tester.getCenter(find.text('H')); secondLocation = tester.getCenter(find.text('Target')); gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); // scrolls off screen! await gesture.up(); await tester.pump(); expect(events, equals(<String>[])); expect(find.text('Target'), findsNothing); events.clear(); }); testWidgets('Drag and drop - horizontal and vertical draggables in horizontal block', (WidgetTester tester) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation, thirdLocation; await tester.pumpWidget(MaterialApp( home: ListView( dragStartBehavior: DragStartBehavior.down, scrollDirection: Axis.horizontal, children: <Widget>[ DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const Text('Target'); }, onAccept: (int? data) { events.add('drop $data'); }, onAcceptWithDetails: (DragTargetDetails<int> _) { events.add('details'); }, ), Container(width: 400.0), const Draggable<int>( data: 1, feedback: Text('Dragging'), affinity: Axis.horizontal, child: Text('H'), ), const Draggable<int>( data: 2, feedback: Text('Dragging'), affinity: Axis.vertical, child: Text('V'), ), Container(width: 500.0), Container(width: 500.0), Container(width: 500.0), Container(width: 500.0), ], ), )); expect(events, isEmpty); expect(find.text('Target'), findsOneWidget); expect(find.text('H'), findsOneWidget); expect(find.text('V'), findsOneWidget); // horizontal draggable drags horizontally expect(events, isEmpty); firstLocation = tester.getCenter(find.text('H')); secondLocation = tester.getCenter(find.text('Target')); TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(events, equals(<String>['drop 1', 'details'])); expect(tester.getCenter(find.text('Target')).dx, greaterThan(0.0)); events.clear(); // vertical draggable drags vertically expect(events, isEmpty); firstLocation = tester.getTopLeft(find.text('V')); secondLocation = tester.getBottomLeft(find.text('V')); thirdLocation = tester.getCenter(find.text('Target')); gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); await gesture.moveTo(thirdLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(events, equals(<String>['drop 2', 'details'])); expect(tester.getCenter(find.text('Target')).dx, greaterThan(0.0)); events.clear(); // horizontal draggable drags vertically when there's no competition // from other gesture detectors expect(events, isEmpty); firstLocation = tester.getTopLeft(find.text('H')); secondLocation = tester.getBottomLeft(find.text('H')); thirdLocation = tester.getCenter(find.text('Target')); gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); await gesture.moveTo(thirdLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(events, equals(<String>['drop 1', 'details'])); expect(tester.getCenter(find.text('Target')).dx, greaterThan(0.0)); events.clear(); // vertical draggable doesn't drag horizontally when there is competition // for horizontal gestures expect(events, isEmpty); firstLocation = tester.getCenter(find.text('V')); secondLocation = tester.getCenter(find.text('Target')); gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); // scrolls off screen! await gesture.up(); await tester.pump(); expect(events, equals(<String>[])); expect(find.text('Target'), findsNothing); events.clear(); }); group('Drag and drop - Draggables with a set axis only move along that axis', () { final List<String> events = <String>[]; Widget build() { return MaterialApp( home: ListView( scrollDirection: Axis.horizontal, children: <Widget>[ DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const Text('Target'); }, onAccept: (int? data) { events.add('drop $data'); }, onAcceptWithDetails: (DragTargetDetails<int> _) { events.add('details'); }, ), Container(width: 400.0), const Draggable<int>( data: 1, feedback: Text('H'), childWhenDragging: SizedBox(), axis: Axis.horizontal, child: Text('H'), ), const Draggable<int>( data: 2, feedback: Text('V'), childWhenDragging: SizedBox(), axis: Axis.vertical, child: Text('V'), ), const Draggable<int>( data: 3, feedback: Text('N'), childWhenDragging: SizedBox(), child: Text('N'), ), Container(width: 500.0), Container(width: 500.0), Container(width: 500.0), Container(width: 500.0), ], ), ); } testWidgets('Null axis draggable moves along all axes', (WidgetTester tester) async { await tester.pumpWidget(build()); final Offset firstLocation = tester.getTopLeft(find.text('N')); final Offset secondLocation = firstLocation + const Offset(300.0, 300.0); final Offset thirdLocation = firstLocation + const Offset(-300.0, -300.0); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); expect(tester.getTopLeft(find.text('N')), secondLocation); await gesture.moveTo(thirdLocation); await tester.pump(); expect(tester.getTopLeft(find.text('N')), thirdLocation); }); testWidgets('Horizontal axis draggable moves horizontally', (WidgetTester tester) async { await tester.pumpWidget(build()); final Offset firstLocation = tester.getTopLeft(find.text('H')); final Offset secondLocation = firstLocation + const Offset(300.0, 0.0); final Offset thirdLocation = firstLocation + const Offset(-300.0, 0.0); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); expect(tester.getTopLeft(find.text('H')), secondLocation); await gesture.moveTo(thirdLocation); await tester.pump(); expect(tester.getTopLeft(find.text('H')), thirdLocation); }); testWidgets('Horizontal axis draggable does not move vertically', (WidgetTester tester) async { await tester.pumpWidget(build()); final Offset firstLocation = tester.getTopLeft(find.text('H')); final Offset secondDragLocation = firstLocation + const Offset(300.0, 200.0); // The horizontal drag widget won't scroll vertically. final Offset secondWidgetLocation = firstLocation + const Offset(300.0, 0.0); final Offset thirdDragLocation = firstLocation + const Offset(-300.0, -200.0); final Offset thirdWidgetLocation = firstLocation + const Offset(-300.0, 0.0); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondDragLocation); await tester.pump(); expect(tester.getTopLeft(find.text('H')), secondWidgetLocation); await gesture.moveTo(thirdDragLocation); await tester.pump(); expect(tester.getTopLeft(find.text('H')), thirdWidgetLocation); }); testWidgets('Vertical axis draggable moves vertically', (WidgetTester tester) async { await tester.pumpWidget(build()); final Offset firstLocation = tester.getTopLeft(find.text('V')); final Offset secondLocation = firstLocation + const Offset(0.0, 300.0); final Offset thirdLocation = firstLocation + const Offset(0.0, -300.0); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); expect(tester.getTopLeft(find.text('V')), secondLocation); await gesture.moveTo(thirdLocation); await tester.pump(); expect(tester.getTopLeft(find.text('V')), thirdLocation); }); testWidgets('Vertical axis draggable does not move horizontally', (WidgetTester tester) async { await tester.pumpWidget(build()); final Offset firstLocation = tester.getTopLeft(find.text('V')); final Offset secondDragLocation = firstLocation + const Offset(200.0, 300.0); // The vertical drag widget won't scroll horizontally. final Offset secondWidgetLocation = firstLocation + const Offset(0.0, 300.0); final Offset thirdDragLocation = firstLocation + const Offset(-200.0, -300.0); final Offset thirdWidgetLocation = firstLocation + const Offset(0.0, -300.0); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondDragLocation); await tester.pump(); expect(tester.getTopLeft(find.text('V')), secondWidgetLocation); await gesture.moveTo(thirdDragLocation); await tester.pump(); expect(tester.getTopLeft(find.text('V')), thirdWidgetLocation); }); }); group('Drag and drop - onDragUpdate called if draggable moves along a set axis', () { int updated = 0; Offset dragDelta = Offset.zero; setUp(() { updated = 0; dragDelta = Offset.zero; }); Widget build() { return MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragUpdate: (DragUpdateDetails details) { dragDelta += details.delta; updated++; }, child: const Text('Source'), ), Draggable<int>( data: 2, feedback: const Text('Vertical Dragging'), onDragUpdate: (DragUpdateDetails details) { dragDelta += details.delta; updated++; }, axis: Axis.vertical, child: const Text('Vertical Source'), ), Draggable<int>( data: 3, feedback: const Text('Horizontal Dragging'), onDragUpdate: (DragUpdateDetails details) { dragDelta += details.delta; updated++; }, axis: Axis.horizontal, child: const Text('Horizontal Source'), ), ], ), ); } testWidgets('Null axis onDragUpdate called only if draggable moves in any direction', (WidgetTester tester) async { await tester.pumpWidget(build()); expect(updated, 0); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(updated, 0); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); await gesture.moveBy(const Offset(10, 10)); await tester.pump(); expect(updated, 1); await gesture.moveBy(Offset.zero); await tester.pump(); expect(updated, 1); await gesture.up(); await tester.pump(); expect(updated, 1); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(dragDelta.dx, 10); expect(dragDelta.dy, 10); }); testWidgets('Vertical axis onDragUpdate only called if draggable moves vertical', (WidgetTester tester) async { await tester.pumpWidget(build()); expect(updated, 0); expect(find.text('Vertical Source'), findsOneWidget); expect(find.text('Vertical Dragging'), findsNothing); final Offset firstLocation = tester.getCenter(find.text('Vertical Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(updated, 0); expect(find.text('Vertical Source'), findsOneWidget); expect(find.text('Vertical Dragging'), findsOneWidget); await gesture.moveBy(const Offset(0, 10)); await tester.pump(); expect(updated, 1); await gesture.moveBy(const Offset(10 , 0)); await tester.pump(); expect(updated, 1); await gesture.up(); await tester.pump(); expect(updated, 1); expect(find.text('Vertical Source'), findsOneWidget); expect(find.text('Vertical Dragging'), findsNothing); expect(dragDelta.dx, 0); expect(dragDelta.dy, 10); }); testWidgets('Horizontal axis onDragUpdate only called if draggable moves horizontal', (WidgetTester tester) async { await tester.pumpWidget(build()); expect(updated, 0); expect(find.text('Horizontal Source'), findsOneWidget); expect(find.text('Horizontal Dragging'), findsNothing); final Offset firstLocation = tester.getCenter(find.text('Horizontal Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(updated, 0); expect(find.text('Horizontal Source'), findsOneWidget); expect(find.text('Horizontal Dragging'), findsOneWidget); await gesture.moveBy(const Offset(0, 10)); await tester.pump(); expect(updated, 0); await gesture.moveBy(const Offset(10 , 0)); await tester.pump(); expect(updated, 1); await gesture.up(); await tester.pump(); expect(updated, 1); expect(find.text('Horizontal Source'), findsOneWidget); expect(find.text('Horizontal Dragging'), findsNothing); expect(dragDelta.dx, 10); expect(dragDelta.dy, 0); }); }); testWidgets('Drag and drop - onDraggableCanceled not called if dropped on accepting target', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDraggableCanceledCalled = false; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDraggableCanceled: (Velocity velocity, Offset offset) { onDraggableCanceledCalled = true; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); await gesture.up(); await tester.pump(); expect(accepted, equals(<int>[1])); expect(acceptedDetails, hasLength(1)); expect(acceptedDetails.first.offset, const Offset(256.0, 74.0)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); }); testWidgets('Drag and drop - onDraggableCanceled called if dropped on non-accepting target', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDraggableCanceledCalled = false; late Velocity onDraggableCanceledVelocity; late Offset onDraggableCanceledOffset; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDraggableCanceled: (Velocity velocity, Offset offset) { onDraggableCanceledCalled = true; onDraggableCanceledVelocity = velocity; onDraggableCanceledOffset = offset; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox( height: 100.0, child: Text('Target'), ); }, onWillAccept: (int? data) => false, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); final Offset firstLocation = tester.getTopLeft(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); await gesture.up(); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isTrue); expect(onDraggableCanceledVelocity, equals(Velocity.zero)); expect(onDraggableCanceledOffset, equals(Offset(secondLocation.dx, secondLocation.dy))); }); testWidgets('Drag and drop - onDraggableCanceled called if dropped on non-accepting target with details', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDraggableCanceledCalled = false; late Velocity onDraggableCanceledVelocity; late Offset onDraggableCanceledOffset; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDraggableCanceled: (Velocity velocity, Offset offset) { onDraggableCanceledCalled = true; onDraggableCanceledVelocity = velocity; onDraggableCanceledOffset = offset; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox( height: 100.0, child: Text('Target'), ); }, onWillAcceptWithDetails: (DragTargetDetails<int> details) => false, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); final Offset firstLocation = tester.getTopLeft(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); await gesture.up(); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isTrue); expect(onDraggableCanceledVelocity, equals(Velocity.zero)); expect(onDraggableCanceledOffset, equals(Offset(secondLocation.dx, secondLocation.dy))); }); testWidgets('Drag and drop - onDraggableCanceled called if dropped on non-accepting target with correct velocity', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDraggableCanceledCalled = false; late Velocity onDraggableCanceledVelocity; late Offset onDraggableCanceledOffset; await tester.pumpWidget(MaterialApp( home: Column(children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Source'), onDraggableCanceled: (Velocity velocity, Offset offset) { onDraggableCanceledCalled = true; onDraggableCanceledVelocity = velocity; onDraggableCanceledOffset = offset; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onWillAccept: (int? data) => false, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ]), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isFalse); final Offset flingStart = tester.getTopLeft(find.text('Source')); await tester.flingFrom(flingStart, const Offset(0.0, 100.0), 1000.0); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDraggableCanceledCalled, isTrue); expect(onDraggableCanceledVelocity.pixelsPerSecond.dx.abs(), lessThan(0.0000001)); expect((onDraggableCanceledVelocity.pixelsPerSecond.dy - 1000.0).abs(), lessThan(0.0000001)); expect(onDraggableCanceledOffset, equals(Offset(flingStart.dx, flingStart.dy) + const Offset(0.0, 100.0))); }); testWidgets('Drag and drop - onDragEnd not called if dropped on non-accepting target', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragEndCalled = false; late DraggableDetails onDragEndDraggableDetails; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragEnd: (DraggableDetails details) { onDragEndCalled = true; onDragEndDraggableDetails = details; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onWillAccept: (int? data) => false, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); final Offset firstLocation = tester.getTopLeft(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); await gesture.up(); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isTrue); expect(onDragEndDraggableDetails, isNotNull); expect(onDragEndDraggableDetails.wasAccepted, isFalse); expect(onDragEndDraggableDetails.velocity, equals(Velocity.zero)); expect( onDragEndDraggableDetails.offset, equals(Offset(secondLocation.dx, secondLocation.dy - firstLocation.dy)), ); }); testWidgets('Drag and drop - onDragEnd not called if dropped on non-accepting target with details', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragEndCalled = false; late DraggableDetails onDragEndDraggableDetails; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragEnd: (DraggableDetails details) { onDragEndCalled = true; onDragEndDraggableDetails = details; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onWillAcceptWithDetails: (DragTargetDetails<int> data) => false, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); final Offset firstLocation = tester.getTopLeft(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); await gesture.up(); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isTrue); expect(onDragEndDraggableDetails, isNotNull); expect(onDragEndDraggableDetails.wasAccepted, isFalse); expect(onDragEndDraggableDetails.velocity, equals(Velocity.zero)); expect( onDragEndDraggableDetails.offset, equals(Offset(secondLocation.dx, secondLocation.dy - firstLocation.dy)), ); }); testWidgets('Drag and drop - DragTarget rebuilds with and without rejected data when a rejected draggable enters and leaves', (WidgetTester tester) async { await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return SizedBox( height: 100.0, child: rejects.isNotEmpty ? const Text('Rejected') : const Text('Target'), ); }, onWillAccept: (int? data) => false, ), ], ), )); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(find.text('Rejected'), findsNothing); final Offset firstLocation = tester.getTopLeft(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(find.text('Rejected'), findsNothing); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsNothing); expect(find.text('Rejected'), findsOneWidget); await gesture.moveTo(firstLocation); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(find.text('Rejected'), findsNothing); }); testWidgets('Drag and drop - Can drag and drop over a non-accepting target multiple times', (WidgetTester tester) async { int numberOfTimesOnDraggableCanceledCalled = 0; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDraggableCanceled: (Velocity velocity, Offset offset) { numberOfTimesOnDraggableCanceledCalled++; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return SizedBox( height: 100.0, child: rejects.isNotEmpty ? const Text('Rejected') : const Text('Target'), ); }, onWillAccept: (int? data) => false, ), ], ), )); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(find.text('Rejected'), findsNothing); final Offset firstLocation = tester.getTopLeft(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(find.text('Rejected'), findsNothing); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsNothing); expect(find.text('Rejected'), findsOneWidget); await gesture.up(); await tester.pump(); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(find.text('Rejected'), findsNothing); expect(numberOfTimesOnDraggableCanceledCalled, 1); // Drag and drop the Draggable onto the Target a second time. final TestGesture secondGesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(find.text('Rejected'), findsNothing); await secondGesture.moveTo(secondLocation); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsNothing); expect(find.text('Rejected'), findsOneWidget); await secondGesture.up(); await tester.pump(); expect(numberOfTimesOnDraggableCanceledCalled, 2); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(find.text('Rejected'), findsNothing); }); testWidgets('Drag and drop - onDragCompleted not called if dropped on non-accepting target', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragCompletedCalled = false; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragCompleted: () { onDragCompletedCalled = true; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox( height: 100.0, child: Text('Target'), ); }, onWillAccept: (int? data) => false, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); final Offset firstLocation = tester.getTopLeft(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); await gesture.up(); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); }); testWidgets('Drag and drop - onDragCompleted not called if dropped on non-accepting target with details', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragCompletedCalled = false; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragCompleted: () { onDragCompletedCalled = true; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox( height: 100.0, child: Text('Target'), ); }, onWillAcceptWithDetails: (DragTargetDetails<int> data) => false, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); final Offset firstLocation = tester.getTopLeft(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); await gesture.up(); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); }); testWidgets('Drag and drop - onDragEnd called if dropped on accepting target', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragEndCalled = false; late DraggableDetails onDragEndDraggableDetails; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragEnd: (DraggableDetails details) { onDragEndCalled = true; onDragEndDraggableDetails = details; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); await gesture.up(); await tester.pump(); final Offset droppedLocation = tester.getTopLeft(find.text('Target')); final Offset expectedDropOffset = Offset(droppedLocation.dx, secondLocation.dy - firstLocation.dy); expect(accepted, equals(<int>[1])); expect(acceptedDetails, hasLength(1)); expect(acceptedDetails.first.offset, const Offset(256.0, 74.0)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isTrue); expect(onDragEndDraggableDetails, isNotNull); expect(onDragEndDraggableDetails.wasAccepted, isTrue); expect(onDragEndDraggableDetails.velocity, equals(Velocity.zero)); expect(onDragEndDraggableDetails.offset, equals(expectedDropOffset)); }); testWidgets('DragTarget does not call onDragEnd when remove from the tree', (WidgetTester tester) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation; int timesOnDragEndCalled = 0; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragEnd: (DraggableDetails details) { timesOnDragEndCalled++; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const Text('Target'); }, onAccept: (int? data) { events.add('drop'); }, onAcceptWithDetails: (DragTargetDetails<int> _) { events.add('details'); }, ), ], ), )); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(events, isEmpty); await tester.tap(find.text('Source')); expect(events, isEmpty); firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await tester.pump(const Duration(seconds: 20)); secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); await tester.pumpWidget(const MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), ], ), )); expect(events, isEmpty); expect(timesOnDragEndCalled, equals(1)); await gesture.up(); await tester.pump(); }); testWidgets('Drag and drop - onDragCompleted called if dropped on accepting target', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragCompletedCalled = false; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragCompleted: () { onDragCompletedCalled = true; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); await gesture.up(); await tester.pump(); expect(accepted, equals(<int>[1])); expect(acceptedDetails, hasLength(1)); expect(acceptedDetails.first.offset, const Offset(256.0, 74.0)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isTrue); }); testWidgets('Drag and drop - allow pass through of unaccepted data test', (WidgetTester tester) async { final List<int> acceptedInts = <int>[]; final List<DragTargetDetails<int>> acceptedIntsDetails = <DragTargetDetails<int>>[]; final List<double> acceptedDoubles = <double>[]; final List<DragTargetDetails<double>> acceptedDoublesDetails = <DragTargetDetails<double>>[]; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('IntDragging'), child: Text('IntSource'), ), const Draggable<double>( data: 1.0, feedback: Text('DoubleDragging'), child: Text('DoubleSource'), ), Stack( children: <Widget>[ DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const IgnorePointer( child: SizedBox( height: 100.0, child: Text('Target1'), ), ); }, onAccept: acceptedInts.add, onAcceptWithDetails: acceptedIntsDetails.add, ), DragTarget<double>( builder: (BuildContext context, List<double?> data, List<dynamic> rejects) { return const IgnorePointer( child: SizedBox( height: 100.0, child: Text('Target2'), ), ); }, onAccept: acceptedDoubles.add, onAcceptWithDetails: acceptedDoublesDetails.add, ), ], ), ], ), )); expect(acceptedInts, isEmpty); expect(acceptedIntsDetails, isEmpty); expect(acceptedDoubles, isEmpty); expect(acceptedDoublesDetails, isEmpty); expect(find.text('IntSource'), findsOneWidget); expect(find.text('IntDragging'), findsNothing); expect(find.text('DoubleSource'), findsOneWidget); expect(find.text('DoubleDragging'), findsNothing); expect(find.text('Target1'), findsOneWidget); expect(find.text('Target2'), findsOneWidget); final Offset intLocation = tester.getCenter(find.text('IntSource')); final Offset doubleLocation = tester.getCenter(find.text('DoubleSource')); final Offset targetLocation = tester.getCenter(find.text('Target1')); // Drag the double draggable. final TestGesture doubleGesture = await tester.startGesture(doubleLocation, pointer: 7); await tester.pump(); expect(acceptedInts, isEmpty); expect(acceptedIntsDetails, isEmpty); expect(acceptedDoubles, isEmpty); expect(acceptedDoublesDetails, isEmpty); expect(find.text('IntDragging'), findsNothing); expect(find.text('DoubleDragging'), findsOneWidget); await doubleGesture.moveTo(targetLocation); await tester.pump(); expect(acceptedInts, isEmpty); expect(acceptedIntsDetails, isEmpty); expect(acceptedDoubles, isEmpty); expect(acceptedDoublesDetails, isEmpty); expect(find.text('IntDragging'), findsNothing); expect(find.text('DoubleDragging'), findsOneWidget); await doubleGesture.up(); await tester.pump(); expect(acceptedInts, isEmpty); expect(acceptedIntsDetails, isEmpty); expect(acceptedDoubles, equals(<double>[1.0])); expect(acceptedDoublesDetails, hasLength(1)); expect(acceptedDoublesDetails.first.offset, const Offset(112.0, 122.0)); expect(find.text('IntDragging'), findsNothing); expect(find.text('DoubleDragging'), findsNothing); acceptedDoubles.clear(); acceptedDoublesDetails.clear(); // Drag the int draggable. final TestGesture intGesture = await tester.startGesture(intLocation, pointer: 7); await tester.pump(); expect(acceptedInts, isEmpty); expect(acceptedIntsDetails, isEmpty); expect(acceptedDoubles, isEmpty); expect(acceptedDoublesDetails, isEmpty); expect(find.text('IntDragging'), findsOneWidget); expect(find.text('DoubleDragging'), findsNothing); await intGesture.moveTo(targetLocation); await tester.pump(); expect(acceptedInts, isEmpty); expect(acceptedIntsDetails, isEmpty); expect(acceptedDoubles, isEmpty); expect(acceptedDoublesDetails, isEmpty); expect(find.text('IntDragging'), findsOneWidget); expect(find.text('DoubleDragging'), findsNothing); await intGesture.up(); await tester.pump(); expect(acceptedInts, equals(<int>[1])); expect(acceptedIntsDetails, hasLength(1)); expect(acceptedIntsDetails.first.offset, const Offset(184.0, 122.0)); expect(acceptedDoubles, isEmpty); expect(acceptedDoublesDetails, isEmpty); expect(find.text('IntDragging'), findsNothing); expect(find.text('DoubleDragging'), findsNothing); }); testWidgets('Drag and drop - allow pass through of unaccepted data twice test', (WidgetTester tester) async { final List<DragTargetData> acceptedDragTargetDatas = <DragTargetData>[]; final List<DragTargetDetails<DragTargetData>> acceptedDragTargetDataDetails = <DragTargetDetails<DragTargetData>>[]; final List<ExtendedDragTargetData> acceptedExtendedDragTargetDatas = <ExtendedDragTargetData>[]; final List<DragTargetDetails<ExtendedDragTargetData>> acceptedExtendedDragTargetDataDetails = <DragTargetDetails<ExtendedDragTargetData>>[]; final DragTargetData dragTargetData = DragTargetData(); await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<DragTargetData>( data: dragTargetData, feedback: const Text('Dragging'), child: const Text('Source'), ), Stack( children: <Widget>[ DragTarget<DragTargetData>( builder: (BuildContext context, List<DragTargetData?> data, List<dynamic> rejects) { return const IgnorePointer( child: SizedBox( height: 100.0, child: Text('Target1'), ), ); }, onAccept: acceptedDragTargetDatas.add, onAcceptWithDetails: acceptedDragTargetDataDetails.add, ), DragTarget<ExtendedDragTargetData>( builder: (BuildContext context, List<ExtendedDragTargetData?> data, List<dynamic> rejects) { return const IgnorePointer( child: SizedBox( height: 100.0, child: Text('Target2'), ), ); }, onAccept: acceptedExtendedDragTargetDatas.add, onAcceptWithDetails: acceptedExtendedDragTargetDataDetails.add, ), ], ), ], ), )); final Offset dragTargetLocation = tester.getCenter(find.text('Source')); final Offset targetLocation = tester.getCenter(find.text('Target1')); for (int i = 0; i < 2; i += 1) { final TestGesture gesture = await tester.startGesture(dragTargetLocation); await tester.pump(); await gesture.moveTo(targetLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(acceptedDragTargetDatas, equals(<DragTargetData>[dragTargetData])); expect(acceptedDragTargetDataDetails, hasLength(1)); expect(acceptedDragTargetDataDetails.first.offset, const Offset(256.0, 74.0)); expect(acceptedExtendedDragTargetDatas, isEmpty); expect(acceptedExtendedDragTargetDataDetails, isEmpty); acceptedDragTargetDatas.clear(); acceptedDragTargetDataDetails.clear(); await tester.pump(); } }); testWidgets('Drag and drop - maxSimultaneousDrags', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; Widget build(int maxSimultaneousDrags) { return MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, maxSimultaneousDrags: maxSimultaneousDrags, feedback: const Text('Dragging'), child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), ); } await tester.pumpWidget(build(0)); final Offset firstLocation = tester.getCenter(find.text('Source')); final Offset secondLocation = tester.getCenter(find.text('Target')); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); await gesture.up(); await tester.pumpWidget(build(2)); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); final TestGesture gesture1 = await tester.startGesture(firstLocation, pointer: 8); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); final TestGesture gesture2 = await tester.startGesture(firstLocation, pointer: 9); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNWidgets(2)); expect(find.text('Target'), findsOneWidget); final TestGesture gesture3 = await tester.startGesture(firstLocation, pointer: 10); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNWidgets(2)); expect(find.text('Target'), findsOneWidget); await gesture1.moveTo(secondLocation); await gesture2.moveTo(secondLocation); await gesture3.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNWidgets(2)); expect(find.text('Target'), findsOneWidget); await gesture1.up(); await tester.pump(); expect(accepted, equals(<int>[1])); expect(acceptedDetails, hasLength(1)); expect(acceptedDetails.first.offset, const Offset(256.0, 74.0)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); await gesture2.up(); await tester.pump(); expect(accepted, equals(<int>[1, 1])); expect(acceptedDetails, hasLength(2)); expect(acceptedDetails[0].offset, const Offset(256.0, 74.0)); expect(acceptedDetails[1].offset, const Offset(256.0, 74.0)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); await gesture3.up(); await tester.pump(); expect(accepted, equals(<int>[1, 1])); expect(acceptedDetails, hasLength(2)); expect(acceptedDetails[0].offset, const Offset(256.0, 74.0)); expect(acceptedDetails[1].offset, const Offset(256.0, 74.0)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); }); testWidgets('Drag and drop - onAccept is not called if dropped with null data', (WidgetTester tester) async { bool onAcceptCalled = false; bool onAcceptWithDetailsCalled = false; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: (int data) { onAcceptCalled = true; }, onAcceptWithDetails: (DragTargetDetails<int> details) { onAcceptWithDetailsCalled =true; }, ), ], ), )); expect(onAcceptCalled, isFalse); expect(onAcceptWithDetailsCalled, isFalse); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(onAcceptCalled, isFalse); expect(onAcceptWithDetailsCalled, isFalse); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(onAcceptCalled, isFalse); expect(onAcceptWithDetailsCalled, isFalse); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); await gesture.up(); await tester.pump(); expect(onAcceptCalled, isFalse, reason: 'onAccept should not be called when data is null'); expect(onAcceptWithDetailsCalled, isFalse, reason: 'onAcceptWithDetails should not be called when data is null'); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); }); testWidgets('Draggable disposes recognizer', (WidgetTester tester) async { late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); bool didTap = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) => GestureDetector( onTap: () { didTap = true; }, child: Draggable<Object>( feedback: Container( width: 100.0, height: 100.0, color: const Color(0xFFFF0000), ), child: Container( color: const Color(0xFFFFFF00), ), ), ), ), ], ), ), ); final TestGesture gesture = await tester.startGesture(const Offset(10.0, 10.0)); expect(didTap, isFalse); // This tears down the draggable without terminating the gesture sequence, // which used to trigger asserts in the multi-drag gesture recognizer. await tester.pumpWidget(Container(key: UniqueKey())); expect(didTap, isFalse); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); // Regression test for https://github.com/flutter/flutter/issues/6128. testWidgets('Draggable plays nice with onTap', (WidgetTester tester) async { late final OverlayEntry entry; addTearDown(() => entry..remove()..dispose()); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Overlay( initialEntries: <OverlayEntry>[ entry = OverlayEntry( builder: (BuildContext context) => GestureDetector( onTap: () { /* registers a tap recognizer */ }, child: Draggable<Object>( feedback: Container( width: 100.0, height: 100.0, color: const Color(0xFFFF0000), ), child: Container( color: const Color(0xFFFFFF00), ), ), ), ), ], ), ), ); final TestGesture firstGesture = await tester.startGesture(const Offset(10.0, 10.0), pointer: 24); final TestGesture secondGesture = await tester.startGesture(const Offset(10.0, 20.0), pointer: 25); await firstGesture.moveBy(const Offset(100.0, 0.0)); await secondGesture.up(); }); testWidgets('DragTarget does not set state when remove from the tree', (WidgetTester tester) async { final List<String> events = <String>[]; Offset firstLocation, secondLocation; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const Text('Target'); }, onAccept: (int? data) { events.add('drop'); }, onAcceptWithDetails: (DragTargetDetails<int> _) { events.add('details'); }, ), ], ), )); expect(events, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(events, isEmpty); await tester.tap(find.text('Source')); expect(events, isEmpty); firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await tester.pump(const Duration(seconds: 20)); secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); await tester.pumpWidget(const MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), ], ), )); expect(events, isEmpty); await gesture.up(); await tester.pump(); }); testWidgets('Drag and drop - remove draggable', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsNothing); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsNothing); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); await gesture.up(); await tester.pump(); expect(accepted, equals(<int>[1])); expect(acceptedDetails, hasLength(1)); expect(acceptedDetails.first.offset, const Offset(256.0, 26.0)); expect(find.text('Source'), findsNothing); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); }); testWidgets('Tap above long-press draggable works', (WidgetTester tester) async { final List<String> events = <String>[]; await tester.pumpWidget(MaterialApp( home: Material( child: Center( child: GestureDetector( onTap: () { events.add('tap'); }, child: const LongPressDraggable<int>( feedback: Text('Feedback'), child: Text('X'), ), ), ), ), )); expect(events, isEmpty); await tester.tap(find.text('X')); expect(events, equals(<String>['tap'])); }); testWidgets('long-press draggable calls onDragEnd called if dropped on accepting target', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragEndCalled = false; late DraggableDetails onDragEndDraggableDetails; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ LongPressDraggable<int>( data: 1, feedback: const Text('Dragging'), onDragEnd: (DraggableDetails details) { onDragEndCalled = true; onDragEndDraggableDetails = details; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); await tester.pump(kLongPressTimeout); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isFalse); await gesture.up(); await tester.pump(); final Offset droppedLocation = tester.getTopLeft(find.text('Target')); final Offset expectedDropOffset = Offset(droppedLocation.dx, secondLocation.dy - firstLocation.dy); expect(accepted, equals(<int>[1])); expect(acceptedDetails, hasLength(1)); expect(acceptedDetails.first.offset, expectedDropOffset); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragEndCalled, isTrue); expect(onDragEndDraggableDetails, isNotNull); expect(onDragEndDraggableDetails.wasAccepted, isTrue); expect(onDragEndDraggableDetails.velocity, equals(Velocity.zero)); expect(onDragEndDraggableDetails.offset, equals(expectedDropOffset)); }); testWidgets('long-press draggable calls onDragCompleted called if dropped on accepting target', (WidgetTester tester) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; bool onDragCompletedCalled = false; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ LongPressDraggable<int>( data: 1, feedback: const Text('Dragging'), onDragCompleted: () { onDragCompletedCalled = true; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), )); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); await tester.pump(kLongPressTimeout); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isFalse); await gesture.up(); await tester.pump(); expect(accepted, equals(<int>[1])); expect(acceptedDetails.first.offset, const Offset(256.0, 74.0)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(onDragCompletedCalled, isTrue); }); testWidgets('long-press draggable calls onDragStartedCalled after long press', (WidgetTester tester) async { bool onDragStartedCalled = false; await tester.pumpWidget(MaterialApp( home: LongPressDraggable<int>( data: 1, feedback: const Text('Dragging'), onDragStarted: () { onDragStartedCalled = true; }, child: const Text('Source'), ), )); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); await tester.pump(kLongPressTimeout); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(onDragStartedCalled, isTrue); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); testWidgets('Custom long press delay for LongPressDraggable', (WidgetTester tester) async { bool onDragStartedCalled = false; await tester.pumpWidget(MaterialApp( home: LongPressDraggable<int>( data: 1, delay: const Duration(seconds: 2), feedback: const Text('Dragging'), onDragStarted: () { onDragStartedCalled = true; }, child: const Text('Source'), ), )); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); // Halfway into the long press duration. await tester.pump(const Duration(seconds: 1)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); // Long press draggable should be showing. await tester.pump(const Duration(seconds: 1)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(onDragStartedCalled, isTrue); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); testWidgets('Default long press delay for LongPressDraggable', (WidgetTester tester) async { bool onDragStartedCalled = false; await tester.pumpWidget(MaterialApp( home: LongPressDraggable<int>( data: 1, feedback: const Text('Dragging'), onDragStarted: () { onDragStartedCalled = true; }, child: const Text('Source'), ), )); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); // Halfway into the long press duration. await tester.pump(const Duration(milliseconds: 250)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); // Long press draggable should be showing. await tester.pump(const Duration(milliseconds: 250)); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(onDragStartedCalled, isTrue); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); testWidgets('long-press draggable calls Haptic Feedback onStart', (WidgetTester tester) async { await _testLongPressDraggableHapticFeedback(tester: tester, hapticFeedbackOnStart: true, expectedHapticFeedbackCount: 1); }); testWidgets('long-press draggable can disable Haptic Feedback', (WidgetTester tester) async { await _testLongPressDraggableHapticFeedback(tester: tester, hapticFeedbackOnStart: false, expectedHapticFeedbackCount: 0); }); testWidgets('Drag feedback with child anchor positions correctly', (WidgetTester tester) async { await _testChildAnchorFeedbackPosition(tester: tester); }); testWidgets('Drag feedback with child anchor within a non-global Overlay positions correctly', (WidgetTester tester) async { await _testChildAnchorFeedbackPosition(tester: tester, left: 100.0, top: 100.0); }); testWidgets('Drag feedback is put on root overlay with [rootOverlay] flag', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> childNavigatorKey = GlobalKey<NavigatorState>(); // Create a [MaterialApp], with a nested [Navigator], which has the // [Draggable]. await tester.pumpWidget(MaterialApp( navigatorKey: rootNavigatorKey, home: Column( children: <Widget>[ SizedBox( height: 200.0, child: Navigator( key: childNavigatorKey, onGenerateRoute: (RouteSettings settings) { if (settings.name == '/') { return MaterialPageRoute<void>( settings: settings, builder: (BuildContext context) => const Draggable<int>( data: 1, feedback: Text('Dragging'), rootOverlay: true, child: Text('Source'), ), ); } throw UnsupportedError('Unsupported route: $settings'); }, ), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox( height: 300.0, child: Center(child: Text('Target 1')), ); }, ), ], ), )); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); final Offset secondLocation = tester.getCenter(find.text('Target 1')); await gesture.moveTo(secondLocation); await tester.pump(); // Expect that the feedback widget is a descendant of the root overlay, // but not a descendant of the child overlay. expect( find.descendant( of: find.byType(Overlay).first, matching: find.text('Dragging'), ), findsOneWidget, ); expect( find.descendant( of: find.byType(Overlay).last, matching: find.text('Dragging'), ), findsNothing, ); }); // Regression test for https://github.com/flutter/flutter/issues/72483 testWidgets('Drag and drop - DragTarget<Object> can accept Draggable<int> data', (WidgetTester tester) async { final List<Object> accepted = <Object>[]; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<int>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<Object>( builder: (BuildContext context, List<Object?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, ), ], ), )); expect(accepted, isEmpty); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(accepted, equals(<int>[1])); }); testWidgets('Drag and drop - DragTarget<int> can accept Draggable<Object> data when runtime type is int', (WidgetTester tester) async { final List<int> accepted = <int>[]; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<Object>( data: 1, feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, ), ], ), )); expect(accepted, isEmpty); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(accepted, equals(<int>[1])); }); testWidgets('Drag and drop - DragTarget<int> should not accept Draggable<Object> data when runtime type null', (WidgetTester tester) async { final List<int> accepted = <int>[]; bool isReceiveNullDataForCheck = false; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ const Draggable<Object>( feedback: Text('Dragging'), child: Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onWillAccept: (int? data) { if (data == null) { isReceiveNullDataForCheck = true; } return data != null; }, ), ], ), )); expect(accepted, isEmpty); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); final Offset secondLocation = tester.getCenter(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); await gesture.up(); await tester.pump(); expect(accepted, isEmpty); expect(isReceiveNullDataForCheck, true); }); testWidgets('Drag and drop can contribute semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(MaterialApp( home: ListView( scrollDirection: Axis.horizontal, addSemanticIndexes: false, children: <Widget>[ DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const Text('Target'); }, ), Container(width: 400.0), const Draggable<int>( data: 1, feedback: Text('H'), childWhenDragging: SizedBox(), axis: Axis.horizontal, ignoringFeedbackSemantics: false, child: Text('H'), ), const Draggable<int>( data: 2, feedback: Text('V'), childWhenDragging: SizedBox(), axis: Axis.vertical, ignoringFeedbackSemantics: false, child: Text('V'), ), const Draggable<int>( data: 3, feedback: Text('N'), childWhenDragging: SizedBox(), child: Text('N'), ), ], ), )); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 3, flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( id: 4, children: <TestSemantics>[ TestSemantics( id: 9, flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], actions: <SemanticsAction>[SemanticsAction.scrollLeft], children: <TestSemantics>[ TestSemantics( id: 5, tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], label: 'Target', textDirection: TextDirection.ltr, ), TestSemantics( id: 6, tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], label: 'H', textDirection: TextDirection.ltr, ), TestSemantics( id: 7, tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], label: 'V', textDirection: TextDirection.ltr, ), TestSemantics( id: 8, tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], label: 'N', textDirection: TextDirection.ltr, ), ], ), ], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreRect: true, )); final Offset firstLocation = tester.getTopLeft(find.text('N')); final Offset secondLocation = firstLocation + const Offset(300.0, 300.0); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); await gesture.moveTo(secondLocation); await tester.pump(); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( id: 1, textDirection: TextDirection.ltr, children: <TestSemantics>[ TestSemantics( id: 2, children: <TestSemantics>[ TestSemantics( id: 3, flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( id: 4, children: <TestSemantics>[ TestSemantics( id: 9, flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling], children: <TestSemantics>[ TestSemantics( id: 5, tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], label: 'Target', textDirection: TextDirection.ltr, ), TestSemantics( id: 6, tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], label: 'H', textDirection: TextDirection.ltr, ), TestSemantics( id: 7, tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')], label: 'V', textDirection: TextDirection.ltr, ), /// N is moved offscreen. ], ), ], ), ], ), ], ), ], ), ], ), ignoreTransform: true, ignoreRect: true, )); semantics.dispose(); }); testWidgets('Drag and drop - when a dragAnchorStrategy is provided it gets called', (WidgetTester tester) async { bool dragAnchorStrategyCalled = false; await tester.pumpWidget(MaterialApp( home: Column( children: <Widget>[ Draggable<int>( feedback: const Text('Feedback'), dragAnchorStrategy: (Draggable<Object> widget, BuildContext context, Offset position) { dragAnchorStrategyCalled = true; return Offset.zero; }, child: const Text('Source'), ), ], ), )); final Offset location = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(location, pointer: 7); expect(dragAnchorStrategyCalled, true); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); }); testWidgets('configurable Draggable hit test behavior', (WidgetTester tester) async { const HitTestBehavior hitTestBehavior = HitTestBehavior.deferToChild; await tester.pumpWidget( const MaterialApp( home: Column( children: <Widget>[ Draggable<int>( feedback: SizedBox(height: 50.0, child: Text('Draggable')), child: SizedBox(height: 50.0, child: Text('Target')), ), ], ), ), ); expect(tester.widget<Listener>(find.byType(Listener).first).behavior, hitTestBehavior); }); // Regression test for https://github.com/flutter/flutter/issues/92083 testWidgets('feedback respect the MouseRegion cursor configure', // TODO(polina-c): clean up leaks, https://github.com/flutter/flutter/issues/134787 [leaks-to-clean] experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(), (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: Column( children: <Widget>[ Draggable<int>( ignoringFeedbackPointer: false, feedback: MouseRegion( cursor: SystemMouseCursors.grabbing, child: SizedBox(height: 50.0, child: Text('Draggable')), ), child: SizedBox(height: 50.0, child: Text('Target')), ), ], ), ), ); final Offset location = tester.getCenter(find.text('Target')); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: location); await gesture.down(location); await tester.pump(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.grabbing); }); testWidgets('configurable feedback ignore pointer behavior', (WidgetTester tester) async { bool onTap = false; await tester.pumpWidget( MaterialApp( home: Column( children: <Widget>[ Draggable<int>( ignoringFeedbackPointer: false, feedback: GestureDetector( onTap: () => onTap = true, child: const SizedBox(height: 50.0, child: Text('Draggable')), ), child: const SizedBox(height: 50.0, child: Text('Target')), ), ], ), ), ); final Offset location = tester.getCenter(find.text('Target')); final TestGesture gesture = await tester.startGesture(location, pointer: 7); final Offset secondLocation = location + const Offset(7.0, 7.0); await gesture.moveTo(secondLocation); await tester.pump(); await tester.tap(find.text('Draggable')); expect(onTap, true); }); testWidgets('configurable feedback ignore pointer behavior - LongPressDraggable', (WidgetTester tester) async { bool onTap = false; await tester.pumpWidget( MaterialApp( home: Column( children: <Widget>[ LongPressDraggable<int>( ignoringFeedbackPointer: false, feedback: GestureDetector( onTap: () => onTap = true, child: const SizedBox(height: 50.0, child: Text('Draggable')), ), child: const SizedBox(height: 50.0, child: Text('Target')), ), ], ), ), ); final Offset location = tester.getCenter(find.text('Target')); final TestGesture gesture = await tester.startGesture(location, pointer: 7); await tester.pump(kLongPressTimeout); final Offset secondLocation = location + const Offset(7.0, 7.0); await gesture.moveTo(secondLocation); await tester.pump(); await tester.tap(find.text('Draggable')); expect(onTap, true); }); testWidgets('configurable DragTarget hit test behavior', (WidgetTester tester) async { const HitTestBehavior hitTestBehavior = HitTestBehavior.deferToChild; await tester.pumpWidget( MaterialApp( home: Column( children: <Widget>[ DragTarget<int>( hitTestBehavior: hitTestBehavior, builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, ), ], ), ), ); expect(tester.widget<MetaData>(find.byType(MetaData)).behavior, hitTestBehavior); }); testWidgets('LongPressDraggable.dragAnchorStrategy', (WidgetTester tester) async { const Widget widget1 = Placeholder(key: ValueKey<int>(1)); const Widget widget2 = Placeholder(key: ValueKey<int>(2)); Offset dummyStrategy(Draggable<Object> draggable, BuildContext context, Offset position) => Offset.zero; expect(const LongPressDraggable<int>(feedback: widget2, child: widget1), isA<Draggable<int>>()); expect(const LongPressDraggable<int>(feedback: widget2, child: widget1).child, widget1); expect(const LongPressDraggable<int>(feedback: widget2, child: widget1).feedback, widget2); expect(LongPressDraggable<int>(feedback: widget2, dragAnchorStrategy: dummyStrategy, child: widget1).dragAnchorStrategy, dummyStrategy); }); testWidgets('Test allowedButtonsFilter', (WidgetTester tester) async { Widget build(bool Function(int buttons)? allowedButtonsFilter) { return MaterialApp( home: Draggable<int>( key: UniqueKey(), allowedButtonsFilter: allowedButtonsFilter, feedback: const Text('Dragging'), child: const Text('Source'), ), ); } await tester.pumpWidget(build(null)); final Offset firstLocation = tester.getCenter(find.text('Source')); expect(find.text('Dragging'), findsNothing); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); await gesture.up(); await tester.pumpWidget(build((int buttons) => buttons == kSecondaryButton)); expect(find.text('Dragging'), findsNothing); final TestGesture gesture1 = await tester.startGesture(firstLocation, pointer: 8); await tester.pump(); expect(find.text('Dragging'), findsNothing); await gesture1.up(); await tester.pumpWidget(build((int buttons) => buttons & kTertiaryButton != 0 || buttons & kPrimaryButton != 0)); expect(find.text('Dragging'), findsNothing); final TestGesture gesture2 = await tester.startGesture(firstLocation, pointer: 8); await tester.pump(); expect(find.text('Dragging'), findsOneWidget); await gesture2.up(); await tester.pumpWidget(build((int buttons) => false)); expect(find.text('Dragging'), findsNothing); final TestGesture gesture3 = await tester.startGesture(firstLocation, pointer: 8); await tester.pump(); expect(find.text('Dragging'), findsNothing); await gesture3.up(); }); testWidgets('throws error when both onWillAccept and onWillAcceptWithDetails are provided', (WidgetTester tester) async { expect(() => DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onWillAccept: (int? data) => true, onWillAcceptWithDetails: (DragTargetDetails<int> details) => false, ), throwsAssertionError); }); } Future<void> _testLongPressDraggableHapticFeedback({ required WidgetTester tester, required bool hapticFeedbackOnStart, required int expectedHapticFeedbackCount }) async { bool onDragStartedCalled = false; int hapticFeedbackCalls = 0; tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { if (methodCall.method == 'HapticFeedback.vibrate') { hapticFeedbackCalls++; } return null; }); await tester.pumpWidget(MaterialApp( home: LongPressDraggable<int>( data: 1, feedback: const Text('Dragging'), hapticFeedbackOnStart: hapticFeedbackOnStart, onDragStarted: () { onDragStartedCalled = true; }, child: const Text('Source'), ), )); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(onDragStartedCalled, isFalse); await tester.pump(kLongPressTimeout); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(onDragStartedCalled, isTrue); expect(hapticFeedbackCalls, expectedHapticFeedbackCount); // Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); } Future<void> _testChildAnchorFeedbackPosition({ required WidgetTester tester, double top = 0.0, double left = 0.0 }) async { final List<int> accepted = <int>[]; final List<DragTargetDetails<int>> acceptedDetails = <DragTargetDetails<int>>[]; int dragStartedCount = 0; await tester.pumpWidget( Stack( textDirection: TextDirection.ltr, children: <Widget>[ Positioned( left: left, top: top, right: 0.0, bottom: 0.0, child: MaterialApp( home: Column( children: <Widget>[ Draggable<int>( data: 1, feedback: const Text('Dragging'), onDragStarted: () { ++dragStartedCount; }, child: const Text('Source'), ), DragTarget<int>( builder: (BuildContext context, List<int?> data, List<dynamic> rejects) { return const SizedBox(height: 100.0, child: Text('Target')); }, onAccept: accepted.add, onAcceptWithDetails: acceptedDetails.add, ), ], ), ), ), ], ), ); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsNothing); expect(find.text('Target'), findsOneWidget); expect(dragStartedCount, 0); final Offset firstLocation = tester.getCenter(find.text('Source')); final TestGesture gesture = await tester.startGesture(firstLocation, pointer: 7); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(dragStartedCount, 1); final Offset secondLocation = tester.getBottomRight(find.text('Target')); await gesture.moveTo(secondLocation); await tester.pump(); expect(accepted, isEmpty); expect(acceptedDetails, isEmpty); expect(find.text('Source'), findsOneWidget); expect(find.text('Dragging'), findsOneWidget); expect(find.text('Target'), findsOneWidget); expect(dragStartedCount, 1); final Offset feedbackTopLeft = tester.getTopLeft(find.text('Dragging')); final Offset sourceTopLeft = tester.getTopLeft(find.text('Source')); final Offset dragOffset = secondLocation - firstLocation; expect(feedbackTopLeft, equals(sourceTopLeft + dragOffset)); } class DragTargetData { } class ExtendedDragTargetData extends DragTargetData { }
flutter/packages/flutter/test/widgets/draggable_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/draggable_test.dart", "repo_id": "flutter", "token_count": 55532 }
738
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; 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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart'; void main() { final GlobalKey widgetKey = GlobalKey(); Future<BuildContext> setupWidget(WidgetTester tester) async { await tester.pumpWidget(Container(key: widgetKey)); return widgetKey.currentContext!; } group(FocusNode, () { testWidgets('Can add children.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusNode parent = FocusNode(); addTearDown(parent.dispose); final FocusAttachment parentAttachment = parent.attach(context); final FocusNode child1 = FocusNode(); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); parentAttachment.reparent(parent: tester.binding.focusManager.rootScope); child1Attachment.reparent(parent: parent); expect(child1.parent, equals(parent)); expect(parent.children.first, equals(child1)); expect(parent.children.last, equals(child1)); child2Attachment.reparent(parent: parent); expect(child1.parent, equals(parent)); expect(child2.parent, equals(parent)); expect(parent.children.first, equals(child1)); expect(parent.children.last, equals(child2)); }); testWidgets('Can remove children.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusNode parent = FocusNode(); addTearDown(parent.dispose); final FocusAttachment parentAttachment = parent.attach(context); final FocusNode child1 = FocusNode(); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); parentAttachment.reparent(parent: tester.binding.focusManager.rootScope); child1Attachment.reparent(parent: parent); child2Attachment.reparent(parent: parent); expect(child1.parent, equals(parent)); expect(child2.parent, equals(parent)); expect(parent.children.first, equals(child1)); expect(parent.children.last, equals(child2)); child1Attachment.detach(); expect(child1.parent, isNull); expect(child2.parent, equals(parent)); expect(parent.children.first, equals(child2)); expect(parent.children.last, equals(child2)); child2Attachment.detach(); expect(child1.parent, isNull); expect(child2.parent, isNull); expect(parent.children, isEmpty); }); testWidgets('Geometry is transformed properly.', (WidgetTester tester) async { final FocusNode focusNode1 = FocusNode(debugLabel: 'Test Node 1'); addTearDown(focusNode1.dispose); final FocusNode focusNode2 = FocusNode(debugLabel: 'Test Node 2'); addTearDown(focusNode2.dispose); await tester.pumpWidget( Padding( padding: const EdgeInsets.all(8.0), child: Column( children: <Widget>[ Focus( focusNode: focusNode1, child: const SizedBox(width: 200, height: 100), ), Transform.translate( offset: const Offset(10, 20), child: Transform.scale( scale: 0.33, child: Transform.rotate( angle: math.pi, child: Focus(focusNode: focusNode2, child: const SizedBox(width: 200, height: 100)), ), ), ), ], ), ), ); focusNode2.requestFocus(); await tester.pump(); expect(focusNode1.rect, equals(const Rect.fromLTRB(300.0, 8.0, 500.0, 108.0))); expect(focusNode2.rect, equals(const Rect.fromLTRB(443.0, 194.5, 377.0, 161.5))); expect(focusNode1.size, equals(const Size(200.0, 100.0))); expect(focusNode2.size, equals(const Size(-66.0, -33.0))); expect(focusNode1.offset, equals(const Offset(300.0, 8.0))); expect(focusNode2.offset, equals(const Offset(443.0, 194.5))); }); testWidgets('descendantsAreFocusable disables focus for descendants.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope); parent2Attachment.reparent(parent: scope); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent2); child1.requestFocus(); await tester.pump(); expect(tester.binding.focusManager.primaryFocus, equals(child1)); expect(scope.focusedChild, equals(child1)); expect(scope.traversalDescendants.contains(child1), isTrue); expect(scope.traversalDescendants.contains(child2), isTrue); parent2.descendantsAreFocusable = false; // Node should still be focusable, even if descendants are not. parent2.requestFocus(); await tester.pump(); expect(parent2.hasPrimaryFocus, isTrue); child2.requestFocus(); await tester.pump(); expect(tester.binding.focusManager.primaryFocus, isNot(equals(child2))); expect(tester.binding.focusManager.primaryFocus, equals(parent2)); expect(scope.focusedChild, equals(parent2)); expect(scope.traversalDescendants.contains(child1), isTrue); expect(scope.traversalDescendants.contains(child2), isFalse); parent1.descendantsAreFocusable = false; await tester.pump(); expect(tester.binding.focusManager.primaryFocus, isNot(equals(child2))); expect(tester.binding.focusManager.primaryFocus, isNot(equals(child1))); expect(scope.focusedChild, equals(parent2)); expect(scope.traversalDescendants.contains(child1), isFalse); expect(scope.traversalDescendants.contains(child2), isFalse); }); testWidgets('descendantsAreTraversable disables traversal for descendants.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope); parent2Attachment.reparent(parent: scope); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent2); expect(scope.traversalDescendants, equals(<FocusNode>[child1, parent1, child2, parent2])); parent2.descendantsAreTraversable = false; expect(scope.traversalDescendants, equals(<FocusNode>[child1, parent1, parent2])); parent1.descendantsAreTraversable = false; expect(scope.traversalDescendants, equals(<FocusNode>[parent1, parent2])); parent1.descendantsAreTraversable = true; parent2.descendantsAreTraversable = true; scope.descendantsAreTraversable = false; expect(scope.traversalDescendants, equals(<FocusNode>[])); }); testWidgets("canRequestFocus doesn't affect traversalChildren", (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope); parent2Attachment.reparent(parent: scope); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent2); child1.requestFocus(); await tester.pump(); expect(tester.binding.focusManager.primaryFocus, equals(child1)); expect(scope.focusedChild, equals(child1)); expect(parent2.traversalChildren.contains(child2), isTrue); expect(scope.traversalChildren.contains(parent2), isTrue); parent2.canRequestFocus = false; await tester.pump(); expect(parent2.traversalChildren.contains(child2), isTrue); expect(scope.traversalChildren.contains(parent2), isFalse); }); testWidgets('implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final FocusNode focusNode = FocusNode(debugLabel: 'Label'); addTearDown(focusNode.dispose); focusNode.debugFillProperties(builder); final List<String> description = builder.properties.map((DiagnosticsNode n) => n.toString()).toList(); expect(description, <String>[ 'context: null', 'descendantsAreFocusable: true', 'descendantsAreTraversable: true', 'canRequestFocus: true', 'hasFocus: false', 'hasPrimaryFocus: false', ]); }); testWidgets('onKeyEvent and onKey correctly cooperate', (WidgetTester tester) async { final FocusNode focusNode1 = FocusNode(debugLabel: 'Test Node 1'); addTearDown(focusNode1.dispose); final FocusNode focusNode2 = FocusNode(debugLabel: 'Test Node 2'); addTearDown(focusNode2.dispose); final FocusNode focusNode3 = FocusNode(debugLabel: 'Test Node 3'); addTearDown(focusNode3.dispose); List<List<KeyEventResult>> results = <List<KeyEventResult>>[ <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], ]; final List<int> logs = <int>[]; await tester.pumpWidget( Focus( focusNode: focusNode1, onKeyEvent: (_, KeyEvent event) { logs.add(0); return results[0][0]; }, onKey: (_, RawKeyEvent event) { logs.add(1); return results[0][1]; }, child: Focus( focusNode: focusNode2, onKeyEvent: (_, KeyEvent event) { logs.add(10); return results[1][0]; }, onKey: (_, RawKeyEvent event) { logs.add(11); return results[1][1]; }, child: Focus( focusNode: focusNode3, onKeyEvent: (_, KeyEvent event) { logs.add(20); return results[2][0]; }, onKey: (_, RawKeyEvent event) { logs.add(21); return results[2][1]; }, child: const SizedBox(width: 200, height: 100), ), ), ), ); focusNode3.requestFocus(); await tester.pump(); // All ignored. results = <List<KeyEventResult>>[ <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], ]; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[20, 21, 10, 11, 0, 1]); logs.clear(); // The onKeyEvent should be able to stop propagation. results = <List<KeyEventResult>>[ <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.handled, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], ]; expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), true); expect(logs, <int>[20, 21, 10, 11]); logs.clear(); // The onKey should be able to stop propagation. results = <List<KeyEventResult>>[ <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.handled], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], ]; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(logs, <int>[20, 21, 10, 11]); logs.clear(); // KeyEventResult.skipRemainingHandlers works. results = <List<KeyEventResult>>[ <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.skipRemainingHandlers, KeyEventResult.ignored], <KeyEventResult>[KeyEventResult.ignored, KeyEventResult.ignored], ]; expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[20, 21, 10, 11]); logs.clear(); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('FocusManager ignores app lifecycle changes on Android.', (WidgetTester tester) async { final bool shouldRespond = kIsWeb || defaultTargetPlatform != TargetPlatform.android; if (shouldRespond) { return; } Future<void> setAppLifecycleState(AppLifecycleState state) async { final ByteData? message = const StringCodec().encodeMessage(state.toString()); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .handlePlatformMessage('flutter/lifecycle', message, (_) {}); } final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode focusNode = FocusNode(debugLabel: 'Focus Node'); addTearDown(focusNode.dispose); final FocusAttachment focusNodeAttachment = focusNode.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); focusNodeAttachment.reparent(parent: scope); focusNode.requestFocus(); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); await setAppLifecycleState(AppLifecycleState.paused); expect(focusNode.hasPrimaryFocus, isTrue); await setAppLifecycleState(AppLifecycleState.resumed); expect(focusNode.hasPrimaryFocus, isTrue); }); testWidgets('FocusManager responds to app lifecycle changes.', (WidgetTester tester) async { final bool shouldRespond = kIsWeb || defaultTargetPlatform != TargetPlatform.android; if (!shouldRespond) { return; } Future<void> setAppLifecycleState(AppLifecycleState state) async { final ByteData? message = const StringCodec().encodeMessage(state.toString()); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .handlePlatformMessage('flutter/lifecycle', message, (_) {}); } final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode focusNode = FocusNode(debugLabel: 'Focus Node'); addTearDown(focusNode.dispose); final FocusAttachment focusNodeAttachment = focusNode.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); focusNodeAttachment.reparent(parent: scope); focusNode.requestFocus(); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); await setAppLifecycleState(AppLifecycleState.paused); expect(focusNode.hasPrimaryFocus, isFalse); await setAppLifecycleState(AppLifecycleState.resumed); expect(focusNode.hasPrimaryFocus, isTrue); }); testWidgets('Node is removed completely even if app is paused.', (WidgetTester tester) async { Future<void> setAppLifecycleState(AppLifecycleState state) async { final ByteData? message = const StringCodec().encodeMessage(state.toString()); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .handlePlatformMessage('flutter/lifecycle', message, (_) {}); } final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode focusNode = FocusNode(debugLabel: 'Focus Node'); addTearDown(focusNode.dispose); final FocusAttachment focusNodeAttachment = focusNode.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); focusNodeAttachment.reparent(parent: scope); focusNode.requestFocus(); await tester.pump(); expect(focusNode.hasPrimaryFocus, isTrue); await setAppLifecycleState(AppLifecycleState.paused); focusNodeAttachment.detach(); expect(focusNode.hasPrimaryFocus, isFalse); await setAppLifecycleState(AppLifecycleState.resumed); expect(focusNode.hasPrimaryFocus, isFalse); }); }); group(FocusScopeNode, () { testWidgets('Can setFirstFocus on a scope with no manager.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); scope.attach(context); final FocusScopeNode parent = FocusScopeNode(debugLabel: 'Parent'); addTearDown(parent.dispose); parent.attach(context); final FocusScopeNode child1 = FocusScopeNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusScopeNode child2 = FocusScopeNode(debugLabel: 'Child 2'); addTearDown(child2.dispose); child2.attach(context); scope.setFirstFocus(parent); parent.setFirstFocus(child1); parent.setFirstFocus(child2); child1.requestFocus(); await tester.pump(); expect(scope.hasFocus, isFalse); expect(child1.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(scope.focusedChild, equals(parent)); expect(parent.focusedChild, equals(child1)); child1Attachment.detach(); expect(scope.hasFocus, isFalse); expect(scope.focusedChild, equals(parent)); }); testWidgets('Removing a node removes it from scope.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode parent = FocusNode(); addTearDown(parent.dispose); final FocusAttachment parentAttachment = parent.attach(context); final FocusNode child1 = FocusNode(); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); parentAttachment.reparent(parent: scope); child1Attachment.reparent(parent: parent); child2Attachment.reparent(parent: parent); child1.requestFocus(); await tester.pump(); expect(scope.hasFocus, isTrue); expect(child1.hasFocus, isTrue); expect(child1.hasPrimaryFocus, isTrue); expect(scope.focusedChild, equals(child1)); child1Attachment.detach(); expect(scope.hasFocus, isFalse); expect(scope.focusedChild, isNull); }); testWidgets('Can add children to scope and focus', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode parent = FocusNode(); addTearDown(parent.dispose); final FocusAttachment parentAttachment = parent.attach(context); final FocusNode child1 = FocusNode(); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); parentAttachment.reparent(parent: scope); child1Attachment.reparent(parent: parent); child2Attachment.reparent(parent: parent); expect(scope.children.first, equals(parent)); expect(parent.parent, equals(scope)); expect(child1.parent, equals(parent)); expect(child2.parent, equals(parent)); expect(parent.children.first, equals(child1)); expect(parent.children.last, equals(child2)); child1.requestFocus(); await tester.pump(); expect(scope.focusedChild, equals(child1)); expect(parent.hasFocus, isTrue); expect(parent.hasPrimaryFocus, isFalse); expect(child1.hasFocus, isTrue); expect(child1.hasPrimaryFocus, isTrue); expect(child2.hasFocus, isFalse); expect(child2.hasPrimaryFocus, isFalse); child2.requestFocus(); await tester.pump(); expect(scope.focusedChild, equals(child2)); expect(parent.hasFocus, isTrue); expect(parent.hasPrimaryFocus, isFalse); expect(child1.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(child2.hasFocus, isTrue); expect(child2.hasPrimaryFocus, isTrue); }); // Regression test for https://github.com/flutter/flutter/issues/136758 testWidgets('removing grandchildren from scope updates focusedChild', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); // Sets up this focus node tree: // // root // | // scope1 // | // child1 // | // child2 final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1'); addTearDown(scope1.dispose); final FocusAttachment scope2Attachment = scope1.attach(context); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child2Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child3Attachment = child2.attach(context); child2Attachment.reparent(parent: scope1); child3Attachment.reparent(parent: child1); expect(child1.parent, equals(scope1)); expect(scope1.children.first, equals(child1)); child2.requestFocus(); await tester.pump(); expect(scope1.focusedChild, equals(child2)); // Detach the middle child and make sure that the scope is updated so that // it no longer references child2 as the focused child. child2Attachment.detach(); expect(scope1.focusedChild, isNull); }); testWidgets('Requesting focus before adding to tree results in a request after adding', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode child = FocusNode(); addTearDown(child.dispose); child.requestFocus(); expect(child.hasPrimaryFocus, isFalse); // not attached yet. scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); await tester.pump(); expect(scope.focusedChild, isNull); expect(child.hasPrimaryFocus, isFalse); // not attached yet. final FocusAttachment childAttachment = child.attach(context); expect(child.hasPrimaryFocus, isFalse); // not parented yet. childAttachment.reparent(parent: scope); await tester.pump(); expect(child.hasPrimaryFocus, isTrue); // now attached and parented, so focus finally happened. }); testWidgets('Autofocus works.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode parent = FocusNode(debugLabel: 'Parent'); addTearDown(parent.dispose); final FocusAttachment parentAttachment = parent.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); parentAttachment.reparent(parent: scope); child1Attachment.reparent(parent: parent); child2Attachment.reparent(parent: parent); scope.autofocus(child2); await tester.pump(); expect(scope.focusedChild, equals(child2)); expect(parent.hasFocus, isTrue); expect(child1.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(child2.hasFocus, isTrue); expect(child2.hasPrimaryFocus, isTrue); child1.requestFocus(); scope.autofocus(child2); await tester.pump(); expect(scope.focusedChild, equals(child1)); expect(parent.hasFocus, isTrue); expect(child1.hasFocus, isTrue); expect(child1.hasPrimaryFocus, isTrue); expect(child2.hasFocus, isFalse); expect(child2.hasPrimaryFocus, isFalse); }); testWidgets('Adding a focusedChild to a scope sets scope as focusedChild in parent scope', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context); final FocusScopeNode scope2 = FocusScopeNode(); addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context); final FocusNode child1 = FocusNode(); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: scope1); child1Attachment.reparent(parent: scope1); child2Attachment.reparent(parent: scope2); child2.requestFocus(); await tester.pump(); expect(scope2.focusedChild, equals(child2)); expect(scope1.focusedChild, equals(scope2)); expect(child1.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(child2.hasFocus, isTrue); expect(child2.hasPrimaryFocus, isTrue); child1.requestFocus(); await tester.pump(); expect(scope2.focusedChild, equals(child2)); expect(scope1.focusedChild, equals(child1)); expect(child1.hasFocus, isTrue); expect(child1.hasPrimaryFocus, isTrue); expect(child2.hasFocus, isFalse); expect(child2.hasPrimaryFocus, isFalse); }); testWidgets('Can move node with focus without losing focus', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope); parent2Attachment.reparent(parent: scope); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); expect(scope.children.first, equals(parent1)); expect(scope.children.last, equals(parent2)); expect(parent1.parent, equals(scope)); expect(parent2.parent, equals(scope)); expect(child1.parent, equals(parent1)); expect(child2.parent, equals(parent1)); expect(parent1.children.first, equals(child1)); expect(parent1.children.last, equals(child2)); child1.requestFocus(); await tester.pump(); child1Attachment.reparent(parent: parent2); await tester.pump(); expect(scope.focusedChild, equals(child1)); expect(child1.parent, equals(parent2)); expect(child2.parent, equals(parent1)); expect(parent1.children.first, equals(child2)); expect(parent2.children.first, equals(child1)); }); test('FocusScopeNode.canRequestFocus affects descendantsAreFocusable', () { final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); scope.descendantsAreFocusable = false; expect(scope.descendantsAreFocusable, isFalse); expect(scope.canRequestFocus, isTrue); scope.descendantsAreFocusable = true; expect(scope.descendantsAreFocusable, isTrue); expect(scope.canRequestFocus, isTrue); scope.canRequestFocus = false; expect(scope.descendantsAreFocusable, isFalse); expect(scope.canRequestFocus, isFalse); scope.canRequestFocus = true; expect(scope.descendantsAreFocusable, isTrue); expect(scope.canRequestFocus, isTrue); }); testWidgets('canRequestFocus affects children.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope); parent2Attachment.reparent(parent: scope); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child1.requestFocus(); await tester.pump(); expect(tester.binding.focusManager.primaryFocus, equals(child1)); expect(scope.focusedChild, equals(child1)); expect(scope.traversalDescendants.contains(child1), isTrue); expect(scope.traversalDescendants.contains(child2), isTrue); expect(scope.traversalChildren.contains(parent1), isTrue); expect(parent1.traversalChildren.contains(child2), isTrue); scope.canRequestFocus = false; await tester.pump(); child2.requestFocus(); await tester.pump(); expect(tester.binding.focusManager.primaryFocus, isNot(equals(child2))); expect(tester.binding.focusManager.primaryFocus, isNot(equals(child1))); expect(scope.focusedChild, equals(child1)); expect(scope.traversalDescendants.contains(child1), isFalse); expect(scope.traversalDescendants.contains(child2), isFalse); expect(scope.traversalChildren.contains(parent1), isFalse); expect(parent1.traversalChildren.contains(child2), isFalse); }); testWidgets("skipTraversal doesn't affect children.", (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope'); addTearDown(scope.dispose); final FocusAttachment scopeAttachment = scope.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); scopeAttachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope); parent2Attachment.reparent(parent: scope); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child1.requestFocus(); await tester.pump(); expect(tester.binding.focusManager.primaryFocus, equals(child1)); expect(scope.focusedChild, equals(child1)); expect(tester.binding.focusManager.rootScope.traversalDescendants.contains(scope), isTrue); expect(scope.traversalDescendants.contains(child1), isTrue); expect(scope.traversalDescendants.contains(child2), isTrue); scope.skipTraversal = true; await tester.pump(); expect(tester.binding.focusManager.primaryFocus, equals(child1)); expect(scope.focusedChild, equals(child1)); expect(tester.binding.focusManager.rootScope.traversalDescendants.contains(scope), isFalse); expect(scope.traversalDescendants.contains(child1), isTrue); expect(scope.traversalDescendants.contains(child2), isTrue); }); testWidgets('Can move node between scopes and lose scope focus', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context); final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2'); addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'parent2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); final FocusNode child3 = FocusNode(debugLabel: 'child3'); addTearDown(child3.dispose); final FocusAttachment child3Attachment = child3.attach(context); final FocusNode child4 = FocusNode(debugLabel: 'child4'); addTearDown(child4.dispose); final FocusAttachment child4Attachment = child4.attach(context); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope1); parent2Attachment.reparent(parent: scope2); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child3Attachment.reparent(parent: parent2); child4Attachment.reparent(parent: parent2); child1.requestFocus(); await tester.pump(); expect(scope1.focusedChild, equals(child1)); expect(parent2.children.contains(child1), isFalse); child1Attachment.reparent(parent: parent2); await tester.pump(); expect(scope1.focusedChild, isNull); expect(parent2.children.contains(child1), isTrue); }); testWidgets('ancestors and descendants are computed and recomputed properly', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1'); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context); final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2'); addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'parent2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); final FocusNode child3 = FocusNode(debugLabel: 'child3'); addTearDown(child3.dispose); final FocusAttachment child3Attachment = child3.attach(context); final FocusNode child4 = FocusNode(debugLabel: 'child4'); addTearDown(child4.dispose); final FocusAttachment child4Attachment = child4.attach(context); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope1); parent2Attachment.reparent(parent: scope2); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child3Attachment.reparent(parent: parent2); child4Attachment.reparent(parent: parent2); child4.requestFocus(); await tester.pump(); expect(child4.ancestors, equals(<FocusNode>[parent2, scope2, tester.binding.focusManager.rootScope])); expect(tester.binding.focusManager.rootScope.descendants, equals(<FocusNode>[child1, child2, parent1, scope1, child3, child4, parent2, scope2])); scope2Attachment.reparent(parent: child2); await tester.pump(); expect(child4.ancestors, equals(<FocusNode>[parent2, scope2, child2, parent1, scope1, tester.binding.focusManager.rootScope])); expect(tester.binding.focusManager.rootScope.descendants, equals(<FocusNode>[child1, child3, child4, parent2, scope2, child2, parent1, scope1])); }); testWidgets('Can move focus between scopes and keep focus', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context); final FocusScopeNode scope2 = FocusScopeNode(); addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context); final FocusNode parent1 = FocusNode(); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); final FocusNode child3 = FocusNode(); addTearDown(child3.dispose); final FocusAttachment child3Attachment = child3.attach(context); final FocusNode child4 = FocusNode(); addTearDown(child4.dispose); final FocusAttachment child4Attachment = child4.attach(context); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope1); parent2Attachment.reparent(parent: scope2); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child3Attachment.reparent(parent: parent2); child4Attachment.reparent(parent: parent2); child4.requestFocus(); await tester.pump(); child1.requestFocus(); await tester.pump(); expect(child4.hasFocus, isFalse); expect(child4.hasPrimaryFocus, isFalse); expect(child1.hasFocus, isTrue); expect(child1.hasPrimaryFocus, isTrue); expect(scope1.hasFocus, isTrue); expect(scope1.hasPrimaryFocus, isFalse); expect(scope2.hasFocus, isFalse); expect(scope2.hasPrimaryFocus, isFalse); expect(parent1.hasFocus, isTrue); expect(parent2.hasFocus, isFalse); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child4)); scope2.requestFocus(); await tester.pump(); expect(child4.hasFocus, isTrue); expect(child4.hasPrimaryFocus, isTrue); expect(child1.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(scope1.hasFocus, isFalse); expect(scope1.hasPrimaryFocus, isFalse); expect(scope2.hasFocus, isTrue); expect(scope2.hasPrimaryFocus, isFalse); expect(parent1.hasFocus, isFalse); expect(parent2.hasFocus, isTrue); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child4)); }); testWidgets('Unfocus with disposition previouslyFocusedChild works properly', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context); final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2'); addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'parent2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); final FocusNode child3 = FocusNode(debugLabel: 'child3'); addTearDown(child3.dispose); final FocusAttachment child3Attachment = child3.attach(context); final FocusNode child4 = FocusNode(debugLabel: 'child4'); addTearDown(child4.dispose); final FocusAttachment child4Attachment = child4.attach(context); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope1); parent2Attachment.reparent(parent: scope2); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child3Attachment.reparent(parent: parent2); child4Attachment.reparent(parent: parent2); // Build up a history. child4.requestFocus(); await tester.pump(); child2.requestFocus(); await tester.pump(); child3.requestFocus(); await tester.pump(); child1.requestFocus(); await tester.pump(); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child3)); child1.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild); await tester.pump(); expect(scope1.focusedChild, equals(child2)); expect(scope2.focusedChild, equals(child3)); expect(scope1.hasFocus, isTrue); expect(scope2.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(child2.hasPrimaryFocus, isTrue); // Can re-focus child. child1.requestFocus(); await tester.pump(); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child3)); expect(scope1.hasFocus, isTrue); expect(scope2.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isTrue); expect(child3.hasPrimaryFocus, isFalse); // The same thing happens when unfocusing a second time. child1.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild); await tester.pump(); expect(scope1.focusedChild, equals(child2)); expect(scope2.focusedChild, equals(child3)); expect(scope1.hasFocus, isTrue); expect(scope2.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(child2.hasPrimaryFocus, isTrue); // When the scope gets unfocused, then the sibling scope gets focus. child1.requestFocus(); await tester.pump(); scope1.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild); await tester.pump(); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child3)); expect(scope1.hasFocus, isFalse); expect(scope2.hasFocus, isTrue); expect(child1.hasPrimaryFocus, isFalse); expect(child3.hasPrimaryFocus, isTrue); }); testWidgets('Unfocus with disposition scope works properly', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context); final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2'); addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'parent2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); final FocusNode child3 = FocusNode(debugLabel: 'child3'); addTearDown(child3.dispose); final FocusAttachment child3Attachment = child3.attach(context); final FocusNode child4 = FocusNode(debugLabel: 'child4'); addTearDown(child4.dispose); final FocusAttachment child4Attachment = child4.attach(context); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope1); parent2Attachment.reparent(parent: scope2); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child3Attachment.reparent(parent: parent2); child4Attachment.reparent(parent: parent2); // Build up a history. child4.requestFocus(); await tester.pump(); child2.requestFocus(); await tester.pump(); child3.requestFocus(); await tester.pump(); child1.requestFocus(); await tester.pump(); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child3)); child1.unfocus(); await tester.pump(); // Focused child doesn't change. expect(scope1.focusedChild, isNull); expect(scope2.focusedChild, equals(child3)); // Focus does change. expect(scope1.hasPrimaryFocus, isTrue); expect(scope2.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(child2.hasPrimaryFocus, isFalse); // Can re-focus child. child1.requestFocus(); await tester.pump(); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child3)); expect(scope1.hasFocus, isTrue); expect(scope2.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isTrue); expect(child3.hasPrimaryFocus, isFalse); // The same thing happens when unfocusing a second time. child1.unfocus(); await tester.pump(); expect(scope1.focusedChild, isNull); expect(scope2.focusedChild, equals(child3)); expect(scope1.hasPrimaryFocus, isTrue); expect(scope2.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(child2.hasPrimaryFocus, isFalse); // When the scope gets unfocused, then its parent scope (the root scope) // gets focus, but it doesn't mess with the focused children. child1.requestFocus(); await tester.pump(); scope1.unfocus(); await tester.pump(); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child3)); expect(scope1.hasFocus, isFalse); expect(scope2.hasFocus, isFalse); expect(child1.hasPrimaryFocus, isFalse); expect(child3.hasPrimaryFocus, isFalse); expect(FocusManager.instance.rootScope.hasPrimaryFocus, isTrue); }); testWidgets('Unfocus works properly when some nodes are unfocusable', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context); final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2'); addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'parent2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); final FocusNode child3 = FocusNode(debugLabel: 'child3'); addTearDown(child3.dispose); final FocusAttachment child3Attachment = child3.attach(context); final FocusNode child4 = FocusNode(debugLabel: 'child4'); addTearDown(child4.dispose); final FocusAttachment child4Attachment = child4.attach(context); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope1); parent2Attachment.reparent(parent: scope2); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child3Attachment.reparent(parent: parent2); child4Attachment.reparent(parent: parent2); // Build up a history. child4.requestFocus(); await tester.pump(); child2.requestFocus(); await tester.pump(); child3.requestFocus(); await tester.pump(); child1.requestFocus(); await tester.pump(); expect(child1.hasPrimaryFocus, isTrue); scope1.canRequestFocus = false; await tester.pump(); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child3)); expect(child3.hasPrimaryFocus, isTrue); child1.unfocus(); await tester.pump(); expect(child3.hasPrimaryFocus, isTrue); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child3)); expect(scope1.hasPrimaryFocus, isFalse); expect(scope2.hasFocus, isTrue); expect(child1.hasPrimaryFocus, isFalse); expect(child2.hasPrimaryFocus, isFalse); child1.unfocus(disposition: UnfocusDisposition.previouslyFocusedChild); await tester.pump(); expect(child3.hasPrimaryFocus, isTrue); expect(scope1.focusedChild, equals(child1)); expect(scope2.focusedChild, equals(child3)); expect(scope1.hasPrimaryFocus, isFalse); expect(scope2.hasFocus, isTrue); expect(child1.hasPrimaryFocus, isFalse); expect(child2.hasPrimaryFocus, isFalse); }); testWidgets('Requesting focus on a scope works properly when some focusedChild nodes are unfocusable', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1')..attach(context); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context); final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2'); addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'parent2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); final FocusNode child3 = FocusNode(debugLabel: 'child3'); addTearDown(child3.dispose); final FocusAttachment child3Attachment = child3.attach(context); final FocusNode child4 = FocusNode(debugLabel: 'child4'); addTearDown(child4.dispose); final FocusAttachment child4Attachment = child4.attach(context); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope1); parent2Attachment.reparent(parent: scope2); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child3Attachment.reparent(parent: parent2); child4Attachment.reparent(parent: parent2); // Build up a history. child4.requestFocus(); await tester.pump(); child2.requestFocus(); await tester.pump(); child3.requestFocus(); await tester.pump(); child1.requestFocus(); await tester.pump(); expect(child1.hasPrimaryFocus, isTrue); child1.canRequestFocus = false; child3.canRequestFocus = false; await tester.pump(); scope1.requestFocus(); await tester.pump(); expect(scope1.focusedChild, equals(child2)); expect(child2.hasPrimaryFocus, isTrue); scope2.requestFocus(); await tester.pump(); expect(scope2.focusedChild, equals(child4)); expect(child4.hasPrimaryFocus, isTrue); }); testWidgets('Key handling bubbles up and terminates when handled.', (WidgetTester tester) async { final Set<FocusNode> receivedAnEvent = <FocusNode>{}; final Set<FocusNode> shouldHandle = <FocusNode>{}; KeyEventResult handleEvent(FocusNode node, RawKeyEvent event) { if (shouldHandle.contains(node)) { receivedAnEvent.add(node); return KeyEventResult.handled; } return KeyEventResult.ignored; } Future<void> sendEvent() async { receivedAnEvent.clear(); await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'fuchsia'); } final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'Scope 1'); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context, onKey: handleEvent); final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'Scope 2'); addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context, onKey: handleEvent); final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1', onKey: handleEvent); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2', onKey: handleEvent); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context, onKey: handleEvent); final FocusNode child2 = FocusNode(debugLabel: 'Child 2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context, onKey: handleEvent); final FocusNode child3 = FocusNode(debugLabel: 'Child 3'); addTearDown(child3.dispose); final FocusAttachment child3Attachment = child3.attach(context, onKey: handleEvent); final FocusNode child4 = FocusNode(debugLabel: 'Child 4'); addTearDown(child4.dispose); final FocusAttachment child4Attachment = child4.attach(context, onKey: handleEvent); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope1); parent2Attachment.reparent(parent: scope2); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child3Attachment.reparent(parent: parent2); child4Attachment.reparent(parent: parent2); child4.requestFocus(); await tester.pump(); shouldHandle.addAll(<FocusNode>{scope2, parent2, child2, child4}); await sendEvent(); expect(receivedAnEvent, equals(<FocusNode>{child4})); shouldHandle.remove(child4); await sendEvent(); expect(receivedAnEvent, equals(<FocusNode>{parent2})); shouldHandle.remove(parent2); await sendEvent(); expect(receivedAnEvent, equals(<FocusNode>{scope2})); shouldHandle.clear(); await sendEvent(); expect(receivedAnEvent, isEmpty); child1.requestFocus(); await tester.pump(); shouldHandle.addAll(<FocusNode>{scope2, parent2, child2, child4}); await sendEvent(); // Since none of the focused nodes handle this event, nothing should // receive it. expect(receivedAnEvent, isEmpty); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('Initial highlight mode guesses correctly.', (WidgetTester tester) async { FocusManager.instance.highlightStrategy = FocusHighlightStrategy.automatic; switch (defaultTargetPlatform) { case TargetPlatform.fuchsia: case TargetPlatform.android: case TargetPlatform.iOS: expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); } }, variant: TargetPlatformVariant.all()); testWidgets('Mouse events change initial focus highlight mode on mobile.', (WidgetTester tester) async { expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); RendererBinding.instance.initMouseTracker(); // Clear out the mouse state. final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 0); await gesture.moveTo(Offset.zero); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); }, variant: TargetPlatformVariant.mobile()); testWidgets('Mouse events change initial focus highlight mode on desktop.', (WidgetTester tester) async { expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); RendererBinding.instance.initMouseTracker(); // Clear out the mouse state. final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 0); await gesture.moveTo(Offset.zero); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); }, variant: TargetPlatformVariant.desktop()); testWidgets('Keyboard events change initial focus highlight mode.', (WidgetTester tester) async { await tester.sendKeyEvent(LogicalKeyboardKey.enter); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); }, variant: TargetPlatformVariant.all()); testWidgets('Events change focus highlight mode.', (WidgetTester tester) async { await setupWidget(tester); int callCount = 0; FocusHighlightMode? lastMode; void handleModeChange(FocusHighlightMode mode) { lastMode = mode; callCount++; } FocusManager.instance.addHighlightModeListener(handleModeChange); addTearDown(() => FocusManager.instance.removeHighlightModeListener(handleModeChange)); expect(callCount, equals(0)); expect(lastMode, isNull); FocusManager.instance.highlightStrategy = FocusHighlightStrategy.automatic; expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); await tester.sendKeyEvent(LogicalKeyboardKey.metaLeft, platform: 'fuchsia'); expect(callCount, equals(1)); expect(lastMode, FocusHighlightMode.traditional); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); await tester.tap(find.byType(Container), warnIfMissed: false); expect(callCount, equals(2)); expect(lastMode, FocusHighlightMode.touch); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); final TestGesture gesture = await tester.startGesture(Offset.zero, kind: PointerDeviceKind.mouse); await gesture.up(); expect(callCount, equals(3)); expect(lastMode, FocusHighlightMode.traditional); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); await tester.tap(find.byType(Container), warnIfMissed: false); expect(callCount, equals(4)); expect(lastMode, FocusHighlightMode.touch); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; expect(callCount, equals(5)); expect(lastMode, FocusHighlightMode.traditional); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.traditional)); FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch; expect(callCount, equals(6)); expect(lastMode, FocusHighlightMode.touch); expect(FocusManager.instance.highlightMode, equals(FocusHighlightMode.touch)); }); testWidgets('implements debugFillProperties', (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final FocusScopeNode scope = FocusScopeNode(debugLabel: 'Scope Label'); addTearDown(scope.dispose); scope.debugFillProperties(builder); final List<String> description = builder.properties.map((DiagnosticsNode n) => n.toString()).toList(); expect(description, <String>[ 'context: null', 'descendantsAreFocusable: true', 'descendantsAreTraversable: true', 'canRequestFocus: true', 'hasFocus: false', 'hasPrimaryFocus: false', ]); }); testWidgets('debugDescribeFocusTree produces correct output', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'Scope 1'); addTearDown(scope1.dispose); final FocusAttachment scope1Attachment = scope1.attach(context); final FocusScopeNode scope2 = FocusScopeNode(); // No label, Just to test that it works. addTearDown(scope2.dispose); final FocusAttachment scope2Attachment = scope2.attach(context); final FocusNode parent1 = FocusNode(debugLabel: 'Parent 1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode parent2 = FocusNode(debugLabel: 'Parent 2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'Child 1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(); // No label, Just to test that it works. addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); final FocusNode child3 = FocusNode(debugLabel: 'Child 3'); addTearDown(child3.dispose); final FocusAttachment child3Attachment = child3.attach(context); final FocusNode child4 = FocusNode(debugLabel: 'Child 4'); addTearDown(child4.dispose); final FocusAttachment child4Attachment = child4.attach(context); scope1Attachment.reparent(parent: tester.binding.focusManager.rootScope); scope2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: scope1); parent2Attachment.reparent(parent: scope2); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent1); child3Attachment.reparent(parent: parent2); child4Attachment.reparent(parent: parent2); child4.requestFocus(); await tester.pump(); final String description = debugDescribeFocusTree(); expect( description, equalsIgnoringHashCodes( 'FocusManager#00000\n' ' │ primaryFocus: FocusNode#00000(Child 4 [PRIMARY FOCUS])\n' ' │ primaryFocusCreator: Container-[GlobalKey#00000] ← MediaQuery ←\n' ' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n' ' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n' ' │ [root]\n' ' │\n' ' └─rootScope: FocusScopeNode#00000(Root Focus Scope [IN FOCUS PATH])\n' ' │ IN FOCUS PATH\n' ' │ focusedChildren: FocusScopeNode#00000([IN FOCUS PATH])\n' ' │\n' ' ├─Child 1: FocusScopeNode#00000(Scope 1)\n' ' │ │ context: Container-[GlobalKey#00000]\n' ' │ │\n' ' │ └─Child 1: FocusNode#00000(Parent 1)\n' ' │ │ context: Container-[GlobalKey#00000]\n' ' │ │\n' ' │ ├─Child 1: FocusNode#00000(Child 1)\n' ' │ │ context: Container-[GlobalKey#00000]\n' ' │ │\n' ' │ └─Child 2: FocusNode#00000\n' ' │ context: Container-[GlobalKey#00000]\n' ' │\n' ' └─Child 2: FocusScopeNode#00000([IN FOCUS PATH])\n' ' │ context: Container-[GlobalKey#00000]\n' ' │ IN FOCUS PATH\n' ' │ focusedChildren: FocusNode#00000(Child 4 [PRIMARY FOCUS])\n' ' │\n' ' └─Child 1: FocusNode#00000(Parent 2 [IN FOCUS PATH])\n' ' │ context: Container-[GlobalKey#00000]\n' ' │ IN FOCUS PATH\n' ' │\n' ' ├─Child 1: FocusNode#00000(Child 3)\n' ' │ context: Container-[GlobalKey#00000]\n' ' │\n' ' └─Child 2: FocusNode#00000(Child 4 [PRIMARY FOCUS])\n' ' context: Container-[GlobalKey#00000]\n' ' PRIMARY FOCUS\n', ), ); }); }); group('Autofocus', () { testWidgets( 'works when the previous focused node is detached', (WidgetTester tester) async { final FocusNode node1 = FocusNode(); addTearDown(node1.dispose); final FocusNode node2 = FocusNode(); addTearDown(node2.dispose); await tester.pumpWidget( FocusScope( child: Focus(autofocus: true, focusNode: node1, child: const Placeholder()), ), ); await tester.pump(); expect(node1.hasPrimaryFocus, isTrue); await tester.pumpWidget( FocusScope( child: SizedBox( child: Focus(autofocus: true, focusNode: node2, child: const Placeholder()), ), ), ); await tester.pump(); expect(node2.hasPrimaryFocus, isTrue); }); testWidgets( 'node detached before autofocus is applied', (WidgetTester tester) async { final FocusScopeNode scopeNode = FocusScopeNode(); addTearDown(scopeNode.dispose); final FocusNode node1 = FocusNode(); addTearDown(node1.dispose); await tester.pumpWidget( FocusScope( node: scopeNode, child: Focus( autofocus: true, focusNode: node1, child: const Placeholder(), ), ), ); await tester.pumpWidget( FocusScope( node: scopeNode, child: const Focus(child: Placeholder()), ), ); await tester.pump(); expect(node1.hasPrimaryFocus, isFalse); expect(scopeNode.hasPrimaryFocus, isTrue); }); testWidgets('autofocus the first candidate', (WidgetTester tester) async { final FocusNode node1 = FocusNode(); addTearDown(node1.dispose); final FocusNode node2 = FocusNode(); addTearDown(node2.dispose); final FocusNode node3 = FocusNode(); addTearDown(node3.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Column( children: <Focus>[ Focus( autofocus: true, focusNode: node1, child: const SizedBox(), ), Focus( autofocus: true, focusNode: node2, child: const SizedBox(), ), Focus( autofocus: true, focusNode: node3, child: const SizedBox(), ), ], ), ), ); expect(node1.hasPrimaryFocus, isTrue); }); testWidgets('Autofocus works with global key reparenting', (WidgetTester tester) async { final FocusNode node = FocusNode(); addTearDown(node.dispose); final FocusScopeNode scope1 = FocusScopeNode(debugLabel: 'scope1'); addTearDown(scope1.dispose); final FocusScopeNode scope2 = FocusScopeNode(debugLabel: 'scope2'); addTearDown(scope2.dispose); final GlobalKey key = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Column( children: <Focus>[ FocusScope( node: scope1, child: Focus( key: key, focusNode: node, child: const SizedBox(), ), ), FocusScope(node: scope2, child: const SizedBox()), ], ), ), ); // _applyFocusChange will be called before persistentCallbacks, // guaranteeing the focus changes are applied before the BuildContext // `node` attaches to gets reparented. scope1.autofocus(node); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Column( children: <Focus>[ FocusScope(node: scope1, child: const SizedBox()), FocusScope( node: scope2, child: Focus( key: key, focusNode: node, child: const SizedBox(), ), ), ], ), ), ); expect(node.hasPrimaryFocus, isTrue); expect(scope2.hasFocus, isTrue); }); }); testWidgets("Doesn't lose focused child when reparenting if the nearestScope doesn't change.", (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusScopeNode parent2 = FocusScopeNode(debugLabel: 'parent2'); addTearDown(parent2.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); parent1Attachment.reparent(parent: tester.binding.focusManager.rootScope); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: child1); parent1.autofocus(child2); await tester.pump(); parent2Attachment.reparent(parent: tester.binding.focusManager.rootScope); parent2.requestFocus(); await tester.pump(); expect(parent1.focusedChild, equals(child2)); child2Attachment.reparent(parent: parent1); expect(parent1.focusedChild, equals(child2)); parent1.requestFocus(); await tester.pump(); expect(parent1.focusedChild, equals(child2)); }); testWidgets('Ancestors get notified exactly as often as needed if focused child changes focus.', (WidgetTester tester) async { bool topFocus = false; bool parent1Focus = false; bool parent2Focus = false; bool child1Focus = false; bool child2Focus = false; int topNotify = 0; int parent1Notify = 0; int parent2Notify = 0; int child1Notify = 0; int child2Notify = 0; void clear() { topFocus = false; parent1Focus = false; parent2Focus = false; child1Focus = false; child2Focus = false; topNotify = 0; parent1Notify = 0; parent2Notify = 0; child1Notify = 0; child2Notify = 0; } final BuildContext context = await setupWidget(tester); final FocusScopeNode top = FocusScopeNode(debugLabel: 'top'); addTearDown(top.dispose); final FocusAttachment topAttachment = top.attach(context); final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusScopeNode parent2 = FocusScopeNode(debugLabel: 'parent2'); addTearDown(parent2.dispose); final FocusAttachment parent2Attachment = parent2.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); topAttachment.reparent(parent: tester.binding.focusManager.rootScope); parent1Attachment.reparent(parent: top); parent2Attachment.reparent(parent: top); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: parent2); top.addListener(() { topNotify++; topFocus = top.hasFocus; }); parent1.addListener(() { parent1Notify++; parent1Focus = parent1.hasFocus; }); parent2.addListener(() { parent2Notify++; parent2Focus = parent2.hasFocus; }); child1.addListener(() { child1Notify++; child1Focus = child1.hasFocus; }); child2.addListener(() { child2Notify++; child2Focus = child2.hasFocus; }); child1.requestFocus(); await tester.pump(); expect(topFocus, isTrue); expect(parent1Focus, isTrue); expect(child1Focus, isTrue); expect(parent2Focus, isFalse); expect(child2Focus, isFalse); expect(topNotify, equals(1)); expect(parent1Notify, equals(1)); expect(child1Notify, equals(1)); expect(parent2Notify, equals(0)); expect(child2Notify, equals(0)); clear(); child1.unfocus(); await tester.pump(); expect(topFocus, isFalse); expect(parent1Focus, isTrue); expect(child1Focus, isFalse); expect(parent2Focus, isFalse); expect(child2Focus, isFalse); expect(topNotify, equals(0)); expect(parent1Notify, equals(1)); expect(child1Notify, equals(1)); expect(parent2Notify, equals(0)); expect(child2Notify, equals(0)); clear(); child1.requestFocus(); await tester.pump(); expect(topFocus, isFalse); expect(parent1Focus, isTrue); expect(child1Focus, isTrue); expect(parent2Focus, isFalse); expect(child2Focus, isFalse); expect(topNotify, equals(0)); expect(parent1Notify, equals(1)); expect(child1Notify, equals(1)); expect(parent2Notify, equals(0)); expect(child2Notify, equals(0)); clear(); child2.requestFocus(); await tester.pump(); expect(topFocus, isFalse); expect(parent1Focus, isFalse); expect(child1Focus, isFalse); expect(parent2Focus, isTrue); expect(child2Focus, isTrue); expect(topNotify, equals(0)); expect(parent1Notify, equals(1)); expect(child1Notify, equals(1)); expect(parent2Notify, equals(1)); expect(child2Notify, equals(1)); // Changing the focus back before the pump shouldn't cause notifications. clear(); child1.requestFocus(); child2.requestFocus(); await tester.pump(); expect(topFocus, isFalse); expect(parent1Focus, isFalse); expect(child1Focus, isFalse); expect(parent2Focus, isFalse); expect(child2Focus, isFalse); expect(topNotify, equals(0)); expect(parent1Notify, equals(0)); expect(child1Notify, equals(0)); expect(parent2Notify, equals(0)); expect(child2Notify, equals(0)); }); testWidgets('Focus changes notify listeners.', (WidgetTester tester) async { final BuildContext context = await setupWidget(tester); final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); final FocusNode child2 = FocusNode(debugLabel: 'child2'); addTearDown(child2.dispose); final FocusAttachment child2Attachment = child2.attach(context); parent1Attachment.reparent(parent: tester.binding.focusManager.rootScope); child1Attachment.reparent(parent: parent1); child2Attachment.reparent(parent: child1); int notifyCount = 0; void handleFocusChange() { notifyCount++; } tester.binding.focusManager.addListener(handleFocusChange); parent1.autofocus(child2); expect(notifyCount, equals(0)); await tester.pump(); expect(notifyCount, equals(1)); notifyCount = 0; child1.requestFocus(); child2.requestFocus(); child1.requestFocus(); await tester.pump(); expect(notifyCount, equals(1)); notifyCount = 0; child2.requestFocus(); await tester.pump(); expect(notifyCount, equals(1)); notifyCount = 0; child2.unfocus(); await tester.pump(); expect(notifyCount, equals(1)); notifyCount = 0; tester.binding.focusManager.removeListener(handleFocusChange); }); test('$FocusManager dispatches object creation in constructor', () async { await expectLater( await memoryEvents(() => FocusManager().dispose(), FocusManager), areCreateAndDispose, ); }); test('$FocusNode dispatches object creation in constructor', () async { await expectLater( await memoryEvents(() => FocusNode().dispose(), FocusNode), areCreateAndDispose, ); }); testWidgets('FocusManager.addEarlyKeyEventHandler works', (WidgetTester tester) async { final FocusNode focusNode1 = FocusNode(debugLabel: 'Test Node 1'); addTearDown(focusNode1.dispose); final List<int> logs = <int>[]; KeyEventResult earlyResult = KeyEventResult.ignored; KeyEventResult focusResult = KeyEventResult.ignored; await tester.pumpWidget( Focus( focusNode: focusNode1, onKeyEvent: (_, KeyEvent event) { logs.add(0); if (event is KeyDownEvent) { return focusResult; } return KeyEventResult.ignored; }, onKey: (_, RawKeyEvent event) { logs.add(1); if (event is KeyDownEvent) { return focusResult; } return KeyEventResult.ignored; }, child: const SizedBox(), ), ); focusNode1.requestFocus(); await tester.pump(); KeyEventResult earlyHandler(KeyEvent event) { if (event is KeyDownEvent) { return earlyResult; } return KeyEventResult.ignored; } expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), false); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); FocusManager.instance.addEarlyKeyEventHandler(earlyHandler); logs.clear(); focusResult = KeyEventResult.ignored; earlyResult = KeyEventResult.handled; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1]); logs.clear(); focusResult = KeyEventResult.ignored; earlyResult = KeyEventResult.ignored; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), false); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); logs.clear(); focusResult = KeyEventResult.handled; earlyResult = KeyEventResult.ignored; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); FocusManager.instance.removeEarlyKeyEventHandler(earlyHandler); logs.clear(); focusResult = KeyEventResult.ignored; earlyResult = KeyEventResult.handled; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), false); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); logs.clear(); focusResult = KeyEventResult.handled; earlyResult = KeyEventResult.ignored; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('FocusManager.addLateKeyEventHandler works', (WidgetTester tester) async { final FocusNode focusNode1 = FocusNode(debugLabel: 'Test Node 1'); addTearDown(focusNode1.dispose); final List<int> logs = <int>[]; KeyEventResult lateResult = KeyEventResult.ignored; KeyEventResult focusResult = KeyEventResult.ignored; await tester.pumpWidget( Focus( focusNode: focusNode1, onKeyEvent: (_, KeyEvent event) { logs.add(0); if (event is KeyDownEvent) { return focusResult; } return KeyEventResult.ignored; }, onKey: (_, RawKeyEvent event) { logs.add(1); if (event is KeyDownEvent) { return focusResult; } return KeyEventResult.ignored; }, child: const SizedBox(), ), ); focusNode1.requestFocus(); await tester.pump(); KeyEventResult lateHandler(KeyEvent event) { if (event is KeyDownEvent) { return lateResult; } return KeyEventResult.ignored; } expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), false); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); FocusManager.instance.addLateKeyEventHandler(lateHandler); logs.clear(); focusResult = KeyEventResult.ignored; lateResult = KeyEventResult.handled; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); logs.clear(); focusResult = KeyEventResult.ignored; lateResult = KeyEventResult.ignored; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), false); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); logs.clear(); focusResult = KeyEventResult.handled; lateResult = KeyEventResult.ignored; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); FocusManager.instance.removeLateKeyEventHandler(lateHandler); logs.clear(); focusResult = KeyEventResult.ignored; lateResult = KeyEventResult.handled; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), false); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); logs.clear(); focusResult = KeyEventResult.handled; lateResult = KeyEventResult.ignored; expect(await simulateKeyDownEvent(LogicalKeyboardKey.digit1), true); expect(await simulateKeyUpEvent(LogicalKeyboardKey.digit1), false); expect(logs, <int>[0, 1, 0, 1]); }, variant: KeySimulatorTransitModeVariant.all()); testWidgets('FocusManager notifies listeners when a widget loses focus because it was removed.', (WidgetTester tester) async { final FocusNode nodeA = FocusNode(debugLabel: 'a'); addTearDown(nodeA.dispose); final FocusNode nodeB = FocusNode(debugLabel: 'b'); addTearDown(nodeB.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, child: Column( children: <Widget>[ Focus(focusNode: nodeA , child: const Text('a')), Focus(focusNode: nodeB, child: const Text('b')), ], ), ), ); int notifyCount = 0; void handleFocusChange() { notifyCount++; } tester.binding.focusManager.addListener(handleFocusChange); nodeA.requestFocus(); await tester.pump(); expect(nodeA.hasPrimaryFocus, isTrue); expect(notifyCount, equals(1)); notifyCount = 0; await tester.pumpWidget( Directionality( textDirection: TextDirection.rtl, child: Column( children: <Widget>[ Focus(focusNode: nodeB, child: const Text('b')), ], ), ), ); await tester.pump(); expect(nodeA.hasPrimaryFocus, isFalse); expect(nodeB.hasPrimaryFocus, isFalse); expect(notifyCount, equals(1)); notifyCount = 0; tester.binding.focusManager.removeListener(handleFocusChange); }); testWidgets('debugFocusChanges causes logging of focus changes', (WidgetTester tester) async { final bool oldDebugFocusChanges = debugFocusChanges; final DebugPrintCallback oldDebugPrint = debugPrint; final StringBuffer messages = StringBuffer(); debugPrint = (String? message, {int? wrapWidth}) { messages.writeln(message ?? ''); }; debugFocusChanges = true; try { final BuildContext context = await setupWidget(tester); final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1'); addTearDown(parent1.dispose); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode child1 = FocusNode(debugLabel: 'child1'); addTearDown(child1.dispose); final FocusAttachment child1Attachment = child1.attach(context); parent1Attachment.reparent(parent: tester.binding.focusManager.rootScope); child1Attachment.reparent(parent: parent1); int notifyCount = 0; void handleFocusChange() { notifyCount++; } tester.binding.focusManager.addListener(handleFocusChange); parent1.requestFocus(); expect(notifyCount, equals(0)); await tester.pump(); expect(notifyCount, equals(1)); notifyCount = 0; child1.requestFocus(); await tester.pump(); expect(notifyCount, equals(1)); notifyCount = 0; tester.binding.focusManager.removeListener(handleFocusChange); } finally { debugFocusChanges = oldDebugFocusChanges; debugPrint = oldDebugPrint; } final String messagesStr = messages.toString(); expect(messagesStr, contains(RegExp(r' └─Child 1: FocusScopeNode#[a-f0-9]{5}\(parent1 \[PRIMARY FOCUS\]\)'))); expect(messagesStr, contains('FOCUS: Notified 2 dirty nodes')); expect(messagesStr, contains(RegExp(r'FOCUS: Scheduling update, current focus is null, next focus will be FocusScopeNode#.*parent1'))); }); testWidgets("doesn't call toString on a focus node when debugFocusChanges is false", (WidgetTester tester) async { final bool oldDebugFocusChanges = debugFocusChanges; final DebugPrintCallback oldDebugPrint = debugPrint; final StringBuffer messages = StringBuffer(); debugPrint = (String? message, {int? wrapWidth}) { messages.writeln(message ?? ''); }; Future<void> testDebugFocusChanges() async { final BuildContext context = await setupWidget(tester); final FocusScopeNode parent1 = FocusScopeNode(debugLabel: 'parent1'); final FocusAttachment parent1Attachment = parent1.attach(context); final FocusNode child1 = debugFocusChanges ? FocusNode(debugLabel: 'child1') : _LoggingTestFocusNode(debugLabel: 'child1'); final FocusAttachment child1Attachment = child1.attach(context); parent1Attachment.reparent(parent: tester.binding.focusManager.rootScope); child1Attachment.reparent(parent: parent1); child1.requestFocus(); await tester.pump(); child1.dispose(); parent1.dispose(); await tester.pump(); } try { debugFocusChanges = false; await testDebugFocusChanges(); expect(messages, isEmpty); expect(tester.takeException(), isNull); debugFocusChanges = true; await testDebugFocusChanges(); expect(messages.toString(), contains('FOCUS: Notified 3 dirty nodes:')); expect(tester.takeException(), isNull); } finally { debugFocusChanges = oldDebugFocusChanges; debugPrint = oldDebugPrint; } }); } class _LoggingTestFocusNode extends FocusNode { _LoggingTestFocusNode({super.debugLabel}); @override String toString({ DiagnosticLevel minLevel = DiagnosticLevel.debug, }) { throw StateError("Shouldn't call toString here"); } @override String toStringDeep({ String prefixLineOne = '', String? prefixOtherLines, DiagnosticLevel minLevel = DiagnosticLevel.debug, }) { throw StateError("Shouldn't call toStringDeep here"); } }
flutter/packages/flutter/test/widgets/focus_manager_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/focus_manager_test.dart", "repo_id": "flutter", "token_count": 36674 }
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/gestures.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('toString control test', (WidgetTester tester) async { await tester.pumpWidget(const Center(child: Text('Hello', textDirection: TextDirection.ltr))); final HitTestResult result = tester.hitTestOnBinding(Offset.zero); expect(result, hasOneLineDescription); expect(result.path.first, hasOneLineDescription); }); testWidgets('A mouse click should only cause one hit test', (WidgetTester tester) async { int hitCount = 0; await tester.pumpWidget( _HitTestCounter( onHitTestCallback: () { hitCount += 1; }, child: Container(), ), ); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(_HitTestCounter)), kind: PointerDeviceKind.mouse); await gesture.up(); expect(hitCount, 1); }); testWidgets('Non-mouse events should not cause movement hit tests', (WidgetTester tester) async { int hitCount = 0; await tester.pumpWidget( _HitTestCounter( onHitTestCallback: () { hitCount += 1; }, child: Container(), ), ); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(_HitTestCounter))); await gesture.moveBy(const Offset(1, 1)); await gesture.up(); expect(hitCount, 1); }); } // The [_HitTestCounter] invokes [onHitTestCallback] every time // [hitTestChildren] is called. class _HitTestCounter extends SingleChildRenderObjectWidget { const _HitTestCounter({ required Widget super.child, required this.onHitTestCallback, }); final VoidCallback? onHitTestCallback; @override _RenderHitTestCounter createRenderObject(BuildContext context) { return _RenderHitTestCounter() .._onHitTestCallback = onHitTestCallback; } @override void updateRenderObject( BuildContext context, _RenderHitTestCounter renderObject, ) { renderObject._onHitTestCallback = onHitTestCallback; } } class _RenderHitTestCounter extends RenderProxyBox { VoidCallback? _onHitTestCallback; @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { _onHitTestCallback?.call(); return super.hitTestChildren(result, position: position); } }
flutter/packages/flutter/test/widgets/hit_testing_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/hit_testing_test.dart", "repo_id": "flutter", "token_count": 872 }
740
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ui' show FlutterView; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; class ScheduledFrameTrackingPlatformDispatcher extends TestPlatformDispatcher { ScheduledFrameTrackingPlatformDispatcher({ required super.platformDispatcher }); int _scheduledFrameCount = 0; int get scheduledFrameCount => _scheduledFrameCount; void resetScheduledFrameCount() { _scheduledFrameCount = 0; } @override void scheduleFrame() { _scheduledFrameCount++; super.scheduleFrame(); } } class ScheduledFrameTrackingBindings extends AutomatedTestWidgetsFlutterBinding { late final ScheduledFrameTrackingPlatformDispatcher _platformDispatcher = ScheduledFrameTrackingPlatformDispatcher(platformDispatcher: super.platformDispatcher); @override ScheduledFrameTrackingPlatformDispatcher get platformDispatcher => _platformDispatcher; } class OffscreenRenderView extends RenderView { OffscreenRenderView({required super.view}) : super( configuration: TestViewConfiguration.fromView(view: view), ); @override void compositeFrame() { // Don't draw to ui.window } } class OffscreenWidgetTree { OffscreenWidgetTree(this.view) { renderView.attach(pipelineOwner); renderView.prepareInitialFrame(); pipelineOwner.requestVisualUpdate(); } final FlutterView view; late final RenderView renderView = OffscreenRenderView(view: view); final BuildOwner buildOwner = BuildOwner(focusManager: FocusManager()); final PipelineOwner pipelineOwner = PipelineOwner(); RenderObjectToWidgetElement<RenderBox>? root; void pumpWidget(Widget? app) { root = RenderObjectToWidgetAdapter<RenderBox>( container: renderView, debugShortDescription: '[root]', child: app, ).attachToRenderTree(buildOwner, root); pumpFrame(); } void pumpFrame() { buildOwner.buildScope(root!); pipelineOwner.flushLayout(); pipelineOwner.flushCompositingBits(); pipelineOwner.flushPaint(); renderView.compositeFrame(); pipelineOwner.flushSemantics(); buildOwner.finalizeTree(); } } class Counter { int count = 0; } class Trigger { VoidCallback? callback; void fire() { callback?.call(); } } class TriggerableWidget extends StatefulWidget { const TriggerableWidget({ super.key, required this.trigger, required this.counter, }); final Trigger trigger; final Counter counter; @override TriggerableState createState() => TriggerableState(); } class TriggerableState extends State<TriggerableWidget> { @override void initState() { super.initState(); widget.trigger.callback = fire; } @override void didUpdateWidget(TriggerableWidget oldWidget) { super.didUpdateWidget(oldWidget); widget.trigger.callback = fire; } int _count = 0; void fire() { setState(() { _count++; }); } @override Widget build(BuildContext context) { widget.counter.count++; return Text('Bang $_count!', textDirection: TextDirection.ltr); } } class TestFocusable extends StatefulWidget { const TestFocusable({ super.key, required this.focusNode, this.autofocus = true, }); final bool autofocus; final FocusNode focusNode; @override TestFocusableState createState() => TestFocusableState(); } class TestFocusableState extends State<TestFocusable> { bool _didAutofocus = false; @override void didChangeDependencies() { super.didChangeDependencies(); if (!_didAutofocus && widget.autofocus) { _didAutofocus = true; FocusScope.of(context).autofocus(widget.focusNode); } } @override Widget build(BuildContext context) { return const Text('Test focus node', textDirection: TextDirection.ltr); } } void main() { // Override the bindings for this test suite so that we can track the number // of times a frame has been scheduled. ScheduledFrameTrackingBindings(); testWidgets('RenderObjectToWidgetAdapter.attachToRenderTree does not schedule frame', (WidgetTester tester) async { expect(WidgetsBinding.instance, isA<ScheduledFrameTrackingBindings>()); final ScheduledFrameTrackingPlatformDispatcher platformDispatcher = tester.platformDispatcher as ScheduledFrameTrackingPlatformDispatcher; platformDispatcher.resetScheduledFrameCount(); expect(platformDispatcher.scheduledFrameCount, isZero); final OffscreenWidgetTree tree = OffscreenWidgetTree(tester.view); tree.pumpWidget(const SizedBox.shrink()); expect(platformDispatcher.scheduledFrameCount, isZero); }); testWidgets('no crosstalk between widget build owners', (WidgetTester tester) async { final Trigger trigger1 = Trigger(); final Counter counter1 = Counter(); final Trigger trigger2 = Trigger(); final Counter counter2 = Counter(); final OffscreenWidgetTree tree = OffscreenWidgetTree(tester.view); // Both counts should start at zero expect(counter1.count, equals(0)); expect(counter2.count, equals(0)); // Lay out the "onscreen" in the default test binding await tester.pumpWidget(TriggerableWidget(trigger: trigger1, counter: counter1)); // Only the "onscreen" widget should have built expect(counter1.count, equals(1)); expect(counter2.count, equals(0)); // Lay out the "offscreen" in a separate tree tree.pumpWidget(TriggerableWidget(trigger: trigger2, counter: counter2)); // Now both widgets should have built expect(counter1.count, equals(1)); expect(counter2.count, equals(1)); // Mark both as needing layout trigger1.fire(); trigger2.fire(); // Marking as needing layout shouldn't immediately build anything expect(counter1.count, equals(1)); expect(counter2.count, equals(1)); // Pump the "onscreen" layout await tester.pump(); // Only the "onscreen" widget should have rebuilt expect(counter1.count, equals(2)); expect(counter2.count, equals(1)); // Pump the "offscreen" layout tree.pumpFrame(); // Now both widgets should have rebuilt expect(counter1.count, equals(2)); expect(counter2.count, equals(2)); // Mark both as needing layout, again trigger1.fire(); trigger2.fire(); // Now pump the "offscreen" layout first tree.pumpFrame(); // Only the "offscreen" widget should have rebuilt expect(counter1.count, equals(2)); expect(counter2.count, equals(3)); // Pump the "onscreen" layout await tester.pump(); // Now both widgets should have rebuilt expect(counter1.count, equals(3)); expect(counter2.count, equals(3)); }); testWidgets('no crosstalk between focus nodes', (WidgetTester tester) async { final OffscreenWidgetTree tree = OffscreenWidgetTree(tester.view); final FocusNode onscreenFocus = FocusNode(); addTearDown(onscreenFocus.dispose); final FocusNode offscreenFocus = FocusNode(); addTearDown(offscreenFocus.dispose); await tester.pumpWidget( TestFocusable( focusNode: onscreenFocus, ), ); tree.pumpWidget( TestFocusable( focusNode: offscreenFocus, ), ); // Autofocus is delayed one frame. await tester.pump(); tree.pumpFrame(); expect(onscreenFocus.hasFocus, isTrue); expect(offscreenFocus.hasFocus, isTrue); }); testWidgets('able to tear down offscreen tree', (WidgetTester tester) async { final OffscreenWidgetTree tree = OffscreenWidgetTree(tester.view); final List<WidgetState> states = <WidgetState>[]; tree.pumpWidget(SizedBox(child: TestStates(states: states))); expect(states, <WidgetState>[WidgetState.initialized]); expect(tree.renderView.child, isNotNull); tree.pumpWidget(null); // The root node should be allowed to have no child. expect(states, <WidgetState>[WidgetState.initialized, WidgetState.disposed]); expect(tree.renderView.child, isNull); }); } enum WidgetState { initialized, disposed, } class TestStates extends StatefulWidget { const TestStates({super.key, required this.states}); final List<WidgetState> states; @override TestStatesState createState() => TestStatesState(); } class TestStatesState extends State<TestStates> { @override void initState() { super.initState(); widget.states.add(WidgetState.initialized); } @override void dispose() { widget.states.add(WidgetState.disposed); super.dispose(); } @override Widget build(BuildContext context) => Container(); }
flutter/packages/flutter/test/widgets/independent_widget_layout_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/independent_widget_layout_test.dart", "repo_id": "flutter", "token_count": 2827 }
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/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter/src/widgets/basic.dart'; import 'package:flutter/src/widgets/framework.dart'; import 'package:flutter/src/widgets/layout_builder.dart'; import 'package:flutter/src/widgets/media_query.dart'; import 'package:flutter/src/widgets/scroll_view.dart'; import 'package:flutter/src/widgets/sliver_layout_builder.dart'; import 'package:flutter_test/flutter_test.dart'; class Wrapper extends StatelessWidget { const Wrapper({ super.key, required this.child, }); final Widget child; @override Widget build(BuildContext context) => child; } void main() { testWidgets('Moving a global key from another LayoutBuilder at layout time', (WidgetTester tester) async { final GlobalKey victimKey = GlobalKey(); await tester.pumpWidget(Row( textDirection: TextDirection.ltr, children: <Widget>[ Wrapper( child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { return const SizedBox(); }), ), Wrapper( child: Wrapper( child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { return Wrapper( child: SizedBox(key: victimKey), ); }), ), ), ], )); await tester.pumpWidget(Row( textDirection: TextDirection.ltr, children: <Widget>[ Wrapper( child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { return Wrapper( child: SizedBox(key: victimKey), ); }), ), Wrapper( child: Wrapper( child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { return const SizedBox(); }), ), ), ], )); expect(tester.takeException(), null); }); testWidgets('Moving a global key from another SliverLayoutBuilder at layout time', (WidgetTester tester) async { final GlobalKey victimKey1 = GlobalKey(); final GlobalKey victimKey2 = GlobalKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { return SliverPadding(key: victimKey1, padding: const EdgeInsets.fromLTRB(1, 2, 3, 4)); }, ), SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { return SliverPadding(key: victimKey2, padding: const EdgeInsets.fromLTRB(5, 7, 11, 13)); }, ), SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { return const SliverPadding(padding: EdgeInsets.fromLTRB(5, 7, 11, 13)); }, ), ], ), ), ); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { return SliverPadding(key: victimKey2, padding: const EdgeInsets.fromLTRB(1, 2, 3, 4)); }, ), SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { return const SliverPadding(padding: EdgeInsets.fromLTRB(5, 7, 11, 13)); }, ), SliverLayoutBuilder( builder: (BuildContext context, SliverConstraints constraint) { return SliverPadding(key: victimKey1, padding: const EdgeInsets.fromLTRB(5, 7, 11, 13)); }, ), ], ), ), ); expect(tester.takeException(), null); }); testWidgets('LayoutBuilder does not layout twice', (WidgetTester tester) async { // This widget marks itself dirty when the closest MediaQuery changes. final _LayoutCount widget = _LayoutCount(); late StateSetter setState; bool updated = false; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: StatefulBuilder( builder: (BuildContext context, StateSetter setter) { setState = setter; return MediaQuery( data: updated ? const MediaQueryData(platformBrightness: Brightness.dark) : const MediaQueryData(), child: LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { return Center( child: SizedBox.square( dimension: 20, child: Center( child: SizedBox.square( dimension: updated ? 10 : 20, child: widget, ), ), ), ); }, ), ); } ), ), ); assert(widget._renderObject.layoutCount == 1); setState(() { updated = true; }); await tester.pump(); expect(widget._renderObject.layoutCount, 2); }); } class _LayoutCount extends LeafRenderObjectWidget { late final _RenderLayoutCount _renderObject; @override RenderObject createRenderObject(BuildContext context) { return _renderObject = _RenderLayoutCount(MediaQuery.of(context)); } @override void updateRenderObject(BuildContext context, _RenderLayoutCount renderObject) { renderObject.mediaQuery = MediaQuery.of(context); } } class _RenderLayoutCount extends RenderProxyBox { _RenderLayoutCount(this._mediaQuery); int layoutCount = 0; MediaQueryData get mediaQuery => _mediaQuery; MediaQueryData _mediaQuery; set mediaQuery(MediaQueryData newValue) { if (newValue != _mediaQuery) { _mediaQuery = newValue; markNeedsLayout(); } } @override bool get sizedByParent => true; @override void performLayout() { layoutCount += 1; } }
flutter/packages/flutter/test/widgets/layout_builder_mutations_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/layout_builder_mutations_test.dart", "repo_id": "flutter", "token_count": 2891 }
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 'dart:math' as math; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'gesture_utils.dart'; void main() { testWidgets('Events bubble up the tree', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( Listener( onPointerDown: (_) { log.add('top'); }, child: Listener( onPointerDown: (_) { log.add('middle'); }, child: DecoratedBox( decoration: const BoxDecoration(), child: Listener( onPointerDown: (_) { log.add('bottom'); }, child: const Text('X', textDirection: TextDirection.ltr), ), ), ), ), ); await tester.tap(find.text('X')); expect(log, equals(<String>[ 'bottom', 'middle', 'top', ])); }); testWidgets('Detects hover events from touch devices', (WidgetTester tester) async { final List<String> log = <String>[]; await tester.pumpWidget( Center( child: SizedBox( width: 300, height: 300, child: Listener( onPointerHover: (_) { log.add('bottom'); }, child: const Text('X', textDirection: TextDirection.ltr), ), ), ), ); final TestGesture gesture = await tester.createGesture(); await gesture.addPointer(); await gesture.moveTo(tester.getCenter(find.byType(Listener))); expect(log, equals(<String>[ 'bottom', ])); }); group('transformed events', () { testWidgets('simple offset for touch/signal', (WidgetTester tester) async { final List<PointerEvent> events = <PointerEvent>[]; final Key key = UniqueKey(); await tester.pumpWidget( Center( child: Listener( onPointerDown: (PointerDownEvent event) { events.add(event); }, onPointerUp: (PointerUpEvent event) { events.add(event); }, onPointerMove: (PointerMoveEvent event) { events.add(event); }, onPointerSignal: (PointerSignalEvent event) { events.add(event); }, child: Container( key: key, color: Colors.red, height: 100, width: 100, ), ), ), ); const Offset moved = Offset(20, 30); final Offset center = tester.getCenter(find.byKey(key)); final Offset topLeft = tester.getTopLeft(find.byKey(key)); final TestGesture gesture = await tester.startGesture(center); await gesture.moveBy(moved); await gesture.up(); expect(events, hasLength(3)); final PointerDownEvent down = events[0] as PointerDownEvent; final PointerMoveEvent move = events[1] as PointerMoveEvent; final PointerUpEvent up = events[2] as PointerUpEvent; final Matrix4 expectedTransform = Matrix4.translationValues(-topLeft.dx, -topLeft.dy, 0); expect(center, isNot(const Offset(50, 50))); expect(down.localPosition, const Offset(50, 50)); expect(down.position, center); expect(down.delta, Offset.zero); expect(down.localDelta, Offset.zero); expect(down.transform, expectedTransform); expect(move.localPosition, const Offset(50, 50) + moved); expect(move.position, center + moved); expect(move.delta, moved); expect(move.localDelta, moved); expect(move.transform, expectedTransform); expect(up.localPosition, const Offset(50, 50) + moved); expect(up.position, center + moved); expect(up.delta, Offset.zero); expect(up.localDelta, Offset.zero); expect(up.transform, expectedTransform); events.clear(); await scrollAt(center, tester); expect(events.single.localPosition, const Offset(50, 50)); expect(events.single.position, center); expect(events.single.delta, Offset.zero); expect(events.single.localDelta, Offset.zero); expect(events.single.transform, expectedTransform); }); testWidgets('scaled for touch/signal', (WidgetTester tester) async { final List<PointerEvent> events = <PointerEvent>[]; final Key key = UniqueKey(); const double scaleFactor = 2; await tester.pumpWidget( Align( alignment: Alignment.topLeft, child: Transform( transform: Matrix4.identity()..scale(scaleFactor), child: Listener( onPointerDown: (PointerDownEvent event) { events.add(event); }, onPointerUp: (PointerUpEvent event) { events.add(event); }, onPointerMove: (PointerMoveEvent event) { events.add(event); }, onPointerSignal: (PointerSignalEvent event) { events.add(event); }, child: Container( key: key, color: Colors.red, height: 100, width: 100, ), ), ), ), ); const Offset moved = Offset(20, 30); final Offset center = tester.getCenter(find.byKey(key)); final TestGesture gesture = await tester.startGesture(center); await gesture.moveBy(moved); await gesture.up(); expect(events, hasLength(3)); final PointerDownEvent down = events[0] as PointerDownEvent; final PointerMoveEvent move = events[1] as PointerMoveEvent; final PointerUpEvent up = events[2] as PointerUpEvent; final Matrix4 expectedTransform = Matrix4.identity() ..scale(1 / scaleFactor, 1 / scaleFactor, 1.0); expect(center, isNot(const Offset(50, 50))); expect(down.localPosition, const Offset(50, 50)); expect(down.position, center); expect(down.delta, Offset.zero); expect(down.localDelta, Offset.zero); expect(down.transform, expectedTransform); expect(move.localPosition, const Offset(50, 50) + moved / scaleFactor); expect(move.position, center + moved); expect(move.delta, moved); expect(move.localDelta, moved / scaleFactor); expect(move.transform, expectedTransform); expect(up.localPosition, const Offset(50, 50) + moved / scaleFactor); expect(up.position, center + moved); expect(up.delta, Offset.zero); expect(up.localDelta, Offset.zero); expect(up.transform, expectedTransform); events.clear(); await scrollAt(center, tester); expect(events.single.localPosition, const Offset(50, 50)); expect(events.single.position, center); expect(events.single.delta, Offset.zero); expect(events.single.localDelta, Offset.zero); expect(events.single.transform, expectedTransform); }); testWidgets('scaled and offset for touch/signal', (WidgetTester tester) async { final List<PointerEvent> events = <PointerEvent>[]; final Key key = UniqueKey(); const double scaleFactor = 2; await tester.pumpWidget( Center( child: Transform( transform: Matrix4.identity()..scale(scaleFactor), child: Listener( onPointerDown: (PointerDownEvent event) { events.add(event); }, onPointerUp: (PointerUpEvent event) { events.add(event); }, onPointerMove: (PointerMoveEvent event) { events.add(event); }, onPointerSignal: (PointerSignalEvent event) { events.add(event); }, child: Container( key: key, color: Colors.red, height: 100, width: 100, ), ), ), ), ); const Offset moved = Offset(20, 30); final Offset center = tester.getCenter(find.byKey(key)); final Offset topLeft = tester.getTopLeft(find.byKey(key)); final TestGesture gesture = await tester.startGesture(center); await gesture.moveBy(moved); await gesture.up(); expect(events, hasLength(3)); final PointerDownEvent down = events[0] as PointerDownEvent; final PointerMoveEvent move = events[1] as PointerMoveEvent; final PointerUpEvent up = events[2] as PointerUpEvent; final Matrix4 expectedTransform = Matrix4.identity() ..scale(1 / scaleFactor, 1 / scaleFactor, 1.0) ..translate(-topLeft.dx, -topLeft.dy); expect(center, isNot(const Offset(50, 50))); expect(down.localPosition, const Offset(50, 50)); expect(down.position, center); expect(down.delta, Offset.zero); expect(down.localDelta, Offset.zero); expect(down.transform, expectedTransform); expect(move.localPosition, const Offset(50, 50) + moved / scaleFactor); expect(move.position, center + moved); expect(move.delta, moved); expect(move.localDelta, moved / scaleFactor); expect(move.transform, expectedTransform); expect(up.localPosition, const Offset(50, 50) + moved / scaleFactor); expect(up.position, center + moved); expect(up.delta, Offset.zero); expect(up.localDelta, Offset.zero); expect(up.transform, expectedTransform); events.clear(); await scrollAt(center, tester); expect(events.single.localPosition, const Offset(50, 50)); expect(events.single.position, center); expect(events.single.delta, Offset.zero); expect(events.single.localDelta, Offset.zero); expect(events.single.transform, expectedTransform); }); testWidgets('rotated for touch/signal', (WidgetTester tester) async { final List<PointerEvent> events = <PointerEvent>[]; final Key key = UniqueKey(); await tester.pumpWidget( Center( child: Transform( transform: Matrix4.identity() ..rotateZ(math.pi / 2), // 90 degrees clockwise around Container origin child: Listener( onPointerDown: (PointerDownEvent event) { events.add(event); }, onPointerUp: (PointerUpEvent event) { events.add(event); }, onPointerMove: (PointerMoveEvent event) { events.add(event); }, onPointerSignal: (PointerSignalEvent event) { events.add(event); }, child: Container( key: key, color: Colors.red, height: 100, width: 100, ), ), ), ), ); const Offset moved = Offset(20, 30); final Offset downPosition = tester.getCenter(find.byKey(key)) + const Offset(10, 5); final TestGesture gesture = await tester.startGesture(downPosition); await gesture.moveBy(moved); await gesture.up(); expect(events, hasLength(3)); final PointerDownEvent down = events[0] as PointerDownEvent; final PointerMoveEvent move = events[1] as PointerMoveEvent; final PointerUpEvent up = events[2] as PointerUpEvent; const Offset offset = Offset((800 - 100) / 2, (600 - 100) / 2); final Matrix4 expectedTransform = Matrix4.identity() ..rotateZ(-math.pi / 2) ..translate(-offset.dx, -offset.dy); final Offset localDownPosition = const Offset(50, 50) + const Offset(5, -10); expect(down.localPosition, within(distance: 0.001, from: localDownPosition)); expect(down.position, downPosition); expect(down.delta, Offset.zero); expect(down.localDelta, Offset.zero); expect(down.transform, expectedTransform); const Offset localDelta = Offset(30, -20); expect(move.localPosition, within(distance: 0.001, from: localDownPosition + localDelta)); expect(move.position, downPosition + moved); expect(move.delta, moved); expect(move.localDelta, localDelta); expect(move.transform, expectedTransform); expect(up.localPosition, within(distance: 0.001, from: localDownPosition + localDelta)); expect(up.position, downPosition + moved); expect(up.delta, Offset.zero); expect(up.localDelta, Offset.zero); expect(up.transform, expectedTransform); events.clear(); await scrollAt(downPosition, tester); expect(events.single.localPosition, within(distance: 0.001, from: localDownPosition)); expect(events.single.position, downPosition); expect(events.single.delta, Offset.zero); expect(events.single.localDelta, Offset.zero); expect(events.single.transform, expectedTransform); }); }); testWidgets("RenderPointerListener's debugFillProperties when default", (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final RenderPointerListener renderListener = RenderPointerListener(); addTearDown(renderListener.dispose); renderListener.debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[ 'parentData: MISSING', 'constraints: MISSING', 'size: MISSING', 'behavior: deferToChild', 'listeners: <none>', ]); }); testWidgets("RenderPointerListener's debugFillProperties when full", (WidgetTester tester) async { final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); final RenderErrorBox renderErrorBox = RenderErrorBox(); addTearDown(() => renderErrorBox.dispose()); final RenderPointerListener renderListener = RenderPointerListener( onPointerDown: (PointerDownEvent event) {}, onPointerUp: (PointerUpEvent event) {}, onPointerMove: (PointerMoveEvent event) {}, onPointerHover: (PointerHoverEvent event) {}, onPointerCancel: (PointerCancelEvent event) {}, onPointerSignal: (PointerSignalEvent event) {}, behavior: HitTestBehavior.opaque, child: renderErrorBox, ); addTearDown(renderListener.dispose); renderListener.debugFillProperties(builder); final List<String> description = builder.properties .where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info)) .map((DiagnosticsNode node) => node.toString()) .toList(); expect(description, <String>[ 'parentData: MISSING', 'constraints: MISSING', 'size: MISSING', 'behavior: opaque', 'listeners: down, move, up, hover, cancel, signal', ]); }); }
flutter/packages/flutter/test/widgets/listener_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/listener_test.dart", "repo_id": "flutter", "token_count": 6493 }
743
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Render and element tree stay in sync when keyed children move around', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/48855. await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Column( children: <Widget>[ Text('0', key: ValueKey<int>(0)), Text('1', key: ValueKey<int>(1)), Text('2', key: ValueKey<int>(2)), Text('3', key: ValueKey<int>(3)), Text('4', key: ValueKey<int>(4)), Text('5', key: ValueKey<int>(5)), Text('6', key: ValueKey<int>(6)), Text('7', key: ValueKey<int>(7)), Text('8', key: ValueKey<int>(8)), ], ), ), ); expect( _getChildOrder(tester.renderObject<RenderFlex>(find.byType(Column))), <String>['0', '1', '2', '3', '4', '5', '6', '7', '8'], ); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: Column( children: <Widget>[ Text('0', key: ValueKey<int>(0)), Text('6', key: ValueKey<int>(6)), Text('7', key: ValueKey<int>(7)), Text('8', key: ValueKey<int>(8)), Text('1', key: ValueKey<int>(1)), Text('2', key: ValueKey<int>(2)), Text('3', key: ValueKey<int>(3)), Text('4', key: ValueKey<int>(4)), Text('5', key: ValueKey<int>(5)), ], ), ), ); expect( _getChildOrder(tester.renderObject<RenderFlex>(find.byType(Column))), <String>['0', '6', '7', '8', '1', '2', '3', '4', '5'], ); }); testWidgets('Building a new MultiChildRenderObjectElement with children having duplicated keys throws', (WidgetTester tester) async { const ValueKey<int> duplicatedKey = ValueKey<int>(1); await tester.pumpWidget(const Column( children: <Widget>[ Text('Text 1', textDirection: TextDirection.ltr, key: duplicatedKey), Text('Text 2', textDirection: TextDirection.ltr, key: duplicatedKey), ], )); expect( tester.takeException(), isA<FlutterError>().having( (FlutterError error) => error.message, 'error.message', startsWith('Duplicate keys found.'), ), ); }); testWidgets('Updating a MultiChildRenderObjectElement to have children with duplicated keys throws', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/81541 const ValueKey<int> key1 = ValueKey<int>(1); const ValueKey<int> key2 = ValueKey<int>(2); Future<void> buildWithKey(Key key) { return tester.pumpWidget(Column( children: <Widget>[ const Text('Text 1', textDirection: TextDirection.ltr, key: key1), Text('Text 2', textDirection: TextDirection.ltr, key: key), ], )); } // Initial build with two different keys. await buildWithKey(key2); expect(tester.takeException(), isNull); // Subsequent build with duplicated keys. await buildWithKey(key1); expect( tester.takeException(), isA<FlutterError>().having( (FlutterError error) => error.message, 'error.message', startsWith('Duplicate keys found.'), ), ); }); } // Do not use tester.renderObjectList(find.byType(RenderParagraph). That returns // the RenderObjects in the order of their associated RenderObjectWidgets. The // point of this test is to assert the children order in the render tree, though. List<String> _getChildOrder(RenderFlex flex) { final List<String> childOrder = <String>[]; flex.visitChildren((RenderObject child) { childOrder.add(((child as RenderParagraph).text as TextSpan).text!); }); return childOrder; }
flutter/packages/flutter/test/widgets/multichildobject_with_keys_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/multichildobject_with_keys_test.dart", "repo_id": "flutter", "token_count": 1739 }
744
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math' as math; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; final Matcher doesNotOverscroll = isNot(paints..circle()); Future<void> slowDrag(WidgetTester tester, Offset start, Offset offset) async { final TestGesture gesture = await tester.startGesture(start); for (int index = 0; index < 10; index += 1) { await gesture.moveBy(offset); await tester.pump(const Duration(milliseconds: 20)); } await gesture.up(); } void main() { testWidgets('Overscroll indicator color', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 2000.0)), ], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); expect(painter, doesNotOverscroll); // the scroll gesture from tester.scroll happens in zero time, so nothing should appear: await tester.drag(find.byType(Scrollable), const Offset(0.0, 100.0)); expect(painter, doesNotOverscroll); await tester.pump(); // allow the ticker to register itself expect(painter, doesNotOverscroll); await tester.pump(const Duration(milliseconds: 100)); // animate expect(painter, doesNotOverscroll); final TestGesture gesture = await tester.startGesture(const Offset(200.0, 200.0)); await tester.pump(const Duration(milliseconds: 100)); // animate expect(painter, doesNotOverscroll); await gesture.up(); expect(painter, doesNotOverscroll); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); expect(painter, paints..circle(color: const Color(0x0DFFFFFF))); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); }); testWidgets('Nested scrollable', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GlowingOverscrollIndicator( axisDirection: AxisDirection.down, color: const Color(0x0DFFFFFF), notificationPredicate: (ScrollNotification notification) => notification.depth == 1, child: const SingleChildScrollView( scrollDirection: Axis.horizontal, child: SizedBox( width: 600.0, child: CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 2000.0)), ], ), ), ), ), ), ); final RenderObject outerPainter = tester.renderObject(find.byType(CustomPaint).first); final RenderObject innerPainter = tester.renderObject(find.byType(CustomPaint).last); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); expect(outerPainter, paints..circle()); expect(innerPainter, paints..circle()); }); testWidgets('Overscroll indicator changes side when you drag on the other side', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 2000.0)), ], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(400.0, 200.0), const Offset(0.0, 10.0)); expect(painter, paints..circle(x: 400.0)); await slowDrag(tester, const Offset(100.0, 200.0), const Offset(0.0, 10.0)); expect(painter, paints..something((Symbol method, List<dynamic> arguments) { if (method != #drawCircle) { return false; } final Offset center = arguments[0] as Offset; if (center.dx < 400.0) { return true; } throw 'Dragging on left hand side did not overscroll on left hand side.'; })); await slowDrag(tester, const Offset(700.0, 200.0), const Offset(0.0, 10.0)); expect(painter, paints..something((Symbol method, List<dynamic> arguments) { if (method != #drawCircle) { return false; } final Offset center = arguments[0] as Offset; if (center.dx > 400.0) { return true; } throw 'Dragging on right hand side did not overscroll on right hand side.'; })); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); }); testWidgets('Overscroll indicator changes side when you shift sides', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 2000.0)), ], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); final TestGesture gesture = await tester.startGesture(const Offset(300.0, 200.0)); await gesture.moveBy(const Offset(0.0, 10.0)); await tester.pump(const Duration(milliseconds: 20)); double oldX = 0.0; for (int index = 0; index < 10; index += 1) { await gesture.moveBy(const Offset(50.0, 50.0)); await tester.pump(const Duration(milliseconds: 20)); expect(painter, paints..something((Symbol method, List<dynamic> arguments) { if (method != #drawCircle) { return false; } final Offset center = arguments[0] as Offset; if (center.dx <= oldX) { throw 'Sliding to the right did not make the center of the radius slide to the right.'; } oldX = center.dx; return true; })); } await gesture.up(); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); }); group("Flipping direction of scrollable doesn't change overscroll behavior", () { testWidgets('down', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( physics: AlwaysScrollableScrollPhysics(), slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 20.0)), ], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); expect(painter, paints..save()..circle()..restore()..save()..scale(y: -1.0)..restore()..restore()); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); }); testWidgets('up', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( reverse: true, physics: AlwaysScrollableScrollPhysics(), slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 20.0)), ], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); expect(painter, paints..save()..scale(y: -1.0)..restore()..save()..circle()..restore()..restore()); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); }); }); testWidgets('Overscroll in both directions', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( physics: AlwaysScrollableScrollPhysics(), slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 20.0)), ], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); expect(painter, paints..circle()); expect(painter, isNot(paints..circle()..circle())); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, -5.0)); expect(painter, paints..circle()..circle()); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); }); testWidgets('Overscroll ignored from alternate axis', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: ScrollConfiguration( behavior: TestScrollBehaviorNoGlow(), child: GlowingOverscrollIndicator( axisDirection: AxisDirection.right, color: Color(0xFF0000FF), child: CustomScrollView( physics: AlwaysScrollableScrollPhysics(), slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 20.0)), ], ), ), ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); expect(painter, doesNotOverscroll); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, -5.0)); expect(painter, doesNotOverscroll); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); }); testWidgets('Overscroll horizontally', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: CustomScrollView( scrollDirection: Axis.horizontal, physics: AlwaysScrollableScrollPhysics(), slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 20.0)), ], ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(5.0, 0.0)); expect(painter, paints..rotate(angle: math.pi / 2.0)..circle()..saveRestore()); expect(painter, isNot(paints..circle()..circle())); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(-5.0, 0.0)); expect( painter, paints ..rotate(angle: math.pi / 2.0) ..circle() ..rotate(angle: math.pi / 2.0) ..circle(), ); await tester.pumpAndSettle(const Duration(seconds: 1)); expect(painter, doesNotOverscroll); }); testWidgets('Nested overscrolls do not throw exceptions', (WidgetTester tester) async { await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView( children: <Widget>[ ListView( children: <Widget>[ Container( width: 2000.0, height: 2000.0, color: const Color(0xFF00FF00), ), ], ), ], ), )); await tester.dragFrom(const Offset(100.0, 100.0), const Offset(0.0, 2000.0)); await tester.pumpAndSettle(); }); testWidgets('Changing settings', (WidgetTester tester) async { RenderObject painter; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: ScrollConfiguration( behavior: TestScrollBehavior1(), child: CustomScrollView( scrollDirection: Axis.horizontal, physics: AlwaysScrollableScrollPhysics(), reverse: true, slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 20.0)), ], ), ), ), ); painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(5.0, 0.0)); expect(painter, paints..rotate(angle: math.pi / 2.0)..circle(color: const Color(0x0A00FF00))); expect(painter, isNot(paints..circle()..circle())); await tester.pumpAndSettle(const Duration(seconds: 1)); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: ScrollConfiguration( behavior: TestScrollBehavior2(), child: CustomScrollView( scrollDirection: Axis.horizontal, physics: AlwaysScrollableScrollPhysics(), slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 20.0)), ], ), ), ), ); painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(5.0, 0.0)); expect(painter, paints..rotate(angle: math.pi / 2.0)..circle(color: const Color(0x0A0000FF))..saveRestore()); expect(painter, isNot(paints..circle()..circle())); }); testWidgets('CustomScrollView overscroll indicator works if there is sliver before center', (WidgetTester tester) async { final Key centerKey = UniqueKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ScrollConfiguration( behavior: const TestScrollBehavior2(), child: CustomScrollView( center: centerKey, physics: const AlwaysScrollableScrollPhysics(), slivers: <Widget>[ SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('First sliver $index'), childCount: 2, ), ), SliverList( key: centerKey, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('Second sliver $index'), childCount: 5, ), ), ], ), ), ), ); expect(find.text('First sliver 1'), findsNothing); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 300.0)); expect(find.text('First sliver 1'), findsOneWidget); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); // The scroll offset and paint extend should cancel out each other. expect(painter, paints..save()..translate(y: 0.0)..scale()..circle()); }); testWidgets('CustomScrollView overscroll indicator works well with [CustomScrollView.center] and [OverscrollIndicatorNotification.paintOffset]', (WidgetTester tester) async { final Key centerKey = UniqueKey(); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ScrollConfiguration( behavior: const TestScrollBehavior2(), child: NotificationListener<OverscrollIndicatorNotification>( onNotification: (OverscrollIndicatorNotification notification) { if (notification.leading) { notification.paintOffset = 50.0; } return false; }, child: CustomScrollView( center: centerKey, physics: const AlwaysScrollableScrollPhysics(), slivers: <Widget>[ SliverList( delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('First sliver $index'), childCount: 2, ), ), SliverList( key: centerKey, delegate: SliverChildBuilderDelegate( (BuildContext context, int index) => Text('Second sliver $index'), childCount: 5, ), ), ], ), ), ), ), ); expect(find.text('First sliver 1'), findsNothing); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); // offset will be magnified ten times expect(find.text('First sliver 1'), findsOneWidget); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting. expect(painter, paints..save()..translate(y: 50.0)..scale()..circle()); }); testWidgets('The OverscrollIndicator should not overflow the scrollable view edge', (WidgetTester tester) async { // Regressing test for https://github.com/flutter/flutter/issues/64149 await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<OverscrollIndicatorNotification>( onNotification: (OverscrollIndicatorNotification notification) { notification.paintOffset = 50.0; // both the leading and trailing indicator have a 50.0 pixels offset. return false; }, child: const CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 2000.0)), ], ), ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); expect(painter, paints..save()..translate(y: 50.0)..scale()..circle()); // Reverse scroll (30 pixels), and the offset < notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, -30.0)); await tester.pump(); // The OverscrollIndicator should move with the CustomScrollView. expect(painter, paints..save()..translate(y: 50.0 - 30.0)..scale()..circle()); // Reverse scroll (30+20 pixels) and offset == notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, -20.0)); await tester.pump(); expect(painter, paints..save()..translate(y: 50.0 - 50.0)..scale()..circle()); // Reverse scroll (30+20+10 pixels) and offset > notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, -10.0)); await tester.pump(); // The OverscrollIndicator should not overflow the CustomScrollView's edge. expect(painter, paints..save()..translate(y: 50.0 - 50.0)..scale()..circle()); await tester.pumpAndSettle(); // Finish the leading indicator. // trigger the trailing indicator await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, -200.0)); expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0)..scale()..circle()); // Reverse scroll (30 pixels), and the offset < notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, 30.0)); await tester.pump(); // The OverscrollIndicator should move with the CustomScrollView. expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0 - 30.0)..scale()..circle()); // Reverse scroll (30+20 pixels) and offset == notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, 20.0)); await tester.pump(); expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0 - 50.0)..scale()..circle()); // Reverse scroll (30+20+10 pixels) and offset > notification.paintOffset. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, 10.0)); await tester.pump(); // The OverscrollIndicator should not overflow the CustomScrollView's edge. expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0 - 50.0)..scale()..circle()); }); group('[OverscrollIndicatorNotification.paintOffset] test', () { testWidgets('Leading', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<OverscrollIndicatorNotification>( onNotification: (OverscrollIndicatorNotification notification) { if (notification.leading) { notification.paintOffset = 50.0; } return false; }, child: const CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 2000.0)), ], ), ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, 5.0)); // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting. expect(painter, paints..save()..translate(y: 50.0)..scale()..circle()); // Reverse scroll direction. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, -30.0)); await tester.pump(); // The OverscrollIndicator should move with the CustomScrollView. expect(painter, paints..save()..translate(y: 50.0 - 30.0)..scale()..circle()); }); testWidgets('Trailing', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: NotificationListener<OverscrollIndicatorNotification>( onNotification: (OverscrollIndicatorNotification notification) { if (!notification.leading) { notification.paintOffset = 50.0; } return false; }, child: const CustomScrollView( slivers: <Widget>[ SliverToBoxAdapter(child: SizedBox(height: 2000.0)), ], ), ), ), ); final RenderObject painter = tester.renderObject(find.byType(CustomPaint)); await tester.dragFrom(const Offset(200.0, 200.0), const Offset(200.0, -10000.0)); await tester.pump(); await slowDrag(tester, const Offset(200.0, 200.0), const Offset(0.0, -5.0)); // The OverscrollIndicator should respect the [OverscrollIndicatorNotification.paintOffset] setting. expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0)..scale()..circle()); // Reverse scroll direction. await tester.dragFrom(const Offset(200.0, 200.0), const Offset(0.0, 30.0)); await tester.pump(); // The OverscrollIndicator should move with the CustomScrollView. expect(painter, paints..scale(y: -1.0)..save()..translate(y: 50.0 - 30.0)..scale()..circle()); }); }); } class TestScrollBehavior1 extends ScrollBehavior { const TestScrollBehavior1(); @override Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) { return GlowingOverscrollIndicator( axisDirection: details.direction, color: const Color(0xFF00FF00), child: child, ); } } class TestScrollBehavior2 extends ScrollBehavior { const TestScrollBehavior2(); @override Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) { return GlowingOverscrollIndicator( axisDirection: details.direction, color: const Color(0xFF0000FF), child: child, ); } } class TestScrollBehaviorNoGlow extends ScrollBehavior { const TestScrollBehaviorNoGlow(); @override Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) { return child; } }
flutter/packages/flutter/test/widgets/overscroll_indicator_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/overscroll_indicator_test.dart", "repo_id": "flutter", "token_count": 9997 }
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/foundation.dart'; import 'package:flutter/services.dart'; const String fakeAction1Id = 'fakeActivity.fakeAction1'; const String fakeAction2Id = 'fakeActivity.fakeAction2'; const String fakeAction1Label = 'Action1'; const String fakeAction2Label = 'Action2'; class MockProcessTextHandler { String? lastCalledActionId; String? lastTextToProcess; Future<Object?> handleMethodCall(MethodCall call) async { if (call.method == 'ProcessText.queryTextActions') { // Simulate that only the Android engine will return a non-null result. if (defaultTargetPlatform == TargetPlatform.android) { return <String, String>{ fakeAction1Id: fakeAction1Label, fakeAction2Id: fakeAction2Label, }; } } if (call.method == 'ProcessText.processTextAction') { final List<dynamic> args = call.arguments as List<dynamic>; final String actionId = args[0] as String; final String textToProcess = args[1] as String; lastCalledActionId = actionId; lastTextToProcess = textToProcess; if (actionId == fakeAction1Id) { // Simulates an action that returns a transformed text. return '$textToProcess!!!'; } // Simulates an action that failed or does not transform text. return null; } return null; } }
flutter/packages/flutter/test/widgets/process_text_utils.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/process_text_utils.dart", "repo_id": "flutter", "token_count": 520 }
746
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'restoration.dart'; void main() { final TestAutomatedTestWidgetsFlutterBinding binding = TestAutomatedTestWidgetsFlutterBinding(); setUp(() { binding._restorationManager = MockRestorationManager(); }); tearDown(() { binding._restorationManager.dispose(); }); testWidgets('does not inject root bucket if inside scope', (WidgetTester tester) async { final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); final Map<String, dynamic> rawData = <String, dynamic>{}; final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData); addTearDown(root.dispose); expect(rawData, isEmpty); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: UnmanagedRestorationScope( bucket: root, child: const RootRestorationScope( restorationId: 'root-child', child: BucketSpy( child: Text('Hello'), ), ), ), ), ); manager.doSerialization(); expect(binding.restorationManager.rootBucketAccessed, 0); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket!.restorationId, 'root-child'); expect((rawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), isTrue); expect(find.text('Hello'), findsOneWidget); }); testWidgets('waits for root bucket', (WidgetTester tester) async { final Completer<RestorationBucket> bucketCompleter = Completer<RestorationBucket>(); binding.restorationManager.rootBucket = bucketCompleter.future; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', child: BucketSpy( child: Text('Hello'), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 1); // Child rendering is delayed until root bucket is available. expect(find.text('Hello'), findsNothing); expect(binding.firstFrameIsDeferred, isTrue); // Complete the future. final Map<String, dynamic> rawData = <String, dynamic>{}; final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: rawData); addTearDown(root.dispose); bucketCompleter.complete(root); await tester.pump(const Duration(milliseconds: 100)); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); expect(binding.firstFrameIsDeferred, isFalse); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket!.restorationId, 'root-child'); expect((rawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), isTrue); }); testWidgets('no delay when root is available synchronously', (WidgetTester tester) async { final Map<String, dynamic> rawData = <String, dynamic>{}; final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: rawData); addTearDown(root.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(root); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', child: BucketSpy( child: Text('Hello'), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); expect(binding.firstFrameIsDeferred, isFalse); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket!.restorationId, 'root-child'); expect((rawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), isTrue); }); testWidgets('does not insert root when restoration id is null', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: null, child: BucketSpy( child: Text('Hello'), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 0); expect(find.text('Hello'), findsOneWidget); expect(binding.firstFrameIsDeferred, isFalse); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket, isNull); // Change restoration id to non-null. final Completer<RestorationBucket> bucketCompleter = Completer<RestorationBucket>(); binding.restorationManager.rootBucket = bucketCompleter.future; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', child: BucketSpy( child: Text('Hello'), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); expect(state.bucket, isNull); // root bucket future has not completed yet. // Complete the future. final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: <String, dynamic>{}); addTearDown(root.dispose); bucketCompleter.complete(root); await tester.pump(const Duration(milliseconds: 100)); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); expect(state.bucket!.restorationId, 'root-child'); // Change ID back to null. await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: null, child: BucketSpy( child: Text('Hello'), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); expect(state.bucket, isNull); }); testWidgets('injects root bucket when moved out of scope', (WidgetTester tester) async { final Key rootScopeKey = GlobalKey(); final MockRestorationManager manager = MockRestorationManager(); addTearDown(manager.dispose); final Map<String, dynamic> inScopeRawData = <String, dynamic>{}; final RestorationBucket inScopeRootBucket = RestorationBucket.root(manager: manager, rawData: inScopeRawData); addTearDown(inScopeRootBucket.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: UnmanagedRestorationScope( bucket: inScopeRootBucket, child: RootRestorationScope( key: rootScopeKey, restorationId: 'root-child', child: const BucketSpy( child: Text('Hello'), ), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 0); expect(find.text('Hello'), findsOneWidget); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket!.restorationId, 'root-child'); expect((inScopeRawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), isTrue); // Move out of scope. final Completer<RestorationBucket> bucketCompleter = Completer<RestorationBucket>(); binding.restorationManager.rootBucket = bucketCompleter.future; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: RootRestorationScope( key: rootScopeKey, restorationId: 'root-child', child: const BucketSpy( child: Text('Hello'), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); final Map<String, dynamic> outOfScopeRawData = <String, dynamic>{}; final RestorationBucket outOfScopeRootBucket = RestorationBucket.root(manager: binding.restorationManager, rawData: outOfScopeRawData); addTearDown(outOfScopeRootBucket.dispose); bucketCompleter.complete(outOfScopeRootBucket); await tester.pump(const Duration(milliseconds: 100)); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); expect(state.bucket!.restorationId, 'root-child'); expect((outOfScopeRawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), isTrue); expect(inScopeRawData, isEmpty); // Move into scope. await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: UnmanagedRestorationScope( bucket: inScopeRootBucket, child: RootRestorationScope( key: rootScopeKey, restorationId: 'root-child', child: const BucketSpy( child: Text('Hello'), ), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); expect(state.bucket!.restorationId, 'root-child'); expect(outOfScopeRawData, isEmpty); expect((inScopeRawData[childrenMapKey] as Map<Object?, Object?>).containsKey('root-child'), isTrue); }); testWidgets('injects new root when old one is decommissioned', (WidgetTester tester) async { final Map<String, dynamic> firstRawData = <String, dynamic>{}; final RestorationBucket firstRoot = RestorationBucket.root(manager: binding.restorationManager, rawData: firstRawData); addTearDown(firstRoot.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(firstRoot); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', child: BucketSpy( child: Text('Hello'), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); final BucketSpyState state = tester.state(find.byType(BucketSpy)); state.bucket!.write('foo', 42); expect((((firstRawData[childrenMapKey] as Map<Object?, Object?>)['root-child']! as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['foo'], 42); final RestorationBucket firstBucket = state.bucket!; // Replace with new root. final Map<String, dynamic> secondRawData = <String, dynamic>{ childrenMapKey: <String, dynamic>{ 'root-child': <String, dynamic>{ valuesMapKey: <String, dynamic>{ 'foo': 22, }, }, }, }; final RestorationBucket secondRoot = RestorationBucket.root(manager: binding.restorationManager, rawData: secondRawData); addTearDown(secondRoot.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(secondRoot); await tester.pump(); expect(state.bucket, isNot(same(firstBucket))); expect(state.bucket!.read<int>('foo'), 22); }); testWidgets('injects null when rootBucket is null', (WidgetTester tester) async { final Completer<RestorationBucket?> completer = Completer<RestorationBucket?>(); binding.restorationManager.rootBucket = completer.future; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', child: BucketSpy( child: Text('Hello'), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsNothing); completer.complete(); await tester.pump(const Duration(milliseconds: 100)); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket, isNull); final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: null); addTearDown(root.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(root); await tester.pump(); expect(binding.restorationManager.rootBucketAccessed, 2); expect(find.text('Hello'), findsOneWidget); expect(state.bucket, isNotNull); }); testWidgets('can switch to null', (WidgetTester tester) async { final RestorationBucket root = RestorationBucket.root(manager: binding.restorationManager, rawData: null); addTearDown(root.dispose); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket>(root); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: RootRestorationScope( restorationId: 'root-child', child: BucketSpy( child: Text('Hello'), ), ), ), ); expect(binding.restorationManager.rootBucketAccessed, 1); expect(find.text('Hello'), findsOneWidget); final BucketSpyState state = tester.state(find.byType(BucketSpy)); expect(state.bucket, isNotNull); binding.restorationManager.rootBucket = SynchronousFuture<RestorationBucket?>(null); await tester.pump(); expect(binding.restorationManager.rootBucketAccessed, 2); expect(find.text('Hello'), findsOneWidget); expect(state.bucket, isNull); }); } class TestAutomatedTestWidgetsFlutterBinding extends AutomatedTestWidgetsFlutterBinding { late MockRestorationManager _restorationManager; @override MockRestorationManager get restorationManager => _restorationManager; @override TestRestorationManager createRestorationManager() { return TestRestorationManager(); } int _deferred = 0; bool get firstFrameIsDeferred => _deferred > 0; @override void deferFirstFrame() { _deferred++; super.deferFirstFrame(); } @override void allowFirstFrame() { _deferred--; super.allowFirstFrame(); } }
flutter/packages/flutter/test/widgets/root_restoration_scope_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/root_restoration_scope_test.dart", "repo_id": "flutter", "token_count": 5447 }
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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Scroll flings twice in a row does not crash', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( children: <Widget>[ Container(height: 100000.0), ], ), ), ); final ScrollableState scrollable = tester.state<ScrollableState>(find.byType(Scrollable)); expect(scrollable.position.pixels, equals(0.0)); await tester.flingFrom(const Offset(200.0, 300.0), const Offset(0.0, -200.0), 500.0); await tester.pump(); await tester.pump(const Duration(seconds: 5)); expect(scrollable.position.pixels, greaterThan(0.0)); final double oldOffset = scrollable.position.pixels; await tester.flingFrom(const Offset(200.0, 300.0), const Offset(0.0, -200.0), 500.0); await tester.pump(); await tester.pump(const Duration(seconds: 5)); expect(scrollable.position.pixels, greaterThan(oldOffset)); }); }
flutter/packages/flutter/test/widgets/scroll_interaction_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/scroll_interaction_test.dart", "repo_id": "flutter", "token_count": 487 }
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/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { SemanticsTester semantics; setUp(() { debugResetSemanticsIdCounter(); }); testWidgets('scrollable exposes the correct semantic actions', (WidgetTester tester) async { semantics = SemanticsTester(tester); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView(children: List<Widget>.generate(80, (int i) => Text('$i'))), ), ); expect(semantics,includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp])); await flingUp(tester); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown])); await flingDown(tester, repetitions: 2); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp])); await flingUp(tester, repetitions: 5); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollDown])); await flingDown(tester); expect(semantics, includesNodeWith(actions: <SemanticsAction>[SemanticsAction.scrollUp, SemanticsAction.scrollDown])); semantics.dispose(); }); testWidgets('showOnScreen works in scrollable', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation const double kItemHeight = 40.0; final List<Widget> containers = List<Widget>.generate(80, (int i) => MergeSemantics( child: SizedBox( height: kItemHeight, child: Text('container $i', textDirection: TextDirection.ltr), ), )); final ScrollController scrollController = ScrollController( initialScrollOffset: kItemHeight / 2, ); addTearDown(scrollController.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( controller: scrollController, children: containers, ), ), ); expect(scrollController.offset, kItemHeight / 2); final int firstContainerId = tester.renderObject(find.byWidget(containers.first)).debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); await tester.pump(); await tester.pump(const Duration(seconds: 5)); expect(scrollController.offset, 0.0); semantics.dispose(); }); testWidgets('showOnScreen works with pinned app bar and sliver list', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation const double kItemHeight = 100.0; const double kExpandedAppBarHeight = 56.0; final List<Widget> containers = List<Widget>.generate(80, (int i) => MergeSemantics( child: SizedBox( height: kItemHeight, child: Text('container $i'), ), )); final ScrollController scrollController = ScrollController( initialScrollOffset: kItemHeight / 2, ); addTearDown(scrollController.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: MediaQuery( data: const MediaQueryData(), child: Scrollable( controller: scrollController, viewportBuilder: (BuildContext context, ViewportOffset offset) { return Viewport( offset: offset, slivers: <Widget>[ const SliverAppBar( pinned: true, expandedHeight: kExpandedAppBarHeight, flexibleSpace: FlexibleSpaceBar( title: Text('App Bar'), ), ), SliverList( delegate: SliverChildListDelegate(containers), ), ], ); }, ), ), ), )); expect(scrollController.offset, kItemHeight / 2); final int firstContainerId = tester.renderObject(find.byWidget(containers.first)).debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); await tester.pump(); await tester.pump(const Duration(seconds: 5)); expect(tester.getTopLeft(find.byWidget(containers.first)).dy, kExpandedAppBarHeight); semantics.dispose(); }); testWidgets('showOnScreen works with pinned app bar and individual slivers', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation const double kItemHeight = 100.0; const double kExpandedAppBarHeight = 256.0; final List<Widget> children = <Widget>[]; final List<Widget> slivers = List<Widget>.generate(30, (int i) { final Widget child = MergeSemantics( child: SizedBox( height: 72.0, child: Text('Item $i'), ), ); children.add(child); return SliverToBoxAdapter( child: child, ); }); final ScrollController scrollController = ScrollController( initialScrollOffset: 2.5 * kItemHeight, ); addTearDown(scrollController.dispose); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: Localizations( locale: const Locale('en', 'us'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultMaterialLocalizations.delegate, ], child: Scrollable( controller: scrollController, viewportBuilder: (BuildContext context, ViewportOffset offset) { return Viewport( offset: offset, slivers: <Widget>[ const SliverAppBar( pinned: true, expandedHeight: kExpandedAppBarHeight, flexibleSpace: FlexibleSpaceBar( title: Text('App Bar'), ), ), ...slivers, ], ); }, ), ), ), )); expect(scrollController.offset, 2.5 * kItemHeight); final int id0 = tester.renderObject(find.byWidget(children[0])).debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(id0, SemanticsAction.showOnScreen); await tester.pump(); await tester.pump(const Duration(seconds: 5)); expect(tester.getTopLeft(find.byWidget(children[0])).dy, kToolbarHeight); semantics.dispose(); }); testWidgets('correct scrollProgress', (WidgetTester tester) async { semantics = SemanticsTester(tester); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: ListView(children: List<Widget>.generate(80, (int i) => Text('$i'))), )); expect(semantics, includesNodeWith( scrollExtentMin: 0.0, scrollPosition: 0.0, scrollExtentMax: 520.0, actions: <SemanticsAction>[ SemanticsAction.scrollUp, ], )); await flingUp(tester); expect(semantics, includesNodeWith( scrollExtentMin: 0.0, scrollPosition: 394.3, scrollExtentMax: 520.0, actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], )); await flingUp(tester); expect(semantics, includesNodeWith( scrollExtentMin: 0.0, scrollPosition: 520.0, scrollExtentMax: 520.0, actions: <SemanticsAction>[ SemanticsAction.scrollDown, ], )); semantics.dispose(); }); testWidgets('correct scrollProgress for unbound', (WidgetTester tester) async { semantics = SemanticsTester(tester); await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: ListView.builder( dragStartBehavior: DragStartBehavior.down, itemExtent: 20.0, itemBuilder: (BuildContext context, int index) { return Text('entry $index'); }, ), )); expect(semantics, includesNodeWith( scrollExtentMin: 0.0, scrollPosition: 0.0, scrollExtentMax: double.infinity, actions: <SemanticsAction>[ SemanticsAction.scrollUp, ], )); await flingUp(tester); expect(semantics, includesNodeWith( scrollExtentMin: 0.0, scrollPosition: 394.3, scrollExtentMax: double.infinity, actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], )); await flingUp(tester); expect(semantics, includesNodeWith( scrollExtentMin: 0.0, scrollPosition: 788.6, scrollExtentMax: double.infinity, actions: <SemanticsAction>[ SemanticsAction.scrollUp, SemanticsAction.scrollDown, ], )); semantics.dispose(); }); testWidgets('Semantics tree is populated mid-scroll', (WidgetTester tester) async { semantics = SemanticsTester(tester); final List<Widget> children = List<Widget>.generate(80, (int i) => SizedBox( height: 40.0, child: Text('Item $i'), )); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView(children: children), ), ); final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(ListView))); await gesture.moveBy(const Offset(0.0, -40.0)); await tester.pump(); expect(semantics, includesNodeWith(label: 'Item 1')); expect(semantics, includesNodeWith(label: 'Item 2')); expect(semantics, includesNodeWith(label: 'Item 3')); semantics.dispose(); }); testWidgets('Can toggle semantics on, off, on without crash', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: ListView( children: List<Widget>.generate(40, (int i) { return SizedBox( height: 400.0, child: Text('item $i'), ); }), ), ), ); final TestSemantics expectedSemantics = TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], actions: <SemanticsAction>[SemanticsAction.scrollUp], children: <TestSemantics>[ TestSemantics( label: r'item 0', textDirection: TextDirection.ltr, ), TestSemantics( label: r'item 1', textDirection: TextDirection.ltr, ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isHidden, ], label: r'item 2', ), ], ), ], ), ], ); // Start with semantics off. expect(tester.binding.pipelineOwner.semanticsOwner, isNull); // Semantics on semantics = SemanticsTester(tester); await tester.pumpAndSettle(); expect(tester.binding.pipelineOwner.semanticsOwner, isNotNull); expect(semantics, hasSemantics(expectedSemantics, ignoreId: true, ignoreRect: true, ignoreTransform: true)); // Semantics off semantics.dispose(); await tester.pumpAndSettle(); expect(tester.binding.pipelineOwner.semanticsOwner, isNull); // Semantics on semantics = SemanticsTester(tester); await tester.pumpAndSettle(); expect(tester.binding.pipelineOwner.semanticsOwner, isNotNull); expect(semantics, hasSemantics(expectedSemantics, ignoreId: true, ignoreRect: true, ignoreTransform: true)); semantics.dispose(); }, semanticsEnabled: false); group('showOnScreen', () { const double kItemHeight = 100.0; late List<Widget> children; late ScrollController scrollController; late Widget widgetUnderTest; setUp(() { children = List<Widget>.generate(10, (int i) { return MergeSemantics( child: SizedBox( height: kItemHeight, child: Text('container $i'), ), ); }); scrollController = ScrollController( initialScrollOffset: kItemHeight / 2, ); widgetUnderTest = Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: 2 * kItemHeight, child: ListView( controller: scrollController, children: children, ), ), ), ); }); testWidgets('brings item above leading edge to leading edge', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation await tester.pumpWidget(widgetUnderTest); expect(scrollController.offset, kItemHeight / 2); final int firstContainerId = tester.renderObject(find.byWidget(children.first)).debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); await tester.pumpAndSettle(); expect(scrollController.offset, 0.0); semantics.dispose(); }); testWidgets('brings item below trailing edge to trailing edge', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation await tester.pumpWidget(widgetUnderTest); expect(scrollController.offset, kItemHeight / 2); final int firstContainerId = tester.renderObject(find.byWidget(children[2])).debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); await tester.pumpAndSettle(); expect(scrollController.offset, kItemHeight); semantics.dispose(); }); testWidgets('does not change position of items already fully on-screen', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation await tester.pumpWidget(widgetUnderTest); expect(scrollController.offset, kItemHeight / 2); final int firstContainerId = tester.renderObject(find.byWidget(children[1])).debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); await tester.pumpAndSettle(); expect(scrollController.offset, kItemHeight / 2); semantics.dispose(); }); }); group('showOnScreen with negative children', () { const double kItemHeight = 100.0; late List<Widget> children; late ScrollController scrollController; late Widget widgetUnderTest; setUp(() { final Key center = GlobalKey(); children = List<Widget>.generate(10, (int i) { return SliverToBoxAdapter( key: i == 5 ? center : null, child: MergeSemantics( key: ValueKey<int>(i), child: SizedBox( height: kItemHeight, child: Text('container $i'), ), ), ); }); scrollController = ScrollController( initialScrollOffset: -2.5 * kItemHeight, ); // 'container 0' is at offset -500 // 'container 1' is at offset -400 // 'container 2' is at offset -300 // 'container 3' is at offset -200 // 'container 4' is at offset -100 // 'container 5' is at offset 0 widgetUnderTest = Directionality( textDirection: TextDirection.ltr, child: Center( child: SizedBox( height: 2 * kItemHeight, child: Scrollable( controller: scrollController, viewportBuilder: (BuildContext context, ViewportOffset offset) { return Viewport( cacheExtent: 0.0, offset: offset, center: center, slivers: children, ); }, ), ), ), ); }); tearDown(() { scrollController.dispose(); }); testWidgets('brings item above leading edge to leading edge', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation await tester.pumpWidget(widgetUnderTest); expect(scrollController.offset, -250.0); final int firstContainerId = tester.renderObject(find.byKey(const ValueKey<int>(2))).debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); await tester.pumpAndSettle(); expect(scrollController.offset, -300.0); semantics.dispose(); }); testWidgets('brings item below trailing edge to trailing edge', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation await tester.pumpWidget(widgetUnderTest); expect(scrollController.offset, -250.0); final int firstContainerId = tester.renderObject(find.byKey(const ValueKey<int>(4))).debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); await tester.pumpAndSettle(); expect(scrollController.offset, -200.0); semantics.dispose(); }); testWidgets('does not change position of items already fully on-screen', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation await tester.pumpWidget(widgetUnderTest); expect(scrollController.offset, -250.0); final int firstContainerId = tester.renderObject(find.byKey(const ValueKey<int>(3))).debugSemantics!.id; tester.binding.pipelineOwner.semanticsOwner!.performAction(firstContainerId, SemanticsAction.showOnScreen); await tester.pumpAndSettle(); expect(scrollController.offset, -250.0); semantics.dispose(); }); }); testWidgets('transform of inner node from useTwoPaneSemantics scrolls correctly with nested scrollables', (WidgetTester tester) async { semantics = SemanticsTester(tester); // enables semantics tree generation // Context: https://github.com/flutter/flutter/issues/61631 await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: SingleChildScrollView( child: ListView( shrinkWrap: true, children: <Widget>[ for (int i = 0; i < 50; ++i) Text('$i'), ], ), ), ), ); final SemanticsNode rootScrollNode = semantics.nodesWith(actions: <SemanticsAction>[SemanticsAction.scrollUp]).single; final SemanticsNode innerListPane = semantics.nodesWith(ancestor: rootScrollNode, scrollExtentMax: 0).single; final SemanticsNode outerListPane = innerListPane.parent!; final List<SemanticsNode> hiddenNodes = semantics.nodesWith(flags: <SemanticsFlag>[SemanticsFlag.isHidden]).toList(); // This test is only valid if some children are offscreen. // Increase the number of Text children if this assert fails. assert(hiddenNodes.length >= 3); // Scroll to end -> beginning -> middle to test both directions. final List<SemanticsNode> targetNodes = <SemanticsNode>[ hiddenNodes.last, hiddenNodes.first, hiddenNodes[hiddenNodes.length ~/ 2], ]; expect(nodeGlobalRect(innerListPane), nodeGlobalRect(outerListPane)); for (final SemanticsNode node in targetNodes) { tester.binding.pipelineOwner.semanticsOwner!.performAction(node.id, SemanticsAction.showOnScreen); await tester.pumpAndSettle(); expect(nodeGlobalRect(innerListPane), nodeGlobalRect(outerListPane)); } semantics.dispose(); }); } Future<void> flingUp(WidgetTester tester, { int repetitions = 1 }) => fling(tester, const Offset(0.0, -200.0), repetitions); Future<void> flingDown(WidgetTester tester, { int repetitions = 1 }) => fling(tester, const Offset(0.0, 200.0), repetitions); Future<void> fling(WidgetTester tester, Offset offset, int repetitions) async { while (repetitions-- > 0) { await tester.fling(find.byType(ListView), offset, 1000.0); await tester.pump(); await tester.pump(const Duration(seconds: 5)); } } Rect nodeGlobalRect(SemanticsNode node) { Matrix4 globalTransform = node.transform ?? Matrix4.identity(); for (SemanticsNode? parent = node.parent; parent != null; parent = parent.parent) { if (parent.transform != null) { globalTransform = parent.transform!.multiplied(globalTransform); } } return MatrixUtils.transformRect(globalTransform, node.rect); }
flutter/packages/flutter/test/widgets/scrollable_semantics_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/scrollable_semantics_test.dart", "repo_id": "flutter", "token_count": 8688 }
749
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'semantics_tester.dart'; void main() { testWidgets('Semantics 7 - Merging', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); String label; label = '1'; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Stack( fit: StackFit.expand, children: <Widget>[ MergeSemantics( child: Semantics( checked: true, container: true, child: Semantics( container: true, label: label, ), ), ), MergeSemantics( child: Stack( fit: StackFit.expand, children: <Widget>[ Semantics( checked: true, ), Semantics( label: label, ), ], ), ), ], ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, label: label, rect: TestSemantics.fullScreen, ), // IDs 2 and 3 are used up by the nodes that get merged in TestSemantics.rootChild( id: 4, flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, label: label, rect: TestSemantics.fullScreen, ), // IDs 5 and 6 are used up by the nodes that get merged in ], ), )); label = '2'; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Stack( fit: StackFit.expand, children: <Widget>[ MergeSemantics( child: Semantics( checked: true, container: true, child: Semantics( container: true, label: label, ), ), ), MergeSemantics( child: Stack( fit: StackFit.expand, children: <Widget>[ Semantics( checked: true, ), Semantics( label: label, ), ], ), ), ], ), ), ); expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( id: 1, flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, label: label, rect: TestSemantics.fullScreen, ), // IDs 2 and 3 are used up by the nodes that get merged in TestSemantics.rootChild( id: 4, flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index, label: label, rect: TestSemantics.fullScreen, ), // IDs 5 and 6 are used up by the nodes that get merged in ], ), )); semantics.dispose(); }); }
flutter/packages/flutter/test/widgets/semantics_7_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/semantics_7_test.dart", "repo_id": "flutter", "token_count": 1981 }
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/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('setState() overbuild test', (WidgetTester tester) async { final List<String> log = <String>[]; final Builder inner = Builder( builder: (BuildContext context) { log.add('inner'); return const Text('inner', textDirection: TextDirection.ltr); }, ); int value = 0; await tester.pumpWidget(Builder( builder: (BuildContext context) { log.add('outer'); return StatefulBuilder( builder: (BuildContext context, StateSetter setState) { log.add('stateful'); return GestureDetector( onTap: () { setState(() { value += 1; }); }, child: Builder( builder: (BuildContext context) { log.add('middle $value'); return inner; }, ), ); }, ); }, )); log.add('---'); await tester.tap(find.text('inner')); await tester.pump(); log.add('---'); expect(log, equals(<String>[ 'outer', 'stateful', 'middle 0', 'inner', '---', 'stateful', 'middle 1', '---', ])); }); }
flutter/packages/flutter/test/widgets/set_state_2_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/set_state_2_test.dart", "repo_id": "flutter", "token_count": 726 }
751
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('precedingScrollExtent is reported as infinity for Sliver of unknown size', (WidgetTester tester) async { await tester.pumpWidget( MaterialApp( home: CustomScrollView( slivers: <Widget>[ const SliverToBoxAdapter(child: SizedBox(width: double.infinity, height: 150.0)), const SliverToBoxAdapter(child: SizedBox(width: double.infinity, height: 150.0)), SliverList( delegate: SliverChildBuilderDelegate((BuildContext context, int index) { if (index < 100) { return const SizedBox(width: double.infinity, height: 150.0); } else { return null; } }), ), const SliverToBoxAdapter( key: Key('final_sliver'), child: SizedBox(width: double.infinity, height: 150.0), ), ], ), ), ); // The last Sliver comes after a SliverList that has many more items than // can fit in the viewport, and the SliverList doesn't report a child count, // so the SliverList leads to an infinite precedingScrollExtent. final RenderViewport renderViewport = tester.renderObject(find.byType(Viewport)); final RenderSliver lastRenderSliver = renderViewport.lastChild!; expect(lastRenderSliver.constraints.precedingScrollExtent, double.infinity); }); }
flutter/packages/flutter/test/widgets/sliver_constraints_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/sliver_constraints_test.dart", "repo_id": "flutter", "token_count": 709 }
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 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; Future<void> test(WidgetTester tester, double offset) { final ViewportOffset viewportOffset = ViewportOffset.fixed(offset); addTearDown(viewportOffset.dispose); return tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: viewportOffset, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(const <Widget>[ SizedBox(height: 400.0, child: Text('a')), SizedBox(height: 400.0, child: Text('b')), SizedBox(height: 400.0, child: Text('c')), SizedBox(height: 400.0, child: Text('d')), SizedBox(height: 400.0, child: Text('e')), ]), ), ], ), ), ); } Future<void> testWithConstChildDelegate(WidgetTester tester, double offset) { final ViewportOffset viewportOffset = ViewportOffset.fixed(offset); addTearDown(viewportOffset.dispose); return tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: viewportOffset, slivers: const <Widget>[ SliverList( delegate: SliverChildListDelegate.fixed(<Widget>[ SizedBox(height: 400.0, child: Text('a')), SizedBox(height: 400.0, child: Text('b')), SizedBox(height: 400.0, child: Text('c')), SizedBox(height: 400.0, child: Text('d')), SizedBox(height: 400.0, child: Text('e')), ]), ), ], ), ), ); } 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 basic test', (WidgetTester tester) async { await test(tester, 0.0); expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 400.0), ], 'ab'); await test(tester, 200.0); verify(tester, <Offset>[ const Offset(0.0, -200.0), const Offset(0.0, 200.0), ], 'ab'); await test(tester, 600.0); verify(tester, <Offset>[ const Offset(0.0, -200.0), const Offset(0.0, 200.0), ], 'bc'); await test(tester, 900.0); verify(tester, <Offset>[ const Offset(0.0, -100.0), const Offset(0.0, 300.0), ], 'cd'); await test(tester, 200.0); verify(tester, <Offset>[ const Offset(0.0, -200.0), const Offset(0.0, 200.0), ], 'ab'); }); testWidgets('Viewport+SliverBlock basic test with constant SliverChildListDelegate', (WidgetTester tester) async { await testWithConstChildDelegate(tester, 0.0); expect(tester.renderObject<RenderBox>(find.byType(Viewport)).size, equals(const Size(800.0, 600.0))); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 400.0), ], 'ab'); await testWithConstChildDelegate(tester, 200.0); verify(tester, <Offset>[ const Offset(0.0, -200.0), const Offset(0.0, 200.0), ], 'ab'); await testWithConstChildDelegate(tester, 600.0); verify(tester, <Offset>[ const Offset(0.0, -200.0), const Offset(0.0, 200.0), ], 'bc'); await testWithConstChildDelegate(tester, 900.0); verify(tester, <Offset>[ const Offset(0.0, -100.0), const Offset(0.0, 300.0), ], 'cd'); await testWithConstChildDelegate(tester, 200.0); verify(tester, <Offset>[ const Offset(0.0, -200.0), const Offset(0.0, 200.0), ], 'ab'); }); testWidgets('Viewport with GlobalKey reparenting', (WidgetTester tester) async { final Key key1 = GlobalKey(); final ViewportOffset offset = ViewportOffset.zero(); addTearDown(offset.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(<Widget>[ const SizedBox(height: 251.0, child: Text('a')), const SizedBox(height: 252.0, child: Text('b')), SizedBox(key: key1, height: 253.0, child: const Text('c')), ]), ), ], ), ), ); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 251.0), const Offset(0.0, 503.0), ], 'abc'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(<Widget>[ SizedBox(key: key1, height: 253.0, child: const Text('c')), const SizedBox(height: 251.0, child: Text('a')), const SizedBox(height: 252.0, child: Text('b')), ]), ), ], ), ), ); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 253.0), const Offset(0.0, 504.0), ], 'cab'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(<Widget>[ const SizedBox(height: 251.0, child: Text('a')), SizedBox(key: key1, height: 253.0, child: const Text('c')), const SizedBox(height: 252.0, child: Text('b')), ]), ), ], ), ), ); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 251.0), const Offset(0.0, 504.0), ], 'acb'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(const <Widget>[ SizedBox(height: 251.0, child: Text('a')), SizedBox(height: 252.0, child: Text('b')), ]), ), ], ), ), ); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 251.0), ], 'ab'); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(<Widget>[ const SizedBox(height: 251.0, child: Text('a')), SizedBox(key: key1, height: 253.0, child: const Text('c')), const SizedBox(height: 252.0, child: Text('b')), ]), ), ], ), ), ); verify(tester, <Offset>[ Offset.zero, const Offset(0.0, 251.0), const Offset(0.0, 504.0), ], 'acb'); }); testWidgets('Viewport overflow clipping of SliverToBoxAdapter', (WidgetTester tester) async { final ViewportOffset offset1 = ViewportOffset.zero(); addTearDown(offset1.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset1, slivers: const <Widget>[ SliverToBoxAdapter( child: SizedBox(height: 400.0, child: Text('a')), ), ], ), ), ); expect(find.byType(Viewport), isNot(paints..clipRect())); final ViewportOffset offset2 = ViewportOffset.fixed(100.0); addTearDown(offset2.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset2, slivers: const <Widget>[ SliverToBoxAdapter( child: SizedBox(height: 400.0, child: Text('a')), ), ], ), ), ); expect(find.byType(Viewport), paints..clipRect()); final ViewportOffset offset3 = ViewportOffset.fixed(100.0); addTearDown(offset3.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset3, slivers: const <Widget>[ SliverToBoxAdapter( child: SizedBox(height: 4000.0, child: Text('a')), ), ], ), ), ); expect(find.byType(Viewport), paints..clipRect()); final ViewportOffset offset4 = ViewportOffset.zero(); addTearDown(offset4.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset4, slivers: const <Widget>[ SliverToBoxAdapter( child: SizedBox(height: 4000.0, child: Text('a')), ), ], ), ), ); expect(find.byType(Viewport), paints..clipRect()); }); testWidgets('Viewport overflow clipping of SliverBlock', (WidgetTester tester) async { final ViewportOffset offset1 = ViewportOffset.zero(); addTearDown(offset1.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset1, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(const <Widget>[ SizedBox(height: 400.0, child: Text('a')), ]), ), ], ), ), ); expect(find.byType(Viewport), isNot(paints..clipRect())); final ViewportOffset offset2 = ViewportOffset.fixed(100.0); addTearDown(offset2.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset2, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(const <Widget>[ SizedBox(height: 400.0, child: Text('a')), ]), ), ], ), ), ); expect(find.byType(Viewport), paints..clipRect()); final ViewportOffset offset3 = ViewportOffset.fixed(100.0); addTearDown(offset3.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset3, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(const <Widget>[ SizedBox(height: 4000.0, child: Text('a')), ]), ), ], ), ), ); expect(find.byType(Viewport), paints..clipRect()); final ViewportOffset offset4 = ViewportOffset.zero(); addTearDown(offset4.dispose); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Viewport( offset: offset4, slivers: <Widget>[ SliverList( delegate: SliverChildListDelegate(const <Widget>[ SizedBox(height: 4000.0, child: Text('a')), ]), ), ], ), ), ); expect(find.byType(Viewport), paints..clipRect()); }); }
flutter/packages/flutter/test/widgets/slivers_block_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/slivers_block_test.dart", "repo_id": "flutter", "token_count": 5786 }
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_test/flutter_test.dart'; class TestWidget extends StatefulWidget { const TestWidget({ super.key, required this.child, required this.persistentState, required this.syncedState, }); final Widget child; final int persistentState; final int syncedState; @override TestWidgetState createState() => TestWidgetState(); } class TestWidgetState extends State<TestWidget> { late int persistentState; late int syncedState; int updates = 0; @override void initState() { super.initState(); persistentState = widget.persistentState; syncedState = widget.syncedState; } @override void didUpdateWidget(TestWidget oldWidget) { super.didUpdateWidget(oldWidget); syncedState = widget.syncedState; // we explicitly do NOT sync the persistentState from the new instance // because we're using that to track whether we got recreated updates += 1; } @override Widget build(BuildContext context) => widget.child; } void main() { testWidgets('no change', (WidgetTester tester) async { await tester.pumpWidget( ColoredBox( color: Colors.blue, child: ColoredBox( color: Colors.blue, child: TestWidget( persistentState: 1, syncedState: 0, child: Container(), ), ), ), ); final TestWidgetState state = tester.state(find.byType(TestWidget)); expect(state.persistentState, equals(1)); expect(state.updates, equals(0)); await tester.pumpWidget( ColoredBox( color: Colors.blue, child: ColoredBox( color: Colors.blue, child: TestWidget( persistentState: 2, syncedState: 0, child: Container(), ), ), ), ); expect(state.persistentState, equals(1)); expect(state.updates, equals(1)); await tester.pumpWidget(Container()); }); testWidgets('remove one', (WidgetTester tester) async { await tester.pumpWidget( ColoredBox( color: Colors.blue, child: ColoredBox( color: Colors.blue, child: TestWidget( persistentState: 10, syncedState: 0, child: Container(), ), ), ), ); TestWidgetState state = tester.state(find.byType(TestWidget)); expect(state.persistentState, equals(10)); expect(state.updates, equals(0)); await tester.pumpWidget( ColoredBox( color: Colors.green, child: TestWidget( persistentState: 11, syncedState: 0, child: Container(), ), ), ); state = tester.state(find.byType(TestWidget)); expect(state.persistentState, equals(11)); expect(state.updates, equals(0)); await tester.pumpWidget(Container()); }); testWidgets('swap instances around', (WidgetTester tester) async { const Widget a = TestWidget(persistentState: 0x61, syncedState: 0x41, child: Text('apple', textDirection: TextDirection.ltr)); const Widget b = TestWidget(persistentState: 0x62, syncedState: 0x42, child: Text('banana', textDirection: TextDirection.ltr)); await tester.pumpWidget(const Column()); final GlobalKey keyA = GlobalKey(); final GlobalKey keyB = GlobalKey(); await tester.pumpWidget( Column( children: <Widget>[ Container( key: keyA, child: a, ), Container( key: keyB, child: b, ), ], ), ); TestWidgetState first, second; first = tester.state(find.byWidget(a)); second = tester.state(find.byWidget(b)); expect(first.widget, equals(a)); expect(first.persistentState, equals(0x61)); expect(first.syncedState, equals(0x41)); expect(second.widget, equals(b)); expect(second.persistentState, equals(0x62)); expect(second.syncedState, equals(0x42)); await tester.pumpWidget( Column( children: <Widget>[ Container( key: keyA, child: a, ), Container( key: keyB, child: b, ), ], ), ); first = tester.state(find.byWidget(a)); second = tester.state(find.byWidget(b)); // same as before expect(first.widget, equals(a)); expect(first.persistentState, equals(0x61)); expect(first.syncedState, equals(0x41)); expect(second.widget, equals(b)); expect(second.persistentState, equals(0x62)); expect(second.syncedState, equals(0x42)); // now we swap the nodes over // since they are both "old" nodes, they shouldn't sync with each other even though they look alike await tester.pumpWidget( Column( children: <Widget>[ Container( key: keyA, child: b, ), Container( key: keyB, child: a, ), ], ), ); first = tester.state(find.byWidget(b)); second = tester.state(find.byWidget(a)); expect(first.widget, equals(b)); expect(first.persistentState, equals(0x61)); expect(first.syncedState, equals(0x42)); expect(second.widget, equals(a)); expect(second.persistentState, equals(0x62)); expect(second.syncedState, equals(0x41)); }); }
flutter/packages/flutter/test/widgets/syncing_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/syncing_test.dart", "repo_id": "flutter", "token_count": 2364 }
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'; void main() { testWidgets('TrackingScrollController saves offset', (WidgetTester tester) async { final TrackingScrollController controller = TrackingScrollController(); addTearDown(controller.dispose); const double listItemHeight = 100.0; await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: PageView.builder( itemBuilder: (BuildContext context, int index) { return ListView( controller: controller, children: List<Widget>.generate( 10, (int i) => SizedBox( height: listItemHeight, child: Text('Page$index-Item$i'), ), ).toList(), ); }, ), ), ); expect(find.text('Page0-Item1'), findsOneWidget); expect(find.text('Page1-Item1'), findsNothing); expect(find.text('Page2-Item0'), findsNothing); expect(find.text('Page2-Item1'), findsNothing); controller.jumpTo(listItemHeight + 10); await tester.pumpAndSettle(); await tester.fling(find.text('Page0-Item1'), const Offset(-100.0, 0.0), 10000.0); await tester.pumpAndSettle(); expect(find.text('Page0-Item1'), findsNothing); expect(find.text('Page1-Item1'), findsOneWidget); expect(find.text('Page2-Item0'), findsNothing); expect(find.text('Page2-Item1'), findsNothing); await tester.fling(find.text('Page1-Item1'), const Offset(-100.0, 0.0), 10000.0); await tester.pumpAndSettle(); expect(find.text('Page0-Item1'), findsNothing); expect(find.text('Page1-Item1'), findsNothing); expect(find.text('Page2-Item0'), findsNothing); expect(find.text('Page2-Item1'), findsOneWidget); await tester.pumpWidget(const Text('Another page', textDirection: TextDirection.ltr)); expect(controller.initialScrollOffset, 0.0); }); testWidgets('TrackingScrollController saves offset', (WidgetTester tester) async { int attach = 0; int detach = 0; final TrackingScrollController controller = TrackingScrollController( onAttach: (_) { attach++; }, onDetach: (_) { detach++; }, ); addTearDown(controller.dispose); const double listItemHeight = 100.0; await tester.pumpWidget(Directionality( textDirection: TextDirection.ltr, child: PageView.builder( itemBuilder: (BuildContext context, int index) { return ListView( controller: controller, children: List<Widget>.generate( 10, (int i) => SizedBox( height: listItemHeight, child: Text('Page$index-Item$i'), ), ).toList(), ); }, ), )); await tester.pumpAndSettle(); expect(attach, 1); expect(detach, 0); await tester.pumpWidget(Container()); await tester.pumpAndSettle(); expect(attach, 1); expect(detach, 1); }); }
flutter/packages/flutter/test/widgets/tracking_scroll_controller_test.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/tracking_scroll_controller_test.dart", "repo_id": "flutter", "token_count": 1343 }
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 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; /// Tuple-like test class for storing a [stream] and [eventKind]. /// /// Used to store the [stream] and [eventKind] that a dispatched event would be /// sent on. @immutable class DispatchedEventKey { const DispatchedEventKey({required this.stream, required this.eventKind}); final String stream; final String eventKind; @override String toString() { return '[DispatchedEventKey]($stream, $eventKind)'; } @override bool operator ==(Object other) { return other is DispatchedEventKey && stream == other.stream && eventKind == other.eventKind; } @override int get hashCode => Object.hash(stream, eventKind); } class TestWidgetInspectorService extends Object with WidgetInspectorService { TestWidgetInspectorService() { selection.addListener(() { if (selectionChangedCallback != null) { selectionChangedCallback!(); } }); } final Map<String, ServiceExtensionCallback> extensions = <String, ServiceExtensionCallback>{}; final Map<DispatchedEventKey, List<Map<Object, Object?>>> eventsDispatched = <DispatchedEventKey, List<Map<Object, Object?>>>{}; final List<Object?> objectsInspected = <Object?>[]; @override void registerServiceExtension({ required String name, required ServiceExtensionCallback callback, required RegisterServiceExtensionCallback registerExtension, }) { assert(!extensions.containsKey(name)); extensions[name] = callback; } @override void postEvent( String eventKind, Map<Object, Object?> eventData, { String stream = 'Extension', }) { dispatchedEvents(eventKind, stream: stream).add(eventData); } @override void inspect(Object? object) { objectsInspected.add(object); } List<Map<Object, Object?>> dispatchedEvents( String eventKind, { String stream = 'Extension', }) { return eventsDispatched.putIfAbsent( DispatchedEventKey(stream: stream, eventKind: eventKind), () => <Map<Object, Object?>>[], ); } List<Object?> inspectedObjects(){ return objectsInspected; } Iterable<Map<Object, Object?>> getServiceExtensionStateChangedEvents(String extensionName) { return dispatchedEvents('Flutter.ServiceExtensionStateChanged') .where((Map<Object, Object?> event) => event['extension'] == extensionName); } Future<Object?> testExtension(String name, Map<String, String> arguments) async { expect(extensions, contains(name)); // Encode and decode to JSON to match behavior using a real service // extension where only JSON is allowed. return (json.decode(json.encode(await extensions[name]!(arguments))) as Map<String, dynamic>)['result']; } Future<String> testBoolExtension(String name, Map<String, String> arguments) async { expect(extensions, contains(name)); // Encode and decode to JSON to match behavior using a real service // extension where only JSON is allowed. return (json.decode(json.encode(await extensions[name]!(arguments))) as Map<String, dynamic>)['enabled'] as String; } int rebuildCount = 0; @override Future<void> forceRebuild() async { rebuildCount++; final WidgetsBinding binding = WidgetsBinding.instance; if (binding.rootElement != null) { binding.buildOwner!.reassemble(binding.rootElement!); } } @override void resetAllState() { super.resetAllState(); eventsDispatched.clear(); objectsInspected.clear(); rebuildCount = 0; } }
flutter/packages/flutter/test/widgets/widget_inspector_test_utils.dart/0
{ "file_path": "flutter/packages/flutter/test/widgets/widget_inspector_test_utils.dart", "repo_id": "flutter", "token_count": 1249 }
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/material.dart'; void main() { // Changes made in https://github.com/flutter/flutter/pull/86198 AppBarTheme appBarTheme = AppBarTheme(); appBarTheme = AppBarTheme(brightness: Brightness.light); appBarTheme = AppBarTheme(brightness: Brightness.dark); appBarTheme = AppBarTheme(error: ''); appBarTheme = appBarTheme.copyWith(error: ''); appBarTheme = appBarTheme.copyWith(brightness: Brightness.light); appBarTheme = appBarTheme.copyWith(brightness: Brightness.dark); appBarTheme.brightness; TextTheme myTextTheme = TextTheme(); AppBarTheme appBarTheme = AppBarTheme(); appBarTheme = AppBarTheme(textTheme: myTextTheme); appBarTheme = AppBarTheme(textTheme: myTextTheme); appBarTheme = appBarTheme.copyWith(textTheme: myTextTheme); appBarTheme = appBarTheme.copyWith(textTheme: myTextTheme); AppBarTheme appBarTheme = AppBarTheme(); appBarTheme = AppBarTheme(backwardsCompatibility: true); appBarTheme = AppBarTheme(backwardsCompatibility: false); appBarTheme = appBarTheme.copyWith(backwardsCompatibility: true); appBarTheme = appBarTheme.copyWith(backwardsCompatibility: false); appBarTheme.backwardsCompatibility; // Removing field reference not supported. AppBarTheme appBarTheme = AppBarTheme(); appBarTheme.color; }
flutter/packages/flutter/test_fixes/material/app_bar_theme.dart/0
{ "file_path": "flutter/packages/flutter/test_fixes/material/app_bar_theme.dart", "repo_id": "flutter", "token_count": 441 }
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/painting.dart'; void main() { // Change made in https://github.com/flutter/flutter/pull/121152 final EdgeInsets insets = EdgeInsets.fromWindowPadding(ViewPadding.zero, 3.0); // Change made in https://github.com/flutter/flutter/pull/128522 const TextStyle textStyle = TextStyle() ..getTextStyle(textScaleFactor: math.min(_kTextScaleFactor, 1.0)) ..getTextStyle(); TextPainter(text: inlineSpan); TextPainter(textScaleFactor: someValue); TextPainter.computeWidth(textScaleFactor: textScaleFactor); TextPainter.computeMaxIntrinsicWidth(textScaleFactor: textScaleFactor); }
flutter/packages/flutter/test_fixes/painting/painting.dart/0
{ "file_path": "flutter/packages/flutter/test_fixes/painting/painting.dart", "repo_id": "flutter", "token_count": 250 }
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/widgets.dart'; void main() { // Changes made in https://flutter.dev/docs/release/breaking-changes/clip-behavior ListWheelScrollView listWheelScrollView = ListWheelScrollView(); listWheelScrollView = ListWheelScrollView(clipToSize: true); listWheelScrollView = ListWheelScrollView(clipToSize: false); listWheelScrollView = ListWheelScrollView(error: ''); listWheelScrollView = ListWheelScrollView.useDelegate(); listWheelScrollView = ListWheelScrollView.useDelegate(clipToSize: true); listWheelScrollView = ListWheelScrollView.useDelegate(clipToSize: false); listWheelScrollView = ListWheelScrollView.useDelegate(error: ''); listWheelScrollView.clipToSize; }
flutter/packages/flutter/test_fixes/widgets/list_wheel_scroll_view.dart/0
{ "file_path": "flutter/packages/flutter/test_fixes/widgets/list_wheel_scroll_view.dart", "repo_id": "flutter", "token_count": 247 }
759
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Can build widget tree in profile mode with asserts enabled', (WidgetTester tester) async { await tester.pumpWidget(const MaterialApp(home: Scaffold(body: Center(child: Text('Hello World'))))); expect(tester.takeException(), isNull); }); }
flutter/packages/flutter/test_profile/basic_test.dart/0
{ "file_path": "flutter/packages/flutter/test_profile/basic_test.dart", "repo_id": "flutter", "token_count": 161 }
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. /// Indexes a list of `enum` values by simple name. /// /// In Dart enum names are prefixed with enum class name. For example, for /// `enum Vote { yea, nay }`, `Vote.yea.toString()` produces `"Vote.yea"` /// rather than just `"yea"` - the simple name. This class provides methods for /// getting and looking up by simple names. /// /// Example: /// /// enum Vote { yea, nay } /// final index = EnumIndex(Vote.values); /// index.lookupBySimpleName('yea'); // returns Vote.yea /// index.toSimpleName(Vote.nay); // returns 'nay' class EnumIndex<E> { /// Creates an index of [enumValues]. EnumIndex(List<E> enumValues) : _nameToValue = Map<String, E>.fromIterable( enumValues, key: _getSimpleName, ), _valueToName = Map<E, String>.fromIterable( enumValues, value: _getSimpleName, ); final Map<String, E> _nameToValue; final Map<E, String> _valueToName; /// Given a [simpleName] finds the corresponding enum value. E lookupBySimpleName(String simpleName) => _nameToValue[simpleName]!; /// Returns the simple name for [enumValue]. String toSimpleName(E enumValue) => _valueToName[enumValue]!; } String _getSimpleName(dynamic enumValue) { return enumValue.toString().split('.').last; }
flutter/packages/flutter_driver/lib/src/common/enum_util.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/common/enum_util.dart", "repo_id": "flutter", "token_count": 498 }
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 'dart:convert'; import 'message.dart'; /// A Flutter Driver command that waits until a given [condition] is satisfied. class WaitForCondition extends Command { /// Creates a command that waits for the given [condition] is met. const WaitForCondition(this.condition, {super.timeout}); /// Deserializes this command from the value generated by [serialize]. WaitForCondition.deserialize(super.json) : condition = _deserialize(json), super.deserialize(); /// The condition that this command shall wait for. final SerializableWaitCondition condition; @override Map<String, String> serialize() => super.serialize()..addAll(condition.serialize()); @override String get kind => 'waitForCondition'; @override bool get requiresRootWidgetAttached => condition.requiresRootWidgetAttached; } /// Thrown to indicate a serialization error. class SerializationException implements Exception { /// Creates a [SerializationException] with an optional error message. const SerializationException([this.message]); /// The error message, possibly null. final String? message; @override String toString() => 'SerializationException($message)'; } /// Base class for Flutter Driver wait conditions, objects that describe conditions /// the driver can wait for. /// /// This class is sent from the driver script running on the host to the driver /// extension on device to perform waiting on a given condition. In the extension, /// it will be converted to a `WaitCondition` that actually defines the wait logic. /// /// If you subclass this, you also need to implement a `WaitCondition` in the extension. abstract class SerializableWaitCondition { /// A const constructor to allow subclasses to be const. const SerializableWaitCondition(); /// Identifies the name of the wait condition. String get conditionName; /// Serializes the object to JSON. Map<String, String> serialize() { return <String, String>{ 'conditionName': conditionName, }; } /// Whether this command requires the widget tree to be initialized before /// the command may be run. /// /// This defaults to true to force the application under test to call [runApp] /// before attempting to remotely drive the application. Subclasses may /// override this to return false if they allow invocation before the /// application has started. /// /// See also: /// /// * [WidgetsBinding.isRootWidgetAttached], which indicates whether the /// widget tree has been initialized. bool get requiresRootWidgetAttached => true; } /// A condition that waits until no transient callbacks are scheduled. class NoTransientCallbacks extends SerializableWaitCondition { /// Creates a [NoTransientCallbacks] condition. const NoTransientCallbacks(); /// Factory constructor to parse a [NoTransientCallbacks] instance from the /// given JSON map. factory NoTransientCallbacks.deserialize(Map<String, String> json) { if (json['conditionName'] != 'NoTransientCallbacksCondition') { throw SerializationException('Error occurred during deserializing the NoTransientCallbacksCondition JSON string: $json'); } return const NoTransientCallbacks(); } @override String get conditionName => 'NoTransientCallbacksCondition'; } /// A condition that waits until no pending frame is scheduled. class NoPendingFrame extends SerializableWaitCondition { /// Creates a [NoPendingFrame] condition. const NoPendingFrame(); /// Factory constructor to parse a [NoPendingFrame] instance from the given /// JSON map. factory NoPendingFrame.deserialize(Map<String, String> json) { if (json['conditionName'] != 'NoPendingFrameCondition') { throw SerializationException('Error occurred during deserializing the NoPendingFrameCondition JSON string: $json'); } return const NoPendingFrame(); } @override String get conditionName => 'NoPendingFrameCondition'; } /// A condition that waits until the Flutter engine has rasterized the first frame. class FirstFrameRasterized extends SerializableWaitCondition { /// Creates a [FirstFrameRasterized] condition. const FirstFrameRasterized(); /// Factory constructor to parse a [FirstFrameRasterized] instance from the /// given JSON map. factory FirstFrameRasterized.deserialize(Map<String, String> json) { if (json['conditionName'] != 'FirstFrameRasterizedCondition') { throw SerializationException('Error occurred during deserializing the FirstFrameRasterizedCondition JSON string: $json'); } return const FirstFrameRasterized(); } @override String get conditionName => 'FirstFrameRasterizedCondition'; @override bool get requiresRootWidgetAttached => false; } /// A condition that waits until there are no pending platform messages. class NoPendingPlatformMessages extends SerializableWaitCondition { /// Creates a [NoPendingPlatformMessages] condition. const NoPendingPlatformMessages(); /// Factory constructor to parse a [NoPendingPlatformMessages] instance from the /// given JSON map. factory NoPendingPlatformMessages.deserialize(Map<String, String> json) { if (json['conditionName'] != 'NoPendingPlatformMessagesCondition') { throw SerializationException('Error occurred during deserializing the NoPendingPlatformMessagesCondition JSON string: $json'); } return const NoPendingPlatformMessages(); } @override String get conditionName => 'NoPendingPlatformMessagesCondition'; } /// A combined condition that waits until all the given [conditions] are met. class CombinedCondition extends SerializableWaitCondition { /// Creates a [CombinedCondition] condition. const CombinedCondition(this.conditions); /// Factory constructor to parse a [CombinedCondition] instance from the /// given JSON map. factory CombinedCondition.deserialize(Map<String, String> jsonMap) { if (jsonMap['conditionName'] != 'CombinedCondition') { throw SerializationException('Error occurred during deserializing the CombinedCondition JSON string: $jsonMap'); } if (jsonMap['conditions'] == null) { return const CombinedCondition(<SerializableWaitCondition>[]); } final List<SerializableWaitCondition> conditions = <SerializableWaitCondition>[]; for (final Map<String, dynamic> condition in (json.decode(jsonMap['conditions']!) as List<dynamic>).cast<Map<String, dynamic>>()) { conditions.add(_deserialize(condition.cast<String, String>())); } return CombinedCondition(conditions); } /// A list of conditions it waits for. final List<SerializableWaitCondition> conditions; @override String get conditionName => 'CombinedCondition'; @override Map<String, String> serialize() { final Map<String, String> jsonMap = super.serialize(); final List<Map<String, String>> jsonConditions = conditions.map( (SerializableWaitCondition condition) { return condition.serialize(); }).toList(); jsonMap['conditions'] = json.encode(jsonConditions); return jsonMap; } } /// Parses a [SerializableWaitCondition] or its subclass from the given [json] map. SerializableWaitCondition _deserialize(Map<String, String> json) { final String conditionName = json['conditionName']!; switch (conditionName) { case 'NoTransientCallbacksCondition': return NoTransientCallbacks.deserialize(json); case 'NoPendingFrameCondition': return NoPendingFrame.deserialize(json); case 'FirstFrameRasterizedCondition': return FirstFrameRasterized.deserialize(json); case 'NoPendingPlatformMessagesCondition': return NoPendingPlatformMessages.deserialize(json); case 'CombinedCondition': return CombinedCondition.deserialize(json); } throw SerializationException( 'Unsupported wait condition $conditionName in the JSON string $json'); }
flutter/packages/flutter_driver/lib/src/common/wait.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/common/wait.dart", "repo_id": "flutter", "token_count": 2213 }
762
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:file/file.dart'; import 'package:matcher/matcher.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; import 'package:vm_service/vm_service.dart' as vms; import 'package:webdriver/async_io.dart' as async_io; import 'package:webdriver/support/async.dart'; import '../common/error.dart'; import '../common/message.dart'; import 'common.dart'; import 'driver.dart'; import 'timeline.dart'; /// An implementation of the Flutter Driver using the WebDriver. /// /// Example of how to test WebFlutterDriver: /// 1. Launch WebDriver binary: ./chromedriver --port=4444 /// 2. Run test script: flutter drive --target=test_driver/scroll_perf_web.dart -d web-server --release class WebFlutterDriver extends FlutterDriver { /// Creates a driver that uses a connection provided by the given /// [_connection]. WebFlutterDriver.connectedTo( this._connection, { bool printCommunication = false, bool logCommunicationToFile = true, }) : _printCommunication = printCommunication, _logCommunicationToFile = logCommunicationToFile, _startTime = DateTime.now(), _driverId = _nextDriverId++ { _logFilePathName = path.join(testOutputsDirectory, 'flutter_driver_commands_$_driverId.log'); } final FlutterWebConnection _connection; DateTime _startTime; static int _nextDriverId = 0; /// The unique ID of this driver instance. final int _driverId; /// Start time for tracing. @visibleForTesting DateTime get startTime => _startTime; @override vms.Isolate get appIsolate => throw UnsupportedError('WebFlutterDriver does not support appIsolate'); @override vms.VmService get serviceClient => throw UnsupportedError('WebFlutterDriver does not support serviceClient'); @override async_io.WebDriver get webDriver => _connection._driver; /// Whether to print communication between host and app to `stdout`. final bool _printCommunication; /// Whether to log communication between host and app to `flutter_driver_commands.log`. final bool _logCommunicationToFile; /// Logs are written here when _logCommunicationToFile is true. late final String _logFilePathName; /// Getter for file pathname where logs are written when _logCommunicationToFile is true String get logFilePathName => _logFilePathName; /// Creates a driver that uses a connection provided by the given /// [hostUrl] which would fallback to environment variable VM_SERVICE_URL. /// Driver also depends on environment variables DRIVER_SESSION_ID, /// BROWSER_SUPPORTS_TIMELINE, DRIVER_SESSION_URI, DRIVER_SESSION_SPEC, /// DRIVER_SESSION_CAPABILITIES and ANDROID_CHROME_ON_EMULATOR for /// configurations. /// /// See [FlutterDriver.connect] for more documentation. static Future<FlutterDriver> connectWeb({ String? hostUrl, bool printCommunication = false, bool logCommunicationToFile = true, Duration? timeout, }) async { hostUrl ??= Platform.environment['VM_SERVICE_URL']; final Map<String, dynamic> settings = <String, dynamic>{ 'support-timeline-action': Platform.environment['SUPPORT_TIMELINE_ACTION'] == 'true', 'session-id': Platform.environment['DRIVER_SESSION_ID'], 'session-uri': Platform.environment['DRIVER_SESSION_URI'], 'session-spec': Platform.environment['DRIVER_SESSION_SPEC'], 'android-chrome-on-emulator': Platform.environment['ANDROID_CHROME_ON_EMULATOR'] == 'true', 'session-capabilities': Platform.environment['DRIVER_SESSION_CAPABILITIES'], }; final FlutterWebConnection connection = await FlutterWebConnection.connect (hostUrl!, settings, timeout: timeout); return WebFlutterDriver.connectedTo( connection, printCommunication: printCommunication, logCommunicationToFile: logCommunicationToFile, ); } static DriverError _createMalformedExtensionResponseError(Object? data) { throw DriverError( 'Received malformed response from the FlutterDriver extension.\n' 'Expected a JSON map containing a "response" field and, optionally, an ' '"isError" field, but got ${data.runtimeType}: $data' ); } @override Future<Map<String, dynamic>> sendCommand(Command command) async { final Map<String, dynamic> response; final Object? data; final Map<String, String> serialized = command.serialize(); _logCommunication('>>> $serialized'); try { data = await _connection.sendCommand("window.\$flutterDriver('${jsonEncode(serialized)}')", command.timeout); // The returned data is expected to be a string. If it's null or anything // other than a string, something's wrong. if (data is! String) { throw _createMalformedExtensionResponseError(data); } final Object? decoded = json.decode(data); if (decoded is! Map<String, dynamic>) { throw _createMalformedExtensionResponseError(data); } else { response = decoded; } _logCommunication('<<< $response'); } on DriverError catch (_) { rethrow; } catch (error, stackTrace) { throw DriverError( 'FlutterDriver command ${command.runtimeType} failed due to a remote error.\n' 'Command sent: ${jsonEncode(serialized)}', error, stackTrace ); } final Object? isError = response['isError']; final Object? responseData = response['response']; if (isError is! bool?) { throw _createMalformedExtensionResponseError(data); } else if (isError ?? false) { throw DriverError('Error in Flutter application: $responseData'); } if (responseData is! Map<String, dynamic>) { throw _createMalformedExtensionResponseError(data); } return responseData; } @override Future<void> close() => _connection.close(); @override Future<void> waitUntilFirstFrameRasterized() async { throw UnimplementedError(); } void _logCommunication(String message) { if (_printCommunication) { driverLog('WebFlutterDriver', message); } if (_logCommunicationToFile) { final File file = fs.file(_logFilePathName); file.createSync(recursive: true); // no-op if file exists file.writeAsStringSync('${DateTime.now()} $message\n', mode: FileMode.append, flush: true); } } @override Future<List<int>> screenshot() async { await Future<void>.delayed(const Duration(seconds: 2)); return _connection.screenshot(); } @override Future<void> startTracing({ List<TimelineStream> streams = const <TimelineStream>[TimelineStream.all], Duration timeout = kUnusuallyLongTimeout, }) async { _checkBrowserSupportsTimeline(); } @override Future<Timeline> stopTracingAndDownloadTimeline({Duration timeout = kUnusuallyLongTimeout}) async { _checkBrowserSupportsTimeline(); final List<Map<String, dynamic>> events = <Map<String, dynamic>>[]; for (final async_io.LogEntry entry in await _connection.logs.toList()) { if (_startTime.isBefore(entry.timestamp)) { final Map<String, dynamic> data = (jsonDecode(entry.message!) as Map<String, dynamic>)['message'] as Map<String, dynamic>; if (data['method'] == 'Tracing.dataCollected') { // 'ts' data collected from Chrome is in double format, conversion needed try { final Map<String, dynamic> params = data['params'] as Map<String, dynamic>; params['ts'] = double.parse(params['ts'].toString()).toInt(); } on FormatException catch (_) { // data is corrupted, skip continue; } events.add(data['params']! as Map<String, dynamic>); } } } final Map<String, dynamic> json = <String, dynamic>{ 'traceEvents': events, }; return Timeline.fromJson(json); } @override Future<Timeline> traceAction(Future<dynamic> Function() action, { List<TimelineStream> streams = const <TimelineStream>[TimelineStream.all], bool retainPriorEvents = false, }) async { _checkBrowserSupportsTimeline(); if (!retainPriorEvents) { await clearTimeline(); } await startTracing(streams: streams); await action(); return stopTracingAndDownloadTimeline(); } @override Future<void> clearTimeline({Duration timeout = kUnusuallyLongTimeout}) async { _checkBrowserSupportsTimeline(); // Reset start time _startTime = DateTime.now(); } /// Checks whether browser supports Timeline related operations. void _checkBrowserSupportsTimeline() { if (!_connection.supportsTimelineAction) { throw UnsupportedError('Timeline action is not supported by current testing browser'); } } } /// Encapsulates connection information to an instance of a Flutter Web application. class FlutterWebConnection { /// Creates a FlutterWebConnection with WebDriver /// and whether the WebDriver supports timeline action. FlutterWebConnection(this._driver, this.supportsTimelineAction); final async_io.WebDriver _driver; /// Whether the connected WebDriver supports timeline action for Flutter Web Driver. bool supportsTimelineAction; /// Starts WebDriver with the given [settings] and /// establishes the connection to Flutter Web application. static Future<FlutterWebConnection> connect( String url, Map<String, dynamic> settings, {Duration? timeout}) async { final String sessionId = settings['session-id'].toString(); final Uri sessionUri = Uri.parse(settings['session-uri'].toString()); final async_io.WebDriver driver = async_io.WebDriver( sessionUri, sessionId, json.decode(settings['session-capabilities'] as String) as Map<String, dynamic>, async_io.AsyncIoRequestClient(sessionUri.resolve('session/$sessionId/')), async_io.WebDriverSpec.W3c, ); if (settings['android-chrome-on-emulator'] == true) { final Uri localUri = Uri.parse(url); // Converts to Android Emulator Uri. // Hardcode the host to 10.0.2.2 based on // https://developer.android.com/studio/run/emulator-networking url = Uri(scheme: localUri.scheme, host: '10.0.2.2', port:localUri.port).toString(); } await driver.get(url); await waitUntilExtensionInstalled(driver, timeout); return FlutterWebConnection(driver, settings['support-timeline-action'] as bool); } /// Sends command via WebDriver to Flutter web application. Future<dynamic> sendCommand(String script, Duration? duration) async { // This code should not be reachable before the VM service extension is // initialized. The VM service extension is expected to initialize both // `$flutterDriverResult` and `$flutterDriver` variables before attempting // to send commands. This part checks that `$flutterDriverResult` is present. // `$flutterDriver` is not checked because it is covered by the `script` // that's executed next. try { await _driver.execute(r'return $flutterDriverResult', <String>[]); } catch (error, stackTrace) { throw DriverError( 'Driver extension has not been initialized correctly.\n' 'If the test uses a custom VM service extension, make sure it conforms ' 'to the protocol used by package:integration_test and ' 'package:flutter_driver.\n' 'If the test uses VM service extensions provided by the Flutter SDK, ' 'then this error is likely caused by a bug in Flutter. Please report it ' 'by filing a bug on GitHub:\n' ' https://github.com/flutter/flutter/issues/new?template=2_bug.yml', error, stackTrace, ); } String phase = 'executing'; try { // Execute the script, which should leave the result in the `$flutterDriverResult` global variable. await _driver.execute(script, <void>[]); // Read the result. phase = 'reading'; final dynamic result = await waitFor<dynamic>( () => _driver.execute(r'return $flutterDriverResult', <String>[]), matcher: isNotNull, timeout: duration ?? const Duration(days: 30), ); // Reset the result to null to avoid polluting the results of future commands. phase = 'resetting'; await _driver.execute(r'$flutterDriverResult = null', <void>[]); return result; } catch (error, stackTrace) { throw DriverError( 'Error while $phase FlutterDriver result for command: $script', error, stackTrace, ); } } /// Gets performance log from WebDriver. Stream<async_io.LogEntry> get logs => _driver.logs.get(async_io.LogType.performance); /// Takes screenshot via WebDriver. Future<List<int>> screenshot() => _driver.captureScreenshotAsList(); /// Closes the WebDriver. Future<void> close() async { await _driver.quit(closeSession: false); } } /// Waits until extension is installed. Future<void> waitUntilExtensionInstalled(async_io.WebDriver driver, Duration? timeout) async { await waitFor<void>(() => driver.execute(r'return typeof(window.$flutterDriver)', <String>[]), matcher: 'function', timeout: timeout ?? const Duration(days: 365)); }
flutter/packages/flutter_driver/lib/src/driver/web_driver.dart/0
{ "file_path": "flutter/packages/flutter_driver/lib/src/driver/web_driver.dart", "repo_id": "flutter", "token_count": 4525 }
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 'package:flutter_driver/flutter_driver.dart'; class StubFinder extends SerializableFinder { StubFinder(this.keyString); final String keyString; @override String get finderType => 'Stub'; @override Map<String, String> serialize() { return super.serialize()..addAll(<String, String>{'keyString': keyString}); } }
flutter/packages/flutter_driver/test/src/real_tests/stubs/stub_finder.dart/0
{ "file_path": "flutter/packages/flutter_driver/test/src/real_tests/stubs/stub_finder.dart", "repo_id": "flutter", "token_count": 156 }
764
{ "datePickerHourSemanticsLabelOne": "Saat $hour", "datePickerHourSemanticsLabelOther": "Saat $hour", "datePickerMinuteSemanticsLabelOne": "1 dəqiqə", "datePickerMinuteSemanticsLabelOther": "$minute dəqiqə", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "Bu gün", "alertDialogLabel": "Bildiriş", "timerPickerHourLabelOne": "saat", "timerPickerHourLabelOther": "saat", "timerPickerMinuteLabelOne": "dəq.", "timerPickerMinuteLabelOther": "dəq.", "timerPickerSecondLabelOne": "san.", "timerPickerSecondLabelOther": "san.", "cutButtonLabel": "Kəsin", "copyButtonLabel": "Kopyalayın", "pasteButtonLabel": "Yerləşdirin", "clearButtonLabel": "Clear", "selectAllButtonLabel": "Hamısını seçin", "tabSemanticsLabel": "Tab $tabIndex/$tabCount", "modalBarrierDismissLabel": "İmtina edin", "searchTextFieldPlaceholderLabel": "Axtarın", "noSpellCheckReplacementsLabel": "Əvəzləmə Tapılmadı", "menuDismissLabel": "Menyunu qapadın", "lookUpButtonLabel": "Axtarın", "searchWebButtonLabel": "Vebdə axtarın", "shareButtonLabel": "Paylaşın..." }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_az.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_az.arb", "repo_id": "flutter", "token_count": 484 }
765
{ "lookUpButtonLabel": "Regarder en haut", "searchWebButtonLabel": "Rechercher sur le Web", "shareButtonLabel": "Partager…", "noSpellCheckReplacementsLabel": "Aucun remplacement trouvé", "menuDismissLabel": "Ignorer le menu", "searchTextFieldPlaceholderLabel": "Rechercher", "tabSemanticsLabel": "Onglet $tabIndex sur $tabCount", "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": "min", "timerPickerMinuteLabelOther": "min", "timerPickerSecondLabelOne": "s", "timerPickerSecondLabelOther": "s", "cutButtonLabel": "Couper", "copyButtonLabel": "Copier", "pasteButtonLabel": "Coller", "selectAllButtonLabel": "Tout sélectionner", "modalBarrierDismissLabel": "Ignorer" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_fr_CA.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_fr_CA.arb", "repo_id": "flutter", "token_count": 429 }
766
{ "datePickerHourSemanticsLabelOne": "\u0024\u0068\u006f\u0075\u0072\u0020\u0c97\u0c82\u0c9f\u0cc6", "datePickerHourSemanticsLabelOther": "\u0024\u0068\u006f\u0075\u0072\u0020\u0c97\u0c82\u0c9f\u0cc6", "datePickerMinuteSemanticsLabelOne": "\u0031\u0020\u0ca8\u0cbf\u0cae\u0cbf\u0cb7", "datePickerMinuteSemanticsLabelOther": "\u0024\u006d\u0069\u006e\u0075\u0074\u0065\u0020\u0ca8\u0cbf\u0cae\u0cbf\u0cb7\u0c97\u0cb3\u0cc1", "datePickerDateOrder": "\u0064\u006d\u0079", "datePickerDateTimeOrder": "\u0064\u0061\u0074\u0065\u005f\u0074\u0069\u006d\u0065\u005f\u0064\u0061\u0079\u0050\u0065\u0072\u0069\u006f\u0064", "anteMeridiemAbbreviation": "\u0cac\u0cc6\u0cb3\u0cbf\u0c97\u0ccd\u0c97\u0cc6", "postMeridiemAbbreviation": "\u0cb8\u0c82\u0c9c\u0cc6", "todayLabel": "\u0c87\u0c82\u0ca6\u0cc1", "alertDialogLabel": "\u0c8e\u0c9a\u0ccd\u0c9a\u0cb0\u0cbf\u0c95\u0cc6", "timerPickerHourLabelOne": "\u0c97\u0c82\u0c9f\u0cc6", "timerPickerHourLabelOther": "\u0c97\u0c82\u0c9f\u0cc6\u0c97\u0cb3\u0cc1", "timerPickerMinuteLabelOne": "\u0ca8\u0cbf\u0cae\u0cbf\u002e", "timerPickerMinuteLabelOther": "\u0ca8\u0cbf\u0cae\u0cbf\u002e", "timerPickerSecondLabelOne": "\u0cb8\u0cc6\u002e", "timerPickerSecondLabelOther": "\u0cb8\u0cc6\u002e", "cutButtonLabel": "\u0c95\u0ca4\u0ccd\u0ca4\u0cb0\u0cbf\u0cb8\u0cbf", "copyButtonLabel": "\u0ca8\u0c95\u0cb2\u0cbf\u0cb8\u0cbf", "pasteButtonLabel": "\u0c85\u0c82\u0c9f\u0cbf\u0cb8\u0cbf", "selectAllButtonLabel": "\u0c8e\u0cb2\u0ccd\u0cb2\u0cb5\u0ca8\u0ccd\u0ca8\u0cc2\u0020\u0c86\u0caf\u0ccd\u0c95\u0cc6\u0cae\u0cbe\u0ca1\u0cbf", "modalBarrierDismissLabel": "\u0cb5\u0c9c\u0cbe\u0c97\u0cca\u0cb3\u0cbf\u0cb8\u0cbf", "tabSemanticsLabel": "\u0024\u0074\u0061\u0062\u0043\u006f\u0075\u006e\u0074\u0020\u0cb0\u0cb2\u0ccd\u0cb2\u0cbf\u0ca8\u0020\u0024\u0074\u0061\u0062\u0049\u006e\u0064\u0065\u0078\u0020\u0c9f\u0ccd\u0caf\u0cbe\u0cac\u0ccd", "searchTextFieldPlaceholderLabel": "\u0cb9\u0cc1\u0ca1\u0cc1\u0c95\u0cbf", "noSpellCheckReplacementsLabel": "\u0caf\u0cbe\u0cb5\u0cc1\u0ca6\u0cc7\u0020\u0cac\u0ca6\u0cb2\u0cbe\u0cb5\u0ca3\u0cc6\u0c97\u0cb3\u0cc1\u0020\u0c95\u0c82\u0ca1\u0cc1\u0cac\u0c82\u0ca6\u0cbf\u0cb2\u0ccd\u0cb2", "menuDismissLabel": "\u0cae\u0cc6\u0ca8\u0cc1\u0cb5\u0ca8\u0ccd\u0ca8\u0cc1\u0020\u0cb5\u0c9c\u0cbe\u0c97\u0cc6\u0cc2\u0cb3\u0cbf\u0cb8\u0cbf", "lookUpButtonLabel": "\u0cae\u0cc7\u0cb2\u0cc6\u0020\u0ca8\u0ccb\u0ca1\u0cbf", "searchWebButtonLabel": "\u0cb5\u0cc6\u0cac\u0ccd\u200c\u0ca8\u0cb2\u0ccd\u0cb2\u0cbf\u0020\u0cb9\u0cc1\u0ca1\u0cc1\u0c95\u0cbf", "shareButtonLabel": "\u0cb9\u0c82\u0c9a\u0cbf\u0c95\u0cca\u0cb3\u0ccd\u0cb3\u0cbf\u002e\u002e\u002e", "clearButtonLabel": "\u0043\u006c\u0065\u0061\u0072" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_kn.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_kn.arb", "repo_id": "flutter", "token_count": 1715 }
767
{ "datePickerHourSemanticsLabelOne": "$hourଟା", "datePickerHourSemanticsLabelOther": "$hourଟା", "datePickerMinuteSemanticsLabelOne": "1 ମିନିଟ୍", "datePickerMinuteSemanticsLabelOther": "$minute ମିନିଟ୍", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "ଆଜି", "alertDialogLabel": "ଆଲର୍ଟ", "timerPickerHourLabelOne": "ଘଣ୍ଟା", "timerPickerHourLabelOther": "ଘଣ୍ଟା", "timerPickerMinuteLabelOne": "ମିନିଟ୍", "timerPickerMinuteLabelOther": "ମିନିଟ୍", "timerPickerSecondLabelOne": "ସେକେଣ୍ଡ", "timerPickerSecondLabelOther": "ସେକେଣ୍ଡ", "cutButtonLabel": "କଟ୍ କରନ୍ତୁ", "copyButtonLabel": "କପି କରନ୍ତୁ", "pasteButtonLabel": "ପେଷ୍ଟ କରନ୍ତୁ", "selectAllButtonLabel": "ସମସ୍ତ ଚୟନ କରନ୍ତୁ", "tabSemanticsLabel": "$tabCountର $tabIndex ଟାବ୍", "modalBarrierDismissLabel": "ଖାରଜ କରନ୍ତୁ", "searchTextFieldPlaceholderLabel": "ସନ୍ଧାନ କରନ୍ତୁ", "noSpellCheckReplacementsLabel": "କୌଣସି ରିପ୍ଲେସମେଣ୍ଟ ମିଳିଲା ନାହିଁ", "menuDismissLabel": "ମେନୁ ଖାରଜ କରନ୍ତୁ", "lookUpButtonLabel": "ଉପରକୁ ଦେଖନ୍ତୁ", "searchWebButtonLabel": "ୱେବ ସର୍ଚ୍ଚ କରନ୍ତୁ", "shareButtonLabel": "ସେୟାର୍ କରନ୍ତୁ...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_or.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_or.arb", "repo_id": "flutter", "token_count": 1010 }
768
{ "datePickerHourSemanticsLabelOne": "$hour అవుతుంది", "datePickerHourSemanticsLabelOther": "$hour అవుతుంది", "datePickerMinuteSemanticsLabelOne": "1 నిమిషం", "datePickerMinuteSemanticsLabelOther": "$minute నిమిషాలు", "datePickerDateOrder": "mdy", "datePickerDateTimeOrder": "date_time_dayPeriod", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "todayLabel": "ఈరోజు", "alertDialogLabel": "అలర్ట్", "timerPickerHourLabelOne": "గంట", "timerPickerHourLabelOther": "గంటలు", "timerPickerMinuteLabelOne": "నిమి.", "timerPickerMinuteLabelOther": "నిమి.", "timerPickerSecondLabelOne": "సెకన్లు.", "timerPickerSecondLabelOther": "సెకన్లు.", "cutButtonLabel": "కత్తిరించండి", "copyButtonLabel": "కాపీ చేయి", "pasteButtonLabel": "పేస్ట్ చేయండి", "selectAllButtonLabel": "అన్నింటినీ ఎంచుకోండి", "tabSemanticsLabel": "$tabCountలో $tabIndexవ ట్యాబ్", "modalBarrierDismissLabel": "విస్మరించు", "searchTextFieldPlaceholderLabel": "సెర్చ్ చేయి", "noSpellCheckReplacementsLabel": "రీప్లేస్‌మెంట్‌లు ఏవీ కనుగొనబడలేదు", "menuDismissLabel": "మెనూను తీసివేయండి", "lookUpButtonLabel": "వెతకండి", "searchWebButtonLabel": "వెబ్‌లో సెర్చ్ చేయండి", "shareButtonLabel": "షేర్ చేయండి...", "clearButtonLabel": "Clear" }
flutter/packages/flutter_localizations/lib/src/l10n/cupertino_te.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_te.arb", "repo_id": "flutter", "token_count": 1075 }
769
{ "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "Maak navigasiekieslys oop", "backButtonTooltip": "Terug", "closeButtonTooltip": "Maak toe", "deleteButtonTooltip": "Vee uit", "nextMonthTooltip": "Volgende maand", "previousMonthTooltip": "Vorige maand", "nextPageTooltip": "Volgende bladsy", "previousPageTooltip": "Vorige bladsy", "firstPageTooltip": "Eerste bladsy", "lastPageTooltip": "Laaste bladsy", "showMenuTooltip": "Wys kieslys", "aboutListTileTitle": "Meer oor $applicationName", "licensesPageTitle": "Lisensies", "pageRowsInfoTitle": "$firstRow–$lastRow van $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow van ongeveer $rowCount", "rowsPerPageTitle": "Rye per bladsy:", "tabLabel": "Oortjie $tabIndex van $tabCount", "selectedRowCountTitleOne": "1 item is gekies", "selectedRowCountTitleOther": "$selectedRowCount items is gekies", "cancelButtonLabel": "Kanselleer", "closeButtonLabel": "Maak toe", "continueButtonLabel": "Gaan voort", "copyButtonLabel": "Kopieer", "cutButtonLabel": "Knip", "scanTextButtonLabel": "Skandeer teks", "okButtonLabel": "OK", "pasteButtonLabel": "Plak", "selectAllButtonLabel": "Kies alles", "viewLicensesButtonLabel": "Bekyk lisensies", "anteMeridiemAbbreviation": "vm.", "postMeridiemAbbreviation": "nm.", "timePickerHourModeAnnouncement": "Kies ure", "timePickerMinuteModeAnnouncement": "Kies minute", "modalBarrierDismissLabel": "Maak toe", "signedInLabel": "Aangemeld", "hideAccountsLabel": "Versteek rekeninge", "showAccountsLabel": "Wys rekeninge", "drawerLabel": "Navigasiekieslys", "popupMenuLabel": "Opspringkieslys", "dialogLabel": "Dialoog", "alertDialogLabel": "Opletberig", "searchFieldLabel": "Soek", "reorderItemToStart": "Skuif na die begin", "reorderItemToEnd": "Skuif na die einde", "reorderItemUp": "Skuif op", "reorderItemDown": "Skuif af", "reorderItemLeft": "Skuif na links", "reorderItemRight": "Skuif na regs", "expandedIconTapHint": "Vou in", "collapsedIconTapHint": "Vou uit", "remainingTextFieldCharacterCountOne": "1 karakter oor", "remainingTextFieldCharacterCountOther": "$remainingCount karakters oor", "refreshIndicatorSemanticLabel": "Herlaai", "moreButtonTooltip": "Nog", "dateSeparator": "-", "dateHelpText": "dd-mm-jjjj", "selectYearSemanticsLabel": "Kies jaar", "unspecifiedDate": "Datum", "unspecifiedDateRange": "Datumreeks", "dateInputLabel": "Voer datum in", "dateRangeStartLabel": "Begindatum", "dateRangeEndLabel": "Einddatum", "dateRangeStartDateSemanticLabel": "Begindatum $fullDate", "dateRangeEndDateSemanticLabel": "Einddatum $fullDate", "invalidDateFormatLabel": "Ongeldige formaat.", "invalidDateRangeLabel": "Ongeldige reeks.", "dateOutOfRangeLabel": "Buite reeks.", "saveButtonLabel": "Stoor", "datePickerHelpText": "Kies datum", "dateRangePickerHelpText": "Kies reeks", "calendarModeButtonLabel": "Skakel oor na kalender", "inputDateModeButtonLabel": "Skakel oor na invoer", "timePickerDialHelpText": "Kies tyd", "timePickerInputHelpText": "Voer tyd in", "timePickerHourLabel": "Uur", "timePickerMinuteLabel": "Minuut", "invalidTimeLabel": "Voer 'n geldige tyd in", "dialModeButtonLabel": "Skakel oor na wyserplaatkiesermodus", "inputTimeModeButtonLabel": "Skakel oor na teksinvoermodus", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "1 lisensie", "licensesPackageDetailTextOther": "$licenseCount lisensies", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Channel Down", "keyboardKeyChannelUp": "Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Power", "keyboardKeyPowerOff": "Power Off", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Spasie", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Kieslysbalkkieslys", "currentDateLabel": "Vandag", "scrimLabel": "Skerm", "bottomSheetLabel": "Onderste blad", "scrimOnTapHint": "Maak $modalRouteContentName toe", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "dubbeltik om in te vou", "expansionTileCollapsedHint": "dubbeltik om uit te vou", "expansionTileExpandedTapHint": "Vou in", "expansionTileCollapsedTapHint": "Vou uit vir meer besonderhede", "expandedHint": "Ingevou", "collapsedHint": "Uitgevou", "menuDismissLabel": "Maak kieslys toe", "lookUpButtonLabel": "Kyk op", "searchWebButtonLabel": "Deursoek web", "shareButtonLabel": "Deel …", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_af.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_af.arb", "repo_id": "flutter", "token_count": 2242 }
770
{ "scriptCategory": "English-like", "@scriptCategory": { "description": "The name of the language's script category (see https://material.io/design/typography/language-support.html#language-categories-reference).", "x-flutter-type": "scriptCategory" }, "timeOfDayFormat": "h:mm a", "@timeOfDayFormat": { "description": "The ICU 'Short Time' pattern, such as 'HH:mm', 'h:mm a', 'H:mm'. See: http://demo.icu-project.org/icu-bin/locexp?d_=en&_=en_US", "x-flutter-type": "icuShortTimePattern" }, "openAppDrawerTooltip": "Open navigation menu", "@openAppDrawerTooltip": { "description": "The tooltip for the leading app bar menu (aka 'hamburger') button." }, "backButtonTooltip": "Back", "@backButtonTooltip": { "description": "The tooltip for the back button, which closes the current page and returns to the previous one." }, "clearButtonTooltip": "Clear text", "@clearButtonTooltip": { "description": "The tooltip for the button that clears the text input on the search view." }, "closeButtonTooltip": "Close", "@closeButtonTooltip": { "description": "The tooltip for the close button, which closes the current page and returns to the previous one." }, "deleteButtonTooltip": "Delete", "@deleteButtonTooltip": { "description": "The tooltip for the delete button of chips." }, "moreButtonTooltip": "More", "@moreButtonTooltip": { "description": "The tooltip for the more button in the text selection menu, which shows the overflowing menu items." }, "nextMonthTooltip": "Next month", "@nextMonthTooltip": { "description": "The tooltip for the month picker's 'next month' button." }, "previousMonthTooltip": "Previous month", "@previousMonthTooltip": { "description": "The tooltip for the month picker's 'previous month' button." }, "nextPageTooltip": "Next page", "@nextPageTooltip": { "description": "The tooltip for the button that sends the user to the next page of a paginated data table." }, "previousPageTooltip": "Previous page", "@previousPageTooltip": { "description": "The tooltip for the button that sends the user to the previous page of a paginated data table." }, "firstPageTooltip": "First page", "@firstPageTooltip": { "description": "The tooltip for the button that sends the user to the first page of a paginated data table." }, "lastPageTooltip": "Last page", "@lastPageTooltip": { "description": "The tooltip for the button that sends the user to the last page of a paginated data table." }, "showMenuTooltip": "Show menu", "@showMenuTooltip": { "description": "The tooltip for the button that shows a popup menu." }, "scrimLabel": "Scrim", "@scrimLabel": { "description": "The label for the scrim rendered underneath the content of a bottom sheet (used as the 'modalRouteContentName' of the 'scrimOnTapHint' message)." }, "bottomSheetLabel": "Bottom Sheet", "@bottomSheetLabel": { "description": "The label for a BottomSheet." }, "scrimOnTapHint": "Close $modalRouteContentName", "@scrimOnTapHint": { "description": "The onTapHint for the scrim rendered underneath the content of a modal route (especially a bottom sheet) which users can tap to dismiss the content.", "parameters": "modalRouteContentName" }, "aboutListTileTitle": "About $applicationName", "@aboutListTileTitle": { "description": "The default title for the drawer item that shows an about page for the application. The value of $applicationName is the name of the application, like GMail or Chrome.", "parameters": "applicationName" }, "licensesPageTitle": "Licenses", "@licensesPageTitle": { "description": "The title for the Flutter licenses page." }, "licensesPackageDetailTextZero": "No licenses", "@licensesPackageDetailTextZero": { "optional": true }, "licensesPackageDetailTextOne": "1 license", "@licensesPackageDetailTextOne": { "optional": true }, "@licensesPackageDetailTextTwo": { "optional": true }, "@licensesPackageDetailTextFew": { "optional": true }, "@licensesPackageDetailTextMany": { "optional": true }, "licensesPackageDetailTextOther": "$licenseCount licenses", "@licensesPackageDetailText": { "description": "The subtitle and detail text for a package displayed on the Flutter licenses page. The value of $licenseCount is an integer which indicates the number of licenses the package has.", "plural": "licenseCount" }, "pageRowsInfoTitle": "$firstRow–$lastRow of $rowCount", "@pageRowsInfoTitle": { "description": "The text shown in the footer of a paginated data table when the exact overall row count is known. This message describes an integer range where $firstRow is the index of the start of the range, $lastRow is the index of the end of the range, and $rowCount is the limit of the range. All values are greater than or equal to zero.", "parameters": "firstRow, lastRow, rowCount" }, "pageRowsInfoTitleApproximate": "$firstRow–$lastRow of about $rowCount", "@pageRowsInfoTitleApproximate": { "description": "The text shown in the footer of a paginated data table when the exact overall row count is unknown. This message describes an integer range where $firstRow is the index of the start of the range, $lastRow is the index of the end of the range, and $rowCount is the limit of the range. All values are greater than or equal to zero.", "parameters": "firstRow, lastRow, rowCount" }, "rowsPerPageTitle": "Rows per page:", "@rowsPerPageTitle": { "description": "The caption for the drop-down button on a paginated data table's footer that allows the user to control the number of rows of data per page of the table." }, "tabLabel": "Tab $tabIndex of $tabCount", "@tabLabel": { "description": "The accessibility label used on a tab. This message describes the index of the selected tab and how many tabs there are, e.g. 'Tab 1 of 2'. All values are greater than or equal to one.", "parameters": "tabIndex, tabCount" }, "selectedRowCountTitleZero": "No items selected", "@selectedRowCountTitleZero": { "optional": true }, "selectedRowCountTitleOne": "1 item selected", "@selectedRowCountTitleOne": { "optional": true }, "@selectedRowCountTitleTwo": { "optional": true }, "@selectedRowCountTitleFew": { "optional": true }, "@selectedRowCountTitleMany": { "optional": true }, "selectedRowCountTitleOther": "$selectedRowCount items selected", "@selectedRowCountTitle": { "description": "The title for the header of a paginated data table when the user is selecting rows. The value of $selectedRowCount is an integer which indicates the number of data table row elements that have been selected.", "plural": "selectedRowCount" }, "cancelButtonLabel": "Cancel", "@cancelButtonLabel": { "description": "The label for cancel buttons and menu items." }, "closeButtonLabel": "Close", "@closeButtonLabel": { "description": "The label for close buttons and menu items." }, "continueButtonLabel": "Continue", "@continueButtonLabel": { "description": "The label for continue buttons and menu items." }, "copyButtonLabel": "Copy", "@copyButtonLabel": { "description": "The label for copy buttons and menu items." }, "cutButtonLabel": "Cut", "@cutButtonLabel": { "description": "The label for cut buttons and menu items." }, "scanTextButtonLabel": "Scan text", "@scanTextButtonLabel": { "description": "The label for scan text buttons and menu items for starting the insertion of text via OCR." }, "lookUpButtonLabel": "Look Up", "@lookUpButtonLabel": { "description": "The label for the Look Up button and menu items." }, "searchWebButtonLabel": "Search Web", "@searchWebButtonLabel": { "description": "The label for the Search Web button and menu items." }, "shareButtonLabel": "Share", "@shareButtonLabel": { "description": "The label for the Share button and menu items." }, "okButtonLabel": "OK", "@okButtonLabel": { "description": "The label for OK buttons and menu items." }, "pasteButtonLabel": "Paste", "@pasteButtonLabel": { "description": "The label for paste buttons and menu items." }, "selectAllButtonLabel": "Select all", "@selectAllButtonLabel": { "description": "The label for select-all buttons and menu items." }, "viewLicensesButtonLabel": "View licenses", "@viewLicensesButtonLabel": { "description": "The label for the button in the about box that leads the user to a list of all licenses that apply to the application." }, "anteMeridiemAbbreviation": "AM", "@anteMeridiemAbbreviation": { "description": "The abbreviation for ante meridiem (before noon) shown in the time picker. Translations for this abbreviation will only be provided for locales that support it." }, "postMeridiemAbbreviation": "PM", "@postMeridiemAbbreviation": { "description": "The abbreviation for post meridiem (after noon) shown in the time picker. Translations for this abbreviation will only be provided for locales that support it." }, "timePickerHourModeAnnouncement": "Select hours", "@timePickerHourModeAnnouncement": { "description": "The audio announcement made when the time picker dialog is set to hour mode." }, "timePickerMinuteModeAnnouncement": "Select minutes", "@timePickerMinuteModeAnnouncement": { "description": "The audio announcement made when the time picker dialog is set to minute mode." }, "modalBarrierDismissLabel": "Dismiss", "@modalBarrierDismissLabel": { "description": "Label read out by accessibility tools (TalkBack or VoiceOver) for a modal barrier to indicate that a tap dismisses the barrier. A modal barrier can for example be found behind a alert or popup to block user interaction with elements behind it." }, "menuDismissLabel": "Dismiss menu", "@menuDismissLabel": { "description": "Label read out by accessibility tools (TalkBack or VoiceOver) for the area around a menu to indicate that a tap dismisses the menu." }, "dateSeparator": "/", "@dateSeparator": { "description": "The character string used to separate the parts of a compact date format. For example 'mm/dd/yyyy' has a separator of '/'." }, "dateHelpText": "mm/dd/yyyy", "@dateHelpText": { "description": "The help text used on an empty text input date field to indicate the date format being asked for." }, "selectYearSemanticsLabel": "Select year", "@selectYearSemanticsLabel": { "description": "The accessibility label used to announce when the user has entered the year selection mode in the date picker." }, "unspecifiedDate": "Date", "@unspecifiedDate": { "description": "The label used to indicate a date that has not been entered or selected in the date picker." }, "unspecifiedDateRange": "Date Range", "@unspecifiedDateRange": { "description": "The label used to indicate a date range that has not been entered or selected in the date range picker." }, "dateInputLabel": "Enter Date", "@dateInputLabel": { "description": "The label used to describe the input text field used in the date picker." }, "dateRangeStartLabel": "Start Date", "@dateRangeStartLabel": { "description": "The label used to describe the starting date input text field used in the date range picker." }, "dateRangeEndLabel": "End Date", "@dateRangeEndLabel": { "description": "The label used to describe the ending date input text field used in the date range picker." }, "dateRangeStartDateSemanticLabel": "Start date $fullDate", "@dateRangeStartDateSemanticLabel": { "description": "Accessibility announcement that is used when the user navigates to the selected start date in the date range picker.", "parameters": "$fullDate" }, "dateRangeEndDateSemanticLabel": "End date $fullDate", "@dateRangeEndDateSemanticLabel": { "description": "Accessibility announcement that is used when the user navigates to the selected end date in the date range picker.", "parameters": "$fullDate" }, "invalidDateFormatLabel": "Invalid format.", "@invalidDateFormatLabel": { "description": "Error message displayed to the user when they have entered a text string in an input field of the date picker that is not in a valid date format." }, "invalidDateRangeLabel": "Invalid range.", "@invalidDateRangeLabel": { "description": "Error message displayed to the user when they have entered an invalid date range in the input fields of the date range picker." }, "dateOutOfRangeLabel": "Out of range.", "@dateOutOfRangeLabel": { "description": "Error message displayed to the user when they have entered a date that is outside the valid range for the date picker." }, "saveButtonLabel": "Save", "@saveButtonLabel": { "description": "Label for a 'Save' button used in full screen dialogs." }, "datePickerHelpText": "Select date", "@datePickerHelpText": { "description": "Label used in the header of the date picker dialog" }, "dateRangePickerHelpText": "Select range", "@dateRangePickerHelpText": { "description": "Label used in the header of the date range picker dialog." }, "calendarModeButtonLabel": "Switch to calendar", "@calendarModeButtonLabel": { "description": "Tooltip used for the calendar mode button of the date pickers." }, "inputDateModeButtonLabel": "Switch to input", "@inputDateModeButtonLabel": { "description": "Tooltip used for the text input mode button of the date pickers." }, "timePickerDialHelpText": "Select time", "@timePickerDialHelpText": { "description": "Label used in the header of the time picker dialog when using the clock dial to select a time." }, "timePickerInputHelpText": "Enter time", "@timePickerInputHelpText": { "description": "Label used in the header of the time picker dialog when using the text input to enter a time." }, "timePickerHourLabel": "Hour", "@timePickerHourLabel": { "description": "Label indicating the text field for inputting an hour when entering a time." }, "timePickerMinuteLabel": "Minute", "@timePickerMinuteLabel": { "description": "Label indicating the text field for inputting a minute when entering a time." }, "invalidTimeLabel": "Enter a valid time", "@invalidTimeLabel": { "description": "Error message displayed to the user when they have entered an invalid time." }, "dialModeButtonLabel": "Switch to dial picker mode", "@dialModeButtonLabel": { "description": "Tooltip used for the clock dial mode button of the time picker." }, "inputTimeModeButtonLabel": "Switch to text input mode", "@inputTimeModeButtonLabel": { "description": "Tooltip used for the text input mode button of the time picker." }, "signedInLabel": "Signed in", "@signedInLabel": { "description": "The accessibility label used to indicate which account is signed in, in a UserAccountsDrawerHeader, when the accessibility user navigates the UI. This phrase serves as an adjective with respect to the user. The phrase indicates that the user is currently signed in." }, "hideAccountsLabel": "Hide accounts", "@hideAccountsLabel": { "description": "The accessibility label used for the button on a UserAccountsDrawerHeader that hides the list of accounts." }, "showAccountsLabel": "Show accounts", "@showAccountsLabel": { "description": "The accessibility label used for the button on a UserAccountsDrawerHeader that shows the list of accounts." }, "drawerLabel": "Navigation menu", "@drawerLabel": { "description": "The audio announcement made when the Drawer is opened." }, "menuBarMenuLabel": "Menu bar menu", "@menuBarMenuLabel": { "description": "The audio announcement made when a MenuBarMenu is opened." }, "popupMenuLabel": "Popup menu", "@popupMenuLabel": { "description": "The audio announcement made when a PopupMenu is opened." }, "dialogLabel": "Dialog", "@dialogLabel": { "description": "The audio announcement made when a Dialog is opened." }, "alertDialogLabel": "Alert", "@alertDialogLabel": { "description": "The audio announcement made when an AlertDialog is opened." }, "searchFieldLabel": "Search", "@searchFieldLabel": { "description": "Label indicating that a text field is a search field. This will be used as a hint text in the text field." }, "currentDateLabel": "Today", "@currentDateLabel": { "description": "Label indicating that the focused date is the current date." }, "selectedDateLabel": "Selected", "@selectedDateLabel": { "description": "The semantics label to describe the selected date in the calendar picker invoked using [showDatePicker]." }, "reorderItemToStart": "Move to the start", "@reorderItemToStart": { "description": "The audio announcement to move an item in a Reorderable List to the start of the list." }, "reorderItemToEnd": "Move to the end", "@reorderItemToEnd": { "description": "The audio announcement to move an item in a Reorderable List to the end of the list." }, "reorderItemUp": "Move up", "@reorderItemUp": { "description": "The audio announcement to move an item in a Reorderable List up in the list when it is oriented vertically." }, "reorderItemDown": "Move down", "@reorderItemDown": { "description": "The audio announcement to move an item in a Reorderable List down in the list when it is oriented vertically." }, "reorderItemLeft": "Move left", "@reorderItemLeft": { "description": "The audio announcement to move an item in a Reorderable List left in the list when it is oriented horizontally." }, "reorderItemRight": "Move right", "@reorderItemRight": { "description": "The audio announcement to move an item in a Reorderable List right in the list when it is oriented horizontally." }, "expandedIconTapHint": "Collapse", "@expandedIconTapHint": { "description": "The verb which describes what happens when an expanded ExpandIcon toggle button is pressed. This is used by TalkBack on Android to replace the default hint on the accessibility action. The verb will be concatenated with a prefix string which describes how to perform the action, which by default is 'double tap to activate'. In the case of US english, this would be 'double tap to collapse.' The exact phrasing of the hint will vary based on locale" }, "collapsedIconTapHint": "Expand", "@collapsedIconTapHint": { "description": "The verb which describes what happens when a collapsed ExpandIcon toggle button is pressed. This is used by TalkBack on Android to replace the default hint on the accessibility action. The verb will be concatenated with a prefix string which describes how to perform the action, which by default is 'double tap to activate'. In the case of US english, this would be 'double tap to expand.' The exact phrasing of the hint will vary based on locale" }, "expansionTileExpandedHint": "double tap to collapse", "@expansionTileExpandedHint": { "description": "The verb which describes the tap action on an expanded ExpansionTile. This is used by VoiceOver on iOS and macOS. This string will be appended to the collapsedHint string which describes the action to be performed on an expanded ExpansionTile. In the case of US english, this would be 'Expanded\n double tap to collapse.' The exact phrasing of the hint will vary based on locale" }, "expansionTileCollapsedHint": "double tap to expand", "@expansionTileCollapsedHint": { "description": "The verb which describes the tap action on a collapsed ExpansionTile. This is used by VoiceOver on iOS and macOS. This string will be appended to the expandedHint string which describes the action to be performed on a collapsed ExpansionTile. In the case of US english, this would be 'Collapsed\n double tap to expand.' The exact phrasing of the hint will vary based on locale" }, "expansionTileExpandedTapHint": "Collapse", "@expansionTileExpandedTapHint": { "description": "The verb which describes what happens when an expanded ExpansionTile is pressed. This is used by TalkBack on Android to replace the default hint on the accessibility action. The verb will be concatenated with a prefix string which describes how to perform the action, which by default is 'double tap to activate'. In the case of US english, this would be 'double tap to collapse.' The exact phrasing of the hint will vary based on locale" }, "expansionTileCollapsedTapHint": "Expand for more details", "@expansionTileCollapsedTapHint": { "description": "The verb which describes what happens when an expanded ExpansionTile is pressed. This is used by TalkBack on Android to replace the default hint on the accessibility action. The verb will be concatenated with a prefix string which describes how to perform the action, which by default is 'double tap to activate'. In the case of US english, this would be 'double tap to expand for more details.' The exact phrasing of the hint will vary based on locale" }, "expandedHint": "Collapsed", "@expandedHint": { "description": "The verb which describes the ExpansionTile state when an expanded ExpansionTile is pressed." }, "collapsedHint": "Expanded", "@collapsedHint": { "description": "The verb which describes the ExpansionTile state when a collapsed ExpansionTile is pressed." }, "remainingTextFieldCharacterCountZero": "No characters remaining", "@remainingTextFieldCharacterCountZero": { "optional": true }, "remainingTextFieldCharacterCountOne": "1 character remaining", "@remainingTextFieldCharacterCountOne": { "optional": true }, "@remainingTextFieldCharacterCountTwo": { "optional": true }, "@remainingTextFieldCharacterCountFew": { "optional": true }, "@remainingTextFieldCharacterCountMany": { "optional": true }, "remainingTextFieldCharacterCountOther": "$remainingCount characters remaining", "@remainingTextFieldCharacterCount": { "description": "The label for the TextField's character counter. remainingCharacters is a integer representing how many more characters the user can type into the text field before using up a given budget. All values are greater than or equal to zero.", "plural": "remainingCount" }, "refreshIndicatorSemanticLabel": "Refresh", "@refreshIndicatorSemanticLabel": { "description": "The verb which describes what happens when a RefreshIndicator is displayed on screen. This is used by TalkBack on Android to announce that a refresh is happening." }, "keyboardKeyAlt": "Alt", "@keyboardKeyAlt": { "description": "Part of a keyboard shortcut label for the keyboard key 'Alt' (alt) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyAltGraph": "AltGr", "@keyboardKeyAltGraph": { "description": "Part of a keyboard shortcut label for the keyboard key 'AltGr' (altGraph) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyBackspace": "Backspace", "@keyboardKeyBackspace": { "description": "Part of a keyboard shortcut label for the keyboard key 'Backspace' (backspace) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyCapsLock": "Caps Lock", "@keyboardKeyCapsLock": { "description": "Part of a keyboard shortcut label for the keyboard key 'Caps Lock' (capsLock) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyChannelDown": "Channel Down", "@keyboardKeyChannelDown": { "description": "Part of a keyboard shortcut label for the keyboard key 'Channel Down' (channelDown) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyChannelUp": "Channel Up", "@keyboardKeyChannelUp": { "description": "Part of a keyboard shortcut label for the keyboard key 'Channel Up' (channelUp) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyControl": "Ctrl", "@keyboardKeyControl": { "description": "Part of a keyboard shortcut label for the keyboard key 'Ctrl' (control) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyDelete": "Del", "@keyboardKeyDelete": { "description": "Part of a keyboard shortcut label for the keyboard key 'Del' (delete) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyEject": "Eject", "@keyboardKeyEject": { "description": "Part of a keyboard shortcut label for the keyboard key 'Eject' (eject) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyEnd": "End", "@keyboardKeyEnd": { "description": "Part of a keyboard shortcut label for the keyboard key 'End' (end) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyEscape": "Esc", "@keyboardKeyEscape": { "description": "Part of a keyboard shortcut label for the keyboard key 'Esc' (escape) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyFn": "Fn", "@keyboardKeyFn": { "description": "Part of a keyboard shortcut label for the keyboard key 'Fn' (fn) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyHome": "Home", "@keyboardKeyHome": { "description": "Part of a keyboard shortcut label for the keyboard key 'Home' (home) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyInsert": "Insert", "@keyboardKeyInsert": { "description": "Part of a keyboard shortcut label for the keyboard key 'Insert' (insert) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyMeta": "Meta", "@keyboardKeyMeta": { "description": "Part of a keyboard shortcut label for the keyboard key 'Meta' (meta) to be displayed in an application menu next to the menu item that this keyboard key triggers on non-macOS and non-Windows hosts. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This key is usually designated by a Windows logo on non-macOS keyboards." }, "keyboardKeyMetaMacOs": "Command", "@keyboardKeyMetaMacOs": { "description": "Part of a keyboard shortcut label for the keyboard key 'Command' (meta) to be displayed in an application menu next to the menu item that this keyboard key triggers on a macOS host. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This key is usually designated by a ⌘ symbol on macOS keyboards." }, "keyboardKeyMetaWindows": "Win", "@keyboardKeyMetaWindows": { "description": "Part of a keyboard shortcut label for the keyboard key 'Windows' (meta) to be displayed in an application menu next to the menu item that this keyboard key triggers on a Windows host. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This key is usually designated by a Windows logo on keyboards." }, "keyboardKeyNumLock": "Num Lock", "@keyboardKeyNumLock": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num Lock' (numLock) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyNumpad1": "Num 1", "@keyboardKeyNumpad1": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 1' (numpad1) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '1', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpad2": "Num 2", "@keyboardKeyNumpad2": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 2' (numpad2) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '2', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpad3": "Num 3", "@keyboardKeyNumpad3": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 3' (numpad3) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '3', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpad4": "Num 4", "@keyboardKeyNumpad4": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 4' (numpad4) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '4', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpad5": "Num 5", "@keyboardKeyNumpad5": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 5' (numpad5) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '5', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpad6": "Num 6", "@keyboardKeyNumpad6": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 6' (numpad6) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '6', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpad7": "Num 7", "@keyboardKeyNumpad7": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 7' (numpad7) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '7', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpad8": "Num 8", "@keyboardKeyNumpad8": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 8' (numpad8) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '8', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpad9": "Num 9", "@keyboardKeyNumpad9": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 9' (numpad9) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '9', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpad0": "Num 0", "@keyboardKeyNumpad0": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num 0' (numpad0) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular number '0', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadAdd": "Num +", "@keyboardKeyNumpadAdd": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num +' (numpadAdd) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular '+', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadComma": "Num ,", "@keyboardKeyNumpadComma": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num ,' (numpadComma) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular ',', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadDecimal": "Num .", "@keyboardKeyNumpadDecimal": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num .' (numpadDecimal) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular '.', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadDivide": "Num /", "@keyboardKeyNumpadDivide": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num /' (numpadDivide) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular '/', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadEnter": "Num Enter", "@keyboardKeyNumpadEnter": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num Enter' (numpadEnter) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular Enter key, but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadEqual": "Num =", "@keyboardKeyNumpadEqual": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num =' (numpadEqual) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular '=', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadMultiply": "Num *", "@keyboardKeyNumpadMultiply": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num *' (numpadMultiply) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular '*', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadParenLeft": "Num (", "@keyboardKeyNumpadParenLeft": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num (' (numpadParenLeft) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular '(', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadParenRight": "Num )", "@keyboardKeyNumpadParenRight": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num )' (numpadParenRight) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular ')', but on the number pad, accessed with the NumLock on." }, "keyboardKeyNumpadSubtract": "Num -", "@keyboardKeyNumpadSubtract": { "description": "Part of a keyboard shortcut label for the keyboard key 'Num -' (numpadSubtract) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is a regular '-', but on the number pad, accessed with the NumLock on." }, "keyboardKeyPageDown": "PgDown", "@keyboardKeyPageDown": { "description": "Part of a keyboard shortcut label for the keyboard key 'PgDown' (pageDown) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyPageUp": "PgUp", "@keyboardKeyPageUp": { "description": "Part of a keyboard shortcut label for the keyboard key 'PgUp' (pageUp) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyPower": "Power", "@keyboardKeyPower": { "description": "Part of a keyboard shortcut label for the keyboard key 'Power' (power) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. The key typically turns the computer off and on." }, "keyboardKeyPowerOff": "Power Off", "@keyboardKeyPowerOff": { "description": "Part of a keyboard shortcut label for the keyboard key 'Power Off' (powerOff) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. The key typically turns off the computer." }, "keyboardKeyPrintScreen": "Print Screen", "@keyboardKeyPrintScreen": { "description": "Part of a keyboard shortcut label for the keyboard key 'Print Screen' (printScreen) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyScrollLock": "Scroll Lock", "@keyboardKeyScrollLock": { "description": "Part of a keyboard shortcut label for the keyboard key 'Scroll Lock' (scrollLock) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeySelect": "Select", "@keyboardKeySelect": { "description": "Part of a keyboard shortcut label for the keyboard key 'Select' (select) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale." }, "keyboardKeyShift": "Shift", "@keyboardKeyShift": { "description": "Part of a keyboard shortcut label for the keyboard key 'Shift' (shift) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is the shift modifier key on the left or right sides of the keyboard." }, "keyboardKeySpace": "Space", "@keyboardKeySpace": { "description": "Part of a keyboard shortcut label for the keyboard key 'Space' (space) to be displayed in an application menu next to the menu item that this keyboard key triggers. Should be as short as possible, using standard computer keyboard symbols/terminology for the key in the locale. This is the space bar key." } }
flutter/packages/flutter_localizations/lib/src/l10n/material_en.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_en.arb", "repo_id": "flutter", "token_count": 11405 }
771
{ "scriptCategory": "tall", "timeOfDayFormat": "H:mm", "selectedRowCountTitleOne": "۱ مورد انتخاب شد", "openAppDrawerTooltip": "باز کردن منوی پیمایش", "backButtonTooltip": "برگشت", "closeButtonTooltip": "بستن", "deleteButtonTooltip": "حذف", "nextMonthTooltip": "ماه بعد", "previousMonthTooltip": "ماه قبل", "nextPageTooltip": "صفحه بعد", "previousPageTooltip": "صفحه قبل", "firstPageTooltip": "صفحه اول", "lastPageTooltip": "صفحه آخر", "showMenuTooltip": "نمایش منو", "aboutListTileTitle": "درباره $applicationName", "licensesPageTitle": "پروانه‌ها", "pageRowsInfoTitle": "$firstRow–$lastRow از $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow از حدود $rowCount", "rowsPerPageTitle": "ردیف در هر صفحه:", "tabLabel": "برگه $tabIndex از $tabCount", "selectedRowCountTitleOther": "$selectedRowCount مورد انتخاب شدند", "cancelButtonLabel": "لغو", "closeButtonLabel": "بستن", "continueButtonLabel": "ادامه", "copyButtonLabel": "کپی", "cutButtonLabel": "برش", "scanTextButtonLabel": "اسکن کردن نوشتار", "okButtonLabel": "تأیید", "pasteButtonLabel": "جای‌گذاری", "selectAllButtonLabel": "انتخاب همه", "viewLicensesButtonLabel": "مشاهده پروانه‌ها", "anteMeridiemAbbreviation": "ق.ظ.", "postMeridiemAbbreviation": "ب.ظ.", "timePickerHourModeAnnouncement": "انتخاب ساعت", "timePickerMinuteModeAnnouncement": "انتخاب دقیقه", "signedInLabel": "واردشده به سیستم", "hideAccountsLabel": "پنهان کردن حساب‌ها", "showAccountsLabel": "نشان دادن حساب‌ها", "modalBarrierDismissLabel": "نپذیرفتن", "drawerLabel": "منوی پیمایش", "popupMenuLabel": "منوی بازشو", "dialogLabel": "کادر گفتگو", "alertDialogLabel": "هشدار", "searchFieldLabel": "جستجو", "reorderItemToStart": "انتقال به ابتدا", "reorderItemToEnd": "انتقال به انتها", "reorderItemUp": "انتقال به بالا", "reorderItemDown": "انتقال به پایین", "reorderItemLeft": "انتقال به راست", "reorderItemRight": "انتقال به چپ", "expandedIconTapHint": "کوچک کردن", "collapsedIconTapHint": "بزرگ کردن", "remainingTextFieldCharacterCountOne": "۱ نویسه باقی مانده است", "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": "۱ پروانه", "licensesPackageDetailTextOther": "$licenseCount پروانه", "keyboardKeyAlt": "دگرساز", "keyboardKeyAltGraph": "دگرساز راست", "keyboardKeyBackspace": "پس‌بَر", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "کانال پایین", "keyboardKeyChannelUp": "کانال بالا", "keyboardKeyControl": "مهار", "keyboardKeyDelete": "حذف", "keyboardKeyEject": "خارج کردن", "keyboardKeyEnd": "پایان", "keyboardKeyEscape": "گریز", "keyboardKeyFn": "عملکرد", "keyboardKeyHome": "صفحه اصلی", "keyboardKeyInsert": "درج", "keyboardKeyMeta": "متا", "keyboardKeyNumLock": "قفل اعداد", "keyboardKeyNumpad1": "عدد ۱", "keyboardKeyNumpad2": "عدد ۲", "keyboardKeyNumpad3": "عدد ۳", "keyboardKeyNumpad4": "عدد ۴", "keyboardKeyNumpad5": "عدد ۵", "keyboardKeyNumpad6": "عدد ۶", "keyboardKeyNumpad7": "عدد ۷", "keyboardKeyNumpad8": "عدد ۸", "keyboardKeyNumpad9": "عدد ۹", "keyboardKeyNumpad0": "عدد ۰", "keyboardKeyNumpadAdd": "عدد +", "keyboardKeyNumpadComma": "عدد ,", "keyboardKeyNumpadDecimal": "عدد .", "keyboardKeyNumpadDivide": "عدد /", "keyboardKeyNumpadEnter": "ورود اعداد", "keyboardKeyNumpadEqual": "عدد =", "keyboardKeyNumpadMultiply": "عدد *", "keyboardKeyNumpadParenLeft": "عدد (", "keyboardKeyNumpadParenRight": "عدد )", "keyboardKeyNumpadSubtract": "عدد -", "keyboardKeyPageDown": "صفحه پایین", "keyboardKeyPageUp": "صفحه بالا", "keyboardKeyPower": "روشن/ خاموش", "keyboardKeyPowerOff": "خاموش کردن", "keyboardKeyPrintScreen": "چاپ صفحه", "keyboardKeyScrollLock": "قفل پیمایش", "keyboardKeySelect": "انتخاب", "keyboardKeySpace": "فاصله", "keyboardKeyMetaMacOs": "فرمان", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "منوی نوار منو", "currentDateLabel": "امروز", "scrimLabel": "رویه", "bottomSheetLabel": "برگ زیرین", "scrimOnTapHint": "بستن $modalRouteContentName", "keyboardKeyShift": "کلید تبدیل", "expansionTileExpandedHint": "برای جمع کردن، دوضربه بزنید", "expansionTileCollapsedHint": "برای ازهم بازکردن، دوضربه بزنید", "expansionTileExpandedTapHint": "جمع کردن", "expansionTileCollapsedTapHint": "ازهم بازکردن برای جزئیات بیشتر", "expandedHint": "جمع‌شده", "collapsedHint": "ازهم بازشده", "menuDismissLabel": "بستن منو", "lookUpButtonLabel": "جستجو", "searchWebButtonLabel": "جستجو در وب", "shareButtonLabel": "هم‌رسانی…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_fa.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_fa.arb", "repo_id": "flutter", "token_count": 3270 }
772
{ "scriptCategory": "dense", "timeOfDayFormat": "H:mm", "selectedRowCountTitleOne": "1 件のアイテムを選択中", "openAppDrawerTooltip": "ナビゲーション メニューを開く", "backButtonTooltip": "戻る", "closeButtonTooltip": "閉じる", "deleteButtonTooltip": "削除", "nextMonthTooltip": "来月", "previousMonthTooltip": "前月", "nextPageTooltip": "次のページ", "previousPageTooltip": "前のページ", "firstPageTooltip": "最初のページ", "lastPageTooltip": "最後のページ", "showMenuTooltip": "メニューを表示", "aboutListTileTitle": "$applicationName について", "licensesPageTitle": "ライセンス", "pageRowsInfoTitle": "$firstRow - $lastRow 行(合計 $rowCount 行)", "pageRowsInfoTitleApproximate": "$firstRow – $lastRow 行(合計約 $rowCount 行)", "rowsPerPageTitle": "ページあたりの行数:", "tabLabel": "タブ: $tabIndex/$tabCount", "selectedRowCountTitleOther": "$selectedRowCount 件のアイテムを選択中", "cancelButtonLabel": "キャンセル", "closeButtonLabel": "閉じる", "continueButtonLabel": "続行", "copyButtonLabel": "コピー", "cutButtonLabel": "切り取り", "scanTextButtonLabel": "テキストをスキャン", "okButtonLabel": "OK", "pasteButtonLabel": "貼り付け", "selectAllButtonLabel": "すべてを選択", "viewLicensesButtonLabel": "ライセンスを表示", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "時間を選択", "timePickerMinuteModeAnnouncement": "分を選択", "signedInLabel": "ログイン中", "hideAccountsLabel": "アカウントを非表示", "showAccountsLabel": "アカウントを表示", "modalBarrierDismissLabel": "閉じる", "drawerLabel": "ナビゲーション メニュー", "popupMenuLabel": "ポップアップ メニュー", "dialogLabel": "ダイアログ", "alertDialogLabel": "通知", "searchFieldLabel": "検索", "reorderItemToStart": "先頭に移動", "reorderItemToEnd": "最後に移動", "reorderItemUp": "上に移動", "reorderItemDown": "下に移動", "reorderItemLeft": "左に移動", "reorderItemRight": "右に移動", "expandedIconTapHint": "折りたたむ", "collapsedIconTapHint": "展開", "remainingTextFieldCharacterCountOne": "残り 1 文字(半角相当)", "remainingTextFieldCharacterCountOther": "残り $remainingCount 文字(半角相当)", "refreshIndicatorSemanticLabel": "更新", "moreButtonTooltip": "その他", "dateSeparator": "/", "dateHelpText": "yyyy/mm/dd", "selectYearSemanticsLabel": "年を選択", "unspecifiedDate": "日付", "unspecifiedDateRange": "期間", "dateInputLabel": "日付を入力", "dateRangeStartLabel": "開始日", "dateRangeEndLabel": "終了日", "dateRangeStartDateSemanticLabel": "開始日 $fullDate", "dateRangeEndDateSemanticLabel": "終了日 $fullDate", "invalidDateFormatLabel": "形式が無効です。", "invalidDateRangeLabel": "範囲が無効です。", "dateOutOfRangeLabel": "範囲外です。", "saveButtonLabel": "保存", "datePickerHelpText": "日付の選択", "dateRangePickerHelpText": "期間の選択", "calendarModeButtonLabel": "カレンダーに切り替え", "inputDateModeButtonLabel": "入力に切り替え", "timePickerDialHelpText": "時間の選択", "timePickerInputHelpText": "時間の入力", "timePickerHourLabel": "時", "timePickerMinuteLabel": "分", "invalidTimeLabel": "有効な時刻を入力してください", "dialModeButtonLabel": "ダイヤル選択ツール モードに切り替えます", "inputTimeModeButtonLabel": "テキスト入力モードに切り替えます", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "ライセンス: 1 件", "licensesPackageDetailTextOther": "ライセンス: $licenseCount 件", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "CapsLock", "keyboardKeyChannelDown": "次のチャンネル", "keyboardKeyChannelUp": "前のチャンネル", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "NumLock", "keyboardKeyNumpad1": "テンキー 1", "keyboardKeyNumpad2": "テンキー 2", "keyboardKeyNumpad3": "テンキー 3", "keyboardKeyNumpad4": "テンキー 4", "keyboardKeyNumpad5": "テンキー 5", "keyboardKeyNumpad6": "テンキー 6", "keyboardKeyNumpad7": "テンキー 7", "keyboardKeyNumpad8": "テンキー 8", "keyboardKeyNumpad9": "テンキー 9", "keyboardKeyNumpad0": "テンキー 0", "keyboardKeyNumpadAdd": "テンキー +", "keyboardKeyNumpadComma": "テンキー ,", "keyboardKeyNumpadDecimal": "テンキー .", "keyboardKeyNumpadDivide": "テンキー /", "keyboardKeyNumpadEnter": "テンキー Enter", "keyboardKeyNumpadEqual": "テンキー =", "keyboardKeyNumpadMultiply": "テンキー *", "keyboardKeyNumpadParenLeft": "テンキー (", "keyboardKeyNumpadParenRight": "テンキー )", "keyboardKeyNumpadSubtract": "テンキー -", "keyboardKeyPageDown": "PageDown", "keyboardKeyPageUp": "PageUp", "keyboardKeyPower": "Power", "keyboardKeyPowerOff": "Power Off", "keyboardKeyPrintScreen": "Printscreen", "keyboardKeyScrollLock": "ScrollLock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Space", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "メニューバーのメニュー", "currentDateLabel": "今日", "scrimLabel": "スクリム", "bottomSheetLabel": "ボトムシート", "scrimOnTapHint": "$modalRouteContentName を閉じる", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "ダブルタップすると閉じます", "expansionTileCollapsedHint": "開くにはダブルタップします", "expansionTileExpandedTapHint": "閉じる", "expansionTileCollapsedTapHint": "開いて詳細を表示", "expandedHint": "閉じました", "collapsedHint": "開きました", "menuDismissLabel": "メニューを閉じる", "lookUpButtonLabel": "調べる", "searchWebButtonLabel": "ウェブを検索", "shareButtonLabel": "共有...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_ja.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_ja.arb", "repo_id": "flutter", "token_count": 2695 }
773
{ "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "openAppDrawerTooltip": "Åpne navigasjonsmenyen", "backButtonTooltip": "Tilbake", "closeButtonTooltip": "Lukk", "deleteButtonTooltip": "Slett", "moreButtonTooltip": "Mer", "nextMonthTooltip": "Neste måned", "previousMonthTooltip": "Forrige måned", "nextPageTooltip": "Neste side", "previousPageTooltip": "Forrige side", "firstPageTooltip": "Første side", "lastPageTooltip": "Siste side", "showMenuTooltip": "Vis meny", "aboutListTileTitle": "Om $applicationName", "licensesPageTitle": "Lisenser", "licensesPackageDetailTextOne": "1 lisens", "licensesPackageDetailTextOther": "$licenseCount lisenser", "pageRowsInfoTitle": "$firstRow–$lastRow av $rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow av omtrent $rowCount", "rowsPerPageTitle": "Rader per side:", "tabLabel": "Fane $tabIndex av $tabCount", "selectedRowCountTitleOne": "1 element er valgt", "selectedRowCountTitleOther": "$selectedRowCount elementer er valgt", "cancelButtonLabel": "Avbryt", "closeButtonLabel": "Lukk", "continueButtonLabel": "Fortsett", "copyButtonLabel": "Kopiér", "cutButtonLabel": "Klipp ut", "scanTextButtonLabel": "Skann tekst", "okButtonLabel": "OK", "pasteButtonLabel": "Lim inn", "selectAllButtonLabel": "Velg alle", "viewLicensesButtonLabel": "Se lisenser", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Angi timer", "timePickerMinuteModeAnnouncement": "Angi minutter", "modalBarrierDismissLabel": "Avvis", "dateSeparator": ".", "dateHelpText": "dd.mm.åååå", "selectYearSemanticsLabel": "Velg året", "unspecifiedDate": "Dato", "unspecifiedDateRange": "Datoperiode", "dateInputLabel": "Skriv inn datoen", "dateRangeStartLabel": "Startdato", "dateRangeEndLabel": "Sluttdato", "dateRangeStartDateSemanticLabel": "Startdato $fullDate", "dateRangeEndDateSemanticLabel": "Sluttdato $fullDate", "invalidDateFormatLabel": "Ugyldig format.", "invalidDateRangeLabel": "Ugyldig periode.", "dateOutOfRangeLabel": "Utenfor perioden.", "saveButtonLabel": "Lagre", "datePickerHelpText": "Velg dato", "dateRangePickerHelpText": "Velg datoperiode", "calendarModeButtonLabel": "Bytt til kalender", "inputDateModeButtonLabel": "Bytt til innskriving", "timePickerDialHelpText": "Velg tidspunkt", "timePickerInputHelpText": "Angi et tidspunkt", "timePickerHourLabel": "Time", "timePickerMinuteLabel": "Minutt", "invalidTimeLabel": "Angi et gyldig klokkeslett", "dialModeButtonLabel": "Bytt til modus for valg fra urskive", "inputTimeModeButtonLabel": "Bytt til tekstinndatamodus", "signedInLabel": "Pålogget", "hideAccountsLabel": "Skjul kontoer", "showAccountsLabel": "Vis kontoer", "drawerLabel": "Navigasjonsmeny", "popupMenuLabel": "Forgrunnsmeny", "dialogLabel": "Dialogboks", "alertDialogLabel": "Varsel", "searchFieldLabel": "Søk", "reorderItemToStart": "Flytt til starten", "reorderItemToEnd": "Flytt til slutten", "reorderItemUp": "Flytt opp", "reorderItemDown": "Flytt ned", "reorderItemLeft": "Flytt til venstre", "reorderItemRight": "Flytt til høyre", "expandedIconTapHint": "Skjul", "collapsedIconTapHint": "Vis", "remainingTextFieldCharacterCountOne": "1 tegn gjenstår", "remainingTextFieldCharacterCountOther": "$remainingCount tegn gjenstår", "refreshIndicatorSemanticLabel": "Laster inn på nytt", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "Alt Gr", "keyboardKeyBackspace": "Tilbaketast", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "Forrige kanal", "keyboardKeyChannelUp": "Neste kanal", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Løs ut", "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": "Av/på", "keyboardKeyPowerOff": "Slå av", "keyboardKeyPrintScreen": "PrtScn", "keyboardKeyScrollLock": "ScrLk", "keyboardKeySelect": "Velg", "keyboardKeySpace": "Mellomrom", "keyboardKeyMetaMacOs": "Kommando", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Meny med menylinje", "currentDateLabel": "I dag", "scrimLabel": "Vev", "bottomSheetLabel": "Felt nederst", "scrimOnTapHint": "Lukk $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "dobbelttrykk for å skjule", "expansionTileCollapsedHint": "dobbelttrykk for å vise", "expansionTileExpandedTapHint": "Skjul", "expansionTileCollapsedTapHint": "Vis for å se mer informasjon", "expandedHint": "Skjules", "collapsedHint": "Vises", "menuDismissLabel": "Lukk menyen", "lookUpButtonLabel": "Slå opp", "searchWebButtonLabel": "Søk på nettet", "shareButtonLabel": "Del…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_nb.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_nb.arb", "repo_id": "flutter", "token_count": 2225 }
774
{ "licensesPackageDetailTextFew": "$licenseCount лиценце", "remainingTextFieldCharacterCountFew": "Преостала су $remainingCount знака", "scriptCategory": "English-like", "timeOfDayFormat": "HH:mm", "selectedRowCountTitleFew": "Изабране су $selectedRowCount ставке", "openAppDrawerTooltip": "Отворите мени за навигацију", "backButtonTooltip": "Назад", "closeButtonTooltip": "Затворите", "deleteButtonTooltip": "Избришите", "nextMonthTooltip": "Следећи месец", "previousMonthTooltip": "Претходни месец", "nextPageTooltip": "Следећа страница", "previousPageTooltip": "Претходна страница", "firstPageTooltip": "Прва страница", "lastPageTooltip": "Последња страница", "showMenuTooltip": "Прикажи мени", "aboutListTileTitle": "О апликацији $applicationName", "licensesPageTitle": "Лиценце", "pageRowsInfoTitle": "$firstRow – $lastRow oд $rowCount", "pageRowsInfoTitleApproximate": "$firstRow – $lastRow oд приближно $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": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "Meta", "keyboardKeyNumLock": "Num Lock", "keyboardKeyNumpad1": "Num 1", "keyboardKeyNumpad2": "Num 2", "keyboardKeyNumpad3": "Num 3", "keyboardKeyNumpad4": "Num 4", "keyboardKeyNumpad5": "Num 5", "keyboardKeyNumpad6": "Num 6", "keyboardKeyNumpad7": "Num 7", "keyboardKeyNumpad8": "Num 8", "keyboardKeyNumpad9": "Num 9", "keyboardKeyNumpad0": "Num 0", "keyboardKeyNumpadAdd": "Num +", "keyboardKeyNumpadComma": "Num ,", "keyboardKeyNumpadDecimal": "Num .", "keyboardKeyNumpadDivide": "Num /", "keyboardKeyNumpadEnter": "Num Enter", "keyboardKeyNumpadEqual": "Num =", "keyboardKeyNumpadMultiply": "Num *", "keyboardKeyNumpadParenLeft": "Num (", "keyboardKeyNumpadParenRight": "Num )", "keyboardKeyNumpadSubtract": "Num -", "keyboardKeyPageDown": "PgDown", "keyboardKeyPageUp": "PgUp", "keyboardKeyPower": "Дугме за укључивање", "keyboardKeyPowerOff": "Дугме за искључивање", "keyboardKeyPrintScreen": "Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Select", "keyboardKeySpace": "Тастер за размак", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Мени трака менија", "currentDateLabel": "Данас", "scrimLabel": "Скрим", "bottomSheetLabel": "Доња табела", "scrimOnTapHint": "Затвори: $modalRouteContentName", "keyboardKeyShift": "Shift", "expansionTileExpandedHint": "двапут додирните да бисте скупили", "expansionTileCollapsedHint": "двапут додирните да бисте проширили", "expansionTileExpandedTapHint": "Скупите", "expansionTileCollapsedTapHint": "Проширите за још детаља", "expandedHint": "Скупљено је", "collapsedHint": "Проширено је", "menuDismissLabel": "Одбаците мени", "lookUpButtonLabel": "Поглед нагоре", "searchWebButtonLabel": "Претражи веб", "shareButtonLabel": "Дели…", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_sr.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_sr.arb", "repo_id": "flutter", "token_count": 3416 }
775
{ "scriptCategory": "English-like", "timeOfDayFormat": "H:mm", "openAppDrawerTooltip": "Vula imenyu yokuzulazula", "backButtonTooltip": "Emuva", "closeButtonTooltip": "Vala", "deleteButtonTooltip": "Susa", "nextMonthTooltip": "Inyanga ezayo", "previousMonthTooltip": "Inyanga edlule", "nextPageTooltip": "Ikhasi elilandelayo", "previousPageTooltip": "Ikhasi elidlule", "firstPageTooltip": "Ikhasi lokuqala", "lastPageTooltip": "Ikhasi lokugcina", "showMenuTooltip": "Bonisa imenyu", "aboutListTileTitle": "Mayelana no-$applicationName", "licensesPageTitle": "Amalayisense", "pageRowsInfoTitle": "$firstRow–$lastRow kokungu-$rowCount", "pageRowsInfoTitleApproximate": "$firstRow–$lastRow cishe kokungu-$rowCount", "rowsPerPageTitle": "Imigqa ekhasini ngalinye:", "tabLabel": "Ithebhu $tabIndex kwangu-$tabCount", "selectedRowCountTitleOne": "1 into ekhethiwe", "selectedRowCountTitleOther": "$selectedRowCount izinto ezikhethiwe", "cancelButtonLabel": "Khansela", "closeButtonLabel": "Vala", "continueButtonLabel": "Qhubeka", "copyButtonLabel": "Kopisha", "cutButtonLabel": "Sika", "scanTextButtonLabel": "Skena umbhalo", "okButtonLabel": "KULUNGILE", "pasteButtonLabel": "Namathisela", "selectAllButtonLabel": "Khetha konke", "viewLicensesButtonLabel": "Buka amalayisense", "anteMeridiemAbbreviation": "AM", "postMeridiemAbbreviation": "PM", "timePickerHourModeAnnouncement": "Khetha amahora", "timePickerMinuteModeAnnouncement": "Khetha amaminithi", "modalBarrierDismissLabel": "Cashisa", "signedInLabel": "Ungene ngemvume", "hideAccountsLabel": "Fihla ama-akhawunti", "showAccountsLabel": "Bonisa ama-akhawunti", "drawerLabel": "Imenyu yokuzulazula", "popupMenuLabel": "Imenyu ye-popup", "dialogLabel": "Ingxoxo", "alertDialogLabel": "Isexwayiso", "searchFieldLabel": "Sesha", "reorderItemToStart": "Yisa ekuqaleni", "reorderItemToEnd": "Yisa ekugcineni", "reorderItemUp": "Iya phezulu", "reorderItemDown": "Iya phansi", "reorderItemLeft": "Hambisa kwesokunxele", "reorderItemRight": "Yisa kwesokudla", "expandedIconTapHint": "Goqa", "collapsedIconTapHint": "Nweba", "remainingTextFieldCharacterCountOne": "1 uhlamvu olusele", "remainingTextFieldCharacterCountOther": "$remainingCount izinhlamvu ezisele", "refreshIndicatorSemanticLabel": "Vuselela", "moreButtonTooltip": "Okuningi", "dateSeparator": ".", "dateHelpText": "mm/dd/yyyy", "selectYearSemanticsLabel": "Khetha unyaka", "unspecifiedDate": "Idethi", "unspecifiedDateRange": "Ibanga ledethi", "dateInputLabel": "Faka idethi", "dateRangeStartLabel": "Idethi yokuqala", "dateRangeEndLabel": "Idethi yokugcina", "dateRangeStartDateSemanticLabel": "Idethi yokuqala umhla ka-$fullDate", "dateRangeEndDateSemanticLabel": "Idethi yokuphela umhla ka-$fullDate", "invalidDateFormatLabel": "Ifomethi engavumelekile.", "invalidDateRangeLabel": "Ibanga elingavumelekile.", "dateOutOfRangeLabel": "Ikude kubanga.", "saveButtonLabel": "Londoloza", "datePickerHelpText": "Khetha usuku", "dateRangePickerHelpText": "Khetha Ibanga", "calendarModeButtonLabel": "Shintshela kukhalenda", "inputDateModeButtonLabel": "Shintshela kokokufaka", "timePickerDialHelpText": "Khetha isikhathi", "timePickerInputHelpText": "Faka isikhathi", "timePickerHourLabel": "Ihora", "timePickerMinuteLabel": "Iminithi", "invalidTimeLabel": "Faka igama elivumelekile", "dialModeButtonLabel": "Shintshela kwimodi yesikhi sokudayela", "inputTimeModeButtonLabel": "Shintshela kwimodi yokufaka yombhalo", "licensesPackageDetailTextZero": "No licenses", "licensesPackageDetailTextOne": "ilayisense e-1", "licensesPackageDetailTextOther": "amalayisense angu-$licenseCount", "keyboardKeyAlt": "Alt", "keyboardKeyAltGraph": "AltGr", "keyboardKeyBackspace": "Backspace", "keyboardKeyCapsLock": "Caps Lock", "keyboardKeyChannelDown": "I-Channel Down", "keyboardKeyChannelUp": "I-Channel Up", "keyboardKeyControl": "Ctrl", "keyboardKeyDelete": "Del", "keyboardKeyEject": "Eject", "keyboardKeyEnd": "End", "keyboardKeyEscape": "Esc", "keyboardKeyFn": "Fn", "keyboardKeyHome": "Home", "keyboardKeyInsert": "Insert", "keyboardKeyMeta": "I-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": "Amandla", "keyboardKeyPowerOff": "Cisha", "keyboardKeyPrintScreen": "-Print Screen", "keyboardKeyScrollLock": "Scroll Lock", "keyboardKeySelect": "Khetha", "keyboardKeySpace": "Space", "keyboardKeyMetaMacOs": "Command", "keyboardKeyMetaWindows": "Win", "menuBarMenuLabel": "Imenyu yebha yemenyu", "currentDateLabel": "Namuhla", "scrimLabel": "I-Scrim", "bottomSheetLabel": "Ishidi Eliphansi", "scrimOnTapHint": "Vala i-$modalRouteContentName", "keyboardKeyShift": "U-Shift", "expansionTileExpandedHint": "thepha kabili ukuze ugoqe", "expansionTileCollapsedHint": "Thepha kabili ukuze unwebe", "expansionTileExpandedTapHint": "Goqa", "expansionTileCollapsedTapHint": "Nweba ukuze uthole imininingwane eyengeziwe", "expandedHint": "Kugoqiwe", "collapsedHint": "Kunwetshiwe", "menuDismissLabel": "Chitha imenyu", "lookUpButtonLabel": "Bheka Phezulu", "searchWebButtonLabel": "Sesha Iwebhu", "shareButtonLabel": "Yabelana...", "clearButtonTooltip": "Clear text", "selectedDateLabel": "Selected" }
flutter/packages/flutter_localizations/lib/src/l10n/material_zu.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_zu.arb", "repo_id": "flutter", "token_count": 2407 }
776
{ "reorderItemToStart": "Μετακίνηση στην αρχή", "reorderItemToEnd": "Μετακίνηση στο τέλος", "reorderItemUp": "Μετακίνηση προς τα πάνω", "reorderItemDown": "Μετακίνηση προς τα κάτω", "reorderItemLeft": "Μετακίνηση αριστερά", "reorderItemRight": "Μετακίνηση δεξιά" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_el.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_el.arb", "repo_id": "flutter", "token_count": 215 }
777
{ "reorderItemToStart": "Eraman hasierara", "reorderItemToEnd": "Eraman amaierara", "reorderItemUp": "Eraman gora", "reorderItemDown": "Eraman behera", "reorderItemLeft": "Eraman ezkerrera", "reorderItemRight": "Eraman eskuinera" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_eu.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_eu.arb", "repo_id": "flutter", "token_count": 104 }
778
{ "reorderItemToStart": "Sposta all'inizio", "reorderItemToEnd": "Sposta alla fine", "reorderItemUp": "Sposta su", "reorderItemDown": "Sposta giù", "reorderItemLeft": "Sposta a sinistra", "reorderItemRight": "Sposta a destra" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_it.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_it.arb", "repo_id": "flutter", "token_count": 98 }
779
{ "reorderItemToStart": "အစသို့ ရွှေ့ရန်", "reorderItemToEnd": "အဆုံးသို့ ‌ရွှေ့ရန်", "reorderItemUp": "အပေါ်သို့ ရွှေ့ရန်", "reorderItemDown": "အောက်သို့ရွှေ့ရန်", "reorderItemLeft": "ဘယ်ဘက်သို့ရွှေ့ရန်", "reorderItemRight": "ညာဘက်သို့ရွှေ့ရန်" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_my.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_my.arb", "repo_id": "flutter", "token_count": 368 }
780
{ "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" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_sq.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_sq.arb", "repo_id": "flutter", "token_count": 109 }
781
{ "reorderItemToStart": "移至開頭", "reorderItemToEnd": "移至結尾", "reorderItemUp": "向上移", "reorderItemDown": "向下移", "reorderItemLeft": "向左移", "reorderItemRight": "向右移" }
flutter/packages/flutter_localizations/lib/src/l10n/widgets_zh_TW.arb/0
{ "file_path": "flutter/packages/flutter_localizations/lib/src/l10n/widgets_zh_TW.arb", "repo_id": "flutter", "token_count": 115 }
782
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { testWidgets('Material2 - Text baseline with CJK locale', (WidgetTester tester) async { // This test in combination with 'Text baseline with EN locale' verify the baselines // used to align text with ideographic baselines are reasonable. We are currently // using the alphabetic baseline to lay out as the ideographic baseline is not yet // properly implemented. When the ideographic baseline is better defined and implemented, // the values of this test should change very slightly. See the issue this is based off // of: https://github.com/flutter/flutter/issues/25782. final Key targetKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), routes: <String, WidgetBuilder>{ '/next': (BuildContext context) { return const Text('Next'); }, }, localizationsDelegates: GlobalMaterialLocalizations.delegates, supportedLocales: const <Locale>[ Locale('en', 'US'), Locale('es', 'ES'), Locale('zh', 'CN'), ], locale: const Locale('zh', 'CN'), home: Material( child: Center( child: Builder( key: targetKey, builder: (BuildContext context) { return PopupMenuButton<int>( onSelected: (int value) { Navigator.pushNamed(context, '/next'); }, itemBuilder: (BuildContext context) { return <PopupMenuItem<int>>[ const PopupMenuItem<int>( value: 1, child: Text( 'hello, world', style: TextStyle(color: Colors.blue), ), ), const PopupMenuItem<int>( value: 2, child: Text( '你好,世界', style: TextStyle(color: Colors.blue), ), ), ]; }, ); }, ), ), ), ), ); await tester.tap(find.byKey(targetKey)); await tester.pumpAndSettle(); expect(find.text('hello, world'), findsOneWidget); expect(find.text('你好,世界'), findsOneWidget); expect(tester.getTopLeft(find.text('hello, world')).dy, 299.5); expect(tester.getBottomLeft(find.text('hello, world')).dy, 316.5); expect(tester.getTopLeft(find.text('你好,世界')).dy, 347.5); expect(tester.getBottomLeft(find.text('你好,世界')).dy, 364.5); }); testWidgets('Material3 - Text baseline with CJK locale', (WidgetTester tester) async { // This test in combination with 'Text baseline with EN locale' verify the baselines // used to align text with ideographic baselines are reasonable. We are currently // using the alphabetic baseline to lay out as the ideographic baseline is not yet // properly implemented. When the ideographic baseline is better defined and implemented, // the values of this test should change very slightly. See the issue this is based off // of: https://github.com/flutter/flutter/issues/25782. final Key targetKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), routes: <String, WidgetBuilder>{ '/next': (BuildContext context) { return const Text('Next'); }, }, localizationsDelegates: GlobalMaterialLocalizations.delegates, supportedLocales: const <Locale>[ Locale('en', 'US'), Locale('es', 'ES'), Locale('zh', 'CN'), ], locale: const Locale('zh', 'CN'), home: Material( child: Center( child: Builder( key: targetKey, builder: (BuildContext context) { return PopupMenuButton<int>( onSelected: (int value) { Navigator.pushNamed(context, '/next'); }, itemBuilder: (BuildContext context) { return <PopupMenuItem<int>>[ const PopupMenuItem<int>( value: 1, child: Text( 'hello, world', style: TextStyle(color: Colors.blue), ), ), const PopupMenuItem<int>( value: 2, child: Text( '你好,世界', style: TextStyle(color: Colors.blue), ), ), ]; }, ); }, ), ), ), ), ); await tester.tap(find.byKey(targetKey)); await tester.pumpAndSettle(); expect(find.text('hello, world'), findsOneWidget); expect(find.text('你好,世界'), findsOneWidget); expect(tester.getTopLeft(find.text('hello, world')).dy, 298.0); expect(tester.getBottomLeft(find.text('hello, world')).dy, 318.0); expect(tester.getTopLeft(find.text('你好,世界')).dy, 346.0); expect(tester.getBottomLeft(find.text('你好,世界')).dy, 366.0); }); testWidgets('Material2 - Text baseline with EN locale', (WidgetTester tester) async { // This test in combination with 'Text baseline with CJK locale' verify the baselines // used to align text with ideographic baselines are reasonable. We are currently // using the alphabetic baseline to lay out as the ideographic baseline is not yet // properly implemented. When the ideographic baseline is better defined and implemented, // the values of this test should change very slightly. See the issue this is based off // of: https://github.com/flutter/flutter/issues/25782. final Key targetKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: false), routes: <String, WidgetBuilder>{ '/next': (BuildContext context) { return const Text('Next'); }, }, localizationsDelegates: GlobalMaterialLocalizations.delegates, supportedLocales: const <Locale>[ Locale('en', 'US'), Locale('es', 'ES'), Locale('zh', 'CN'), ], locale: const Locale('en', 'US'), home: Material( child: Center( child: Builder( key: targetKey, builder: (BuildContext context) { return PopupMenuButton<int>( onSelected: (int value) { Navigator.pushNamed(context, '/next'); }, itemBuilder: (BuildContext context) { return <PopupMenuItem<int>>[ const PopupMenuItem<int>( value: 1, child: Text( 'hello, world', style: TextStyle(color: Colors.blue), ), ), const PopupMenuItem<int>( value: 2, child: Text( '你好,世界', style: TextStyle(color: Colors.blue), ), ), ]; }, ); }, ), ), ), ), ); await tester.tap(find.byKey(targetKey)); await tester.pumpAndSettle(); expect(find.text('hello, world'), findsOneWidget); expect(find.text('你好,世界'), findsOneWidget); expect(tester.getTopLeft(find.text('hello, world')).dy, 300.0); expect(tester.getBottomLeft(find.text('hello, world')).dy, 316.0); expect(tester.getTopLeft(find.text('你好,世界')).dy, 348.0); expect(tester.getBottomLeft(find.text('你好,世界')).dy, 364.0); }); testWidgets('Material3 - Text baseline with EN locale', (WidgetTester tester) async { // This test in combination with 'Text baseline with CJK locale' verify the baselines // used to align text with ideographic baselines are reasonable. We are currently // using the alphabetic baseline to lay out as the ideographic baseline is not yet // properly implemented. When the ideographic baseline is better defined and implemented, // the values of this test should change very slightly. See the issue this is based off // of: https://github.com/flutter/flutter/issues/25782. final Key targetKey = UniqueKey(); await tester.pumpWidget( MaterialApp( theme: ThemeData(useMaterial3: true), routes: <String, WidgetBuilder>{ '/next': (BuildContext context) { return const Text('Next'); }, }, localizationsDelegates: GlobalMaterialLocalizations.delegates, supportedLocales: const <Locale>[ Locale('en', 'US'), Locale('es', 'ES'), Locale('zh', 'CN'), ], locale: const Locale('en', 'US'), home: Material( child: Center( child: Builder( key: targetKey, builder: (BuildContext context) { return PopupMenuButton<int>( onSelected: (int value) { Navigator.pushNamed(context, '/next'); }, itemBuilder: (BuildContext context) { return <PopupMenuItem<int>>[ const PopupMenuItem<int>( value: 1, child: Text( 'hello, world', style: TextStyle(color: Colors.blue), ), ), const PopupMenuItem<int>( value: 2, child: Text( '你好,世界', style: TextStyle(color: Colors.blue), ), ), ]; }, ); }, ), ), ), ), ); await tester.tap(find.byKey(targetKey)); await tester.pumpAndSettle(); expect(find.text('hello, world'), findsOneWidget); expect(find.text('你好,世界'), findsOneWidget); expect(tester.getTopLeft(find.text('hello, world')).dy, 298.0); expect(tester.getBottomLeft(find.text('hello, world')).dy, 318.0); expect(tester.getTopLeft(find.text('你好,世界')).dy, 346.0); expect(tester.getBottomLeft(find.text('你好,世界')).dy, 366.0); }); }
flutter/packages/flutter_localizations/test/text_test.dart/0
{ "file_path": "flutter/packages/flutter_localizations/test/text_test.dart", "repo_id": "flutter", "token_count": 5617 }
783
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'dart:math' as math; import 'dart:ui'; import 'package:flutter/foundation.dart'; import 'package:matcher/expect.dart' show fail; import 'package:path/path.dart' as path; import 'goldens.dart'; import 'test_async_utils.dart'; /// The default [GoldenFileComparator] implementation for `flutter test`. /// /// The term __golden file__ refers to a master image that is considered the /// true rendering of a given widget, state, application, or other visual /// representation you have chosen to capture. This comparator loads golden /// files from the local file system, treating the golden key as a relative /// path from the test file's directory. /// /// This comparator performs a pixel-for-pixel comparison of the decoded PNGs, /// returning true only if there's an exact match. In cases where the captured /// test image does not match the golden file, this comparator will provide /// output to illustrate the difference, described in further detail below. /// /// When using `flutter test --update-goldens`, [LocalFileComparator] /// updates the golden files on disk to match the rendering. /// /// ## Local Output from Golden File Testing /// /// The [LocalFileComparator] will output test feedback when a golden file test /// fails. This output takes the form of differential images contained within a /// `failures` directory that will be generated in the same location specified /// by the golden key. The differential images include the master and test /// images that were compared, as well as an isolated diff of detected pixels, /// and a masked diff that overlays these detected pixels over the master image. /// /// The following images are examples of a test failure output: /// /// | File Name | Image Output | /// |----------------------------|---------------| /// | testName_masterImage.png | ![A golden master image](https://flutter.github.io/assets-for-api-docs/assets/flutter-test/goldens/widget_masterImage.png) | /// | testName_testImage.png | ![Test image](https://flutter.github.io/assets-for-api-docs/assets/flutter-test/goldens/widget_testImage.png) | /// | testName_isolatedDiff.png | ![An isolated pixel difference.](https://flutter.github.io/assets-for-api-docs/assets/flutter-test/goldens/widget_isolatedDiff.png) | /// | testName_maskedDiff.png | ![A masked pixel difference](https://flutter.github.io/assets-for-api-docs/assets/flutter-test/goldens/widget_maskedDiff.png) | /// /// {@macro flutter.flutter_test.matchesGoldenFile.custom_fonts} /// /// See also: /// /// * [GoldenFileComparator], the abstract class that [LocalFileComparator] /// implements. /// * [matchesGoldenFile], the function from [flutter_test] that invokes the /// comparator. class LocalFileComparator extends GoldenFileComparator with LocalComparisonOutput { /// Creates a new [LocalFileComparator] for the specified [testFile]. /// /// Golden file keys will be interpreted as file paths relative to the /// directory in which [testFile] resides. /// /// The [testFile] URL must represent a file. LocalFileComparator(Uri testFile, {path.Style? pathStyle}) : basedir = _getBasedir(testFile, pathStyle), _path = _getPath(pathStyle); static path.Context _getPath(path.Style? style) { return path.Context(style: style ?? path.Style.platform); } static Uri _getBasedir(Uri testFile, path.Style? pathStyle) { final path.Context context = _getPath(pathStyle); final String testFilePath = context.fromUri(testFile); final String testDirectoryPath = context.dirname(testFilePath); return context.toUri(testDirectoryPath + context.separator); } /// The directory in which the test was loaded. /// /// Golden file keys will be interpreted as file paths relative to this /// directory. final Uri basedir; /// Path context exists as an instance variable rather than just using the /// system path context in order to support testing, where we can spoof the /// platform to test behaviors with arbitrary path styles. final path.Context _path; @override Future<bool> compare(Uint8List imageBytes, Uri golden) async { final ComparisonResult result = await GoldenFileComparator.compareLists( imageBytes, await getGoldenBytes(golden), ); if (result.passed) { result.dispose(); return true; } final String error = await generateFailureOutput(result, golden, basedir); result.dispose(); throw FlutterError(error); } @override Future<void> update(Uri golden, Uint8List imageBytes) async { final File goldenFile = _getGoldenFile(golden); await goldenFile.parent.create(recursive: true); await goldenFile.writeAsBytes(imageBytes, flush: true); } /// Returns the bytes of the given [golden] file. /// /// If the file cannot be found, an error will be thrown. @protected Future<List<int>> getGoldenBytes(Uri golden) async { final File goldenFile = _getGoldenFile(golden); if (!goldenFile.existsSync()) { fail( 'Could not be compared against non-existent file: "$golden"' ); } final List<int> goldenBytes = await goldenFile.readAsBytes(); return goldenBytes; } File _getGoldenFile(Uri golden) => File(_path.join(_path.fromUri(basedir), _path.fromUri(golden.path))); } /// A mixin for use in golden file comparators that run locally and provide /// output. mixin LocalComparisonOutput { /// Writes out diffs from the [ComparisonResult] of a golden file test. /// /// Will throw an error if a null result is provided. Future<String> generateFailureOutput( ComparisonResult result, Uri golden, Uri basedir, { String key = '', }) async => TestAsyncUtils.guard<String>(() async { String additionalFeedback = ''; if (result.diffs != null) { additionalFeedback = '\nFailure feedback can be found at ${path.join(basedir.path, 'failures')}'; final Map<String, Image> diffs = result.diffs!; for (final MapEntry<String, Image> entry in diffs.entries) { final File output = getFailureFile( key.isEmpty ? entry.key : '${entry.key}_$key', golden, basedir, ); output.parent.createSync(recursive: true); final ByteData? pngBytes = await entry.value.toByteData(format: ImageByteFormat.png); output.writeAsBytesSync(pngBytes!.buffer.asUint8List()); } } return 'Golden "$golden": ${result.error}$additionalFeedback'; }); /// Returns the appropriate file for a given diff from a [ComparisonResult]. File getFailureFile(String failure, Uri golden, Uri basedir) { final String fileName = golden.pathSegments.last; final String testName = '${fileName.split(path.extension(fileName))[0]}_$failure.png'; return File(path.join( path.fromUri(basedir), path.fromUri(Uri.parse('failures/$testName')), )); } } /// Returns a [ComparisonResult] to describe the pixel differential of the /// [test] and [master] image bytes provided. Future<ComparisonResult> compareLists(List<int>? test, List<int>? master) async { if (test == null || master == null || test.isEmpty || master.isEmpty) { return ComparisonResult( passed: false, diffPercent: 1.0, error: 'Pixel test failed, null image provided.', ); } if (listEquals(test, master)) { return ComparisonResult( passed: true, diffPercent: 0.0, ); } final Codec testImageCodec = await instantiateImageCodec(Uint8List.fromList(test)); final Image testImage = (await testImageCodec.getNextFrame()).image; final ByteData? testImageRgba = await testImage.toByteData(); final Codec masterImageCodec = await instantiateImageCodec(Uint8List.fromList(master)); final Image masterImage = (await masterImageCodec.getNextFrame()).image; final ByteData? masterImageRgba = await masterImage.toByteData(); final int width = testImage.width; final int height = testImage.height; if (width != masterImage.width || height != masterImage.height) { final ComparisonResult result = ComparisonResult( passed: false, diffPercent: 1.0, error: 'Pixel test failed, image sizes do not match.\n' 'Master Image: ${masterImage.width} X ${masterImage.height}\n' 'Test Image: ${testImage.width} X ${testImage.height}', diffs: <String, Image>{ 'masterImage': masterImage, 'testImage': testImage, }, ); return result; } int pixelDiffCount = 0; final int totalPixels = width * height; final ByteData invertedMasterRgba = _invert(masterImageRgba!); final ByteData invertedTestRgba = _invert(testImageRgba!); final Uint8List testImageBytes = (await testImage.toByteData())!.buffer.asUint8List(); final ByteData maskedDiffRgba = ByteData(testImageBytes.length); maskedDiffRgba.buffer.asUint8List().setRange(0, testImageBytes.length, testImageBytes); final ByteData isolatedDiffRgba = ByteData(width * height * 4); for (int x = 0; x < width; x++) { for (int y =0; y < height; y++) { final int byteOffset = (width * y + x) * 4; final int testPixel = testImageRgba.getUint32(byteOffset); final int masterPixel = masterImageRgba.getUint32(byteOffset); final int diffPixel = (_readRed(testPixel) - _readRed(masterPixel)).abs() + (_readGreen(testPixel) - _readGreen(masterPixel)).abs() + (_readBlue(testPixel) - _readBlue(masterPixel)).abs() + (_readAlpha(testPixel) - _readAlpha(masterPixel)).abs(); if (diffPixel != 0 ) { final int invertedMasterPixel = invertedMasterRgba.getUint32(byteOffset); final int invertedTestPixel = invertedTestRgba.getUint32(byteOffset); // We grab the max of the 0xAABBGGRR encoded bytes, and then convert // back to 0xRRGGBBAA for the actual pixel value, since this is how it // was historically done. final int maskPixel = _toRGBA(math.max( _toABGR(invertedMasterPixel), _toABGR(invertedTestPixel), )); maskedDiffRgba.setUint32(byteOffset, maskPixel); isolatedDiffRgba.setUint32(byteOffset, maskPixel); pixelDiffCount++; } } } if (pixelDiffCount > 0) { final double diffPercent = pixelDiffCount / totalPixels; return ComparisonResult( passed: false, diffPercent: diffPercent, error: 'Pixel test failed, ' '${(diffPercent * 100).toStringAsFixed(2)}%, ${pixelDiffCount}px ' 'diff detected.', diffs: <String, Image>{ 'masterImage' : masterImage, 'testImage' : testImage, 'maskedDiff' : await _createImage(maskedDiffRgba, width, height), 'isolatedDiff' : await _createImage(isolatedDiffRgba, width, height), }, ); } masterImage.dispose(); testImage.dispose(); return ComparisonResult(passed: true, diffPercent: 0.0); } /// Inverts [imageBytes], returning a new [ByteData] object. ByteData _invert(ByteData imageBytes) { final ByteData bytes = ByteData(imageBytes.lengthInBytes); // Invert the RGB data (but not A). for (int i = 0; i < imageBytes.lengthInBytes; i += 4) { bytes.setUint8(i, 255 - imageBytes.getUint8(i)); bytes.setUint8(i + 1, 255 - imageBytes.getUint8(i + 1)); bytes.setUint8(i + 2, 255 - imageBytes.getUint8(i + 2)); bytes.setUint8(i + 3, imageBytes.getUint8(i + 3)); } return bytes; } /// An unsupported [WebGoldenComparator] that exists for API compatibility. class DefaultWebGoldenComparator extends WebGoldenComparator { @override Future<bool> compare(double width, double height, Uri golden) { throw UnsupportedError('DefaultWebGoldenComparator is only supported on the web.'); } @override Future<void> update(double width, double height, Uri golden) { throw UnsupportedError('DefaultWebGoldenComparator is only supported on the web.'); } @override Future<bool> compareBytes(Uint8List bytes, Uri golden) { throw UnsupportedError('DefaultWebGoldenComparator is only supported on the web.'); } @override Future<void> updateBytes(Uint8List bytes, Uri golden) { throw UnsupportedError('DefaultWebGoldenComparator is only supported on the web.'); } } /// Reads the red value out of a 32 bit rgba pixel. int _readRed(int pixel) => (pixel >> 24) & 0xff; /// Reads the green value out of a 32 bit rgba pixel. int _readGreen(int pixel) => (pixel >> 16) & 0xff; /// Reads the blue value out of a 32 bit rgba pixel. int _readBlue(int pixel) => (pixel >> 8) & 0xff; /// Reads the alpha value out of a 32 bit rgba pixel. int _readAlpha(int pixel) => pixel & 0xff; /// Convenience wrapper around [decodeImageFromPixels]. Future<Image> _createImage(ByteData bytes, int width, int height) { final Completer<Image> completer = Completer<Image>(); decodeImageFromPixels( bytes.buffer.asUint8List(), width, height, PixelFormat.rgba8888, completer.complete, ); return completer.future; } // Converts a 32 bit rgba pixel to a 32 bit abgr pixel int _toABGR(int rgba) => (_readAlpha(rgba) << 24) | (_readBlue(rgba) << 16) | (_readGreen(rgba) << 8) | _readRed(rgba); // Converts a 32 bit abgr pixel to a 32 bit rgba pixel int _toRGBA(int abgr) => // This is just a mirror of the other conversion. _toABGR(abgr);
flutter/packages/flutter_test/lib/src/_goldens_io.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/_goldens_io.dart", "repo_id": "flutter", "token_count": 4555 }
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 'dart:async'; import 'package:flutter/services.dart'; /// A mock stream handler for an [EventChannel] that mimics the native /// StreamHandler API. /// /// The [onListen] callback is provided a [MockStreamHandlerEventSink] with /// the following API: /// - [MockStreamHandlerEventSink.success] sends a success event. /// - [MockStreamHandlerEventSink.error] sends an error event. /// - [MockStreamHandlerEventSink.endOfStream] sends an end of stream event. abstract class MockStreamHandler { /// Create a new [MockStreamHandler]. const MockStreamHandler(); /// Create a new inline [MockStreamHandler] with the given [onListen] and /// [onCancel] handlers. const factory MockStreamHandler.inline({ required MockStreamHandlerOnListenCallback onListen, MockStreamHandlerOnCancelCallback? onCancel, }) = _InlineMockStreamHandler; /// Handler for the listen event. void onListen(Object? arguments, MockStreamHandlerEventSink events); /// Handler for the cancel event. void onCancel(Object? arguments); } /// Typedef for the inline onListen callback. typedef MockStreamHandlerOnListenCallback = void Function(Object? arguments, MockStreamHandlerEventSink events); /// Typedef for the inline onCancel callback. typedef MockStreamHandlerOnCancelCallback = void Function(Object? arguments); class _InlineMockStreamHandler extends MockStreamHandler { const _InlineMockStreamHandler({ required MockStreamHandlerOnListenCallback onListen, MockStreamHandlerOnCancelCallback? onCancel, }) : _onListenInline = onListen, _onCancelInline = onCancel; final MockStreamHandlerOnListenCallback _onListenInline; final MockStreamHandlerOnCancelCallback? _onCancelInline; @override void onListen(Object? arguments, MockStreamHandlerEventSink events) => _onListenInline(arguments, events); @override void onCancel(Object? arguments) => _onCancelInline?.call(arguments); } /// A mock event sink for a [MockStreamHandler] that mimics the native /// [EventSink](https://api.flutter.dev/javadoc/io/flutter/plugin/common/EventChannel.EventSink.html) /// API. class MockStreamHandlerEventSink { /// Create a new [MockStreamHandlerEventSink] with the given [sink]. MockStreamHandlerEventSink(EventSink<Object?> sink) : _sink = sink; final EventSink<Object?> _sink; /// Send a success event. void success(Object? event) => _sink.add(event); /// Send an error event. void error({ required String code, String? message, Object? details, }) => _sink.addError(PlatformException(code: code, message: message, details: details)); /// Send an end of stream event. void endOfStream() => _sink.close(); }
flutter/packages/flutter_test/lib/src/mock_event_channel.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/mock_event_channel.dart", "repo_id": "flutter", "token_count": 847 }
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' hide window; import 'package:flutter/foundation.dart'; /// Test version of [AccessibilityFeatures] in which specific features may /// be set to arbitrary values. /// /// By default, all features are disabled. For an instance where all the /// features are enabled, consider the [FakeAccessibilityFeatures.allOn] /// constant. @immutable class FakeAccessibilityFeatures implements AccessibilityFeatures { /// Creates a test instance of [AccessibilityFeatures]. /// /// By default, all features are disabled. const FakeAccessibilityFeatures({ this.accessibleNavigation = false, this.invertColors = false, this.disableAnimations = false, this.boldText = false, this.reduceMotion = false, this.highContrast = false, this.onOffSwitchLabels = false, }); /// An instance of [AccessibilityFeatures] where all the features are enabled. static const FakeAccessibilityFeatures allOn = FakeAccessibilityFeatures( accessibleNavigation: true, invertColors: true, disableAnimations: true, boldText: true, reduceMotion: true, highContrast: true, onOffSwitchLabels: true, ); @override final bool accessibleNavigation; @override final bool invertColors; @override final bool disableAnimations; @override final bool boldText; @override final bool reduceMotion; @override final bool highContrast; @override final bool onOffSwitchLabels; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is FakeAccessibilityFeatures && other.accessibleNavigation == accessibleNavigation && other.invertColors == invertColors && other.disableAnimations == disableAnimations && other.boldText == boldText && other.reduceMotion == reduceMotion && other.highContrast == highContrast && other.onOffSwitchLabels == onOffSwitchLabels; } @override int get hashCode { return Object.hash( accessibleNavigation, invertColors, disableAnimations, boldText, reduceMotion, highContrast, onOffSwitchLabels, ); } /// This gives us some grace time when the dart:ui side adds something to /// [AccessibilityFeatures], and makes things easier when we do rolls to /// give us time to catch up. /// /// If you would like to add to this class, changes must first be made in the /// engine, followed by the framework. @override dynamic noSuchMethod(Invocation invocation) { return null; } } /// Used to fake insets and padding for [TestFlutterView]s. /// /// See also: /// /// * [TestFlutterView.padding], [TestFlutterView.systemGestureInsets], /// [TestFlutterView.viewInsets], and [TestFlutterView.viewPadding] for test /// properties that make use of [FakeViewPadding]. @immutable class FakeViewPadding implements ViewPadding { /// Instantiates a new [FakeViewPadding] object for faking insets and padding /// during tests. const FakeViewPadding({ this.left = 0.0, this.top = 0.0, this.right = 0.0, this.bottom = 0.0, }); FakeViewPadding._wrap(ViewPadding base) : left = base.left, top = base.top, right = base.right, bottom = base.bottom; /// A view padding that has zeros for each edge. static const FakeViewPadding zero = FakeViewPadding(); @override final double left; @override final double top; @override final double right; @override final double bottom; } /// [PlatformDispatcher] that wraps another [PlatformDispatcher] and /// allows faking of some properties for testing purposes. /// /// See also: /// /// * [TestFlutterView], which wraps a [FlutterView] for testing and /// mocking purposes. class TestPlatformDispatcher implements PlatformDispatcher { /// Constructs a [TestPlatformDispatcher] that defers all behavior to the given /// [PlatformDispatcher] unless explicitly overridden for test purposes. TestPlatformDispatcher({ required PlatformDispatcher platformDispatcher, }) : _platformDispatcher = platformDispatcher { _updateViewsAndDisplays(); _platformDispatcher.onMetricsChanged = _handleMetricsChanged; } /// The [PlatformDispatcher] that is wrapped by this [TestPlatformDispatcher]. final PlatformDispatcher _platformDispatcher; @override TestFlutterView? get implicitView { return _platformDispatcher.implicitView != null ? _testViews[_platformDispatcher.implicitView!.viewId]! : null; } final Map<int, TestFlutterView> _testViews = <int, TestFlutterView>{}; final Map<int, TestDisplay> _testDisplays = <int, TestDisplay>{}; @override VoidCallback? get onMetricsChanged => _platformDispatcher.onMetricsChanged; VoidCallback? _onMetricsChanged; @override set onMetricsChanged(VoidCallback? callback) { _onMetricsChanged = callback; } void _handleMetricsChanged() { _updateViewsAndDisplays(); _onMetricsChanged?.call(); } @override Locale get locale => _localeTestValue ?? _platformDispatcher.locale; Locale? _localeTestValue; /// Hides the real locale and reports the given [localeTestValue] instead. set localeTestValue(Locale localeTestValue) { // ignore: avoid_setters_without_getters _localeTestValue = localeTestValue; onLocaleChanged?.call(); } /// Deletes any existing test locale and returns to using the real locale. void clearLocaleTestValue() { _localeTestValue = null; onLocaleChanged?.call(); } @override List<Locale> get locales => _localesTestValue ?? _platformDispatcher.locales; List<Locale>? _localesTestValue; /// Hides the real locales and reports the given [localesTestValue] instead. set localesTestValue(List<Locale> localesTestValue) { // ignore: avoid_setters_without_getters _localesTestValue = localesTestValue; onLocaleChanged?.call(); } /// Deletes any existing test locales and returns to using the real locales. void clearLocalesTestValue() { _localesTestValue = null; onLocaleChanged?.call(); } @override VoidCallback? get onLocaleChanged => _platformDispatcher.onLocaleChanged; @override set onLocaleChanged(VoidCallback? callback) { _platformDispatcher.onLocaleChanged = callback; } @override String get initialLifecycleState => _initialLifecycleStateTestValue; String _initialLifecycleStateTestValue = ''; /// Sets a faked initialLifecycleState for testing. set initialLifecycleStateTestValue(String state) { // ignore: avoid_setters_without_getters _initialLifecycleStateTestValue = state; } /// Resets [initialLifecycleState] to the default value for the platform. void resetInitialLifecycleState() { _initialLifecycleStateTestValue = ''; } @override double get textScaleFactor => _textScaleFactorTestValue ?? _platformDispatcher.textScaleFactor; double? _textScaleFactorTestValue; /// Hides the real text scale factor and reports the given /// [textScaleFactorTestValue] instead. set textScaleFactorTestValue(double textScaleFactorTestValue) { // ignore: avoid_setters_without_getters _textScaleFactorTestValue = textScaleFactorTestValue; onTextScaleFactorChanged?.call(); } /// Deletes any existing test text scale factor and returns to using the real /// text scale factor. void clearTextScaleFactorTestValue() { _textScaleFactorTestValue = null; onTextScaleFactorChanged?.call(); } @override Brightness get platformBrightness => _platformBrightnessTestValue ?? _platformDispatcher.platformBrightness; Brightness? _platformBrightnessTestValue; @override VoidCallback? get onPlatformBrightnessChanged => _platformDispatcher.onPlatformBrightnessChanged; @override set onPlatformBrightnessChanged(VoidCallback? callback) { _platformDispatcher.onPlatformBrightnessChanged = callback; } /// Hides the real platform brightness and reports the given /// [platformBrightnessTestValue] instead. set platformBrightnessTestValue(Brightness platformBrightnessTestValue) { // ignore: avoid_setters_without_getters _platformBrightnessTestValue = platformBrightnessTestValue; onPlatformBrightnessChanged?.call(); } /// Deletes any existing test platform brightness and returns to using the /// real platform brightness. void clearPlatformBrightnessTestValue() { _platformBrightnessTestValue = null; onPlatformBrightnessChanged?.call(); } @override bool get alwaysUse24HourFormat => _alwaysUse24HourFormatTestValue ?? _platformDispatcher.alwaysUse24HourFormat; bool? _alwaysUse24HourFormatTestValue; /// Hides the real clock format and reports the given /// [alwaysUse24HourFormatTestValue] instead. set alwaysUse24HourFormatTestValue(bool alwaysUse24HourFormatTestValue) { // ignore: avoid_setters_without_getters _alwaysUse24HourFormatTestValue = alwaysUse24HourFormatTestValue; } /// Deletes any existing test clock format and returns to using the real clock /// format. void clearAlwaysUse24HourTestValue() { _alwaysUse24HourFormatTestValue = null; } @override VoidCallback? get onTextScaleFactorChanged => _platformDispatcher.onTextScaleFactorChanged; @override set onTextScaleFactorChanged(VoidCallback? callback) { _platformDispatcher.onTextScaleFactorChanged = callback; } @override bool get nativeSpellCheckServiceDefined => _nativeSpellCheckServiceDefinedTestValue ?? _platformDispatcher.nativeSpellCheckServiceDefined; bool? _nativeSpellCheckServiceDefinedTestValue; set nativeSpellCheckServiceDefinedTestValue(bool nativeSpellCheckServiceDefinedTestValue) { // ignore: avoid_setters_without_getters _nativeSpellCheckServiceDefinedTestValue = nativeSpellCheckServiceDefinedTestValue; } /// Deletes existing value that determines whether or not a native spell check /// service is defined and returns to the real value. void clearNativeSpellCheckServiceDefined() { _nativeSpellCheckServiceDefinedTestValue = null; } @override bool get brieflyShowPassword => _brieflyShowPasswordTestValue ?? _platformDispatcher.brieflyShowPassword; bool? _brieflyShowPasswordTestValue; /// Hides the real [brieflyShowPassword] and reports the given /// `brieflyShowPasswordTestValue` instead. set brieflyShowPasswordTestValue(bool brieflyShowPasswordTestValue) { // ignore: avoid_setters_without_getters _brieflyShowPasswordTestValue = brieflyShowPasswordTestValue; } /// Resets [brieflyShowPassword] to the default value for the platform. void resetBrieflyShowPassword() { _brieflyShowPasswordTestValue = null; } @override FrameCallback? get onBeginFrame => _platformDispatcher.onBeginFrame; @override set onBeginFrame(FrameCallback? callback) { _platformDispatcher.onBeginFrame = callback; } @override VoidCallback? get onDrawFrame => _platformDispatcher.onDrawFrame; @override set onDrawFrame(VoidCallback? callback) { _platformDispatcher.onDrawFrame = callback; } @override TimingsCallback? get onReportTimings => _platformDispatcher.onReportTimings; @override set onReportTimings(TimingsCallback? callback) { _platformDispatcher.onReportTimings = callback; } @override PointerDataPacketCallback? get onPointerDataPacket => _platformDispatcher.onPointerDataPacket; @override set onPointerDataPacket(PointerDataPacketCallback? callback) { _platformDispatcher.onPointerDataPacket = callback; } @override String get defaultRouteName => _defaultRouteNameTestValue ?? _platformDispatcher.defaultRouteName; String? _defaultRouteNameTestValue; /// Hides the real default route name and reports the given /// [defaultRouteNameTestValue] instead. set defaultRouteNameTestValue(String defaultRouteNameTestValue) { // ignore: avoid_setters_without_getters _defaultRouteNameTestValue = defaultRouteNameTestValue; } /// Deletes any existing test default route name and returns to using the real /// default route name. void clearDefaultRouteNameTestValue() { _defaultRouteNameTestValue = null; } @override void scheduleFrame() { _platformDispatcher.scheduleFrame(); } @override bool get semanticsEnabled => _semanticsEnabledTestValue ?? _platformDispatcher.semanticsEnabled; bool? _semanticsEnabledTestValue; /// Hides the real semantics enabled and reports the given /// [semanticsEnabledTestValue] instead. set semanticsEnabledTestValue(bool semanticsEnabledTestValue) { // ignore: avoid_setters_without_getters _semanticsEnabledTestValue = semanticsEnabledTestValue; onSemanticsEnabledChanged?.call(); } /// Deletes any existing test semantics enabled and returns to using the real /// semantics enabled. void clearSemanticsEnabledTestValue() { _semanticsEnabledTestValue = null; onSemanticsEnabledChanged?.call(); } @override VoidCallback? get onSemanticsEnabledChanged => _platformDispatcher.onSemanticsEnabledChanged; @override set onSemanticsEnabledChanged(VoidCallback? callback) { _platformDispatcher.onSemanticsEnabledChanged = callback; } @override SemanticsActionEventCallback? get onSemanticsActionEvent => _platformDispatcher.onSemanticsActionEvent; @override set onSemanticsActionEvent(SemanticsActionEventCallback? callback) { _platformDispatcher.onSemanticsActionEvent = callback; } @override AccessibilityFeatures get accessibilityFeatures => _accessibilityFeaturesTestValue ?? _platformDispatcher.accessibilityFeatures; AccessibilityFeatures? _accessibilityFeaturesTestValue; /// Hides the real accessibility features and reports the given /// [accessibilityFeaturesTestValue] instead. /// /// Consider using [FakeAccessibilityFeatures] to provide specific /// values for the various accessibility features under test. set accessibilityFeaturesTestValue(AccessibilityFeatures accessibilityFeaturesTestValue) { // ignore: avoid_setters_without_getters _accessibilityFeaturesTestValue = accessibilityFeaturesTestValue; onAccessibilityFeaturesChanged?.call(); } /// Deletes any existing test accessibility features and returns to using the /// real accessibility features. void clearAccessibilityFeaturesTestValue() { _accessibilityFeaturesTestValue = null; onAccessibilityFeaturesChanged?.call(); } @override VoidCallback? get onAccessibilityFeaturesChanged => _platformDispatcher.onAccessibilityFeaturesChanged; @override set onAccessibilityFeaturesChanged(VoidCallback? callback) { _platformDispatcher.onAccessibilityFeaturesChanged = callback; } @override void setIsolateDebugName(String name) { _platformDispatcher.setIsolateDebugName(name); } @override void sendPlatformMessage( String name, ByteData? data, PlatformMessageResponseCallback? callback, ) { _platformDispatcher.sendPlatformMessage(name, data, callback); } /// Delete any test value properties that have been set on this [TestPlatformDispatcher] /// and return to reporting the real [PlatformDispatcher] values for all /// [PlatformDispatcher] properties. /// /// If desired, clearing of properties can be done on an individual basis, /// e.g., [clearLocaleTestValue]. void clearAllTestValues() { clearAccessibilityFeaturesTestValue(); clearAlwaysUse24HourTestValue(); clearDefaultRouteNameTestValue(); clearPlatformBrightnessTestValue(); clearLocaleTestValue(); clearLocalesTestValue(); clearSemanticsEnabledTestValue(); clearTextScaleFactorTestValue(); clearNativeSpellCheckServiceDefined(); resetBrieflyShowPassword(); resetInitialLifecycleState(); resetSystemFontFamily(); } @override VoidCallback? get onFrameDataChanged => _platformDispatcher.onFrameDataChanged; @override set onFrameDataChanged(VoidCallback? value) { _platformDispatcher.onFrameDataChanged = value; } @override KeyDataCallback? get onKeyData => _platformDispatcher.onKeyData; @override set onKeyData(KeyDataCallback? onKeyData) { _platformDispatcher.onKeyData = onKeyData; } @override VoidCallback? get onPlatformConfigurationChanged => _platformDispatcher.onPlatformConfigurationChanged; @override set onPlatformConfigurationChanged(VoidCallback? onPlatformConfigurationChanged) { _platformDispatcher.onPlatformConfigurationChanged = onPlatformConfigurationChanged; } @override Locale? computePlatformResolvedLocale(List<Locale> supportedLocales) => _platformDispatcher.computePlatformResolvedLocale(supportedLocales); @override ByteData? getPersistentIsolateData() => _platformDispatcher.getPersistentIsolateData(); @override Iterable<TestFlutterView> get views => _testViews.values; @override FlutterView? view({required int id}) => _testViews[id]; @override Iterable<TestDisplay> get displays => _testDisplays.values; void _updateViewsAndDisplays() { final List<Object> extraDisplayKeys = <Object>[..._testDisplays.keys]; for (final Display display in _platformDispatcher.displays) { extraDisplayKeys.remove(display.id); if (!_testDisplays.containsKey(display.id)) { _testDisplays[display.id] = TestDisplay(this, display); } } extraDisplayKeys.forEach(_testDisplays.remove); final List<Object> extraViewKeys = <Object>[..._testViews.keys]; for (final FlutterView view in _platformDispatcher.views) { // TODO(pdblasi-google): Remove this try-catch once the Display API is stable and supported on all platforms late final TestDisplay display; try { final Display realDisplay = view.display; if (_testDisplays.containsKey(realDisplay.id)) { display = _testDisplays[view.display.id]!; } else { display = _UnsupportedDisplay( this, view, 'PlatformDispatcher did not contain a Display with id ${realDisplay.id}, ' 'which was expected by FlutterView ($view)', ); } } catch (error){ display = _UnsupportedDisplay(this, view, error); } extraViewKeys.remove(view.viewId); if (!_testViews.containsKey(view.viewId)) { _testViews[view.viewId] = TestFlutterView( view: view, platformDispatcher: this, display: display, ); } } extraViewKeys.forEach(_testViews.remove); } @override ErrorCallback? get onError => _platformDispatcher.onError; @override set onError(ErrorCallback? value) { _platformDispatcher.onError; } @override VoidCallback? get onSystemFontFamilyChanged => _platformDispatcher.onSystemFontFamilyChanged; @override set onSystemFontFamilyChanged(VoidCallback? value) { _platformDispatcher.onSystemFontFamilyChanged = value; } @override FrameData get frameData => _platformDispatcher.frameData; @override void registerBackgroundIsolate(RootIsolateToken token) { _platformDispatcher.registerBackgroundIsolate(token); } @override void requestDartPerformanceMode(DartPerformanceMode mode) { _platformDispatcher.requestDartPerformanceMode(mode); } /// The system font family to use for this test. /// /// Defaults to the value provided by [PlatformDispatcher.systemFontFamily]. /// This can only be set in a test environment to emulate different platform /// configurations. A standard [PlatformDispatcher] is not mutable from the /// framework. /// /// Setting this value to `null` will force [systemFontFamily] to return /// `null`. If you want to have the value default to the platform /// [systemFontFamily], use [resetSystemFontFamily]. /// /// See also: /// /// * [PlatformDispatcher.systemFontFamily] for the standard implementation /// * [resetSystemFontFamily] to reset this value specifically /// * [clearAllTestValues] to reset all test values for this view @override String? get systemFontFamily { return _forceSystemFontFamilyToBeNull ? null : _systemFontFamily ?? _platformDispatcher.systemFontFamily; } String? _systemFontFamily; bool _forceSystemFontFamilyToBeNull = false; set systemFontFamily(String? value) { _systemFontFamily = value; if (value == null) { _forceSystemFontFamilyToBeNull = true; } onSystemFontFamilyChanged?.call(); } /// Resets [systemFontFamily] to the default for the platform. void resetSystemFontFamily() { _systemFontFamily = null; _forceSystemFontFamilyToBeNull = false; onSystemFontFamilyChanged?.call(); } @override void updateSemantics(SemanticsUpdate update) { _platformDispatcher.updateSemantics(update); } /// This gives us some grace time when the dart:ui side adds something to /// [PlatformDispatcher], and makes things easier when we do rolls to give /// us time to catch up. @override dynamic noSuchMethod(Invocation invocation) { return null; } } /// A [FlutterView] that wraps another [FlutterView] and allows faking of /// some properties for testing purposes. /// /// This class should not be instantiated manually, as /// it requires a backing [FlutterView] that must be produced from /// a [PlatformDispatcher]. /// /// See also: /// /// * [WidgetTester.view] which allows for accessing the [TestFlutterView] /// for single view applications or widget testing. /// * [WidgetTester.viewOf] which allows for accessing the appropriate /// [TestFlutterView] in a given situation for multi-view applications. /// * [TestPlatformDispatcher], which allows for faking of platform specific /// functionality. class TestFlutterView implements FlutterView { /// Constructs a [TestFlutterView] that defers all behavior to the given /// [FlutterView] unless explicitly overridden for testing. TestFlutterView({ required FlutterView view, required TestPlatformDispatcher platformDispatcher, required TestDisplay display, }) : _view = view, _platformDispatcher = platformDispatcher, _display = display; /// The [FlutterView] backing this [TestFlutterView]. final FlutterView _view; @override TestPlatformDispatcher get platformDispatcher => _platformDispatcher; final TestPlatformDispatcher _platformDispatcher; @override TestDisplay get display => _display; final TestDisplay _display; @override int get viewId => _view.viewId; /// The device pixel ratio to use for this test. /// /// Defaults to the value provided by [FlutterView.devicePixelRatio]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FlutterView.devicePixelRatio] for the standard implementation /// * [TestDisplay.devicePixelRatio] which will stay in sync with this value /// * [resetDevicePixelRatio] to reset this value specifically /// * [reset] to reset all test values for this view @override double get devicePixelRatio => _display._devicePixelRatio ?? _view.devicePixelRatio; set devicePixelRatio(double value) { _display.devicePixelRatio = value; } /// Resets [devicePixelRatio] for this test view to the default value for this view. /// /// This will also reset the [devicePixelRatio] for the [TestDisplay] /// that is related to this view. void resetDevicePixelRatio() { _display.resetDevicePixelRatio(); } /// The display features to use for this test. /// /// Defaults to the value provided by [FlutterView.displayFeatures]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FlutterView.displayFeatures] for the standard implementation /// * [resetDisplayFeatures] to reset this value specifically /// * [reset] to reset all test values for this view @override List<DisplayFeature> get displayFeatures => _displayFeatures ?? _view.displayFeatures; List<DisplayFeature>? _displayFeatures; set displayFeatures(List<DisplayFeature> value) { _displayFeatures = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [displayFeatures] to the default values for this view. void resetDisplayFeatures() { _displayFeatures = null; platformDispatcher.onMetricsChanged?.call(); } /// The padding to use for this test. /// /// Defaults to the value provided by [FlutterView.padding]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FakeViewPadding] which is used to set this value for testing /// * [FlutterView.padding] for the standard implementation. /// * [resetPadding] to reset this value specifically. /// * [reset] to reset all test values for this view. @override FakeViewPadding get padding => _padding ?? FakeViewPadding._wrap(_view.padding); FakeViewPadding? _padding; set padding(FakeViewPadding value) { _padding = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [padding] to the default value for this view. void resetPadding() { _padding = null; platformDispatcher.onMetricsChanged?.call(); } /// The physical size to use for this test. /// /// Defaults to the value provided by [FlutterView.physicalSize]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// Setting this value also sets [physicalConstraints] to tight constraints /// based on the given size. /// /// See also: /// /// * [FlutterView.physicalSize] for the standard implementation /// * [resetPhysicalSize] to reset this value specifically /// * [reset] to reset all test values for this view @override Size get physicalSize => _physicalSize ?? _view.physicalSize; Size? _physicalSize; set physicalSize(Size value) { _physicalSize = value; // For backwards compatibility the constraints are set based on the provided size. physicalConstraints = ViewConstraints.tight(value); } /// Resets [physicalSize] (and implicitly also the [physicalConstraints]) to /// the default value for this view. void resetPhysicalSize() { _physicalSize = null; resetPhysicalConstraints(); } /// The physical constraints to use for this test. /// /// Defaults to the value provided by [FlutterView.physicalConstraints]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FlutterView.physicalConstraints] for the standard implementation /// * [physicalConstraints] to reset this value specifically /// * [reset] to reset all test values for this view @override ViewConstraints get physicalConstraints => _physicalConstraints ?? _view.physicalConstraints; ViewConstraints? _physicalConstraints; set physicalConstraints(ViewConstraints value) { _physicalConstraints = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [physicalConstraints] to the default value for this view. void resetPhysicalConstraints() { _physicalConstraints = null; platformDispatcher.onMetricsChanged?.call(); } /// The system gesture insets to use for this test. /// /// Defaults to the value provided by [FlutterView.systemGestureInsets]. /// This can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FakeViewPadding] which is used to set this value for testing /// * [FlutterView.systemGestureInsets] for the standard implementation /// * [resetSystemGestureInsets] to reset this value specifically /// * [reset] to reset all test values for this view @override FakeViewPadding get systemGestureInsets => _systemGestureInsets ?? FakeViewPadding._wrap(_view.systemGestureInsets); FakeViewPadding? _systemGestureInsets; set systemGestureInsets(FakeViewPadding value) { _systemGestureInsets = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [systemGestureInsets] to the default value for this view. void resetSystemGestureInsets() { _systemGestureInsets = null; platformDispatcher.onMetricsChanged?.call(); } /// The view insets to use for this test. /// /// Defaults to the value provided by [FlutterView.viewInsets]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FakeViewPadding] which is used to set this value for testing /// * [FlutterView.viewInsets] for the standard implementation /// * [resetViewInsets] to reset this value specifically /// * [reset] to reset all test values for this view @override FakeViewPadding get viewInsets => _viewInsets ?? FakeViewPadding._wrap(_view.viewInsets); FakeViewPadding? _viewInsets; set viewInsets(FakeViewPadding value) { _viewInsets = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [viewInsets] to the default value for this view. void resetViewInsets() { _viewInsets = null; platformDispatcher.onMetricsChanged?.call(); } /// The view padding to use for this test. /// /// Defaults to the value provided by [FlutterView.viewPadding]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FakeViewPadding] which is used to set this value for testing /// * [FlutterView.viewPadding] for the standard implementation /// * [resetViewPadding] to reset this value specifically /// * [reset] to reset all test values for this view @override FakeViewPadding get viewPadding => _viewPadding ?? FakeViewPadding._wrap(_view.viewPadding); FakeViewPadding? _viewPadding; set viewPadding(FakeViewPadding value) { _viewPadding = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [viewPadding] to the default value for this view. void resetViewPadding() { _viewPadding = null; platformDispatcher.onMetricsChanged?.call(); } /// The gesture settings to use for this test. /// /// Defaults to the value provided by [FlutterView.gestureSettings]. This /// can only be set in a test environment to emulate different view /// configurations. A standard [FlutterView] is not mutable from the framework. /// /// See also: /// /// * [FlutterView.gestureSettings] for the standard implementation /// * [resetGestureSettings] to reset this value specifically /// * [reset] to reset all test values for this view @override GestureSettings get gestureSettings => _gestureSettings ?? _view.gestureSettings; GestureSettings? _gestureSettings; set gestureSettings(GestureSettings value) { _gestureSettings = value; platformDispatcher.onMetricsChanged?.call(); } /// Resets [gestureSettings] to the default value for this view. void resetGestureSettings() { _gestureSettings = null; platformDispatcher.onMetricsChanged?.call(); } @override void render(Scene scene, {Size? size}) { _view.render(scene, size: size); } @override void updateSemantics(SemanticsUpdate update) { _view.updateSemantics(update); } /// Resets all test values to the defaults for this view. /// /// See also: /// /// * [resetDevicePixelRatio] to reset [devicePixelRatio] specifically /// * [resetDisplayFeatures] to reset [displayFeatures] specifically /// * [resetPadding] to reset [padding] specifically /// * [resetPhysicalSize] to reset [physicalSize] specifically /// * [resetSystemGestureInsets] to reset [systemGestureInsets] specifically /// * [resetViewInsets] to reset [viewInsets] specifically /// * [resetViewPadding] to reset [viewPadding] specifically /// * [resetGestureSettings] to reset [gestureSettings] specifically void reset() { resetDevicePixelRatio(); resetDisplayFeatures(); resetPadding(); resetPhysicalSize(); // resetPhysicalConstraints is implicitly called by resetPhysicalSize. resetSystemGestureInsets(); resetViewInsets(); resetViewPadding(); resetGestureSettings(); } /// This gives us some grace time when the dart:ui side adds something to /// [FlutterView], and makes things easier when we do rolls to give /// us time to catch up. @override dynamic noSuchMethod(Invocation invocation) { return null; } } /// A version of [Display] that can be modified to allow for testing various /// use cases. /// /// Updates to the [TestDisplay] will be surfaced through /// [PlatformDispatcher.onMetricsChanged]. class TestDisplay implements Display { /// Creates a new [TestDisplay] backed by the given [Display]. TestDisplay(TestPlatformDispatcher platformDispatcher, Display display) : _platformDispatcher = platformDispatcher, _display = display; final Display _display; final TestPlatformDispatcher _platformDispatcher; @override int get id => _display.id; /// The device pixel ratio to use for this test. /// /// Defaults to the value provided by [Display.devicePixelRatio]. This /// can only be set in a test environment to emulate different display /// configurations. A standard [Display] is not mutable from the framework. /// /// See also: /// /// * [Display.devicePixelRatio] for the standard implementation /// * [TestFlutterView.devicePixelRatio] which will stay in sync with this value /// * [resetDevicePixelRatio] to reset this value specifically /// * [reset] to reset all test values for this display @override double get devicePixelRatio => _devicePixelRatio ?? _display.devicePixelRatio; double? _devicePixelRatio; set devicePixelRatio(double value) { _devicePixelRatio = value; _platformDispatcher.onMetricsChanged?.call(); } /// Resets [devicePixelRatio] to the default value for this display. /// /// This will also reset the [devicePixelRatio] for any [TestFlutterView]s /// that are related to this display. void resetDevicePixelRatio() { _devicePixelRatio = null; _platformDispatcher.onMetricsChanged?.call(); } /// The refresh rate to use for this test. /// /// Defaults to the value provided by [Display.refreshRate]. This /// can only be set in a test environment to emulate different display /// configurations. A standard [Display] is not mutable from the framework. /// /// See also: /// /// * [Display.refreshRate] for the standard implementation /// * [resetRefreshRate] to reset this value specifically /// * [reset] to reset all test values for this display @override double get refreshRate => _refreshRate ?? _display.refreshRate; double? _refreshRate; set refreshRate(double value) { _refreshRate = value; _platformDispatcher.onMetricsChanged?.call(); } /// Resets [refreshRate] to the default value for this display. void resetRefreshRate() { _refreshRate = null; _platformDispatcher.onMetricsChanged?.call(); } /// The size of the [Display] to use for this test. /// /// Defaults to the value provided by [Display.refreshRate]. This /// can only be set in a test environment to emulate different display /// configurations. A standard [Display] is not mutable from the framework. /// /// See also: /// /// * [Display.refreshRate] for the standard implementation /// * [resetRefreshRate] to reset this value specifically /// * [reset] to reset all test values for this display @override Size get size => _size ?? _display.size; Size? _size; set size(Size value) { _size = value; _platformDispatcher.onMetricsChanged?.call(); } /// Resets [size] to the default value for this display. void resetSize() { _size = null; _platformDispatcher.onMetricsChanged?.call(); } /// Resets all values on this [TestDisplay]. /// /// See also: /// * [resetDevicePixelRatio] to reset [devicePixelRatio] specifically /// * [resetRefreshRate] to reset [refreshRate] specifically /// * [resetSize] to reset [size] specifically void reset() { resetDevicePixelRatio(); resetRefreshRate(); resetSize(); } /// This gives us some grace time when the dart:ui side adds something to /// [Display], and makes things easier when we do rolls to give /// us time to catch up. @override dynamic noSuchMethod(Invocation invocation) { return null; } } // TODO(pdblasi-google): Remove this once the Display API is stable and supported on all platforms class _UnsupportedDisplay implements TestDisplay { _UnsupportedDisplay(this._platformDispatcher, this._view, this.error); final FlutterView _view; final Object? error; @override final TestPlatformDispatcher _platformDispatcher; @override double get devicePixelRatio => _devicePixelRatio ?? _view.devicePixelRatio; @override double? _devicePixelRatio; @override set devicePixelRatio(double value) { _devicePixelRatio = value; _platformDispatcher.onMetricsChanged?.call(); } @override void resetDevicePixelRatio() { _devicePixelRatio = null; _platformDispatcher.onMetricsChanged?.call(); } @override dynamic noSuchMethod(Invocation invocation) { throw UnsupportedError( 'The Display API is unsupported in this context. ' 'As of the last metrics change on PlatformDispatcher, this was the error ' 'given when trying to prepare the display for testing: $error', ); } } /// Deprecated. Will be removed in a future version of Flutter. /// /// This class has been deprecated to prepare for Flutter's upcoming support /// for multiple views and multiple windows. /// /// [SingletonFlutterWindow] that wraps another [SingletonFlutterWindow] and /// allows faking of some properties for testing purposes. /// /// Tests for certain widgets, e.g., [MaterialApp], might require faking certain /// properties of a [SingletonFlutterWindow]. [TestWindow] facilitates the /// faking of these properties by overriding the properties of a real /// [SingletonFlutterWindow] with desired fake values. The binding used within /// tests, [TestWidgetsFlutterBinding], contains a [TestWindow] that is used by /// all tests. /// /// ## Sample Code /// /// A test can utilize a [TestWindow] in the following way: /// /// ```dart /// testWidgets('your test name here', (WidgetTester tester) async { /// // Retrieve the TestWidgetsFlutterBinding. /// final TestWidgetsFlutterBinding testBinding = tester.binding; /// /// // Fake the desired properties of the TestWindow. All code running /// // within this test will perceive the following fake text scale /// // factor as the real text scale factor of the window. /// testBinding.platformDispatcher.textScaleFactorTestValue = 2.5; /// /// // Test code that depends on text scale factor here. /// }); /// ``` /// /// The [TestWidgetsFlutterBinding] is recreated for each test and /// therefore any fake values defined in one test will not persist /// to the next. /// /// If a test needs to override a real [SingletonFlutterWindow] property and /// then later return to using the real [SingletonFlutterWindow] property, /// [TestWindow] provides methods to clear each individual test value, e.g., /// [clearDevicePixelRatioTestValue]. /// /// To clear all fake test values in a [TestWindow], consider using /// [clearAllTestValues]. /// /// See also: /// /// * [TestPlatformDispatcher], which wraps a [PlatformDispatcher] for /// testing purposes and is used by the [platformDispatcher] property of /// this class. @Deprecated( 'Use TestPlatformDispatcher (via WidgetTester.platformDispatcher) or TestFlutterView (via WidgetTester.view) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) class TestWindow implements SingletonFlutterWindow { /// Constructs a [TestWindow] that defers all behavior to the given /// [SingletonFlutterWindow] unless explicitly overridden for test purposes. @Deprecated( 'Use TestPlatformDispatcher (via WidgetTester.platformDispatcher) or TestFlutterView (via WidgetTester.view) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) TestWindow({ required SingletonFlutterWindow window, }) : platformDispatcher = TestPlatformDispatcher(platformDispatcher: window.platformDispatcher); /// Constructs a [TestWindow] that defers all behavior to the given /// [TestPlatformDispatcher] and its [TestPlatformDispatcher.implicitView]. /// /// This class will not work when multiple views are present. If multiple view /// support is needed use [WidgetTester.platformDispatcher] and /// [WidgetTester.viewOf]. /// /// See also: /// /// * [TestPlatformDispatcher] which allows faking of platform-wide values for /// testing purposes. /// * [TestFlutterView] which allows faking of view-specific values for /// testing purposes. @Deprecated( 'Use TestPlatformDispatcher (via WidgetTester.platformDispatcher) or TestFlutterView (via WidgetTester.view) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) TestWindow.fromPlatformDispatcher({ @Deprecated( 'Use WidgetTester.platformDispatcher instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) required this.platformDispatcher, }); @Deprecated( 'Use WidgetTester.platformDispatcher instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override final TestPlatformDispatcher platformDispatcher; TestFlutterView get _view => platformDispatcher.implicitView!; @Deprecated( 'Use WidgetTester.view.devicePixelRatio instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override double get devicePixelRatio => _view.devicePixelRatio; /// Hides the real device pixel ratio and reports the given [devicePixelRatio] /// instead. @Deprecated( 'Use WidgetTester.view.devicePixelRatio instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set devicePixelRatioTestValue(double devicePixelRatio) { // ignore: avoid_setters_without_getters _view.devicePixelRatio = devicePixelRatio; } /// Deletes any existing test device pixel ratio and returns to using the real /// device pixel ratio. @Deprecated( 'Use WidgetTester.view.resetDevicePixelRatio() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearDevicePixelRatioTestValue() { _view.resetDevicePixelRatio(); } @Deprecated( 'Use WidgetTester.view.physicalSize instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override Size get physicalSize => _view.physicalSize; /// Hides the real physical size and reports the given [physicalSizeTestValue] /// instead. @Deprecated( 'Use WidgetTester.view.physicalSize instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set physicalSizeTestValue (Size physicalSizeTestValue) { // ignore: avoid_setters_without_getters _view.physicalSize = physicalSizeTestValue; } /// Deletes any existing test physical size and returns to using the real /// physical size. @Deprecated( 'Use WidgetTester.view.resetPhysicalSize() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearPhysicalSizeTestValue() { _view.resetPhysicalSize(); } @Deprecated( 'Use WidgetTester.view.viewInsets instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override ViewPadding get viewInsets => _view.viewInsets; /// Hides the real view insets and reports the given [viewInsetsTestValue] /// instead. /// /// Use [FakeViewPadding] to set this value for testing. @Deprecated( 'Use WidgetTester.view.viewInsets instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set viewInsetsTestValue(ViewPadding value) { // ignore: avoid_setters_without_getters _view.viewInsets = value is FakeViewPadding ? value : FakeViewPadding._wrap(value); } /// Deletes any existing test view insets and returns to using the real view /// insets. @Deprecated( 'Use WidgetTester.view.resetViewInsets() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearViewInsetsTestValue() { _view.resetViewInsets(); } @Deprecated( 'Use WidgetTester.view.viewPadding instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override ViewPadding get viewPadding => _view.viewPadding; /// Hides the real view padding and reports the given [paddingTestValue] /// instead. /// /// Use [FakeViewPadding] to set this value for testing. @Deprecated( 'Use WidgetTester.view.viewPadding instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set viewPaddingTestValue(ViewPadding value) { // ignore: avoid_setters_without_getters _view.viewPadding = value is FakeViewPadding ? value : FakeViewPadding._wrap(value); } /// Deletes any existing test view padding and returns to using the real /// viewPadding. @Deprecated( 'Use WidgetTester.view.resetViewPadding() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearViewPaddingTestValue() { _view.resetViewPadding(); } @Deprecated( 'Use WidgetTester.view.padding instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override ViewPadding get padding => _view.padding; /// Hides the real padding and reports the given [paddingTestValue] instead. /// /// Use [FakeViewPadding] to set this value for testing. @Deprecated( 'Use WidgetTester.view.padding instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set paddingTestValue(ViewPadding value) { // ignore: avoid_setters_without_getters _view.padding = value is FakeViewPadding ? value : FakeViewPadding._wrap(value); } /// Deletes any existing test padding and returns to using the real padding. @Deprecated( 'Use WidgetTester.view.resetPadding() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearPaddingTestValue() { _view.resetPadding(); } @Deprecated( 'Use WidgetTester.view.gestureSettings instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override GestureSettings get gestureSettings => _view.gestureSettings; /// Hides the real gesture settings and reports the given [gestureSettingsTestValue] instead. @Deprecated( 'Use WidgetTester.view.gestureSettings instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set gestureSettingsTestValue(GestureSettings gestureSettingsTestValue) { // ignore: avoid_setters_without_getters _view.gestureSettings = gestureSettingsTestValue; } /// Deletes any existing test gesture settings and returns to using the real gesture settings. @Deprecated( 'Use WidgetTester.view.resetGestureSettings() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearGestureSettingsTestValue() { _view.resetGestureSettings(); } @Deprecated( 'Use WidgetTester.view.displayFeatures instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override List<DisplayFeature> get displayFeatures => _view.displayFeatures; /// Hides the real displayFeatures and reports the given [displayFeaturesTestValue] instead. @Deprecated( 'Use WidgetTester.view.displayFeatures instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set displayFeaturesTestValue(List<DisplayFeature> displayFeaturesTestValue) { // ignore: avoid_setters_without_getters _view.displayFeatures = displayFeaturesTestValue; } /// Deletes any existing test padding and returns to using the real padding. @Deprecated( 'Use WidgetTester.view.resetDisplayFeatures() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearDisplayFeaturesTestValue() { _view.resetDisplayFeatures(); } @Deprecated( 'Use WidgetTester.view.systemGestureInsets instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override ViewPadding get systemGestureInsets => _view.systemGestureInsets; /// Hides the real system gesture insets and reports the given /// [systemGestureInsetsTestValue] instead. /// /// Use [FakeViewPadding] to set this value for testing. @Deprecated( 'Use WidgetTester.view.systemGestureInsets instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set systemGestureInsetsTestValue(ViewPadding value) { // ignore: avoid_setters_without_getters _view.systemGestureInsets = value is FakeViewPadding ? value : FakeViewPadding._wrap(value); } /// Deletes any existing test system gesture insets and returns to using the real system gesture insets. @Deprecated( 'Use WidgetTester.view.resetSystemGestureInsets() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearSystemGestureInsetsTestValue() { _view.resetSystemGestureInsets(); } @Deprecated( 'Use WidgetTester.platformDispatcher.onMetricsChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onMetricsChanged => platformDispatcher.onMetricsChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onMetricsChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onMetricsChanged(VoidCallback? callback) { platformDispatcher.onMetricsChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.locale instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override Locale get locale => platformDispatcher.locale; @Deprecated( 'Use WidgetTester.platformDispatcher.locales instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override List<Locale> get locales => platformDispatcher.locales; @Deprecated( 'Use WidgetTester.platformDispatcher.onLocaleChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onLocaleChanged => platformDispatcher.onLocaleChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onLocaleChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onLocaleChanged(VoidCallback? callback) { platformDispatcher.onLocaleChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.initialLifecycleState instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override String get initialLifecycleState => platformDispatcher.initialLifecycleState; @Deprecated( 'Use WidgetTester.platformDispatcher.textScaleFactor instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override double get textScaleFactor => platformDispatcher.textScaleFactor; @Deprecated( 'Use WidgetTester.platformDispatcher.platformBrightness instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override Brightness get platformBrightness => platformDispatcher.platformBrightness; @Deprecated( 'Use WidgetTester.platformDispatcher.onPlatformBrightnessChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onPlatformBrightnessChanged => platformDispatcher.onPlatformBrightnessChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onPlatformBrightnessChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onPlatformBrightnessChanged(VoidCallback? callback) { platformDispatcher.onPlatformBrightnessChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.alwaysUse24HourFormat instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override bool get alwaysUse24HourFormat => platformDispatcher.alwaysUse24HourFormat; @Deprecated( 'Use WidgetTester.platformDispatcher.onTextScaleFactorChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onTextScaleFactorChanged => platformDispatcher.onTextScaleFactorChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onTextScaleFactorChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onTextScaleFactorChanged(VoidCallback? callback) { platformDispatcher.onTextScaleFactorChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.nativeSpellCheckServiceDefined instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override bool get nativeSpellCheckServiceDefined => platformDispatcher.nativeSpellCheckServiceDefined; @Deprecated( 'Use WidgetTester.platformDispatcher.nativeSpellCheckServiceDefinedTestValue instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) set nativeSpellCheckServiceDefinedTestValue(bool nativeSpellCheckServiceDefinedTestValue) { // ignore: avoid_setters_without_getters platformDispatcher.nativeSpellCheckServiceDefinedTestValue = nativeSpellCheckServiceDefinedTestValue; } @Deprecated( 'Use WidgetTester.platformDispatcher.brieflyShowPassword instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override bool get brieflyShowPassword => platformDispatcher.brieflyShowPassword; @Deprecated( 'Use WidgetTester.platformDispatcher.onBeginFrame instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override FrameCallback? get onBeginFrame => platformDispatcher.onBeginFrame; @Deprecated( 'Use WidgetTester.platformDispatcher.onBeginFrame instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onBeginFrame(FrameCallback? callback) { platformDispatcher.onBeginFrame = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.onDrawFrame instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onDrawFrame => platformDispatcher.onDrawFrame; @Deprecated( 'Use WidgetTester.platformDispatcher.onDrawFrame instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onDrawFrame(VoidCallback? callback) { platformDispatcher.onDrawFrame = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.onReportTimings instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override TimingsCallback? get onReportTimings => platformDispatcher.onReportTimings; @Deprecated( 'Use WidgetTester.platformDispatcher.onReportTimings instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onReportTimings(TimingsCallback? callback) { platformDispatcher.onReportTimings = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.onPointerDataPacket instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override PointerDataPacketCallback? get onPointerDataPacket => platformDispatcher.onPointerDataPacket; @Deprecated( 'Use WidgetTester.platformDispatcher.onPointerDataPacket instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onPointerDataPacket(PointerDataPacketCallback? callback) { platformDispatcher.onPointerDataPacket = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.defaultRouteName instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override String get defaultRouteName => platformDispatcher.defaultRouteName; @Deprecated( 'Use WidgetTester.platformDispatcher.scheduleFrame() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void scheduleFrame() { platformDispatcher.scheduleFrame(); } @Deprecated( 'Use WidgetTester.view.render(scene) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void render(Scene scene, {Size? size}) { _view.render(scene, size: size); } @Deprecated( 'Use WidgetTester.platformDispatcher.semanticsEnabled instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override bool get semanticsEnabled => platformDispatcher.semanticsEnabled; @Deprecated( 'Use WidgetTester.platformDispatcher.onSemanticsEnabledChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onSemanticsEnabledChanged => platformDispatcher.onSemanticsEnabledChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onSemanticsEnabledChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onSemanticsEnabledChanged(VoidCallback? callback) { platformDispatcher.onSemanticsEnabledChanged = callback; } @Deprecated( 'Use WidgetTester.platformDispatcher.accessibilityFeatures instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override AccessibilityFeatures get accessibilityFeatures => platformDispatcher.accessibilityFeatures; @Deprecated( 'Use WidgetTester.platformDispatcher.onAccessibilityFeaturesChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onAccessibilityFeaturesChanged => platformDispatcher.onAccessibilityFeaturesChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onAccessibilityFeaturesChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onAccessibilityFeaturesChanged(VoidCallback? callback) { platformDispatcher.onAccessibilityFeaturesChanged = callback; } @Deprecated( 'Use WidgetTester.view.updateSemantics(update) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void updateSemantics(SemanticsUpdate update) { _view.updateSemantics(update); } @Deprecated( 'Use WidgetTester.platformDispatcher.setIsolateDebugName(name) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void setIsolateDebugName(String name) { platformDispatcher.setIsolateDebugName(name); } @Deprecated( 'Use WidgetTester.platformDispatcher.sendPlatformMessage(name, data, callback) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override void sendPlatformMessage( String name, ByteData? data, PlatformMessageResponseCallback? callback, ) { platformDispatcher.sendPlatformMessage(name, data, callback); } /// Delete any test value properties that have been set on this [TestWindow] /// as well as its [platformDispatcher]. /// /// After calling this, the real [SingletonFlutterWindow] and /// [PlatformDispatcher] values are reported again. /// /// If desired, clearing of properties can be done on an individual basis, /// e.g., [clearDevicePixelRatioTestValue]. @Deprecated( 'Use WidgetTester.platformDispatcher.clearAllTestValues() and WidgetTester.view.reset() instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) void clearAllTestValues() { clearDevicePixelRatioTestValue(); clearPaddingTestValue(); clearGestureSettingsTestValue(); clearDisplayFeaturesTestValue(); clearPhysicalSizeTestValue(); clearViewInsetsTestValue(); platformDispatcher.clearAllTestValues(); } @override @Deprecated( 'Use WidgetTester.platformDispatcher.onFrameDataChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) VoidCallback? get onFrameDataChanged => platformDispatcher.onFrameDataChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onFrameDataChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onFrameDataChanged(VoidCallback? value) { platformDispatcher.onFrameDataChanged = value; } @Deprecated( 'Use WidgetTester.platformDispatcher.onKeyData instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override KeyDataCallback? get onKeyData => platformDispatcher.onKeyData; @Deprecated( 'Use WidgetTester.platformDispatcher.onKeyData instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onKeyData(KeyDataCallback? value) { platformDispatcher.onKeyData = value; } @Deprecated( 'Use WidgetTester.platformDispatcher.onSystemFontFamilyChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override VoidCallback? get onSystemFontFamilyChanged => platformDispatcher.onSystemFontFamilyChanged; @Deprecated( 'Use WidgetTester.platformDispatcher.onSystemFontFamilyChanged instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override set onSystemFontFamilyChanged(VoidCallback? value) { platformDispatcher.onSystemFontFamilyChanged = value; } @Deprecated( 'Use WidgetTester.platformDispatcher.computePlatformResolvedLocale(supportedLocales) instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override Locale? computePlatformResolvedLocale(List<Locale> supportedLocales) { return platformDispatcher.computePlatformResolvedLocale(supportedLocales); } @Deprecated( 'Use WidgetTester.platformDispatcher.frameData instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override FrameData get frameData => platformDispatcher.frameData; @Deprecated( 'Use WidgetTester.platformDispatcher.systemFontFamily instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override String? get systemFontFamily => platformDispatcher.systemFontFamily; @Deprecated( 'Use WidgetTester.view.viewId instead. ' 'Deprecated to prepare for the upcoming multi-window support. ' 'This feature was deprecated after v3.9.0-0.1.pre.' ) @override int get viewId => _view.viewId; /// This gives us some grace time when the dart:ui side adds something to /// [SingletonFlutterWindow], and makes things easier when we do rolls to give /// us time to catch up. @override dynamic noSuchMethod(Invocation invocation) { return null; } }
flutter/packages/flutter_test/lib/src/window.dart/0
{ "file_path": "flutter/packages/flutter_test/lib/src/window.dart", "repo_id": "flutter", "token_count": 21062 }
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/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { final LiveTestWidgetsFlutterBinding binding = LiveTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('localToGlobal and globalToLocal calculate correct results', (WidgetTester tester) async { tester.view.physicalSize = const Size(2400, 1800); tester.view.devicePixelRatio = 3.0; final RenderView renderView = RenderView( view: tester.view, configuration: TestViewConfiguration.fromView( view: tester.view, size: const Size(400, 200), ) ); // The configuration above defines a view with a resolution of 2400x1800 // physical pixels. With a device pixel ratio of 3x, this yields a // resolution of 800x600 logical pixels. In this view, a RenderView sized // 400x200 (in logical pixels) is fitted using the BoxFit.contain // algorithm (as documented on TestViewConfiguration. To fit 400x200 into // 800x600 the RenderView is scaled up by 2 to fill the full width and then // vertically positioned in the middle. The origin of the RenderView is // located at (0, 100) in the logical coordinate space of the view: // // View: 800 logical pixels wide (or 2400 physical pixels) // +---------------------------------------+ // | | // | 100px | // | | // +---------------------------------------+ // | | // | RenderView (400x200px) | // | 400px scaled to 800x400px | View: 600 logical pixels high (or 1800 physical pixels) // | | // | | // +---------------------------------------+ // | | // | 200px | // | | // +---------------------------------------+ // // All values in logical pixels until otherwise noted. // // A point can be translated from the local coordinate space of the // RenderView (in logical pixels) to the global coordinate space of the View // (in logical pixels) by multiplying each coordinate by 2 and adding 100 to // the y coordinate. This is what the localToGlobal/globalToLocal methods // do: expect(binding.localToGlobal(const Offset(0, -50), renderView), Offset.zero); expect(binding.localToGlobal(Offset.zero, renderView), const Offset(0, 100)); expect(binding.localToGlobal(const Offset(200, 100), renderView), const Offset(400, 300)); expect(binding.localToGlobal(const Offset(150, 75), renderView), const Offset(300, 250)); expect(binding.localToGlobal(const Offset(400, 200), renderView), const Offset(800, 500)); expect(binding.localToGlobal(const Offset(400, 400), renderView), const Offset(800, 900)); expect(binding.globalToLocal(Offset.zero, renderView), const Offset(0, -50)); expect(binding.globalToLocal(const Offset(0, 100), renderView), Offset.zero); expect(binding.globalToLocal(const Offset(400, 300), renderView), const Offset(200, 100)); expect(binding.globalToLocal(const Offset(300, 250), renderView), const Offset(150, 75)); expect(binding.globalToLocal(const Offset(800, 500), renderView), const Offset(400, 200)); expect(binding.globalToLocal(const Offset(800, 900), renderView), const Offset(400, 400)); }); }
flutter/packages/flutter_test/test/coordinate_translation_test.dart/0
{ "file_path": "flutter/packages/flutter_test/test/coordinate_translation_test.dart", "repo_id": "flutter", "token_count": 1430 }
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 'dart:convert' show json; import 'dart:math' as math; import 'package:args/args.dart'; import 'package:flutter_tools/src/artifacts.dart'; 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'; import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/build_info.dart'; import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/context_runner.dart'; import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/globals.dart' as globals; import 'package:flutter_tools/src/isolated/native_assets/test/native_assets.dart'; import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/test/coverage_collector.dart'; import 'package:flutter_tools/src/test/runner.dart'; import 'package:flutter_tools/src/test/test_wrapper.dart'; const String _kOptionPackages = 'packages'; const String _kOptionShell = 'shell'; const String _kOptionTestDirectory = 'test-directory'; const String _kOptionSdkRoot = 'sdk-root'; const String _kOptionIcudtl = 'icudtl'; const String _kOptionTests = 'tests'; const String _kOptionCoverageDirectory = 'coverage-directory'; const List<String> _kRequiredOptions = <String>[ _kOptionPackages, _kOptionShell, _kOptionSdkRoot, _kOptionIcudtl, _kOptionTests, ]; const String _kOptionCoverage = 'coverage'; const String _kOptionCoveragePath = 'coverage-path'; void main(List<String> args) { runInContext<void>(() => run(args), overrides: <Type, Generator>{ Usage: () => DisabledUsage(), }); } Future<void> run(List<String> args) async { final ArgParser parser = ArgParser() ..addOption(_kOptionPackages, help: 'The .packages file') ..addOption(_kOptionShell, help: 'The Flutter shell binary') ..addOption(_kOptionTestDirectory, help: 'Directory containing the tests') ..addOption(_kOptionSdkRoot, help: 'Path to the SDK platform files') ..addOption(_kOptionIcudtl, help: 'Path to the ICU data file') ..addOption(_kOptionTests, help: 'Path to json file that maps Dart test files to precompiled dill files') ..addOption(_kOptionCoverageDirectory, help: 'The path to the directory that will have coverage collected') ..addFlag(_kOptionCoverage, negatable: false, help: 'Whether to collect coverage information.', ) ..addOption(_kOptionCoveragePath, defaultsTo: 'coverage/lcov.info', help: 'Where to store coverage information (if coverage is enabled).', ); final ArgResults argResults = parser.parse(args); if (_kRequiredOptions .any((String option) => !argResults.options.contains(option))) { throwToolExit('Missing option! All options must be specified.'); } final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_fuchsia_tester.'); try { Cache.flutterRoot = tempDir.path; final String shellPath = globals.fs.file(argResults[_kOptionShell]).resolveSymbolicLinksSync(); if (!globals.fs.isFileSync(shellPath)) { throwToolExit('Cannot find Flutter shell at $shellPath'); } final Directory sdkRootSrc = globals.fs.directory(argResults[_kOptionSdkRoot]); if (!globals.fs.isDirectorySync(sdkRootSrc.path)) { throwToolExit('Cannot find SDK files at ${sdkRootSrc.path}'); } Directory? coverageDirectory; final String? coverageDirectoryPath = argResults[_kOptionCoverageDirectory] as String?; if (coverageDirectoryPath != null) { if (!globals.fs.isDirectorySync(coverageDirectoryPath)) { throwToolExit('Cannot find coverage directory at $coverageDirectoryPath'); } coverageDirectory = globals.fs.directory(coverageDirectoryPath); } // Put the tester shell where runTests expects it. // TODO(garymm): Switch to a Fuchsia-specific Artifacts impl. final Artifacts artifacts = globals.artifacts!; final Link testerDestLink = globals.fs.link(artifacts.getArtifactPath(Artifact.flutterTester)); testerDestLink.parent.createSync(recursive: true); testerDestLink.createSync(globals.fs.path.absolute(shellPath)); final Directory sdkRootDest = globals.fs.directory(artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath)); sdkRootDest.createSync(recursive: true); for (final FileSystemEntity artifact in sdkRootSrc.listSync()) { globals.fs.link(sdkRootDest.childFile(artifact.basename).path).createSync(artifact.path); } // TODO(tvolkert): Remove once flutter_tester no longer looks for this. globals.fs.link(sdkRootDest.childFile('platform.dill').path).createSync('platform_strong.dill'); Directory? testDirectory; CoverageCollector? collector; if (argResults['coverage'] as bool? ?? false) { // If we have a specified coverage directory then accept all libraries by // setting libraryNames to null. final Set<String>? libraryNames = coverageDirectory != null ? null : <String>{FlutterProject.current().manifest.appName}; final String packagesPath = globals.fs.path.normalize(globals.fs.path.absolute(argResults[_kOptionPackages] as String)); collector = CoverageCollector( packagesPath: packagesPath, libraryNames: libraryNames, resolver: await CoverageCollector.getResolver(packagesPath)); if (!argResults.options.contains(_kOptionTestDirectory)) { throwToolExit('Use of --coverage requires setting --test-directory'); } testDirectory = globals.fs.directory(argResults[_kOptionTestDirectory]); } final Map<String, String> tests = <String, String>{}; final List<Map<String, dynamic>> jsonList = List<Map<String, dynamic>>.from( (json.decode(globals.fs.file(argResults[_kOptionTests]).readAsStringSync()) as List<dynamic>).cast<Map<String, dynamic>>()); for (final Map<String, dynamic> map in jsonList) { final String source = globals.fs.file(map['source']).resolveSymbolicLinksSync(); final String dill = globals.fs.file(map['dill']).resolveSymbolicLinksSync(); tests[source] = dill; } // TODO(dnfield): This should be injected. exitCode = await const FlutterTestRunner().runTests( const TestWrapper(), tests.keys.map(Uri.file).toList(), debuggingOptions: DebuggingOptions.enabled( BuildInfo( BuildMode.debug, '', treeShakeIcons: false, packagesPath: globals.fs.path.normalize(globals.fs.path.absolute(argResults[_kOptionPackages] as String)), ), ), watcher: collector, enableVmService: collector != null, precompiledDillFiles: tests, concurrency: math.max(1, globals.platform.numberOfProcessors - 2), icudtlPath: globals.fs.path.absolute(argResults[_kOptionIcudtl] as String), coverageDirectory: coverageDirectory, nativeAssetsBuilder: const TestCompilerNativeAssetsBuilderImpl(), ); if (collector != null) { // collector expects currentDirectory to be the root of the dart // package (i.e. contains lib/ and test/ sub-dirs). In some cases, // test files may appear to be in the root directory. if (coverageDirectory == null) { globals.fs.currentDirectory = testDirectory!.parent; } else { globals.fs.currentDirectory = testDirectory; } if (!await collector.collectCoverageData(argResults[_kOptionCoveragePath] as String?, coverageDirectory: coverageDirectory)) { throwToolExit('Failed to collect coverage data'); } } } finally { tempDir.deleteSync(recursive: true); } // TODO(ianh): There's apparently some sort of lost async task keeping the // process open. Remove the next line once that's been resolved. exit(exitCode); }
flutter/packages/flutter_tools/bin/fuchsia_tester.dart/0
{ "file_path": "flutter/packages/flutter_tools/bin/fuchsia_tester.dart", "repo_id": "flutter", "token_count": 2796 }
788
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="catalog - animated_list" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/catalog/lib/animated_list.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___animated_list.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/catalog___animated_list.xml.copy.tmpl", "repo_id": "flutter", "token_count": 95 }
789
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="layers - sectors" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/layers/widgets/sectors.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___sectors.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/layers___sectors.xml.copy.tmpl", "repo_id": "flutter", "token_count": 92 }
790
<component name="ProjectRunConfigurationManager"> <configuration default="false" name="platform_channel" type="FlutterRunConfigurationType" factoryName="Flutter"> <option name="filePath" value="$PROJECT_DIR$/examples/platform_channel/lib/main.dart" /> <method /> </configuration> </component>
flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/platform_channel.xml.copy.tmpl/0
{ "file_path": "flutter/packages/flutter_tools/ide_templates/intellij/.idea/runConfigurations/platform_channel.xml.copy.tmpl", "repo_id": "flutter", "token_count": 90 }
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. final RegExp _whitespace = RegExp(r'\s+'); /// Convert adb device names into more human readable descriptions. String cleanAdbDeviceName(String name) { // Some emulators use `___` in the name as separators. name = name.replaceAll('___', ', '); // Convert `Nexus_7` / `Nexus_5X` style names to `Nexus 7` ones. name = name.replaceAll('_', ' '); name = name.replaceAll(_whitespace, ' ').trim(); return name; }
flutter/packages/flutter_tools/lib/src/android/adb.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/adb.dart", "repo_id": "flutter", "token_count": 188 }
792
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:math'; import 'package:crypto/crypto.dart'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import 'package:unified_analytics/unified_analytics.dart'; import 'package:xml/xml.dart'; import '../artifacts.dart'; import '../base/analyze_size.dart'; import '../base/common.dart'; import '../base/deferred_component.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/net.dart'; import '../base/platform.dart'; import '../base/process.dart'; import '../base/project_migrator.dart'; import '../base/terminal.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../cache.dart'; import '../convert.dart'; import '../flutter_manifest.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import 'android_builder.dart'; import 'android_studio.dart'; import 'gradle_errors.dart'; import 'gradle_utils.dart'; import 'java.dart'; import 'migrations/android_studio_java_gradle_conflict_migration.dart'; import 'migrations/min_sdk_version_migration.dart'; import 'migrations/top_level_gradle_build_file_migration.dart'; /// The regex to grab variant names from printBuildVariants gradle task /// /// The task is defined in flutter/packages/flutter_tools/gradle/src/main/groovy/flutter.groovy /// /// The expected output from the task should be similar to: /// /// BuildVariant: debug /// BuildVariant: release /// BuildVariant: profile final RegExp _kBuildVariantRegex = RegExp('^BuildVariant: (?<$_kBuildVariantRegexGroupName>.*)\$'); const String _kBuildVariantRegexGroupName = 'variant'; const String _kBuildVariantTaskName = 'printBuildVariants'; String _getOutputAppLinkSettingsTaskFor(String buildVariant) { return _taskForBuildVariant('output', buildVariant, 'AppLinkSettings'); } /// The directory where the APK artifact is generated. Directory getApkDirectory(FlutterProject project) { return project.isModule ? project.android.buildDirectory .childDirectory('host') .childDirectory('outputs') .childDirectory('apk') : project.android.buildDirectory .childDirectory('app') .childDirectory('outputs') .childDirectory('flutter-apk'); } /// The directory where the app bundle artifact is generated. @visibleForTesting Directory getBundleDirectory(FlutterProject project) { return project.isModule ? project.android.buildDirectory .childDirectory('host') .childDirectory('outputs') .childDirectory('bundle') : project.android.buildDirectory .childDirectory('app') .childDirectory('outputs') .childDirectory('bundle'); } /// The directory where the repo is generated. /// Only applicable to AARs. Directory getRepoDirectory(Directory buildDirectory) { return buildDirectory .childDirectory('outputs') .childDirectory('repo'); } /// Returns the name of Gradle task that starts with [prefix]. String _taskFor(String prefix, BuildInfo buildInfo) { final String buildType = camelCase(buildInfo.modeName); final String productFlavor = buildInfo.flavor ?? ''; return _taskForBuildVariant(prefix, '$productFlavor${sentenceCase(buildType)}'); } String _taskForBuildVariant(String prefix, String buildVariant, [String suffix = '']) { return '$prefix${sentenceCase(buildVariant)}$suffix'; } /// Returns the task to build an APK. @visibleForTesting String getAssembleTaskFor(BuildInfo buildInfo) { return _taskFor('assemble', buildInfo); } /// Returns the task to build an AAB. @visibleForTesting String getBundleTaskFor(BuildInfo buildInfo) { return _taskFor('bundle', buildInfo); } /// Returns the task to build an AAR. @visibleForTesting String getAarTaskFor(BuildInfo buildInfo) { return _taskFor('assembleAar', buildInfo); } /// Returns the output APK file names for a given [AndroidBuildInfo]. /// /// For example, when [splitPerAbi] is true, multiple APKs are created. Iterable<String> _apkFilesFor(AndroidBuildInfo androidBuildInfo) { final String buildType = camelCase(androidBuildInfo.buildInfo.modeName); final String productFlavor = androidBuildInfo.buildInfo.lowerCasedFlavor ?? ''; final String flavorString = productFlavor.isEmpty ? '' : '-$productFlavor'; if (androidBuildInfo.splitPerAbi) { return androidBuildInfo.targetArchs.map<String>((AndroidArch arch) { final String abi = arch.archName; return 'app$flavorString-$abi-$buildType.apk'; }); } return <String>['app$flavorString-$buildType.apk']; } // The maximum time to wait before the tool retries a Gradle build. const Duration kMaxRetryTime = Duration(seconds: 10); /// An implementation of the [AndroidBuilder] that delegates to gradle. class AndroidGradleBuilder implements AndroidBuilder { AndroidGradleBuilder({ required Java? java, required Logger logger, required ProcessManager processManager, required FileSystem fileSystem, required Artifacts artifacts, required Usage usage, required Analytics analytics, required GradleUtils gradleUtils, required Platform platform, required AndroidStudio? androidStudio, }) : _java = java, _logger = logger, _fileSystem = fileSystem, _artifacts = artifacts, _usage = usage, _analytics = analytics, _gradleUtils = gradleUtils, _androidStudio = androidStudio, _fileSystemUtils = FileSystemUtils(fileSystem: fileSystem, platform: platform), _processUtils = ProcessUtils(logger: logger, processManager: processManager); final Java? _java; final Logger _logger; final ProcessUtils _processUtils; final FileSystem _fileSystem; final Artifacts _artifacts; final Usage _usage; final Analytics _analytics; final GradleUtils _gradleUtils; final FileSystemUtils _fileSystemUtils; final AndroidStudio? _androidStudio; /// Builds the AAR and POM files for the current Flutter module or plugin. @override Future<void> buildAar({ required FlutterProject project, required Set<AndroidBuildInfo> androidBuildInfo, required String target, String? outputDirectoryPath, required String buildNumber, }) async { Directory outputDirectory = _fileSystem.directory(outputDirectoryPath ?? project.android.buildDirectory); if (project.isModule) { // Module projects artifacts are located in `build/host`. outputDirectory = outputDirectory.childDirectory('host'); } for (final AndroidBuildInfo androidBuildInfo in androidBuildInfo) { await buildGradleAar( project: project, androidBuildInfo: androidBuildInfo, target: target, outputDirectory: outputDirectory, buildNumber: buildNumber, ); } printHowToConsumeAar( buildModes: androidBuildInfo .map<String>((AndroidBuildInfo androidBuildInfo) { return androidBuildInfo.buildInfo.modeName; }).toSet(), androidPackage: project.manifest.androidPackage, repoDirectory: getRepoDirectory(outputDirectory), buildNumber: buildNumber, logger: _logger, fileSystem: _fileSystem, ); } /// Builds the APK. @override Future<void> buildApk({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, bool configOnly = false, }) async { await buildGradleApp( project: project, androidBuildInfo: androidBuildInfo, target: target, isBuildingBundle: false, localGradleErrors: gradleErrors, configOnly: configOnly, maxRetries: 1, ); } /// Builds the App Bundle. @override Future<void> buildAab({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, bool validateDeferredComponents = true, bool deferredComponentsEnabled = false, bool configOnly = false, }) async { await buildGradleApp( project: project, androidBuildInfo: androidBuildInfo, target: target, isBuildingBundle: true, localGradleErrors: gradleErrors, validateDeferredComponents: validateDeferredComponents, deferredComponentsEnabled: deferredComponentsEnabled, configOnly: configOnly, maxRetries: 1, ); } Future<RunResult> _runGradleTask( String taskName, { List<String> options = const <String>[], required FlutterProject project }) async { final Status status = _logger.startProgress( "Running Gradle task '$taskName'...", ); final List<String> command = <String>[ _gradleUtils.getExecutable(project), ...options, // suppresses gradle output. taskName, ]; RunResult result; try { result = await _processUtils.run( command, workingDirectory: project.android.hostAppGradleRoot.path, allowReentrantFlutter: true, environment: _java?.environment, ); } finally { status.stop(); } return result; } /// Builds an app. /// /// * [project] is typically [FlutterProject.current()]. /// * [androidBuildInfo] is the build configuration. /// * [target] is the target dart entry point. Typically, `lib/main.dart`. /// * If [isBuildingBundle] is `true`, then the output artifact is an `*.aab`, /// otherwise the output artifact is an `*.apk`. /// * [maxRetries] If not `null`, this is the max number of build retries in case a retry is triggered. Future<void> buildGradleApp({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, required bool isBuildingBundle, required List<GradleHandledError> localGradleErrors, required bool configOnly, bool validateDeferredComponents = true, bool deferredComponentsEnabled = false, int retry = 0, @visibleForTesting int? maxRetries, }) async { if (!project.android.isSupportedVersion) { _exitWithUnsupportedProjectMessage(_usage, _logger.terminal, analytics: _analytics); } final List<ProjectMigrator> migrators = <ProjectMigrator>[ TopLevelGradleBuildFileMigration(project.android, _logger), AndroidStudioJavaGradleConflictMigration(_logger, project: project.android, androidStudio: _androidStudio, java: globals.java), MinSdkVersionMigration(project.android, _logger), ]; final ProjectMigration migration = ProjectMigration(migrators); migration.run(); final bool usesAndroidX = isAppUsingAndroidX(project.android.hostAppGradleRoot); if (usesAndroidX) { BuildEvent('app-using-android-x', type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: 'app-using-android-x', buildType: 'gradle')); } else if (!usesAndroidX) { BuildEvent('app-not-using-android-x', type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: 'app-not-using-android-x', buildType: 'gradle')); _logger.printStatus("${_logger.terminal.warningMark} Your app isn't using AndroidX.", emphasis: true); _logger.printStatus( 'To avoid potential build failures, you can quickly migrate your app ' 'by following the steps on https://goo.gl/CP92wY .', indent: 4, ); } // The default Gradle script reads the version name and number // from the local.properties file. updateLocalProperties( project: project, buildInfo: androidBuildInfo.buildInfo); final List<String> command = <String>[ // This does more than get gradlewrapper. It creates the file, ensures it // exists and verifies the file is executable. _gradleUtils.getExecutable(project), ]; // All automatically created files should exist. if (configOnly) { _logger.printStatus('Config complete.'); return; } // Assembly work starts here. final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String assembleTask = isBuildingBundle ? getBundleTaskFor(buildInfo) : getAssembleTaskFor(buildInfo); final Status status = _logger.startProgress( "Running Gradle task '$assembleTask'...", ); if (_logger.isVerbose) { command.add('--full-stacktrace'); command.add('--info'); command.add('-Pverbose=true'); } else { command.add('-q'); } if (!buildInfo.androidGradleDaemon) { command.add('--no-daemon'); } if (buildInfo.androidSkipBuildDependencyValidation) { command.add('-PskipDependencyChecks=true'); } final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo; if (localEngineInfo != null) { final Directory localEngineRepo = _getLocalEngineRepo( engineOutPath: localEngineInfo.targetOutPath, androidBuildInfo: androidBuildInfo, fileSystem: _fileSystem, ); _logger.printTrace( 'Using local engine: ${localEngineInfo.targetOutPath}\n' 'Local Maven repo: ${localEngineRepo.path}' ); command.add('-Plocal-engine-repo=${localEngineRepo.path}'); command.add('-Plocal-engine-build-mode=${buildInfo.modeName}'); command.add('-Plocal-engine-out=${localEngineInfo.targetOutPath}'); command.add('-Plocal-engine-host-out=${localEngineInfo.hostOutPath}'); command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath( localEngineInfo.targetOutPath)}'); } else if (androidBuildInfo.targetArchs.isNotEmpty) { final String targetPlatforms = androidBuildInfo .targetArchs .map((AndroidArch e) => e.platformName).join(','); command.add('-Ptarget-platform=$targetPlatforms'); } command.add('-Ptarget=$target'); // If using v1 embedding, we want to use FlutterApplication as the base app. final String baseApplicationName = project.android.getEmbeddingVersion() == AndroidEmbeddingVersion.v2 ? 'android.app.Application' : 'io.flutter.app.FlutterApplication'; command.add('-Pbase-application-name=$baseApplicationName'); final List<DeferredComponent>? deferredComponents = project.manifest.deferredComponents; if (deferredComponents != null) { if (deferredComponentsEnabled) { command.add('-Pdeferred-components=true'); androidBuildInfo.buildInfo.dartDefines.add('validate-deferred-components=$validateDeferredComponents'); } // Pass in deferred components regardless of building split aot to satisfy // android dynamic features registry in build.gradle. final List<String> componentNames = <String>[]; for (final DeferredComponent component in deferredComponents) { componentNames.add(component.name); } if (componentNames.isNotEmpty) { command.add('-Pdeferred-component-names=${componentNames.join(',')}'); // Multi-apk applications cannot use shrinking. This is only relevant when using // android dynamic feature modules. _logger.printStatus( 'Shrinking has been disabled for this build due to deferred components. Shrinking is ' 'not available for multi-apk applications. This limitation is expected to be removed ' 'when Gradle plugin 4.2+ is available in Flutter.', color: TerminalColor.yellow); command.add('-Pshrink=false'); } } command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); if (buildInfo.fileSystemRoots.isNotEmpty) { command.add('-Pfilesystem-roots=${buildInfo.fileSystemRoots.join('|')}'); } if (buildInfo.fileSystemScheme != null) { command.add('-Pfilesystem-scheme=${buildInfo.fileSystemScheme}'); } if (androidBuildInfo.splitPerAbi) { command.add('-Psplit-per-abi=true'); } if (androidBuildInfo.fastStart) { command.add('-Pfast-start=true'); } command.add(assembleTask); GradleHandledError? detectedGradleError; String? detectedGradleErrorLine; String? consumeLog(String line) { if (detectedGradleError != null) { // Pipe stdout/stderr from Gradle. return line; } for (final GradleHandledError gradleError in localGradleErrors) { if (gradleError.test(line)) { detectedGradleErrorLine = line; detectedGradleError = gradleError; // The first error match wins. break; } } // Pipe stdout/stderr from Gradle. return line; } final Stopwatch sw = Stopwatch() ..start(); int exitCode = 1; try { exitCode = await _processUtils.stream( command, workingDirectory: project.android.hostAppGradleRoot.path, allowReentrantFlutter: true, environment: _java?.environment, mapFunction: consumeLog, ); } on ProcessException catch (exception) { consumeLog(exception.toString()); // Rethrow the exception if the error isn't handled by any of the // `localGradleErrors`. if (detectedGradleError == null) { rethrow; } } finally { status.stop(); } final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('build', 'gradle', elapsedDuration); _analytics.send(Event.timing( workflow: 'build', variableName: 'gradle', elapsedMilliseconds: elapsedDuration.inMilliseconds, )); if (exitCode != 0) { if (detectedGradleError == null) { BuildEvent('gradle-unknown-failure', type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: 'gradle-unknown-failure', buildType: 'gradle')); throwToolExit( 'Gradle task $assembleTask failed with exit code $exitCode', exitCode: exitCode, ); } final GradleBuildStatus status = await detectedGradleError!.handler( line: detectedGradleErrorLine!, project: project, usesAndroidX: usesAndroidX, ); if (maxRetries == null || retry < maxRetries) { switch (status) { case GradleBuildStatus.retry: // Use binary exponential backoff before retriggering the build. // The expected wait times are: 100ms, 200ms, 400ms, and so on... final int waitTime = min(pow(2, retry).toInt() * 100, kMaxRetryTime.inMicroseconds); retry += 1; _logger.printStatus('Retrying Gradle Build: #$retry, wait time: ${waitTime}ms'); await Future<void>.delayed(Duration(milliseconds: waitTime)); await buildGradleApp( project: project, androidBuildInfo: androidBuildInfo, target: target, isBuildingBundle: isBuildingBundle, localGradleErrors: localGradleErrors, retry: retry, maxRetries: maxRetries, configOnly: configOnly, ); final String successEventLabel = 'gradle-${detectedGradleError!.eventLabel}-success'; BuildEvent(successEventLabel, type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: successEventLabel, buildType: 'gradle')); return; case GradleBuildStatus.exit: // Continue and throw tool exit. } } final String usageLabel = 'gradle-${detectedGradleError?.eventLabel}-failure'; BuildEvent(usageLabel, type: 'gradle', flutterUsage: _usage).send(); _analytics.send(Event.flutterBuildInfo(label: usageLabel, buildType: 'gradle')); throwToolExit( 'Gradle task $assembleTask failed with exit code $exitCode', exitCode: exitCode, ); } if (isBuildingBundle) { final File bundleFile = findBundleFile(project, buildInfo, _logger, _usage, _analytics); final String appSize = (buildInfo.mode == BuildMode.debug) ? '' // Don't display the size when building a debug variant. : ' (${getSizeAsMB(bundleFile.lengthSync())})'; if (buildInfo.codeSizeDirectory != null) { await _performCodeSizeAnalysis('aab', bundleFile, androidBuildInfo); } _logger.printStatus( '${_logger.terminal.successMark} Built ${_fileSystem.path.relative(bundleFile.path)}$appSize.', color: TerminalColor.green, ); return; } // Gradle produced APKs. final Iterable<String> apkFilesPaths = project.isModule ? findApkFilesModule(project, androidBuildInfo, _logger, _usage, _analytics) : listApkPaths(androidBuildInfo); final Directory apkDirectory = getApkDirectory(project); // Generate sha1 for every generated APKs. for (final File apkFile in apkFilesPaths.map(apkDirectory.childFile)) { if (!apkFile.existsSync()) { _exitWithExpectedFileNotFound( project: project, fileExtension: '.apk', logger: _logger, usage: _usage, analytics: _analytics, ); } final String filename = apkFile.basename; _logger.printTrace('Calculate SHA1: $apkDirectory/$filename'); final File apkShaFile = apkDirectory.childFile('$filename.sha1'); apkShaFile.writeAsStringSync(_calculateSha(apkFile)); final String appSize = (buildInfo.mode == BuildMode.debug) ? '' // Don't display the size when building a debug variant. : ' (${getSizeAsMB(apkFile.lengthSync())})'; _logger.printStatus( '${_logger.terminal.successMark} Built ${_fileSystem.path.relative(apkFile.path)}$appSize.', color: TerminalColor.green, ); if (buildInfo.codeSizeDirectory != null) { await _performCodeSizeAnalysis('apk', apkFile, androidBuildInfo); } } } Future<void> _performCodeSizeAnalysis(String kind, File zipFile, AndroidBuildInfo androidBuildInfo,) async { final SizeAnalyzer sizeAnalyzer = SizeAnalyzer( fileSystem: _fileSystem, logger: _logger, flutterUsage: _usage, analytics: _analytics, ); final String archName = androidBuildInfo.targetArchs.single.archName; final BuildInfo buildInfo = androidBuildInfo.buildInfo; final File aotSnapshot = _fileSystem.directory(buildInfo.codeSizeDirectory) .childFile('snapshot.$archName.json'); final File precompilerTrace = _fileSystem.directory(buildInfo.codeSizeDirectory) .childFile('trace.$archName.json'); final Map<String, Object?> output = await sizeAnalyzer.analyzeZipSizeAndAotSnapshot( zipFile: zipFile, aotSnapshot: aotSnapshot, precompilerTrace: precompilerTrace, kind: kind, ); final File outputFile = _fileSystemUtils.getUniqueFile( _fileSystem .directory(_fileSystemUtils.homeDirPath) .childDirectory('.flutter-devtools'), '$kind-code-size-analysis', 'json', ) ..writeAsStringSync(jsonEncode(output)); // This message is used as a sentinel in analyze_apk_size_test.dart _logger.printStatus( 'A summary of your ${kind.toUpperCase()} analysis can be found at: ${outputFile.path}', ); // DevTools expects a file path relative to the .flutter-devtools/ dir. final String relativeAppSizePath = outputFile.path .split('.flutter-devtools/') .last .trim(); _logger.printStatus( '\nTo analyze your app size in Dart DevTools, run the following command:\n' 'dart devtools --appSizeBase=$relativeAppSizePath' ); } /// Builds AAR and POM files. /// /// * [project] is typically [FlutterProject.current()]. /// * [androidBuildInfo] is the build configuration. /// * [outputDir] is the destination of the artifacts, /// * [buildNumber] is the build number of the output aar, Future<void> buildGradleAar({ required FlutterProject project, required AndroidBuildInfo androidBuildInfo, required String target, required Directory outputDirectory, required String buildNumber, }) async { final FlutterManifest manifest = project.manifest; if (!manifest.isModule) { throwToolExit('AARs can only be built for module projects.'); } final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String aarTask = getAarTaskFor(buildInfo); final Status status = _logger.startProgress( "Running Gradle task '$aarTask'...", ); final String flutterRoot = _fileSystem.path.absolute(Cache.flutterRoot!); final String initScript = _fileSystem.path.join( flutterRoot, 'packages', 'flutter_tools', 'gradle', 'aar_init_script.gradle', ); final List<String> command = <String>[ _gradleUtils.getExecutable(project), '-I=$initScript', '-Pflutter-root=$flutterRoot', '-Poutput-dir=${outputDirectory.path}', '-Pis-plugin=${manifest.isPlugin}', '-PbuildNumber=$buildNumber', ]; if (_logger.isVerbose) { command.add('--full-stacktrace'); command.add('--info'); command.add('-Pverbose=true'); } else { command.add('-q'); } if (!buildInfo.androidGradleDaemon) { command.add('--no-daemon'); } if (target.isNotEmpty) { command.add('-Ptarget=$target'); } command.addAll(androidBuildInfo.buildInfo.toGradleConfig()); if (buildInfo.dartObfuscation && buildInfo.mode != BuildMode.release) { _logger.printStatus( 'Dart obfuscation is not supported in ${sentenceCase(buildInfo.friendlyModeName)}' ' mode, building as un-obfuscated.', ); } final LocalEngineInfo? localEngineInfo = _artifacts.localEngineInfo; if (localEngineInfo != null) { final Directory localEngineRepo = _getLocalEngineRepo( engineOutPath: localEngineInfo.targetOutPath, androidBuildInfo: androidBuildInfo, fileSystem: _fileSystem, ); _logger.printTrace( 'Using local engine: ${localEngineInfo.targetOutPath}\n' 'Local Maven repo: ${localEngineRepo.path}' ); command.add('-Plocal-engine-repo=${localEngineRepo.path}'); command.add('-Plocal-engine-build-mode=${buildInfo.modeName}'); command.add('-Plocal-engine-out=${localEngineInfo.targetOutPath}'); command.add('-Plocal-engine-host-out=${localEngineInfo.hostOutPath}'); // Copy the local engine repo in the output directory. try { copyDirectory( localEngineRepo, getRepoDirectory(outputDirectory), ); } on FileSystemException catch (error, st) { throwToolExit( 'Failed to copy the local engine ${localEngineRepo.path} repo ' 'in ${outputDirectory.path}: $error, $st' ); } command.add('-Ptarget-platform=${_getTargetPlatformByLocalEnginePath( localEngineInfo.targetOutPath)}'); } else if (androidBuildInfo.targetArchs.isNotEmpty) { final String targetPlatforms = androidBuildInfo.targetArchs .map((AndroidArch e) => e.platformName).join(','); command.add('-Ptarget-platform=$targetPlatforms'); } command.add(aarTask); final Stopwatch sw = Stopwatch() ..start(); RunResult result; try { result = await _processUtils.run( command, workingDirectory: project.android.hostAppGradleRoot.path, allowReentrantFlutter: true, environment: _java?.environment, ); } finally { status.stop(); } final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('build', 'gradle-aar', elapsedDuration); _analytics.send(Event.timing( workflow: 'build', variableName: 'gradle-aar', elapsedMilliseconds: elapsedDuration.inMilliseconds, )); if (result.exitCode != 0) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); throwToolExit( 'Gradle task $aarTask failed with exit code ${result.exitCode}.', exitCode: result.exitCode, ); } final Directory repoDirectory = getRepoDirectory(outputDirectory); if (!repoDirectory.existsSync()) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); throwToolExit( 'Gradle task $aarTask failed to produce $repoDirectory.', exitCode: exitCode, ); } _logger.printStatus( '${_logger.terminal.successMark} Built ${_fileSystem.path.relative(repoDirectory.path)}.', color: TerminalColor.green, ); } @override Future<List<String>> getBuildVariants({required FlutterProject project}) async { final Stopwatch sw = Stopwatch() ..start(); final RunResult result = await _runGradleTask( _kBuildVariantTaskName, options: const <String>['-q'], project: project, ); final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('print', 'android build variants', elapsedDuration); _analytics.send(Event.timing( workflow: 'print', variableName: 'android build variants', elapsedMilliseconds: elapsedDuration.inMilliseconds, )); if (result.exitCode != 0) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); return const <String>[]; } final List<String> options = <String>[]; for (final String line in LineSplitter.split(result.stdout)) { final RegExpMatch? match = _kBuildVariantRegex.firstMatch(line); if (match != null) { options.add(match.namedGroup(_kBuildVariantRegexGroupName)!); } } return options; } @override Future<String> outputsAppLinkSettings( String buildVariant, { required FlutterProject project, }) async { final String taskName = _getOutputAppLinkSettingsTaskFor(buildVariant); final Directory directory = await project.buildDirectory .childDirectory('deeplink_data').create(recursive: true); final String outputPath = globals.fs.path.join( directory.absolute.path, 'app-link-settings-$buildVariant.json', ); final Stopwatch sw = Stopwatch() ..start(); final RunResult result = await _runGradleTask( taskName, options: <String>['-q', '-PoutputPath=$outputPath'], project: project, ); final Duration elapsedDuration = sw.elapsed; _usage.sendTiming('outputs', 'app link settings', elapsedDuration); _analytics.send(Event.timing( workflow: 'outputs', variableName: 'app link settings', elapsedMilliseconds: elapsedDuration.inMilliseconds, )); if (result.exitCode != 0) { _logger.printStatus(result.stdout, wrap: false); _logger.printError(result.stderr, wrap: false); throwToolExit(result.stderr); } return outputPath; } } /// Prints how to consume the AAR from a host app. void printHowToConsumeAar({ required Set<String> buildModes, String? androidPackage = 'unknown', required Directory repoDirectory, required Logger logger, required FileSystem fileSystem, String? buildNumber, }) { assert(buildModes.isNotEmpty); buildNumber ??= '1.0'; logger.printStatus('\nConsuming the Module', emphasis: true); logger.printStatus(''' 1. Open ${fileSystem.path.join('<host>', 'app', 'build.gradle')} 2. Ensure you have the repositories configured, otherwise add them: String storageUrl = System.env.$kFlutterStorageBaseUrl ?: "https://storage.googleapis.com" repositories { maven { url '${repoDirectory.path}' } maven { url "\$storageUrl/download.flutter.io" } } 3. Make the host app depend on the Flutter module: dependencies {'''); for (final String buildMode in buildModes) { logger.printStatus(""" ${buildMode}Implementation '$androidPackage:flutter_$buildMode:$buildNumber'"""); } logger.printStatus(''' } '''); if (buildModes.contains('profile')) { logger.printStatus(''' 4. Add the `profile` build type: android { buildTypes { profile { initWith debug } } } '''); } logger.printStatus('To learn more, visit https://flutter.dev/go/build-aar'); } String _hex(List<int> bytes) { final StringBuffer result = StringBuffer(); for (final int part in bytes) { result.write('${part < 16 ? '0' : ''}${part.toRadixString(16)}'); } return result.toString(); } String _calculateSha(File file) { final List<int> bytes = file.readAsBytesSync(); return _hex(sha1.convert(bytes).bytes); } void _exitWithUnsupportedProjectMessage(Usage usage, Terminal terminal, {required Analytics analytics}) { BuildEvent('unsupported-project', type: 'gradle', eventError: 'gradle-plugin', flutterUsage: usage).send(); analytics.send(Event.flutterBuildInfo( label: 'unsupported-project', buildType: 'gradle', error: 'gradle-plugin', )); throwToolExit( '${terminal.warningMark} Your app is using an unsupported Gradle project. ' 'To fix this problem, create a new project by running `flutter create -t app <app-directory>` ' 'and then move the dart code, assets and pubspec.yaml to the new project.', ); } /// Returns [true] if the current app uses AndroidX. // TODO(egarciad): https://github.com/flutter/flutter/issues/40800 // Remove `FlutterManifest.usesAndroidX` and provide a unified `AndroidProject.usesAndroidX`. bool isAppUsingAndroidX(Directory androidDirectory) { final File properties = androidDirectory.childFile('gradle.properties'); if (!properties.existsSync()) { return false; } return properties.readAsStringSync().contains('android.useAndroidX=true'); } /// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo]. @visibleForTesting Iterable<String> findApkFilesModule( FlutterProject project, AndroidBuildInfo androidBuildInfo, Logger logger, Usage usage, Analytics analytics, ) { final Iterable<String> apkFileNames = _apkFilesFor(androidBuildInfo); final Directory apkDirectory = getApkDirectory(project); final Iterable<File> apks = apkFileNames.expand<File>((String apkFileName) { File apkFile = apkDirectory.childFile(apkFileName); if (apkFile.existsSync()) { return <File>[apkFile]; } final BuildInfo buildInfo = androidBuildInfo.buildInfo; final String modeName = camelCase(buildInfo.modeName); apkFile = apkDirectory .childDirectory(modeName) .childFile(apkFileName); if (apkFile.existsSync()) { return <File>[apkFile]; } final String? flavor = buildInfo.flavor; if (flavor != null) { // Android Studio Gradle plugin v3 adds flavor to path. apkFile = apkDirectory .childDirectory(flavor) .childDirectory(modeName) .childFile(apkFileName); if (apkFile.existsSync()) { return <File>[apkFile]; } } return const <File>[]; }); if (apks.isEmpty) { _exitWithExpectedFileNotFound( project: project, fileExtension: '.apk', logger: logger, usage: usage, analytics: analytics, ); } return apks.map((File file) => file.path); } /// Returns the APK files for a given [FlutterProject] and [AndroidBuildInfo]. /// /// The flutter.gradle plugin will copy APK outputs into: /// `$buildDir/app/outputs/flutter-apk/app-<abi>-<flavor-flag>-<build-mode-flag>.apk` @visibleForTesting Iterable<String> listApkPaths( AndroidBuildInfo androidBuildInfo, ) { final String buildType = camelCase(androidBuildInfo.buildInfo.modeName); final List<String> apkPartialName = <String>[ if (androidBuildInfo.buildInfo.flavor?.isNotEmpty ?? false) androidBuildInfo.buildInfo.lowerCasedFlavor!, '$buildType.apk', ]; if (androidBuildInfo.splitPerAbi) { return <String>[ for (final AndroidArch androidArch in androidBuildInfo.targetArchs) <String>[ 'app', androidArch.archName, ...apkPartialName, ].join('-'), ]; } return <String>[ <String>[ 'app', ...apkPartialName, ].join('-'), ]; } @visibleForTesting File findBundleFile(FlutterProject project, BuildInfo buildInfo, Logger logger, Usage usage, Analytics analytics) { final List<File> fileCandidates = <File>[ getBundleDirectory(project) .childDirectory(camelCase(buildInfo.modeName)) .childFile('app.aab'), getBundleDirectory(project) .childDirectory(camelCase(buildInfo.modeName)) .childFile('app-${buildInfo.modeName}.aab'), ]; if (buildInfo.flavor != null) { // The Android Gradle plugin 3.0.0 adds the flavor name to the path. // For example: In release mode, if the flavor name is `foo_bar`, then // the directory name is `foo_barRelease`. fileCandidates.add( getBundleDirectory(project) .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app.aab')); // The Android Gradle plugin 3.5.0 adds the flavor name to file name. // For example: In release mode, if the flavor name is `foo_bar`, then // the file name is `app-foo_bar-release.aab`. fileCandidates.add( getBundleDirectory(project) .childDirectory('${buildInfo.lowerCasedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app-${buildInfo.lowerCasedFlavor}-${buildInfo.modeName}.aab')); // The Android Gradle plugin 4.1.0 does only lowercase the first character of flavor name. fileCandidates.add(getBundleDirectory(project) .childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app-${buildInfo.uncapitalizedFlavor}-${buildInfo.modeName}.aab')); // The Android Gradle plugin uses kebab-case and lowercases the first character of the flavor name // when multiple flavor dimensions are used: // e.g. // flavorDimensions "dimension1","dimension2" // productFlavors { // foo { // dimension "dimension1" // } // bar { // dimension "dimension2" // } // } fileCandidates.add(getBundleDirectory(project) .childDirectory('${buildInfo.uncapitalizedFlavor}${camelCase('_${buildInfo.modeName}')}') .childFile('app-${kebabCase(buildInfo.uncapitalizedFlavor!)}-${buildInfo.modeName}.aab')); } for (final File bundleFile in fileCandidates) { if (bundleFile.existsSync()) { return bundleFile; } } _exitWithExpectedFileNotFound( project: project, fileExtension: '.aab', logger: logger, usage: usage, analytics: analytics, ); } /// Throws a [ToolExit] exception and logs the event. Never _exitWithExpectedFileNotFound({ required FlutterProject project, required String fileExtension, required Logger logger, required Usage usage, required Analytics analytics, }) { final String androidGradlePluginVersion = getGradleVersionForAndroidPlugin(project.android.hostAppGradleRoot, logger); final String gradleBuildSettings = 'androidGradlePluginVersion: $androidGradlePluginVersion, ' 'fileExtension: $fileExtension'; BuildEvent('gradle-expected-file-not-found', type: 'gradle', settings: gradleBuildSettings, flutterUsage: usage, ).send(); analytics.send(Event.flutterBuildInfo( label: 'gradle-expected-file-not-found', buildType: 'gradle', settings: gradleBuildSettings, )); throwToolExit( 'Gradle build failed to produce an $fileExtension file. ' "It's likely that this file was generated under ${project.android.buildDirectory.path}, " "but the tool couldn't find it." ); } void _createSymlink(String targetPath, String linkPath, FileSystem fileSystem) { final File targetFile = fileSystem.file(targetPath); if (!targetFile.existsSync()) { throwToolExit("The file $targetPath wasn't found in the local engine out directory."); } final File linkFile = fileSystem.file(linkPath); final Link symlink = linkFile.parent.childLink(linkFile.basename); try { symlink.createSync(targetPath, recursive: true); } on FileSystemException catch (exception) { throwToolExit( 'Failed to create the symlink $linkPath->$targetPath: $exception' ); } } String _getLocalArtifactVersion(String pomPath, FileSystem fileSystem) { final File pomFile = fileSystem.file(pomPath); if (!pomFile.existsSync()) { throwToolExit("The file $pomPath wasn't found in the local engine out directory."); } XmlDocument document; try { document = XmlDocument.parse(pomFile.readAsStringSync()); } on XmlException { throwToolExit( 'Error parsing $pomPath. Please ensure that this is a valid XML document.' ); } on FileSystemException { throwToolExit( 'Error reading $pomPath. Please ensure that you have read permission to this ' 'file and try again.'); } final Iterable<XmlElement> project = document.findElements('project'); assert(project.isNotEmpty); for (final XmlElement versionElement in document.findAllElements('version')) { if (versionElement.parent == project.first) { return versionElement.innerText; } } throwToolExit('Error while parsing the <version> element from $pomPath'); } /// Returns the local Maven repository for a local engine build. /// For example, if the engine is built locally at <home>/engine/src/out/android_release_unopt /// This method generates symlinks in the temp directory to the engine artifacts /// following the convention specified on https://maven.apache.org/pom.html#Repositories Directory _getLocalEngineRepo({ required String engineOutPath, required AndroidBuildInfo androidBuildInfo, required FileSystem fileSystem, }) { final String abi = _getAbiByLocalEnginePath(engineOutPath); final Directory localEngineRepo = fileSystem.systemTempDirectory .createTempSync('flutter_tool_local_engine_repo.'); final String buildMode = androidBuildInfo.buildInfo.modeName; final String artifactVersion = _getLocalArtifactVersion( fileSystem.path.join( engineOutPath, 'flutter_embedding_$buildMode.pom', ), fileSystem, ); for (final String artifact in const <String>['pom', 'jar']) { // The Android embedding artifacts. _createSymlink( fileSystem.path.join( engineOutPath, 'flutter_embedding_$buildMode.$artifact', ), fileSystem.path.join( localEngineRepo.path, 'io', 'flutter', 'flutter_embedding_$buildMode', artifactVersion, 'flutter_embedding_$buildMode-$artifactVersion.$artifact', ), fileSystem, ); // The engine artifacts (libflutter.so). _createSymlink( fileSystem.path.join( engineOutPath, '${abi}_$buildMode.$artifact', ), fileSystem.path.join( localEngineRepo.path, 'io', 'flutter', '${abi}_$buildMode', artifactVersion, '${abi}_$buildMode-$artifactVersion.$artifact', ), fileSystem, ); } for (final String artifact in <String>['flutter_embedding_$buildMode', '${abi}_$buildMode']) { _createSymlink( fileSystem.path.join( engineOutPath, '$artifact.maven-metadata.xml', ), fileSystem.path.join( localEngineRepo.path, 'io', 'flutter', artifact, 'maven-metadata.xml', ), fileSystem, ); } return localEngineRepo; } String _getAbiByLocalEnginePath(String engineOutPath) { String result = 'armeabi_v7a'; if (engineOutPath.contains('x86')) { result = 'x86'; } else if (engineOutPath.contains('x64')) { result = 'x86_64'; } else if (engineOutPath.contains('arm64')) { result = 'arm64_v8a'; } return result; } String _getTargetPlatformByLocalEnginePath(String engineOutPath) { String result = 'android-arm'; if (engineOutPath.contains('x86')) { result = 'android-x86'; } else if (engineOutPath.contains('x64')) { result = 'android-x64'; } else if (engineOutPath.contains('arm64')) { result = 'android-arm64'; } return result; }
flutter/packages/flutter_tools/lib/src/android/gradle.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/android/gradle.dart", "repo_id": "flutter", "token_count": 16443 }
793
// Copyright 2014 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:file/memory.dart'; import 'package:meta/meta.dart'; import '../convert.dart'; import 'error_handling_io.dart'; import 'file_system.dart'; import 'logger.dart'; import 'platform.dart'; import 'utils.dart'; /// A class to abstract configuration files. class Config { /// Constructs a new [Config] object from a file called [name] in the /// current user's configuration directory as determined by the [Platform] /// and [FileSystem]. /// /// The configuration directory defaults to $XDG_CONFIG_HOME on Linux and /// macOS, but falls back to the home directory if a file named /// `.flutter_$name` already exists there. On other platforms the /// configuration file will always be a file named `.flutter_$name` in the /// home directory. /// /// Uses some good default behaviours: /// - deletes the file if it's not valid JSON /// - reports an empty config in that case /// - logs and catches any exceptions factory Config( String name, { required FileSystem fileSystem, required Logger logger, required Platform platform }) { return Config._common( name, fileSystem: fileSystem, logger: logger, platform: platform ); } /// Similar to the default config constructor, but with some different /// behaviours: /// - will not delete the config if it's not valid JSON /// - will log but also rethrow any exceptions while loading the JSON, so /// you can actually detect whether something went wrong /// /// Useful if you want some more control. factory Config.managed( String name, { required FileSystem fileSystem, required Logger logger, required Platform platform }) { return Config._common( name, fileSystem: fileSystem, logger: logger, platform: platform, managed: true ); } factory Config._common( String name, { required FileSystem fileSystem, required Logger logger, required Platform platform, bool managed = false }) { final String filePath = _configPath(platform, fileSystem, name); final File file = fileSystem.file(filePath); file.parent.createSync(recursive: true); return Config.createForTesting(file, logger, managed: managed); } /// Constructs a new [Config] object from a file called [name] in /// the given [Directory]. /// /// Defaults to [BufferLogger], [MemoryFileSystem], and [name]=test. factory Config.test({ String name = 'test', Directory? directory, Logger? logger, bool managed = false }) { directory ??= MemoryFileSystem.test().directory('/'); return Config.createForTesting( directory.childFile('.${kConfigDir}_$name'), logger ?? BufferLogger.test(), managed: managed ); } /// Test only access to the Config constructor. @visibleForTesting Config.createForTesting(File file, Logger logger, {bool managed = false}) : _file = file, _logger = logger { if (!_file.existsSync()) { return; } try { ErrorHandlingFileSystem.noExitOnFailure(() { _values = castStringKeyedMap(json.decode(_file.readAsStringSync())) ?? <String, Object>{}; }); } on FormatException { _logger ..printError('Failed to decode preferences in ${_file.path}.') ..printError( 'You may need to reapply any previously saved configuration ' 'with the "flutter config" command.', ); if (managed) { rethrow; } else { try { _file.deleteSync(); } on FileSystemException { // ignore } } } on Exception catch (err) { _logger ..printError('Could not read preferences in ${file.path}.\n$err') ..printError( 'You may need to resolve the error above and reapply any previously ' 'saved configuration with the "flutter config" command.', ); if (managed) { rethrow; } } } /// The default directory name for Flutter's configs. /// Configs will be written to the user's config path. If there is already a /// file with the name `.${kConfigDir}_$name` in the user's home path, that /// file will be used instead. static const String kConfigDir = 'flutter'; /// Environment variable specified in the XDG Base Directory /// [specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) /// to specify the user's configuration directory. static const String kXdgConfigHome = 'XDG_CONFIG_HOME'; /// Fallback directory in the user's home directory if `XDG_CONFIG_HOME` is /// not defined. static const String kXdgConfigFallback = '.config'; /// The default name for the Flutter config file. static const String kFlutterSettings = 'settings'; final Logger _logger; File _file; String get configPath => _file.path; Map<String, dynamic> _values = <String, Object>{}; Iterable<String> get keys => _values.keys; bool containsKey(String key) => _values.containsKey(key); Object? getValue(String key) => _values[key]; void setValue(String key, Object value) { _values[key] = value; _flushValues(); } void removeValue(String key) { _values.remove(key); _flushValues(); } void _flushValues() { String json = const JsonEncoder.withIndent(' ').convert(_values); json = '$json\n'; _file.writeAsStringSync(json); } // Reads the process environment to find the current user's home directory. // // If the searched environment variables are not set, '.' is returned instead. // // This is different from [FileSystemUtils.homeDirPath]. static String _userHomePath(Platform platform) { final String envKey = platform.isWindows ? 'APPDATA' : 'HOME'; return platform.environment[envKey] ?? '.'; } static String _configPath( Platform platform, FileSystem fileSystem, String name) { final String homeDirFile = fileSystem.path.join(_userHomePath(platform), '.${kConfigDir}_$name'); if (platform.isLinux || platform.isMacOS) { if (fileSystem.isFileSync(homeDirFile)) { return homeDirFile; } final String configDir = platform.environment[kXdgConfigHome] ?? fileSystem.path.join(_userHomePath(platform), '.config', kConfigDir); return fileSystem.path.join(configDir, name); } return homeDirFile; } }
flutter/packages/flutter_tools/lib/src/base/config.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/config.dart", "repo_id": "flutter", "token_count": 2203 }
794
// Copyright 2014 The Flutter Authors. 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:collection'; import '../globals.dart' as globals; /// A closure type used by the [TaskQueue]. typedef TaskQueueClosure<T> = Future<T> Function(); /// A task queue of Futures to be completed in parallel, throttling /// the number of simultaneous tasks. /// /// The tasks return results of type T. class TaskQueue<T> { /// Creates a task queue with a maximum number of simultaneous jobs. /// The [maxJobs] parameter defaults to the number of CPU cores on the /// system. TaskQueue({int? maxJobs}) : maxJobs = maxJobs ?? globals.platform.numberOfProcessors; /// The maximum number of jobs that this queue will run simultaneously. final int maxJobs; final Queue<_TaskQueueItem<T>> _pendingTasks = Queue<_TaskQueueItem<T>>(); final Set<_TaskQueueItem<T>> _activeTasks = <_TaskQueueItem<T>>{}; final Set<Completer<void>> _completeListeners = <Completer<void>>{}; /// Returns a future that completes when all tasks in the [TaskQueue] are /// complete. Future<void> get tasksComplete { // In case this is called when there are no tasks, we want it to // signal complete immediately. if (_activeTasks.isEmpty && _pendingTasks.isEmpty) { return Future<void>.value(); } final Completer<void> completer = Completer<void>(); _completeListeners.add(completer); return completer.future; } /// Adds a single closure to the task queue, returning a future that /// completes when the task completes. Future<T> add(TaskQueueClosure<T> task) { final Completer<T> completer = Completer<T>(); _pendingTasks.add(_TaskQueueItem<T>(task, completer)); if (_activeTasks.length < maxJobs) { _processTask(); } return completer.future; } // Process a single task. void _processTask() { if (_pendingTasks.isNotEmpty && _activeTasks.length <= maxJobs) { final _TaskQueueItem<T> item = _pendingTasks.removeFirst(); _activeTasks.add(item); item.onComplete = () { _activeTasks.remove(item); _processTask(); }; item.run(); } else { _checkForCompletion(); } } void _checkForCompletion() { if (_activeTasks.isEmpty && _pendingTasks.isEmpty) { for (final Completer<void> completer in _completeListeners) { if (!completer.isCompleted) { completer.complete(); } } _completeListeners.clear(); } } } class _TaskQueueItem<T> { _TaskQueueItem(this._closure, this._completer, {this.onComplete}); final TaskQueueClosure<T> _closure; final Completer<T> _completer; void Function()? onComplete; Future<void> run() async { try { _completer.complete(await _closure()); } catch (e) { // ignore: avoid_catches_without_on_clauses, forwards to Future _completer.completeError(e); } finally { onComplete?.call(); } } }
flutter/packages/flutter_tools/lib/src/base/task_queue.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/base/task_queue.dart", "repo_id": "flutter", "token_count": 1089 }
795
// Copyright 2014 The Flutter Authors. 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/build.dart'; import '../../base/deferred_component.dart'; import '../../base/file_system.dart'; import '../../build_info.dart'; import '../../globals.dart' as globals show xcode; import '../../project.dart'; import '../build_system.dart'; import '../depfile.dart'; import '../exceptions.dart'; import 'assets.dart'; import 'common.dart'; import 'icon_tree_shaker.dart'; /// Prepares the asset bundle in the format expected by flutter.gradle. /// /// The vm_snapshot_data, isolate_snapshot_data, and kernel_blob.bin are /// expected to be in the root output directory. /// /// All assets and manifests are included from flutter_assets/**. abstract class AndroidAssetBundle extends Target { const AndroidAssetBundle(); @override List<Source> get inputs => const <Source>[ Source.pattern('{BUILD_DIR}/app.dill'), ...IconTreeShaker.inputs, ]; @override List<Source> get outputs => const <Source>[]; @override List<String> get depfiles => <String>[ 'flutter_assets.d', ]; @override Future<void> build(Environment environment) async { final String? buildModeEnvironment = environment.defines[kBuildMode]; if (buildModeEnvironment == null) { throw MissingDefineException(kBuildMode, name); } final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment); final Directory outputDirectory = environment.outputDir .childDirectory('flutter_assets') ..createSync(recursive: true); // Only copy the prebuilt runtimes and kernel blob in debug mode. if (buildMode == BuildMode.debug) { final String vmSnapshotData = environment.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug); final String isolateSnapshotData = environment.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug); environment.buildDir.childFile('app.dill') .copySync(outputDirectory.childFile('kernel_blob.bin').path); environment.fileSystem.file(vmSnapshotData) .copySync(outputDirectory.childFile('vm_snapshot_data').path); environment.fileSystem.file(isolateSnapshotData) .copySync(outputDirectory.childFile('isolate_snapshot_data').path); } final Depfile assetDepfile = await copyAssets( environment, outputDirectory, targetPlatform: TargetPlatform.android, buildMode: buildMode, flavor: environment.defines[kFlavor], ); environment.depFileService.writeToFile( assetDepfile, environment.buildDir.childFile('flutter_assets.d'), ); } @override List<Target> get dependencies => const <Target>[ KernelSnapshot(), ]; } /// An implementation of [AndroidAssetBundle] that includes dependencies on vm /// and isolate data. class DebugAndroidApplication extends AndroidAssetBundle { const DebugAndroidApplication(); @override String get name => 'debug_android_application'; @override List<Source> get inputs => <Source>[ ...super.inputs, const Source.artifact(Artifact.vmSnapshotData, mode: BuildMode.debug), const Source.artifact(Artifact.isolateSnapshotData, mode: BuildMode.debug), ]; @override List<Source> get outputs => <Source>[ ...super.outputs, const Source.pattern('{OUTPUT_DIR}/flutter_assets/vm_snapshot_data'), const Source.pattern('{OUTPUT_DIR}/flutter_assets/isolate_snapshot_data'), const Source.pattern('{OUTPUT_DIR}/flutter_assets/kernel_blob.bin'), ]; } /// An implementation of [AndroidAssetBundle] that only includes assets. class AotAndroidAssetBundle extends AndroidAssetBundle { const AotAndroidAssetBundle(); @override String get name => 'aot_android_asset_bundle'; } /// Build a profile android application's Dart artifacts. class ProfileAndroidApplication extends CopyFlutterAotBundle { const ProfileAndroidApplication(); @override String get name => 'profile_android_application'; @override List<Target> get dependencies => const <Target>[ AotElfProfile(TargetPlatform.android_arm), AotAndroidAssetBundle(), ]; } /// Build a release android application's Dart artifacts. class ReleaseAndroidApplication extends CopyFlutterAotBundle { const ReleaseAndroidApplication(); @override String get name => 'release_android_application'; @override List<Target> get dependencies => const <Target>[ AotElfRelease(TargetPlatform.android_arm), AotAndroidAssetBundle(), ]; } /// Generate an ELF binary from a dart kernel file in release mode. /// /// This rule implementation outputs the generated so to a unique location /// based on the Android ABI. This allows concurrent invocations of gen_snapshot /// to run simultaneously. /// /// The name of an instance of this rule would be 'android_aot_profile_android-x64' /// and is relied upon by flutter.gradle to match the correct rule. /// /// It will produce an 'app.so` in the build directory under a folder named with /// the matching Android ABI. class AndroidAot extends AotElfBase { /// Create an [AndroidAot] implementation for a given [targetPlatform] and [buildMode]. const AndroidAot(this.targetPlatform, this.buildMode); /// The name of the produced Android ABI. String get _androidAbiName { return getAndroidArchForName(getNameForTargetPlatform(targetPlatform)).archName; } @override String get name => 'android_aot_${buildMode.cliName}_' '${getNameForTargetPlatform(targetPlatform)}'; /// The specific Android ABI we are building for. final TargetPlatform targetPlatform; /// The selected build mode. /// /// Build mode is restricted to [BuildMode.profile] or [BuildMode.release] for AOT builds. final BuildMode buildMode; @override List<Source> get inputs => <Source>[ const Source.pattern('{FLUTTER_ROOT}/packages/flutter_tools/lib/src/build_system/targets/android.dart'), const Source.pattern('{BUILD_DIR}/app.dill'), const Source.artifact(Artifact.engineDartBinary), const Source.artifact(Artifact.skyEnginePath), Source.artifact(Artifact.genSnapshot, mode: buildMode, platform: targetPlatform, ), ]; @override List<Source> get outputs => <Source>[ Source.pattern('{BUILD_DIR}/$_androidAbiName/app.so'), ]; @override List<String> get depfiles => <String>[ 'flutter_$name.d', ]; @override List<Target> get dependencies => const <Target>[ KernelSnapshot(), ]; @override Future<void> build(Environment environment) async { final AOTSnapshotter snapshotter = AOTSnapshotter( fileSystem: environment.fileSystem, logger: environment.logger, xcode: globals.xcode!, processManager: environment.processManager, artifacts: environment.artifacts, ); final Directory output = environment.buildDir.childDirectory(_androidAbiName); final String? buildModeEnvironment = environment.defines[kBuildMode]; if (buildModeEnvironment == null) { throw MissingDefineException(kBuildMode, 'aot_elf'); } if (!output.existsSync()) { output.createSync(recursive: true); } final List<String> extraGenSnapshotOptions = decodeCommaSeparated(environment.defines, kExtraGenSnapshotOptions); final List<File> outputs = <File>[]; // outputs for the depfile final String manifestPath = '${output.path}${environment.platform.pathSeparator}manifest.json'; if (environment.defines[kDeferredComponents] == 'true') { extraGenSnapshotOptions.add('--loading_unit_manifest=$manifestPath'); outputs.add(environment.fileSystem.file(manifestPath)); } final BuildMode buildMode = BuildMode.fromCliName(buildModeEnvironment); final bool dartObfuscation = environment.defines[kDartObfuscation] == 'true'; final String? codeSizeDirectory = environment.defines[kCodeSizeDirectory]; if (codeSizeDirectory != null) { final File codeSizeFile = environment.fileSystem .directory(codeSizeDirectory) .childFile('snapshot.$_androidAbiName.json'); final File precompilerTraceFile = environment.fileSystem .directory(codeSizeDirectory) .childFile('trace.$_androidAbiName.json'); extraGenSnapshotOptions.add('--write-v8-snapshot-profile-to=${codeSizeFile.path}'); extraGenSnapshotOptions.add('--trace-precompiler-to=${precompilerTraceFile.path}'); } final String? splitDebugInfo = environment.defines[kSplitDebugInfo]; final int snapshotExitCode = await snapshotter.build( platform: targetPlatform, buildMode: buildMode, mainPath: environment.buildDir.childFile('app.dill').path, outputPath: output.path, extraGenSnapshotOptions: extraGenSnapshotOptions, splitDebugInfo: splitDebugInfo, dartObfuscation: dartObfuscation, ); if (snapshotExitCode != 0) { throw Exception('AOT snapshotter exited with code $snapshotExitCode'); } if (environment.defines[kDeferredComponents] == 'true') { // Parse the manifest for .so paths final List<LoadingUnit> loadingUnits = LoadingUnit.parseLoadingUnitManifest(environment.fileSystem.file(manifestPath), environment.logger); for (final LoadingUnit unit in loadingUnits) { outputs.add(environment.fileSystem.file(unit.path)); } } environment.depFileService.writeToFile( Depfile(<File>[], outputs), environment.buildDir.childFile('flutter_$name.d'), writeEmpty: true, ); } } // AndroidAot instances used by the bundle rules below. const AndroidAot androidArmProfile = AndroidAot(TargetPlatform.android_arm, BuildMode.profile); const AndroidAot androidArm64Profile = AndroidAot(TargetPlatform.android_arm64, BuildMode.profile); const AndroidAot androidx64Profile = AndroidAot(TargetPlatform.android_x64, BuildMode.profile); const AndroidAot androidArmRelease = AndroidAot(TargetPlatform.android_arm, BuildMode.release); const AndroidAot androidArm64Release = AndroidAot(TargetPlatform.android_arm64, BuildMode.release); const AndroidAot androidx64Release = AndroidAot(TargetPlatform.android_x64, BuildMode.release); /// A rule paired with [AndroidAot] that copies the produced so file and manifest.json (if present) into the output directory. class AndroidAotBundle extends Target { /// Create an [AndroidAotBundle] implementation for a given [targetPlatform] and [buildMode]. const AndroidAotBundle(this.dependency); /// The [AndroidAot] instance this bundle rule depends on. final AndroidAot dependency; /// The name of the produced Android ABI. String get _androidAbiName { return getAndroidArchForName(getNameForTargetPlatform(dependency.targetPlatform)).archName; } @override String get name => 'android_aot_bundle_${dependency.buildMode.cliName}_' '${getNameForTargetPlatform(dependency.targetPlatform)}'; TargetPlatform get targetPlatform => dependency.targetPlatform; /// The selected build mode. /// /// This is restricted to [BuildMode.profile] or [BuildMode.release]. BuildMode get buildMode => dependency.buildMode; @override List<Source> get inputs => <Source>[ Source.pattern('{BUILD_DIR}/$_androidAbiName/app.so'), ]; // flutter.gradle has been updated to correctly consume it. @override List<Source> get outputs => <Source>[ Source.pattern('{OUTPUT_DIR}/$_androidAbiName/app.so'), ]; @override List<String> get depfiles => <String>[ 'flutter_$name.d', ]; @override List<Target> get dependencies => <Target>[ dependency, const AotAndroidAssetBundle(), ]; @override Future<void> build(Environment environment) async { final Directory buildDir = environment.buildDir.childDirectory(_androidAbiName); final Directory outputDirectory = environment.outputDir .childDirectory(_androidAbiName); if (!outputDirectory.existsSync()) { outputDirectory.createSync(recursive: true); } final File outputLibFile = buildDir.childFile('app.so'); outputLibFile.copySync(outputDirectory.childFile('app.so').path); final List<File> inputs = <File>[]; final List<File> outputs = <File>[]; final File manifestFile = buildDir.childFile('manifest.json'); if (manifestFile.existsSync()) { final File destinationFile = outputDirectory.childFile('manifest.json'); manifestFile.copySync(destinationFile.path); inputs.add(manifestFile); outputs.add(destinationFile); } environment.depFileService.writeToFile( Depfile(inputs, outputs), environment.buildDir.childFile('flutter_$name.d'), writeEmpty: true, ); } } // AndroidBundleAot instances. const AndroidAotBundle androidArmProfileBundle = AndroidAotBundle(androidArmProfile); const AndroidAotBundle androidArm64ProfileBundle = AndroidAotBundle(androidArm64Profile); const AndroidAotBundle androidx64ProfileBundle = AndroidAotBundle(androidx64Profile); const AndroidAotBundle androidArmReleaseBundle = AndroidAotBundle(androidArmRelease); const AndroidAotBundle androidArm64ReleaseBundle = AndroidAotBundle(androidArm64Release); const AndroidAotBundle androidx64ReleaseBundle = AndroidAotBundle(androidx64Release); // Rule that copies split aot library files to the intermediate dirs of each deferred component. class AndroidAotDeferredComponentsBundle extends Target { /// Create an [AndroidAotDeferredComponentsBundle] implementation for a given [targetPlatform] and [buildMode]. /// /// If [components] is not provided, it will be read from the pubspec.yaml manifest. AndroidAotDeferredComponentsBundle(this.dependency, {List<DeferredComponent>? components}) : _components = components; /// The [AndroidAotBundle] instance this bundle rule depends on. final AndroidAotBundle dependency; List<DeferredComponent>? _components; /// The name of the produced Android ABI. String get _androidAbiName { return getAndroidArchForName(getNameForTargetPlatform(dependency.targetPlatform)).archName; } @override String get name => 'android_aot_deferred_components_bundle_${dependency.buildMode.cliName}_' '${getNameForTargetPlatform(dependency.targetPlatform)}'; TargetPlatform get targetPlatform => dependency.targetPlatform; @override List<Source> get inputs => <Source>[ // Tracking app.so is enough to invalidate the dynamically named // loading unit libs as changes to loading units guarantee // changes to app.so as well. This task does not actually // copy app.so. Source.pattern('{OUTPUT_DIR}/$_androidAbiName/app.so'), const Source.pattern('{PROJECT_DIR}/pubspec.yaml'), ]; @override List<Source> get outputs => const <Source>[]; @override List<String> get depfiles => <String>[ 'flutter_$name.d', ]; @override List<Target> get dependencies => <Target>[ dependency, ]; @override Future<void> build(Environment environment) async { _components ??= FlutterProject.current().manifest.deferredComponents ?? <DeferredComponent>[]; final List<String> abis = <String>[_androidAbiName]; final List<LoadingUnit> generatedLoadingUnits = LoadingUnit.parseGeneratedLoadingUnits(environment.outputDir, environment.logger, abis: abis); for (final DeferredComponent component in _components!) { component.assignLoadingUnits(generatedLoadingUnits); } final Depfile libDepfile = copyDeferredComponentSoFiles(environment, _components!, generatedLoadingUnits, environment.projectDir.childDirectory('build'), abis, dependency.buildMode); final File manifestFile = environment.outputDir.childDirectory(_androidAbiName).childFile('manifest.json'); if (manifestFile.existsSync()) { libDepfile.inputs.add(manifestFile); } environment.depFileService.writeToFile( libDepfile, environment.buildDir.childFile('flutter_$name.d'), writeEmpty: true, ); } } Target androidArmProfileDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArmProfileBundle); Target androidArm64ProfileDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArm64ProfileBundle); Target androidx64ProfileDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidx64ProfileBundle); Target androidArmReleaseDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArmReleaseBundle); Target androidArm64ReleaseDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidArm64ReleaseBundle); Target androidx64ReleaseDeferredComponentsBundle = AndroidAotDeferredComponentsBundle(androidx64ReleaseBundle); /// A set of all target names that build deferred component apps. Set<String> deferredComponentsTargets = <String>{ androidArmProfileDeferredComponentsBundle.name, androidArm64ProfileDeferredComponentsBundle.name, androidx64ProfileDeferredComponentsBundle.name, androidArmReleaseDeferredComponentsBundle.name, androidArm64ReleaseDeferredComponentsBundle.name, androidx64ReleaseDeferredComponentsBundle.name, }; /// Utility method to copy and rename the required .so shared libs from the build output /// to the correct component intermediate directory. /// /// The [DeferredComponent]s passed to this method must have had loading units assigned. /// Assigned components are components that have determined which loading units contains /// the dart libraries it has via the DeferredComponent.assignLoadingUnits method. Depfile copyDeferredComponentSoFiles( Environment env, List<DeferredComponent> components, List<LoadingUnit> loadingUnits, Directory buildDir, // generally `<projectDir>/build` List<String> abis, BuildMode buildMode, ) { final List<File> inputs = <File>[]; final List<File> outputs = <File>[]; final Set<int> usedLoadingUnits = <int>{}; // Copy all .so files for loading units that are paired with a deferred component. for (final String abi in abis) { for (final DeferredComponent component in components) { final Set<LoadingUnit>? loadingUnits = component.loadingUnits; if (loadingUnits == null || !component.assigned) { env.logger.printError('Deferred component require loading units to be assigned.'); return Depfile(inputs, outputs); } for (final LoadingUnit unit in loadingUnits) { // ensure the abi for the unit is one of the abis we build for. final List<String>? splitPath = unit.path?.split(env.fileSystem.path.separator); if (splitPath == null || splitPath[splitPath.length - 2] != abi) { continue; } usedLoadingUnits.add(unit.id); // the deferred_libs directory is added as a source set for the component. final File destination = buildDir .childDirectory(component.name) .childDirectory('intermediates') .childDirectory('flutter') .childDirectory(buildMode.cliName) .childDirectory('deferred_libs') .childDirectory(abi) .childFile('libapp.so-${unit.id}.part.so'); if (!destination.existsSync()) { destination.createSync(recursive: true); } final File source = env.fileSystem.file(unit.path); source.copySync(destination.path); inputs.add(source); outputs.add(destination); } } } // Copy unused loading units, which are included in the base module. for (final String abi in abis) { for (final LoadingUnit unit in loadingUnits) { if (usedLoadingUnits.contains(unit.id)) { continue; } // ensure the abi for the unit is one of the abis we build for. final List<String>? splitPath = unit.path?.split(env.fileSystem.path.separator); if (splitPath == null || splitPath[splitPath.length - 2] != abi) { continue; } final File destination = env.outputDir .childDirectory(abi) // Omit 'lib' prefix here as it is added by the gradle task that adds 'lib' to 'app.so'. .childFile('app.so-${unit.id}.part.so'); if (!destination.existsSync()) { destination.createSync(recursive: true); } final File source = env.fileSystem.file(unit.path); source.copySync(destination.path); inputs.add(source); outputs.add(destination); } } return Depfile(inputs, outputs); }
flutter/packages/flutter_tools/lib/src/build_system/targets/android.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/targets/android.dart", "repo_id": "flutter", "token_count": 6613 }
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 '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 '../../build_info.dart'; import '../../convert.dart'; import '../../devfs.dart'; import '../build_system.dart'; /// A wrapper around [ShaderCompiler] to support hot reload of shader sources. class DevelopmentShaderCompiler { DevelopmentShaderCompiler({ required ShaderCompiler shaderCompiler, required FileSystem fileSystem, @visibleForTesting math.Random? random, }) : _shaderCompiler = shaderCompiler, _fileSystem = fileSystem, _random = random ?? math.Random(); final ShaderCompiler _shaderCompiler; final FileSystem _fileSystem; final Pool _compilationPool = Pool(4); final math.Random _random; late TargetPlatform _targetPlatform; bool _debugConfigured = false; /// Configure the output format of the shader compiler for a particular /// flutter device. void configureCompiler(TargetPlatform? platform) { if (platform == null) { return; } _targetPlatform = platform; _debugConfigured = true; } /// Recompile the input shader and return a devfs content that should be synced /// to the attached device in its place. Future<DevFSContent?> recompileShader(DevFSContent inputShader) async { assert(_debugConfigured); 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 (inputShader is DevFSFileContent) { inputFile = inputShader.file as File; } else { inputFile = _fileSystem.systemTempDirectory.childFile('${_random.nextDouble()}.temp'); inputFile.writeAsBytesSync(await inputShader.contentsAsBytes()); cleanupInput = true; } final bool success = await _shaderCompiler.compileShader( input: inputFile, outputPath: output.path, targetPlatform: _targetPlatform, 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 shader compiler /// impellerc. class ShaderCompiler { ShaderCompiler({ 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; List<String> _shaderTargetsFromTargetPlatform(TargetPlatform targetPlatform) { switch (targetPlatform) { case TargetPlatform.android_x64: case TargetPlatform.android_x86: case TargetPlatform.android_arm: case TargetPlatform.android_arm64: case TargetPlatform.android: case TargetPlatform.linux_x64: case TargetPlatform.linux_arm64: case TargetPlatform.windows_x64: case TargetPlatform.windows_arm64: return <String>['--sksl', '--runtime-stage-gles', '--runtime-stage-vulkan']; case TargetPlatform.ios: case TargetPlatform.darwin: return <String>['--sksl', '--runtime-stage-metal']; case TargetPlatform.fuchsia_arm64: case TargetPlatform.fuchsia_x64: case TargetPlatform.tester: return <String>['--sksl', '--runtime-stage-vulkan']; case TargetPlatform.web_javascript: return <String>['--sksl']; } } /// 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/shader_compiler.dart'), Source.hostArtifact(HostArtifact.impellerc), ]; /// Calls impellerc, which transforms the [input] glsl shader into a /// platform specific shader at [outputPath]. /// /// All parameters are required. /// /// If the shader compiler subprocess fails, it will print the stdout and /// stderr to the log and throw a [ShaderCompilerException]. Otherwise, it /// will return true. Future<bool> compileShader({ required File input, required String outputPath, required TargetPlatform targetPlatform, bool fatal = true, }) async { final File impellerc = _fs.file( _artifacts.getHostArtifact(HostArtifact.impellerc), ); if (!impellerc.existsSync()) { throw ShaderCompilerException._( 'The impellerc utility is missing at "${impellerc.path}". ' 'Run "flutter doctor".', ); } final String shaderLibPath = _fs.path.join(impellerc.parent.absolute.path, 'shader_lib'); final List<String> cmd = <String>[ impellerc.path, ..._shaderTargetsFromTargetPlatform(targetPlatform), '--iplr', if (targetPlatform == TargetPlatform.web_javascript) '--json', '--sl=$outputPath', '--spirv=$outputPath.spirv', '--input=${input.path}', '--input-type=frag', '--include=${input.parent.path}', '--include=$shaderLibPath', ]; _logger.printTrace('shaderc command: $cmd'); final Process impellercProcess = await _processManager.start(cmd); final int code = await impellercProcess.exitCode; if (code != 0) { final String stdout = await utf8.decodeStream(impellercProcess.stdout); final String stderr = await utf8.decodeStream(impellercProcess.stderr); _logger.printTrace(stdout); _logger.printError(stderr); if (fatal) { throw ShaderCompilerException._( 'Shader compilation of "${input.path}" to "$outputPath" ' 'failed with exit code $code.\n' 'impellerc stdout:\n$stdout\n' 'impellerc stderr:\n$stderr', ); } return false; } ErrorHandlingFileSystem.deleteIfExists(_fs.file('$outputPath.spirv')); return true; } } class ShaderCompilerException implements Exception { ShaderCompilerException._(this.message); final String message; @override String toString() => 'ShaderCompilerException: $message\n\n'; }
flutter/packages/flutter_tools/lib/src/build_system/tools/shader_compiler.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/build_system/tools/shader_compiler.dart", "repo_id": "flutter", "token_count": 2512 }
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. import 'package:unified_analytics/unified_analytics.dart'; import '../android/android_builder.dart'; import '../android/build_validation.dart'; import '../android/deferred_components_prebuild_validator.dart'; import '../android/gradle_utils.dart'; import '../base/deferred_component.dart'; import '../base/file_system.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 BuildAppBundleCommand extends BuildSubCommand { BuildAppBundleCommand({ 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); addBuildPerformanceFile(hide: !verboseHelp); usesTrackWidgetCreation(verboseHelp: verboseHelp); addNullSafetyModeOptions(hide: !verboseHelp); addEnableExperimentation(hide: !verboseHelp); usesAnalyzeSizeFlag(); addAndroidSpecificBuildOptions(hide: !verboseHelp); addIgnoreDeprecationOption(); argParser.addMultiOption('target-platform', defaultsTo: <String>['android-arm', 'android-arm64', 'android-x64'], allowed: <String>['android-arm', 'android-arm64', 'android-x64'], help: 'The target platform for which the app is compiled.', ); argParser.addFlag('deferred-components', defaultsTo: true, help: 'Setting to false disables building with deferred components. All deferred code ' 'will be compiled into the base app, and assets act as if they were defined under' ' the regular assets section in pubspec.yaml. This flag has no effect on ' 'non-deferred components apps.', ); argParser.addFlag('validate-deferred-components', defaultsTo: true, help: 'When enabled, deferred component apps will fail to build if setup problems are ' 'detected that would prevent deferred components from functioning properly. The ' 'tooling also provides guidance on how to set up the project files to pass this ' 'verification. Disabling setup verification will always attempt to fully build ' 'the app regardless of any problems detected. Builds that are part of CI testing ' 'and advanced users with custom deferred components implementations should disable ' 'setup verification. This flag has no effect on non-deferred components apps.', ); } @override final String name = 'appbundle'; @override List<String> get aliases => const <String>['aab']; @override DeprecationBehavior get deprecationBehavior => boolArg('ignore-deprecation') ? DeprecationBehavior.ignore : DeprecationBehavior.exit; @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{ DevelopmentArtifact.androidGenSnapshot, }; @override final String description = 'Build an Android App Bundle file from your app.\n\n' "This command can build debug and release versions of an app bundle for 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. \n app bundle improves your app size'; @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( commandBuildAppBundleTargetPlatform: stringsArg('target-platform').join(','), commandBuildAppBundleBuildMode: buildMode, ); } @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, buildAppBundleTargetPlatform: stringsArg('target-platform').join(','), buildAppBundleBuildMode: buildMode, ); } @override Future<FlutterCommandResult> runCommand() async { if (globals.androidSdk == null) { exitWithNoSdkMessage(); } final AndroidBuildInfo androidBuildInfo = AndroidBuildInfo(await getBuildInfo(), targetArchs: stringsArg('target-platform').map<AndroidArch>(getAndroidArchForName), ); // Do all setup verification that doesn't involve loading units. Checks that // require generated loading units are done after gen_snapshot in assemble. final List<DeferredComponent>? deferredComponents = FlutterProject.current().manifest.deferredComponents; if (deferredComponents != null && boolArg('deferred-components') && boolArg('validate-deferred-components') && !boolArg('debug')) { final DeferredComponentsPrebuildValidator validator = DeferredComponentsPrebuildValidator( FlutterProject.current().directory, globals.logger, globals.platform, title: 'Deferred components prebuild validation', ); validator.clearOutputDir(); await validator.checkAndroidDynamicFeature(deferredComponents); validator.checkAndroidResourcesStrings(deferredComponents); validator.handleResults(); // Delete intermediates libs dir for components to resolve mismatching // abis supported by base and dynamic feature modules. for (final DeferredComponent component in deferredComponents) { final Directory deferredLibsIntermediate = FlutterProject.current().directory .childDirectory('build') .childDirectory(component.name) .childDirectory('intermediates') .childDirectory('flutter') .childDirectory(androidBuildInfo.buildInfo.mode.cliName) .childDirectory('deferred_libs'); if (deferredLibsIntermediate.existsSync()) { deferredLibsIntermediate.deleteSync(recursive: true); } } } validateBuild(androidBuildInfo); displayNullSafetyMode(androidBuildInfo.buildInfo); globals.terminal.usesTerminalUi = true; await androidBuilder?.buildAab( project: FlutterProject.current(), target: targetFile, androidBuildInfo: androidBuildInfo, validateDeferredComponents: boolArg('validate-deferred-components'), deferredComponentsEnabled: boolArg('deferred-components') && !boolArg('debug'), ); return FlutterCommandResult.success(); } }
flutter/packages/flutter_tools/lib/src/commands/build_appbundle.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/build_appbundle.dart", "repo_id": "flutter", "token_count": 2508 }
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:async/async.dart'; import 'package:meta/meta.dart'; import 'package:uuid/uuid.dart'; import '../android/android_workflow.dart'; import '../application_package.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/terminal.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../convert.dart'; import '../daemon.dart'; import '../device.dart'; import '../device_port_forwarder.dart'; import '../emulator.dart'; import '../features.dart'; import '../globals.dart' as globals; import '../project.dart'; import '../proxied_devices/debounce_data_stream.dart'; import '../proxied_devices/file_transfer.dart'; import '../resident_runner.dart'; import '../run_cold.dart'; import '../run_hot.dart'; import '../runner/flutter_command.dart'; import '../vmservice.dart'; import '../web/web_runner.dart'; const String protocolVersion = '0.6.1'; /// A server process command. This command will start up a long-lived server. /// It reads JSON-RPC based commands from stdin, executes them, and returns /// JSON-RPC based responses and events to stdout. /// /// It can be shutdown with a `daemon.shutdown` command (or by killing the /// process). class DaemonCommand extends FlutterCommand { DaemonCommand({ this.hidden = false }) { argParser.addOption( 'listen-on-tcp-port', help: 'If specified, the daemon will be listening for commands on the specified port instead of stdio.', valueHelp: 'port', ); } @override final String name = 'daemon'; @override final String description = 'Run a persistent, JSON-RPC based server to communicate with devices.'; @override final String category = FlutterCommandCategory.tools; @override final bool hidden; @override Future<FlutterCommandResult> runCommand() async { if (argResults!['listen-on-tcp-port'] != null) { int? port; try { port = int.parse(stringArg('listen-on-tcp-port')!); } on FormatException catch (error) { throwToolExit('Invalid port for `--listen-on-tcp-port`: $error'); } await DaemonServer( port: port, logger: StdoutLogger( terminal: globals.terminal, stdio: globals.stdio, outputPreferences: globals.outputPreferences, ), notifyingLogger: asLogger<NotifyingLogger>(globals.logger), ).run(); return FlutterCommandResult.success(); } globals.printStatus('Starting device daemon...'); final Daemon daemon = Daemon( DaemonConnection( daemonStreams: DaemonStreams.fromStdio(globals.stdio, logger: globals.logger), logger: globals.logger, ), notifyingLogger: asLogger<NotifyingLogger>(globals.logger), ); final int code = await daemon.onExit; if (code != 0) { throwToolExit('Daemon exited with non-zero exit code: $code', exitCode: code); } return FlutterCommandResult.success(); } } @visibleForTesting class DaemonServer { DaemonServer({ this.port, required this.logger, this.notifyingLogger, @visibleForTesting Future<ServerSocket> Function(InternetAddress address, int port) bind = ServerSocket.bind, }) : _bind = bind; final int? port; /// Stdout logger used to print general server-related errors. final Logger logger; // Logger that sends the message to the other end of daemon connection. final NotifyingLogger? notifyingLogger; final Future<ServerSocket> Function(InternetAddress address, int port) _bind; Future<void> run() async { ServerSocket? serverSocket; try { serverSocket = await _bind(InternetAddress.loopbackIPv4, port!); } on SocketException { logger.printTrace('Bind on $port failed with IPv4, retrying on IPv6'); } // If binding on IPv4 failed, try binding on IPv6. // Omit try catch here, let the failure fallthrough. serverSocket ??= await _bind(InternetAddress.loopbackIPv6, port!); logger.printStatus('Daemon server listening on ${serverSocket.port}'); final StreamSubscription<Socket> subscription = serverSocket.listen( (Socket socket) async { // We have to listen to socket.done. Otherwise when the connection is // reset, we will receive an uncatchable exception. // https://github.com/dart-lang/sdk/issues/25518 final Future<void> socketDone = socket.done.then<void>( (_) {}, onError: (Object error, StackTrace stackTrace) { logger.printError('Socket error: $error'); logger.printTrace('$stackTrace'); }); final Daemon daemon = Daemon( DaemonConnection( daemonStreams: DaemonStreams.fromSocket(socket, logger: logger), logger: logger, ), notifyingLogger: notifyingLogger, ); await daemon.onExit; await socketDone; }, ); // Wait indefinitely until the server closes. await subscription.asFuture<void>(); await subscription.cancel(); } } typedef CommandHandler = Future<Object?>? Function(Map<String, Object?> args); typedef CommandHandlerWithBinary = Future<Object?> Function(Map<String, Object?> args, Stream<List<int>>? binary); class Daemon { Daemon( this.connection, { this.notifyingLogger, this.logToStdout = false, FileTransfer fileTransfer = const FileTransfer(), }) { // Set up domains. registerDomain(daemonDomain = DaemonDomain(this)); registerDomain(appDomain = AppDomain(this)); registerDomain(deviceDomain = DeviceDomain(this)); registerDomain(emulatorDomain = EmulatorDomain(this)); registerDomain(devToolsDomain = DevToolsDomain(this)); registerDomain(proxyDomain = ProxyDomain(this, fileTransfer: fileTransfer)); // Start listening. _commandSubscription = connection.incomingCommands.listen( _handleRequest, onDone: () { shutdown(); if (!_onExitCompleter.isCompleted) { _onExitCompleter.complete(0); } }, ); } final DaemonConnection connection; late DaemonDomain daemonDomain; late AppDomain appDomain; late DeviceDomain deviceDomain; EmulatorDomain? emulatorDomain; DevToolsDomain? devToolsDomain; late ProxyDomain proxyDomain; StreamSubscription<DaemonMessage>? _commandSubscription; final NotifyingLogger? notifyingLogger; final bool logToStdout; final Completer<int> _onExitCompleter = Completer<int>(); final Map<String, Domain> _domainMap = <String, Domain>{}; @visibleForTesting void registerDomain(Domain domain) { _domainMap[domain.name] = domain; } Future<int> get onExit => _onExitCompleter.future; void _handleRequest(DaemonMessage request) { // {id, method, params} // [id] is an opaque type to us. final Object? id = request.data['id']; if (id == null) { globals.stdio.stderrWrite('no id for request: $request\n'); return; } try { final String method = request.data['method']! as String; if (!method.contains('.')) { throw DaemonException('method not understood: $method'); } final String prefix = method.substring(0, method.indexOf('.')); final String name = method.substring(method.indexOf('.') + 1); if (_domainMap[prefix] == null) { throw DaemonException('no domain for method: $method'); } _domainMap[prefix]!.handleCommand(name, id, castStringKeyedMap(request.data['params']) ?? const <String, Object?>{}, request.binary); } on Exception catch (error, trace) { connection.sendErrorResponse(id, _toJsonable(error), trace); } } Future<void> shutdown({ Object? error }) async { await devToolsDomain?.dispose(); await _commandSubscription?.cancel(); await connection.dispose(); for (final Domain domain in _domainMap.values) { await domain.dispose(); } if (!_onExitCompleter.isCompleted) { if (error == null) { _onExitCompleter.complete(0); } else { _onExitCompleter.completeError(error); } } } } abstract class Domain { Domain(this.daemon, this.name); final Daemon daemon; final String name; final Map<String, CommandHandler> _handlers = <String, CommandHandler>{}; final Map<String, CommandHandlerWithBinary> _handlersWithBinary = <String, CommandHandlerWithBinary>{}; void registerHandler(String name, CommandHandler handler) { assert(!_handlers.containsKey(name)); assert(!_handlersWithBinary.containsKey(name)); _handlers[name] = handler; } void registerHandlerWithBinary(String name, CommandHandlerWithBinary handler) { assert(!_handlers.containsKey(name)); assert(!_handlersWithBinary.containsKey(name)); _handlersWithBinary[name] = handler; } @override String toString() => name; void handleCommand(String command, Object id, Map<String, Object?> args, Stream<List<int>>? binary) { Future<Object?>.sync(() { if (_handlers.containsKey(command)) { return _handlers[command]!(args); } else if (_handlersWithBinary.containsKey(command)) { return _handlersWithBinary[command]!(args, binary); } throw DaemonException('command not understood: $name.$command'); }).then<Object?>((Object? result) { daemon.connection.sendResponse(id, _toJsonable(result)); return null; }, onError: (Object error, StackTrace stackTrace) { daemon.connection.sendErrorResponse(id, _toJsonable(error), stackTrace); return null; }); } void sendEvent(String name, [ Object? args, List<int>? binary ]) { daemon.connection.sendEvent(name, _toJsonable(args), binary); } String? _getStringArg(Map<String, Object?> args, String name, { bool required = false }) { if (required && !args.containsKey(name)) { throw DaemonException('$name is required'); } final Object? val = args[name]; if (val != null && val is! String) { throw DaemonException('$name is not a String'); } return val as String?; } bool? _getBoolArg(Map<String, Object?> args, String name, { bool required = false }) { if (required && !args.containsKey(name)) { throw DaemonException('$name is required'); } final Object? val = args[name]; if (val != null && val is! bool) { throw DaemonException('$name is not a bool'); } return val as bool?; } int? _getIntArg(Map<String, Object?> args, String name, { bool required = false }) { if (required && !args.containsKey(name)) { throw DaemonException('$name is required'); } final Object? val = args[name]; if (val != null && val is! int) { throw DaemonException('$name is not an int'); } return val as int?; } Future<void> dispose() async { } } /// This domain responds to methods like [version] and [shutdown]. /// /// This domain fires the `daemon.logMessage` event. class DaemonDomain extends Domain { DaemonDomain(Daemon daemon) : super(daemon, 'daemon') { registerHandler('version', version); registerHandler('shutdown', shutdown); registerHandler('getSupportedPlatforms', getSupportedPlatforms); registerHandler('setNotifyVerbose', setNotifyVerbose); sendEvent( 'daemon.connected', <String, Object?>{ 'version': protocolVersion, 'pid': pid, }, ); _subscription = daemon.notifyingLogger!.onMessage.listen((LogMessage message) { if (daemon.logToStdout) { if (message.level == 'status' || message.level == 'trace') { // We use `print()` here instead of `stdout.writeln()` in order to // capture the print output for testing. // ignore: avoid_print print(message.message); } else if (message.level == 'error' || message.level == 'warning') { globals.stdio.stderrWrite('${message.message}\n'); if (message.stackTrace != null) { globals.stdio.stderrWrite( '${message.stackTrace.toString().trimRight()}\n', ); } } } else { if (message.stackTrace != null) { sendEvent('daemon.logMessage', <String, Object?>{ 'level': message.level, 'message': message.message, 'stackTrace': message.stackTrace.toString(), }); } else { sendEvent('daemon.logMessage', <String, Object?>{ 'level': message.level, 'message': message.message, }); } } }); } StreamSubscription<LogMessage>? _subscription; Future<String> version(Map<String, Object?> args) { return Future<String>.value(protocolVersion); } /// Sends a request back to the client asking it to expose/tunnel a URL. /// /// This method should only be called if the client opted-in with the /// --web-allow-expose-url switch. The client may return the same URL back if /// tunnelling is not required for a given URL. Future<String> exposeUrl(String url) async { final Object? res = await daemon.connection.sendRequest('app.exposeUrl', <String, String>{'url': url}); if (res is Map<String, Object?> && res['url'] is String) { return res['url']! as String; } else { globals.printError('Invalid response to exposeUrl - params should include a String url field'); return url; } } Future<void> shutdown(Map<String, Object?> args) { Timer.run(daemon.shutdown); return Future<void>.value(); } @override Future<void> dispose() async { await _subscription?.cancel(); } /// Enumerates the platforms supported by the provided project. /// /// This does not filter based on the current workflow restrictions, such /// as whether command line tools are installed or whether the host platform /// is correct. Future<Map<String, Object>> getSupportedPlatforms(Map<String, Object?> args) async { final String? projectRoot = _getStringArg(args, 'projectRoot', required: true); final List<String> platformTypes = <String>[]; final Map<String, Object> platformTypesMap = <String, Object>{}; try { final FlutterProject flutterProject = FlutterProject.fromDirectory(globals.fs.directory(projectRoot)); final Set<SupportedPlatform> supportedPlatforms = flutterProject.getSupportedPlatforms().toSet(); void handlePlatformType( PlatformType platform, ) { final List<Map<String, Object>> reasons = <Map<String, Object>>[]; switch (platform) { case PlatformType.linux: if (!featureFlags.isLinuxEnabled) { reasons.add(<String, Object>{ 'reasonText': 'the Linux feature is not enabled', 'fixText': 'Run "flutter config --enable-linux-desktop"', 'fixCode': _ReasonCode.config.name, }); } if (!supportedPlatforms.contains(SupportedPlatform.linux)) { reasons.add(<String, Object>{ 'reasonText': 'the Linux platform is not enabled for this project', 'fixText': 'Run "flutter create --platforms=linux ." in your application directory', 'fixCode': _ReasonCode.create.name, }); } case PlatformType.macos: if (!featureFlags.isMacOSEnabled) { reasons.add(<String, Object>{ 'reasonText': 'the macOS feature is not enabled', 'fixText': 'Run "flutter config --enable-macos-desktop"', 'fixCode': _ReasonCode.config.name, }); } if (!supportedPlatforms.contains(SupportedPlatform.macos)) { reasons.add(<String, Object>{ 'reasonText': 'the macOS platform is not enabled for this project', 'fixText': 'Run "flutter create --platforms=macos ." in your application directory', 'fixCode': _ReasonCode.create.name, }); } case PlatformType.windows: if (!featureFlags.isWindowsEnabled) { reasons.add(<String, Object>{ 'reasonText': 'the Windows feature is not enabled', 'fixText': 'Run "flutter config --enable-windows-desktop"', 'fixCode': _ReasonCode.config.name, }); } if (!supportedPlatforms.contains(SupportedPlatform.windows)) { reasons.add(<String, Object>{ 'reasonText': 'the Windows platform is not enabled for this project', 'fixText': 'Run "flutter create --platforms=windows ." in your application directory', 'fixCode': _ReasonCode.create.name, }); } case PlatformType.ios: if (!featureFlags.isIOSEnabled) { reasons.add(<String, Object>{ 'reasonText': 'the iOS feature is not enabled', 'fixText': 'Run "flutter config --enable-ios"', 'fixCode': _ReasonCode.config.name, }); } if (!supportedPlatforms.contains(SupportedPlatform.ios)) { reasons.add(<String, Object>{ 'reasonText': 'the iOS platform is not enabled for this project', 'fixText': 'Run "flutter create --platforms=ios ." in your application directory', 'fixCode': _ReasonCode.create.name, }); } case PlatformType.android: if (!featureFlags.isAndroidEnabled) { reasons.add(<String, Object>{ 'reasonText': 'the Android feature is not enabled', 'fixText': 'Run "flutter config --enable-android"', 'fixCode': _ReasonCode.config.name, }); } if (!supportedPlatforms.contains(SupportedPlatform.android)) { reasons.add(<String, Object>{ 'reasonText': 'the Android platform is not enabled for this project', 'fixText': 'Run "flutter create --platforms=android ." in your application directory', 'fixCode': _ReasonCode.create.name, }); } case PlatformType.web: if (!featureFlags.isWebEnabled) { reasons.add(<String, Object>{ 'reasonText': 'the Web feature is not enabled', 'fixText': 'Run "flutter config --enable-web"', 'fixCode': _ReasonCode.config.name, }); } if (!supportedPlatforms.contains(SupportedPlatform.web)) { reasons.add(<String, Object>{ 'reasonText': 'the Web platform is not enabled for this project', 'fixText': 'Run "flutter create --platforms=web ." in your application directory', 'fixCode': _ReasonCode.create.name, }); } case PlatformType.fuchsia: if (!featureFlags.isFuchsiaEnabled) { reasons.add(<String, Object>{ 'reasonText': 'the Fuchsia feature is not enabled', 'fixText': 'Run "flutter config --enable-fuchsia"', 'fixCode': _ReasonCode.config.name, }); } if (!supportedPlatforms.contains(SupportedPlatform.fuchsia)) { reasons.add(<String, Object>{ 'reasonText': 'the Fuchsia platform is not enabled for this project', 'fixText': 'Run "flutter create --platforms=fuchsia ." in your application directory', 'fixCode': _ReasonCode.create.name, }); } case PlatformType.custom: if (!featureFlags.areCustomDevicesEnabled) { reasons.add(<String, Object>{ 'reasonText': 'the custom devices feature is not enabled', 'fixText': 'Run "flutter config --enable-custom-devices"', 'fixCode': _ReasonCode.config.name, }); } case PlatformType.windowsPreview: // TODO(fujino): detect if there any plugins with native code if (!featureFlags.isPreviewDeviceEnabled) { reasons.add(<String, Object>{ 'reasonText': 'the Preview Device feature is not enabled', 'fixText': 'Run "flutter config --enable-flutter-preview', 'fixCode': _ReasonCode.config.name, }); } if (!supportedPlatforms.contains(SupportedPlatform.windows)) { reasons.add(<String, Object>{ 'reasonText': 'the Windows platform is not enabled for this project', 'fixText': 'Run "flutter create --platforms=windows ." in your application directory', 'fixCode': _ReasonCode.create.name, }); } } if (reasons.isEmpty) { platformTypes.add(platform.name); platformTypesMap[platform.name] = const <String, Object>{ 'isSupported': true, }; } else { platformTypesMap[platform.name] = <String, Object>{ 'isSupported': false, 'reasons': reasons, }; } } PlatformType.values.forEach(handlePlatformType); return <String, Object>{ // TODO(fujino): delete this key https://github.com/flutter/flutter/issues/140473 'platforms': platformTypes, 'platformTypes': platformTypesMap, }; } on Exception catch (err, stackTrace) { sendEvent('log', <String, Object?>{ 'log': 'Failed to parse project metadata', 'stackTrace': stackTrace.toString(), 'error': true, }); // On any sort of failure, fall back to Android and iOS for backwards // compatibility. return const <String, Object>{ 'platforms': <String>[ 'android', 'ios', ], 'platformTypes': <String, Object>{ 'android': <String, Object>{'isSupported': true}, 'ios': <String, Object>{'isSupported': true}, }, }; } } /// If notifyVerbose is set, the daemon will forward all verbose logs. Future<void> setNotifyVerbose(Map<String, Object?> args) async { daemon.notifyingLogger?.notifyVerbose = _getBoolArg(args, 'verbose') ?? true; } } /// The reason a [PlatformType] is not currently supported. /// /// The [name] of this value will be sent as a response to daemon client. enum _ReasonCode { create, config, } typedef RunOrAttach = Future<void> Function({ Completer<DebugConnectionInfo>? connectionInfoCompleter, Completer<void>? appStartedCompleter, }); /// This domain responds to methods like [start] and [stop]. /// /// It fires events for application start, stop, and stdout and stderr. class AppDomain extends Domain { AppDomain(Daemon daemon) : super(daemon, 'app') { registerHandler('restart', restart); registerHandler('callServiceExtension', callServiceExtension); registerHandler('stop', stop); registerHandler('detach', detach); } static const Uuid _uuidGenerator = Uuid(); static String _getNewAppId() => _uuidGenerator.v4(); final List<AppInstance> _apps = <AppInstance>[]; final DebounceOperationQueue<OperationResult, OperationType> operationQueue = DebounceOperationQueue<OperationResult, OperationType>(); Future<AppInstance> startApp( Device device, String projectDirectory, String target, String? route, DebuggingOptions options, bool enableHotReload, { File? applicationBinary, required bool trackWidgetCreation, String? projectRootPath, String? packagesFilePath, String? dillOutputPath, bool ipv6 = false, String? isolateFilter, bool machine = true, String? userIdentifier, bool enableDevTools = true, required HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, }) async { if (!await device.supportsRuntimeMode(options.buildInfo.mode)) { throw Exception( '${sentenceCase(options.buildInfo.friendlyModeName)} ' 'mode is not supported for ${device.name}.', ); } // We change the current working directory for the duration of the `start` command. final Directory cwd = globals.fs.currentDirectory; globals.fs.currentDirectory = globals.fs.directory(projectDirectory); final FlutterProject flutterProject = FlutterProject.current(); final FlutterDevice flutterDevice = await FlutterDevice.create( device, target: target, buildInfo: options.buildInfo, platform: globals.platform, userIdentifier: userIdentifier, ); ResidentRunner runner; if (await device.targetPlatform == TargetPlatform.web_javascript) { runner = webRunnerFactory!.createWebRunner( flutterDevice, flutterProject: flutterProject, target: target, debuggingOptions: options, ipv6: ipv6, stayResident: true, urlTunneller: options.webEnableExposeUrl! ? daemon.daemonDomain.exposeUrl : null, machine: machine, usage: globals.flutterUsage, analytics: globals.analytics, systemClock: globals.systemClock, logger: globals.logger, fileSystem: globals.fs, ); } else if (enableHotReload) { runner = HotRunner( <FlutterDevice>[flutterDevice], target: target, debuggingOptions: options, applicationBinary: applicationBinary, projectRootPath: projectRootPath, dillOutputPath: dillOutputPath, ipv6: ipv6, hostIsIde: true, machine: machine, analytics: globals.analytics, nativeAssetsBuilder: nativeAssetsBuilder, ); } else { runner = ColdRunner( <FlutterDevice>[flutterDevice], target: target, debuggingOptions: options, applicationBinary: applicationBinary, ipv6: ipv6, machine: machine, ); } return launch( runner, ({ Completer<DebugConnectionInfo>? connectionInfoCompleter, Completer<void>? appStartedCompleter, }) { return runner.run( connectionInfoCompleter: connectionInfoCompleter, appStartedCompleter: appStartedCompleter, enableDevTools: enableDevTools, route: route, ); }, device, projectDirectory, enableHotReload, cwd, LaunchMode.run, asLogger<AppRunLogger>(globals.logger), ); } Future<AppInstance> launch( ResidentRunner runner, RunOrAttach runOrAttach, Device device, String? projectDirectory, bool enableHotReload, Directory cwd, LaunchMode launchMode, AppRunLogger logger, ) async { final AppInstance app = AppInstance(_getNewAppId(), runner: runner, logToStdout: daemon.logToStdout, logger: logger); _apps.add(app); // Set the domain and app for the given AppRunLogger. This allows the logger // to log messages containing the app ID to the host. logger.domain = this; logger.app = app; _sendAppEvent(app, 'start', <String, Object?>{ 'deviceId': device.id, 'directory': projectDirectory, 'supportsRestart': isRestartSupported(enableHotReload, device), 'launchMode': launchMode.toString(), 'mode': runner.debuggingOptions.buildInfo.modeName, }); Completer<DebugConnectionInfo>? connectionInfoCompleter; if (runner.debuggingEnabled) { connectionInfoCompleter = Completer<DebugConnectionInfo>(); // We don't want to wait for this future to complete and callbacks won't fail. // As it just writes to stdout. unawaited(connectionInfoCompleter.future.then<void>( (DebugConnectionInfo info) { final Map<String, Object?> params = <String, Object?>{ // The web vmservice proxy does not have an http address. 'port': info.httpUri?.port ?? info.wsUri!.port, 'wsUri': info.wsUri.toString(), }; if (info.baseUri != null) { params['baseUri'] = info.baseUri; } _sendAppEvent(app, 'debugPort', params); }, )); } final Completer<void> appStartedCompleter = Completer<void>(); // We don't want to wait for this future to complete, and callbacks won't fail, // as it just writes to stdout. unawaited(appStartedCompleter.future.then<void>((void value) { _sendAppEvent(app, 'started'); })); await app._runInZone<void>(this, () async { try { await runOrAttach( connectionInfoCompleter: connectionInfoCompleter, appStartedCompleter: appStartedCompleter, ); _sendAppEvent(app, 'stop'); } on Exception catch (error, trace) { _sendAppEvent(app, 'stop', <String, Object?>{ 'error': _toJsonable(error), 'trace': '$trace', }); } finally { // If the full directory is used instead of the path then this causes // a TypeError with the ErrorHandlingFileSystem. globals.fs.currentDirectory = cwd.path; _apps.remove(app); } }); return app; } bool isRestartSupported(bool enableHotReload, Device device) => enableHotReload && device.supportsHotRestart; final int _hotReloadDebounceDurationMs = 50; Future<OperationResult>? restart(Map<String, Object?> args) async { final String? appId = _getStringArg(args, 'appId', required: true); final bool fullRestart = _getBoolArg(args, 'fullRestart') ?? false; final bool pauseAfterRestart = _getBoolArg(args, 'pause') ?? false; final String? restartReason = _getStringArg(args, 'reason'); final bool debounce = _getBoolArg(args, 'debounce') ?? false; // This is an undocumented parameter used for integration tests. final int? debounceDurationOverrideMs = _getIntArg(args, 'debounceDurationOverrideMs'); final AppInstance? app = _getApp(appId); if (app == null) { throw DaemonException("app '$appId' not found"); } return _queueAndDebounceReloadAction( app, fullRestart ? OperationType.restart: OperationType.reload, debounce, debounceDurationOverrideMs, () { return app.restart( fullRestart: fullRestart, pause: pauseAfterRestart, reason: restartReason); }, )!; } /// Debounce and queue reload actions. /// /// Only one reload action will run at a time. Actions requested in quick /// succession (within [_hotReloadDebounceDuration]) will be merged together /// and all return the same result. If an action is requested after an identical /// action has already started, it will be queued and run again once the first /// action completes. Future<OperationResult>? _queueAndDebounceReloadAction( AppInstance app, OperationType operationType, bool debounce, int? debounceDurationOverrideMs, Future<OperationResult> Function() action, ) { final Duration debounceDuration = debounce ? Duration(milliseconds: debounceDurationOverrideMs ?? _hotReloadDebounceDurationMs) : Duration.zero; return operationQueue.queueAndDebounce( operationType, debounceDuration, () => app._runInZone<OperationResult>(this, action), ); } /// Returns an error, or the service extension result (a map with two fixed /// keys, `type` and `method`). The result may have one or more additional keys, /// depending on the specific service extension end-point. For example: /// /// { /// "value":"android", /// "type":"_extensionType", /// "method":"ext.flutter.platformOverride" /// } Future<Map<String, Object?>> callServiceExtension(Map<String, Object?> args) async { final String? appId = _getStringArg(args, 'appId', required: true); final String methodName = _getStringArg(args, 'methodName')!; final Map<String, Object?>? params = args['params'] == null ? <String, Object?>{} : castStringKeyedMap(args['params']); final AppInstance? app = _getApp(appId); if (app == null) { throw DaemonException("app '$appId' not found"); } final FlutterDevice device = app.runner!.flutterDevices.first; final List<FlutterView> views = await device.vmService!.getFlutterViews(); final Map<String, Object?>? result = await device .vmService! .invokeFlutterExtensionRpcRaw( methodName, args: params, isolateId: views .first.uiIsolate!.id! ); if (result == null) { throw DaemonException('method not available: $methodName'); } if (result.containsKey('error')) { // ignore: only_throw_errors throw result['error']!; } return result; } Future<bool> stop(Map<String, Object?> args) async { final String? appId = _getStringArg(args, 'appId', required: true); final AppInstance? app = _getApp(appId); if (app == null) { throw DaemonException("app '$appId' not found"); } return app.stop().then<bool>( (void value) => true, onError: (Object? error, StackTrace stack) { _sendAppEvent(app, 'log', <String, Object?>{'log': '$error', 'error': true}); app.closeLogger(); _apps.remove(app); return false; }, ); } Future<bool> detach(Map<String, Object?> args) async { final String? appId = _getStringArg(args, 'appId', required: true); final AppInstance? app = _getApp(appId); if (app == null) { throw DaemonException("app '$appId' not found"); } return app.detach().then<bool>( (void value) => true, onError: (Object? error, StackTrace stack) { _sendAppEvent(app, 'log', <String, Object?>{'log': '$error', 'error': true}); app.closeLogger(); _apps.remove(app); return false; }, ); } AppInstance? _getApp(String? id) { for (final AppInstance app in _apps) { if (app.id == id) { return app; } } return null; } void _sendAppEvent(AppInstance app, String name, [ Map<String, Object?>? args ]) { sendEvent('app.$name', <String, Object?>{ 'appId': app.id, ...?args, }); } } typedef _DeviceEventHandler = void Function(Device device); /// This domain lets callers list and monitor connected devices. /// /// It exports a `getDevices()` call, as well as firing `device.added` and /// `device.removed` events. class DeviceDomain extends Domain { DeviceDomain(Daemon daemon) : super(daemon, 'device') { registerHandler('getDevices', getDevices); registerHandler('discoverDevices', discoverDevices); registerHandler('enable', enable); registerHandler('disable', disable); registerHandler('forward', forward); registerHandler('unforward', unforward); registerHandler('supportsRuntimeMode', supportsRuntimeMode); registerHandler('uploadApplicationPackage', uploadApplicationPackage); registerHandler('logReader.start', startLogReader); registerHandler('logReader.stop', stopLogReader); registerHandler('startApp', startApp); registerHandler('stopApp', stopApp); registerHandler('takeScreenshot', takeScreenshot); registerHandler('startDartDevelopmentService', startDartDevelopmentService); registerHandler('shutdownDartDevelopmentService', shutdownDartDevelopmentService); registerHandler('setExternalDevToolsUriForDartDevelopmentService', setExternalDevToolsUriForDartDevelopmentService); registerHandler('getDiagnostics', getDiagnostics); // Use the device manager discovery so that client provided device types // are usable via the daemon protocol. globals.deviceManager!.deviceDiscoverers.forEach(addDeviceDiscoverer); } /// An incrementing number used to generate unique ids. int _id = 0; final Map<String, ApplicationPackage?> _applicationPackages = <String, ApplicationPackage?>{}; final Map<String, DeviceLogReader> _logReaders = <String, DeviceLogReader>{}; void addDeviceDiscoverer(DeviceDiscovery discoverer) { if (!discoverer.supportsPlatform) { return; } if (discoverer is PollingDeviceDiscovery) { _discoverers.add(discoverer); discoverer.onAdded.listen(_onDeviceEvent('device.added')); discoverer.onRemoved.listen(_onDeviceEvent('device.removed')); } } Future<void> _serializeDeviceEvents = Future<void>.value(); _DeviceEventHandler _onDeviceEvent(String eventName) { return (Device device) { _serializeDeviceEvents = _serializeDeviceEvents.then<void>((_) async { try { final Map<String, Object?> response = await _deviceToMap(device); sendEvent(eventName, response); } on Exception catch (err) { globals.printError('$err'); } }); }; } final List<PollingDeviceDiscovery> _discoverers = <PollingDeviceDiscovery>[]; /// Return a list of the currently connected devices, with each device /// represented as a map of properties (id, name, platform, ...). Future<List<Map<String, Object?>>> getDevices([ Map<String, Object?>? args ]) async { return <Map<String, Object?>>[ for (final PollingDeviceDiscovery discoverer in _discoverers) for (final Device device in await discoverer.devices(filter: DeviceDiscoveryFilter())) await _deviceToMap(device), ]; } /// Return a list of the current devices, discarding existing cache of devices. Future<List<Map<String, Object?>>> discoverDevices(Map<String, Object?> args) async { final int? timeoutInMilliseconds = _getIntArg(args, 'timeoutInMilliseconds'); final Duration? timeout = timeoutInMilliseconds != null ? Duration(milliseconds: timeoutInMilliseconds) : null; // Calling `discoverDevices()` and `_deviceToMap()` in parallel for better performance. final List<List<Device>> devicesListList = await Future.wait(<Future<List<Device>>>[ for (final PollingDeviceDiscovery discoverer in _discoverers) discoverer.discoverDevices(timeout: timeout), ]); final List<Device> devices = <Device>[ for (final List<Device> devicesList in devicesListList) ...devicesList, ]; return Future.wait(<Future<Map<String, Object?>>>[ for (final Device device in devices) _deviceToMap(device), ]); } /// Enable device events. Future<void> enable(Map<String, Object?> args) async { for (final PollingDeviceDiscovery discoverer in _discoverers) { discoverer.startPolling(); } } /// Disable device events. Future<void> disable(Map<String, Object?> args) async { for (final PollingDeviceDiscovery discoverer in _discoverers) { discoverer.stopPolling(); } } /// Forward a host port to a device port. Future<Map<String, Object?>> forward(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final int devicePort = _getIntArg(args, 'devicePort', required: true)!; int? hostPort = _getIntArg(args, 'hostPort'); final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } hostPort = await device.portForwarder!.forward(devicePort, hostPort: hostPort); return <String, Object?>{'hostPort': hostPort}; } /// Removes a forwarded port. Future<void> unforward(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final int devicePort = _getIntArg(args, 'devicePort', required: true)!; final int hostPort = _getIntArg(args, 'hostPort', required: true)!; final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } return device.portForwarder!.unforward(ForwardedPort(hostPort, devicePort)); } /// Returns whether a device supports runtime mode. Future<bool> supportsRuntimeMode(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } final String buildMode = _getStringArg(args, 'buildMode', required: true)!; return await device.supportsRuntimeMode(BuildMode.fromCliName(buildMode)); } /// Creates an application package from a file in the temp directory. Future<String> uploadApplicationPackage(Map<String, Object?> args) async { final TargetPlatform targetPlatform = getTargetPlatformForName(_getStringArg(args, 'targetPlatform', required: true)!); final File applicationBinary = daemon.proxyDomain.tempDirectory.childFile(_getStringArg(args, 'applicationBinary', required: true)!); final ApplicationPackage? applicationPackage = await ApplicationPackageFactory.instance!.getPackageForPlatform( targetPlatform, applicationBinary: applicationBinary, ); final String id = 'application_package_${_id++}'; _applicationPackages[id] = applicationPackage; return id; } /// Starts the log reader on the device. Future<String> startLogReader(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } final String? applicationPackageId = _getStringArg(args, 'applicationPackageId'); final ApplicationPackage? applicationPackage = applicationPackageId != null ? _applicationPackages[applicationPackageId] : null; final String id = '${deviceId}_${_id++}'; final DeviceLogReader logReader = await device.getLogReader(app: applicationPackage); logReader.logLines.listen((String log) => sendEvent('device.logReader.logLines.$id', log)); _logReaders[id] = logReader; return id; } /// Stops a log reader that was previously started. Future<void> stopLogReader(Map<String, Object?> args) async { final String? id = _getStringArg(args, 'id', required: true); _logReaders.remove(id)?.dispose(); } /// Starts an app on a device. Future<Map<String, Object?>> startApp(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } final String? applicationPackageId = _getStringArg(args, 'applicationPackageId', required: true); final ApplicationPackage applicationPackage = _applicationPackages[applicationPackageId!]!; final LaunchResult result = await device.startApp( applicationPackage, debuggingOptions: DebuggingOptions.fromJson( castStringKeyedMap(args['debuggingOptions'])!, // We are using prebuilts, build info does not matter here. BuildInfo.debug, ), mainPath: _getStringArg(args, 'mainPath'), route: _getStringArg(args, 'route'), platformArgs: castStringKeyedMap(args['platformArgs']) ?? const <String, Object>{}, prebuiltApplication: _getBoolArg(args, 'prebuiltApplication') ?? false, ipv6: _getBoolArg(args, 'ipv6') ?? false, userIdentifier: _getStringArg(args, 'userIdentifier'), ); return <String, Object?>{ 'started': result.started, 'vmServiceUri': result.vmServiceUri?.toString(), // TODO(bkonyi): remove once clients have migrated to relying on vmServiceUri. 'observatoryUri': result.vmServiceUri?.toString(), }; } /// Stops an app. Future<bool> stopApp(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } final String? applicationPackageId = _getStringArg(args, 'applicationPackageId'); ApplicationPackage? applicationPackage; if (applicationPackageId != null) { applicationPackage = _applicationPackages[applicationPackageId]; } return device.stopApp( applicationPackage, userIdentifier: _getStringArg(args, 'userIdentifier'), ); } /// Takes a screenshot. Future<String?> takeScreenshot(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } final String tempFileName = 'screenshot_${_id++}'; final File tempFile = daemon.proxyDomain.tempDirectory.childFile(tempFileName); await device.takeScreenshot(tempFile); if (await tempFile.exists()) { final String imageBase64 = base64.encode(await tempFile.readAsBytes()); return imageBase64; } else { return null; } } /// Starts DDS for the device. Future<String?> startDartDevelopmentService(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final bool? disableServiceAuthCodes = _getBoolArg(args, 'disableServiceAuthCodes'); final String vmServiceUriStr = _getStringArg(args, 'vmServiceUri', required: true)!; final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } await device.dds.startDartDevelopmentService( Uri.parse(vmServiceUriStr), logger: globals.logger, disableServiceAuthCodes: disableServiceAuthCodes, ); unawaited(device.dds.done.whenComplete(() => sendEvent('device.dds.done.$deviceId'))); return device.dds.uri?.toString(); } /// Starts DDS for the device. Future<void> shutdownDartDevelopmentService(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } await device.dds.shutdown(); } Future<void> setExternalDevToolsUriForDartDevelopmentService(Map<String, Object?> args) async { final String? deviceId = _getStringArg(args, 'deviceId', required: true); final String uri = _getStringArg(args, 'uri', required: true)!; final Device? device = await daemon.deviceDomain._getDevice(deviceId); if (device == null) { throw DaemonException("device '$deviceId' not found"); } device.dds.setExternalDevToolsUri(Uri.parse(uri)); } @override Future<void> dispose() { for (final PollingDeviceDiscovery discoverer in _discoverers) { discoverer.dispose(); } return Future<void>.value(); } /// Return the connected device matching the deviceId field in the args. Future<Device?> _getDevice(String? deviceId) async { for (final PollingDeviceDiscovery discoverer in _discoverers) { final List<Device> devices = await discoverer.devices( filter: DeviceDiscoveryFilter(), ); Device? device; for (final Device localDevice in devices) { if (localDevice.id == deviceId) { device = localDevice; } } if (device != null) { return device; } } return null; } /// Gets a list of diagnostic messages pertaining to issues with any connected /// devices. Future<List<String>> getDiagnostics(Map<String, Object?> args) async { // Call `getDiagnostics()` in parallel to improve performance. final List<List<String>> diagnosticsLists = await Future.wait(<Future<List<String>>>[ for (final PollingDeviceDiscovery discoverer in _discoverers) discoverer.getDiagnostics(), ]); return <String>[ for (final List<String> diagnostics in diagnosticsLists) ...diagnostics, ]; } } class DevToolsDomain extends Domain { DevToolsDomain(Daemon daemon) : super(daemon, 'devtools') { registerHandler('serve', serve); } DevtoolsLauncher? _devtoolsLauncher; Future<Map<String, Object?>> serve([ Map<String, Object?>? args ]) async { _devtoolsLauncher ??= DevtoolsLauncher.instance; final DevToolsServerAddress? server = await _devtoolsLauncher?.serve(); return<String, Object?>{ 'host': server?.host, 'port': server?.port, }; } @override Future<void> dispose() async { await _devtoolsLauncher?.close(); } } Future<Map<String, Object?>> _deviceToMap(Device device) async { return <String, Object?>{ 'id': device.id, 'name': device.name, 'platform': getNameForTargetPlatform(await device.targetPlatform), 'emulator': await device.isLocalEmulator, 'category': device.category?.toString(), 'platformType': device.platformType?.toString(), 'ephemeral': device.ephemeral, 'emulatorId': await device.emulatorId, 'sdk': await device.sdkNameAndVersion, 'isConnected': device.isConnected, 'connectionInterface': getNameForDeviceConnectionInterface(device.connectionInterface), 'capabilities': <String, Object>{ 'hotReload': device.supportsHotReload, 'hotRestart': device.supportsHotRestart, 'screenshot': device.supportsScreenshot, 'fastStart': device.supportsFastStart, 'flutterExit': device.supportsFlutterExit, 'hardwareRendering': await device.supportsHardwareRendering, 'startPaused': device.supportsStartPaused, }, }; } Map<String, Object?> _emulatorToMap(Emulator emulator) { return <String, Object?>{ 'id': emulator.id, 'name': emulator.name, 'category': emulator.category.toString(), 'platformType': emulator.platformType.toString(), }; } Map<String, Object?> _operationResultToMap(OperationResult result) { return <String, Object?>{ 'code': result.code, 'message': result.message, }; } Object? _toJsonable(Object? obj) { if (obj is String || obj is int || obj is bool || obj is Map<Object?, Object?> || obj is List<Object?> || obj == null) { return obj; } if (obj is OperationResult) { return _operationResultToMap(obj); } if (obj is ToolExit) { return obj.message; } return '$obj'; } class NotifyingLogger extends DelegatingLogger { NotifyingLogger({ required this.verbose, required Logger parent, this.notifyVerbose = false }) : super(parent) { _messageController = StreamController<LogMessage>.broadcast( onListen: _onListen, ); } final bool verbose; final List<LogMessage> messageBuffer = <LogMessage>[]; late StreamController<LogMessage> _messageController; bool notifyVerbose = false; void _onListen() { if (messageBuffer.isNotEmpty) { messageBuffer.forEach(_messageController.add); messageBuffer.clear(); } } Stream<LogMessage> get onMessage => _messageController.stream; @override void printError( String message, { StackTrace? stackTrace, bool? emphasis = false, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, }) { _sendMessage(LogMessage('error', message, stackTrace)); } @override void printWarning( String message, { bool? emphasis = false, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap, bool fatal = true, }) { _sendMessage(LogMessage('warning', message)); } @override void printStatus( String message, { bool? emphasis = false, TerminalColor? color, bool? newline = true, int? indent, int? hangingIndent, bool? wrap, }) { _sendMessage(LogMessage('status', message)); } @override void printBox(String message, { String? title, }) { _sendMessage(LogMessage('status', title == null ? message : '$title: $message')); } @override void printTrace(String message) { if (notifyVerbose) { _sendMessage(LogMessage('trace', message)); return; } if (!verbose) { return; } super.printError(message); } @override Status startProgress( String message, { Duration? timeout, String? progressId, bool multilineOutput = false, bool includeTiming = true, int progressIndicatorPadding = kDefaultStatusPadding, }) { assert(timeout != null); printStatus(message); return SilentStatus( stopwatch: Stopwatch(), ); } void _sendMessage(LogMessage logMessage) { if (_messageController.hasListener) { return _messageController.add(logMessage); } messageBuffer.add(logMessage); } void dispose() { _messageController.close(); } @override void sendEvent(String name, [Map<String, Object?>? args]) { } @override bool get supportsColor => false; @override bool get hasTerminal => false; // This method is only relevant for terminals. @override void clear() { } } /// A running application, started by this daemon. class AppInstance { AppInstance(this.id, { this.runner, this.logToStdout = false, required AppRunLogger logger }) : _logger = logger; final String id; final ResidentRunner? runner; final bool logToStdout; final AppRunLogger _logger; Future<OperationResult> restart({ bool fullRestart = false, bool pause = false, String? reason }) { return runner!.restart(fullRestart: fullRestart, pause: pause, reason: reason); } Future<void> stop() => runner!.exit(); Future<void> detach() => runner!.detach(); void closeLogger() { _logger.close(); } Future<T> _runInZone<T>(AppDomain domain, FutureOr<T> Function() method) async { return method(); } } /// This domain responds to methods like [getEmulators] and [launch]. class EmulatorDomain extends Domain { EmulatorDomain(Daemon daemon) : super(daemon, 'emulator') { registerHandler('getEmulators', getEmulators); registerHandler('launch', launch); registerHandler('create', create); } EmulatorManager emulators = EmulatorManager( fileSystem: globals.fs, logger: globals.logger, java: globals.java, androidSdk: globals.androidSdk, processManager: globals.processManager, androidWorkflow: androidWorkflow!, ); Future<List<Map<String, Object?>>> getEmulators([ Map<String, Object?>? args ]) async { final List<Emulator> list = await emulators.getAllAvailableEmulators(); return list.map<Map<String, Object?>>(_emulatorToMap).toList(); } Future<void> launch(Map<String, Object?> args) async { final String emulatorId = _getStringArg(args, 'emulatorId', required: true)!; final bool coldBoot = _getBoolArg(args, 'coldBoot') ?? false; final List<Emulator> matches = await emulators.getEmulatorsMatching(emulatorId); if (matches.isEmpty) { throw DaemonException("emulator '$emulatorId' not found"); } else if (matches.length > 1) { throw DaemonException("multiple emulators match '$emulatorId'"); } else { await matches.first.launch(coldBoot: coldBoot); } } Future<Map<String, Object?>> create(Map<String, Object?> args) async { final String? name = _getStringArg(args, 'name'); final CreateEmulatorResult res = await emulators.createEmulator(name: name); return <String, Object?>{ 'success': res.success, 'emulatorName': res.emulatorName, 'error': res.error, }; } } class ProxyDomain extends Domain { ProxyDomain(Daemon daemon, { required FileTransfer fileTransfer, }) : _fileTransfer = fileTransfer, super(daemon, 'proxy') { registerHandlerWithBinary('writeTempFile', writeTempFile); registerHandler('calculateFileHashes', calculateFileHashes); registerHandlerWithBinary('updateFile', updateFile); registerHandler('connect', connect); registerHandler('disconnect', disconnect); registerHandlerWithBinary('write', write); } final FileTransfer _fileTransfer; final Map<String, Socket> _forwardedConnections = <String, Socket>{}; int _id = 0; /// Writes to a file in a local temporary directory. Future<void> writeTempFile(Map<String, Object?> args, Stream<List<int>>? binary) async { final String path = _getStringArg(args, 'path', required: true)!; final File file = tempDirectory.childFile(path); await file.parent.create(recursive: true); await file.openWrite().addStream(binary!); } /// Calculate rolling hashes for a file in the local temporary directory. Future<Map<String, Object?>?> calculateFileHashes(Map<String, Object?> args) async { final String path = _getStringArg(args, 'path', required: true)!; final bool cacheResult = _getBoolArg(args, 'cacheResult') ?? false; final File file = tempDirectory.childFile(path); if (!await file.exists()) { return null; } final File hashFile = file.parent.childFile('${file.basename}.hashes'); if (hashFile.existsSync() && hashFile.statSync().modified.isAfter(file.statSync().modified)) { // If the cached hash file is newer than the file, assume that the cached // is up to date. Return the cached result directly. final String cachedJson = await hashFile.readAsString(); return json.decode(cachedJson) as Map<String, Object?>; } final BlockHashes result = await _fileTransfer.calculateBlockHashesOfFile(file); final Map<String, Object?> resultObject = result.toJson(); if (cacheResult) { await hashFile.writeAsString(json.encode(resultObject)); } return resultObject; } Future<bool?> updateFile(Map<String, Object?> args, Stream<List<int>>? binary) async { final String path = _getStringArg(args, 'path', required: true)!; final File file = tempDirectory.childFile(path); if (!await file.exists()) { return null; } final List<Map<String, Object?>> deltaJson = (args['delta']! as List<Object?>).cast<Map<String, Object?>>(); final List<FileDeltaBlock> delta = FileDeltaBlock.fromJsonList(deltaJson); final bool result = await _fileTransfer.rebuildFile(file, delta, binary!); return result; } /// Opens a connection to a local port, and returns the connection id. Future<String> connect(Map<String, Object?> args) async { final int targetPort = _getIntArg(args, 'port', required: true)!; final String id = 'portForwarder_${targetPort}_${_id++}'; Socket? socket; try { socket = await Socket.connect(InternetAddress.loopbackIPv4, targetPort); } on SocketException { globals.logger.printTrace('Connecting to localhost:$targetPort failed with IPv4'); } try { // If connecting to IPv4 loopback interface fails, try IPv6. socket ??= await Socket.connect(InternetAddress.loopbackIPv6, targetPort); } on SocketException { globals.logger.printError('Connecting to localhost:$targetPort failed'); } if (socket == null) { throw Exception('Failed to connect to the port'); } _forwardedConnections[id] = socket; debounceDataStream(socket).listen((List<int> data) { sendEvent('proxy.data.$id', null, data); }, onError: (Object error, StackTrace stackTrace) { // Socket error, probably disconnected. globals.logger.printTrace('Socket error: $error, $stackTrace'); }); unawaited(socket.done.then<Object?>( (Object? obj) => obj, onError: (Object error, StackTrace stackTrace) { // Socket error, probably disconnected. globals.logger.printTrace('Socket error: $error, $stackTrace'); }).then((Object? _) { sendEvent('proxy.disconnected.$id'); })); return id; } /// Disconnects from a previously established connection. Future<bool> disconnect(Map<String, Object?> args) async { final String? id = _getStringArg(args, 'id', required: true); if (_forwardedConnections.containsKey(id)) { await _forwardedConnections.remove(id)?.close(); return true; } return false; } /// Writes to a previously established connection. Future<bool> write(Map<String, Object?> args, Stream<List<int>>? binary) async { final String? id = _getStringArg(args, 'id', required: true); if (_forwardedConnections.containsKey(id)) { final StreamSubscription<List<int>> subscription = binary!.listen(_forwardedConnections[id!]!.add); await subscription.asFuture<void>(); await subscription.cancel(); return true; } return false; } @override Future<void> dispose() async { for (final Socket connection in _forwardedConnections.values) { connection.destroy(); } // We deliberately not clean up the tempDirectory here. The application package files that // are transferred into this directory through ProxiedDevices are left in the directory // to be reused on any subsequent runs. } Directory? _tempDirectory; Directory get tempDirectory => _tempDirectory ??= globals.fs.systemTempDirectory.childDirectory('flutter_tool_daemon')..createSync(); } /// A [Logger] which sends log messages to a listening daemon client. /// /// This class can either: /// 1) Send stdout messages and progress events to the client IDE /// 1) Log messages to stdout and send progress events to the client IDE // // TODO(devoncarew): To simplify this code a bit, we could choose to specialize // this class into two, one for each of the above use cases. class AppRunLogger extends DelegatingLogger { AppRunLogger({ required Logger parent }) : super(parent); AppDomain? domain; late AppInstance app; int _nextProgressId = 0; Status? _status; @override Status startProgress( String message, { Duration? timeout, String? progressId, bool multilineOutput = false, bool includeTiming = true, int progressIndicatorPadding = kDefaultStatusPadding, }) { final int id = _nextProgressId++; _sendProgressEvent( eventId: id.toString(), eventType: progressId, message: message, ); _status = SilentStatus( onFinish: () { _status = null; _sendProgressEvent( eventId: id.toString(), eventType: progressId, finished: true, ); }, stopwatch: Stopwatch())..start(); return _status!; } void close() { domain = null; } void _sendProgressEvent({ required String eventId, required String? eventType, bool finished = false, String? message, }) { if (domain == null) { // If we're sending progress events before an app has started, send the // progress messages as plain status messages. if (message != null) { printStatus(message); } } else { final Map<String, Object?> event = <String, Object?>{ 'id': eventId, 'progressId': eventType, if (message != null) 'message': message, 'finished': finished, }; domain!._sendAppEvent(app, 'progress', event); } } @override void sendEvent(String name, [Map<String, Object?>? args, List<int>? binary]) { if (domain == null) { printStatus('event sent after app closed: $name'); } else { domain!.sendEvent(name, args, binary); } } @override bool get supportsColor => false; @override bool get hasTerminal => false; // This method is only relevant for terminals. @override void clear() { } } class LogMessage { LogMessage(this.level, this.message, [this.stackTrace]); final String level; final String message; final StackTrace? stackTrace; } /// The method by which the Flutter app was launched. enum LaunchMode { run._('run'), attach._('attach'); const LaunchMode._(this._value); final String _value; @override String toString() => _value; } enum OperationType { reload, restart } /// A queue that debounces operations for a period and merges operations of the same type. /// Only one action (or any type) will run at a time. Actions of the same type requested /// in quick succession will be merged together and all return the same result. If an action /// is requested after an identical action has already started, it will be queued /// and run again once the first action completes. class DebounceOperationQueue<T, K> { final Map<K, RestartableTimer> _debounceTimers = <K, RestartableTimer>{}; final Map<K, Future<T>> _operationQueue = <K, Future<T>>{}; Future<void>? _inProgressAction; Future<T> queueAndDebounce( K operationType, Duration debounceDuration, Future<T> Function() action, ) { // If there is already an operation of this type waiting to run, reset its // debounce timer and return its future. if (_operationQueue[operationType] != null) { _debounceTimers[operationType]?.reset(); return _operationQueue[operationType]!; } // Otherwise, put one in the queue with a timer. final Completer<T> completer = Completer<T>(); _operationQueue[operationType] = completer.future; _debounceTimers[operationType] = RestartableTimer( debounceDuration, () async { // Remove us from the queue so we can't be reset now we've started. unawaited(_operationQueue.remove(operationType)); _debounceTimers.remove(operationType); // No operations should be allowed to run concurrently even if they're // different types. while (_inProgressAction != null) { await _inProgressAction; } _inProgressAction = action() .then(completer.complete, onError: completer.completeError) .whenComplete(() => _inProgressAction = null); }, ); return completer.future; } } /// Specialized exception for returning errors to the daemon client. class DaemonException implements Exception { DaemonException(this.message); final String message; @override String toString() => message; }
flutter/packages/flutter_tools/lib/src/commands/daemon.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/daemon.dart", "repo_id": "flutter", "token_count": 24388 }
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 'dart:async'; import 'package:meta/meta.dart'; import 'package:unified_analytics/unified_analytics.dart' as analytics; import 'package:vm_service/vm_service.dart'; import '../android/android_device.dart'; import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../daemon.dart'; import '../device.dart'; import '../features.dart'; import '../globals.dart' as globals; import '../ios/devices.dart'; import '../macos/macos_ipad_device.dart'; import '../project.dart'; import '../reporting/reporting.dart'; import '../resident_runner.dart'; import '../run_cold.dart'; import '../run_hot.dart'; import '../runner/flutter_command.dart'; import '../runner/flutter_command_runner.dart'; import '../tracing.dart'; import '../vmservice.dart'; import '../web/compile.dart'; import '../web/web_runner.dart'; import 'daemon.dart'; /// Shared logic between `flutter run` and `flutter drive` commands. abstract class RunCommandBase extends FlutterCommand with DeviceBasedDevelopmentArtifacts { RunCommandBase({ required bool verboseHelp }) { addBuildModeFlags(verboseHelp: verboseHelp, defaultToRelease: false); usesDartDefineOption(); usesFlavorOption(); usesWebRendererOption(); usesWebResourcesCdnFlag(); addNativeNullAssertions(hide: !verboseHelp); addBundleSkSLPathOption(hide: !verboseHelp); usesApplicationBinaryOption(); argParser ..addFlag('trace-startup', negatable: false, help: 'Trace application startup, then exit, saving the trace to a file. ' 'By default, this will be saved in the "build" directory. If the ' 'FLUTTER_TEST_OUTPUTS_DIR environment variable is set, the file ' 'will be written there instead.', ) ..addFlag('cache-startup-profile', help: 'Caches the CPU profile collected before the first frame for startup ' 'analysis.', ) ..addFlag('verbose-system-logs', negatable: false, help: 'Include verbose logging from the Flutter engine.', ) ..addFlag('cache-sksl', negatable: false, help: 'Cache the shader in the SkSL format instead of in binary or GLSL formats.', ) ..addFlag('dump-skp-on-shader-compilation', negatable: false, help: 'Automatically dump the skp that triggers new shader compilations. ' 'This is useful for writing custom ShaderWarmUp to reduce jank. ' 'By default, this is not enabled as it introduces significant overhead. ' 'This is only available in profile or debug builds.', ) ..addFlag('purge-persistent-cache', negatable: false, help: 'Removes all existing persistent caches. This allows reproducing ' 'shader compilation jank that normally only happens the first time ' 'an app is run, or for reliable testing of compilation jank fixes ' '(e.g. shader warm-up).', ) ..addOption('route', help: 'Which route to load when running the app.', ) ..addOption('vmservice-out-file', help: 'A file to write the attached vmservice URL to after an ' 'application is started.', valueHelp: 'project/example/out.txt', hide: !verboseHelp, ) ..addFlag('disable-service-auth-codes', negatable: false, hide: !verboseHelp, help: '(deprecated) Allow connections to the VM service without using authentication codes. ' '(Not recommended! This can open your device to remote code execution attacks!)' ) ..addFlag('start-paused', defaultsTo: startPausedDefault, help: 'Start in a paused mode and wait for a debugger to connect.', ) ..addOption('dart-flags', hide: !verboseHelp, help: 'Pass a list of comma separated flags to the Dart instance at ' 'application startup. Flags passed through this option must be ' 'present on the allowlist defined within the Flutter engine. If ' 'a disallowed flag is encountered, the process will be ' 'terminated immediately.\n\n' 'This flag is not available on the stable channel and is only ' 'applied in debug and profile modes. This option should only ' 'be used for experiments and should not be used by typical users.' ) ..addFlag('endless-trace-buffer', negatable: false, help: 'Enable tracing to an infinite buffer, instead of a ring buffer. ' 'This is useful when recording large traces. To use an endless buffer to ' 'record startup traces, combine this with "--trace-startup".', ) ..addFlag('trace-systrace', negatable: false, help: 'Enable tracing to the system tracer. This is only useful on ' 'platforms where such a tracer is available (Android, iOS, ' 'macOS and Fuchsia).', ) ..addOption('trace-to-file', help: 'Write the timeline trace to a file at the specified path. The ' "file will be in Perfetto's proto format; it will be possible to " "load the file into Perfetto's trace viewer.", valueHelp: 'path/to/trace.binpb', ) ..addFlag('trace-skia', negatable: false, help: 'Enable tracing of Skia code. This is useful when debugging ' 'the raster thread (formerly known as the GPU thread). ' 'By default, Flutter will not log Skia code, as it introduces significant ' 'overhead that may affect recorded performance metrics in a misleading way.', ) ..addOption('trace-allowlist', hide: !verboseHelp, help: 'Filters out all trace events except those that are specified in ' 'this comma separated list of allowed prefixes.', valueHelp: 'foo,bar', ) ..addOption('trace-skia-allowlist', hide: !verboseHelp, help: 'Filters out all Skia trace events except those that are specified in ' 'this comma separated list of allowed prefixes.', valueHelp: 'skia.gpu,skia.shaders', ) ..addFlag('enable-dart-profiling', defaultsTo: true, help: 'Whether the Dart VM sampling CPU profiler is enabled. This flag ' 'is only meaningful in debug and profile builds.', ) ..addFlag('enable-software-rendering', negatable: false, help: '(deprecated) Enable rendering using the Skia software backend. ' 'This is useful when testing Flutter on emulators. By default, ' 'Flutter will attempt to either use OpenGL or Vulkan and fall back ' 'to software when neither is available. This option is not supported ' 'when using the Impeller rendering engine.', hide: !verboseHelp, ) ..addFlag('skia-deterministic-rendering', negatable: false, help: '(deprecated) When combined with "--enable-software-rendering", this should provide completely ' 'deterministic (i.e. reproducible) Skia rendering. This is useful for testing purposes ' '(e.g. when comparing screenshots). This option is not supported ' 'when using the Impeller rendering engine.', hide: !verboseHelp, ) ..addMultiOption('dart-entrypoint-args', abbr: 'a', help: 'Pass a list of arguments to the Dart entrypoint at application ' 'startup. By default this is main(List<String> args). Specify ' 'this option multiple times each with one argument to pass ' 'multiple arguments to the Dart entrypoint. Currently this is ' 'only supported on desktop platforms.', ) ..addFlag('uninstall-first', hide: !verboseHelp, help: 'Uninstall previous versions of the app on the device ' 'before reinstalling. Currently only supported on iOS.', ); usesWebOptions(verboseHelp: verboseHelp); usesTargetOption(); usesPortOptions(verboseHelp: verboseHelp); usesIpv6Flag(verboseHelp: verboseHelp); usesPubOption(); usesTrackWidgetCreation(verboseHelp: verboseHelp); addNullSafetyModeOptions(hide: !verboseHelp); usesDeviceUserOption(); usesDeviceTimeoutOption(); usesDeviceConnectionOption(); addDdsOptions(verboseHelp: verboseHelp); addDevToolsOptions(verboseHelp: verboseHelp); addServeObservatoryOptions(verboseHelp: verboseHelp); addAndroidSpecificBuildOptions(hide: !verboseHelp); usesFatalWarningsOption(verboseHelp: verboseHelp); addEnableImpellerFlag(verboseHelp: verboseHelp); addEnableVulkanValidationFlag(verboseHelp: verboseHelp); addEnableEmbedderApiFlag(verboseHelp: verboseHelp); } bool get traceStartup => boolArg('trace-startup'); bool get enableDartProfiling => boolArg('enable-dart-profiling'); bool get cacheSkSL => boolArg('cache-sksl'); bool get dumpSkpOnShaderCompilation => boolArg('dump-skp-on-shader-compilation'); bool get purgePersistentCache => boolArg('purge-persistent-cache'); bool get disableServiceAuthCodes => boolArg('disable-service-auth-codes'); bool get cacheStartupProfile => boolArg('cache-startup-profile'); bool get runningWithPrebuiltApplication => argResults![FlutterOptions.kUseApplicationBinary] != null; bool get trackWidgetCreation => boolArg('track-widget-creation'); ImpellerStatus get enableImpeller => ImpellerStatus.fromBool(argResults!['enable-impeller'] as bool?); bool get enableVulkanValidation => boolArg('enable-vulkan-validation'); bool get uninstallFirst => boolArg('uninstall-first'); bool get enableEmbedderApi => boolArg('enable-embedder-api'); @override bool get refreshWirelessDevices => true; @override bool get reportNullSafety => true; /// Whether to start the application paused by default. bool get startPausedDefault; String? get route => stringArg('route'); String? get traceAllowlist => stringArg('trace-allowlist'); /// Create a debugging options instance for the current `run` or `drive` invocation. @visibleForTesting @protected Future<DebuggingOptions> createDebuggingOptions(bool webMode) async { final BuildInfo buildInfo = await getBuildInfo(); final int? webBrowserDebugPort = featureFlags.isWebEnabled && argResults!.wasParsed('web-browser-debug-port') ? int.parse(stringArg('web-browser-debug-port')!) : null; final List<String> webBrowserFlags = featureFlags.isWebEnabled ? stringsArg(FlutterOptions.kWebBrowserFlag) : const <String>[]; final Map<String, String> webHeaders = featureFlags.isWebEnabled ? extractWebHeaders() : const <String, String>{}; final String? webRendererString = stringArg('web-renderer'); final WebRendererMode webRenderer = (webRendererString != null) ? WebRendererMode.values.byName(webRendererString) : WebRendererMode.auto; if (buildInfo.mode.isRelease) { return DebuggingOptions.disabled( buildInfo, dartEntrypointArgs: stringsArg('dart-entrypoint-args'), hostname: featureFlags.isWebEnabled ? stringArg('web-hostname') : '', port: featureFlags.isWebEnabled ? stringArg('web-port') : '', tlsCertPath: featureFlags.isWebEnabled ? stringArg('web-tls-cert-path') : null, tlsCertKeyPath: featureFlags.isWebEnabled ? stringArg('web-tls-cert-key-path') : null, webUseSseForDebugProxy: featureFlags.isWebEnabled && stringArg('web-server-debug-protocol') == 'sse', webUseSseForDebugBackend: featureFlags.isWebEnabled && stringArg('web-server-debug-backend-protocol') == 'sse', webUseSseForInjectedClient: featureFlags.isWebEnabled && stringArg('web-server-debug-injected-client-protocol') == 'sse', webEnableExposeUrl: featureFlags.isWebEnabled && boolArg('web-allow-expose-url'), webRunHeadless: featureFlags.isWebEnabled && boolArg('web-run-headless'), webBrowserDebugPort: webBrowserDebugPort, webBrowserFlags: webBrowserFlags, webHeaders: webHeaders, webRenderer: webRenderer, enableImpeller: enableImpeller, enableVulkanValidation: enableVulkanValidation, uninstallFirst: uninstallFirst, enableDartProfiling: enableDartProfiling, enableEmbedderApi: enableEmbedderApi, usingCISystem: usingCISystem, debugLogsDirectoryPath: debugLogsDirectoryPath, ); } else { return DebuggingOptions.enabled( buildInfo, startPaused: boolArg('start-paused'), disableServiceAuthCodes: boolArg('disable-service-auth-codes'), cacheStartupProfile: cacheStartupProfile, enableDds: enableDds, dartEntrypointArgs: stringsArg('dart-entrypoint-args'), dartFlags: stringArg('dart-flags') ?? '', useTestFonts: argParser.options.containsKey('use-test-fonts') && boolArg('use-test-fonts'), enableSoftwareRendering: argParser.options.containsKey('enable-software-rendering') && boolArg('enable-software-rendering'), skiaDeterministicRendering: argParser.options.containsKey('skia-deterministic-rendering') && boolArg('skia-deterministic-rendering'), traceSkia: boolArg('trace-skia'), traceAllowlist: traceAllowlist, traceSkiaAllowlist: stringArg('trace-skia-allowlist'), traceSystrace: boolArg('trace-systrace'), traceToFile: stringArg('trace-to-file'), endlessTraceBuffer: boolArg('endless-trace-buffer'), dumpSkpOnShaderCompilation: dumpSkpOnShaderCompilation, cacheSkSL: cacheSkSL, purgePersistentCache: purgePersistentCache, deviceVmServicePort: deviceVmservicePort, hostVmServicePort: hostVmservicePort, disablePortPublication: await disablePortPublication, ddsPort: ddsPort, devToolsServerAddress: devToolsServerAddress, verboseSystemLogs: boolArg('verbose-system-logs'), hostname: featureFlags.isWebEnabled ? stringArg('web-hostname') : '', port: featureFlags.isWebEnabled ? stringArg('web-port') : '', tlsCertPath: featureFlags.isWebEnabled ? stringArg('web-tls-cert-path') : null, tlsCertKeyPath: featureFlags.isWebEnabled ? stringArg('web-tls-cert-key-path') : null, webUseSseForDebugProxy: featureFlags.isWebEnabled && stringArg('web-server-debug-protocol') == 'sse', webUseSseForDebugBackend: featureFlags.isWebEnabled && stringArg('web-server-debug-backend-protocol') == 'sse', webUseSseForInjectedClient: featureFlags.isWebEnabled && stringArg('web-server-debug-injected-client-protocol') == 'sse', webEnableExposeUrl: featureFlags.isWebEnabled && boolArg('web-allow-expose-url'), webRunHeadless: featureFlags.isWebEnabled && boolArg('web-run-headless'), webBrowserDebugPort: webBrowserDebugPort, webBrowserFlags: webBrowserFlags, webEnableExpressionEvaluation: featureFlags.isWebEnabled && boolArg('web-enable-expression-evaluation'), webLaunchUrl: featureFlags.isWebEnabled ? stringArg('web-launch-url') : null, webHeaders: webHeaders, webRenderer: webRenderer, vmserviceOutFile: stringArg('vmservice-out-file'), fastStart: argParser.options.containsKey('fast-start') && boolArg('fast-start') && !runningWithPrebuiltApplication, nullAssertions: boolArg('null-assertions'), nativeNullAssertions: boolArg('native-null-assertions'), enableImpeller: enableImpeller, enableVulkanValidation: enableVulkanValidation, uninstallFirst: uninstallFirst, serveObservatory: boolArg('serve-observatory'), enableDartProfiling: enableDartProfiling, enableEmbedderApi: enableEmbedderApi, usingCISystem: usingCISystem, debugLogsDirectoryPath: debugLogsDirectoryPath, ); } } } class RunCommand extends RunCommandBase { RunCommand({ bool verboseHelp = false, HotRunnerNativeAssetsBuilder? nativeAssetsBuilder, }) : _nativeAssetsBuilder = nativeAssetsBuilder, super(verboseHelp: verboseHelp) { requiresPubspecYaml(); usesFilesystemOptions(hide: !verboseHelp); usesExtraDartFlagOptions(verboseHelp: verboseHelp); usesFrontendServerStarterPathOption(verboseHelp: verboseHelp); addEnableExperimentation(hide: !verboseHelp); usesInitializeFromDillOption(hide: !verboseHelp); usesNativeAssetsOption(hide: !verboseHelp); // By default, the app should to publish the VM service port over mDNS. // This will allow subsequent "flutter attach" commands to connect to the VM // without needing to know the port. addPublishPort(verboseHelp: verboseHelp); addIgnoreDeprecationOption(); argParser ..addFlag('await-first-frame-when-tracing', defaultsTo: true, help: 'Whether to wait for the first frame when tracing startup ("--trace-startup"), ' 'or just dump the trace as soon as the application is running. The first frame ' 'is detected by looking for a Timeline event with the name ' '"${Tracing.firstUsefulFrameEventName}". ' "By default, the widgets library's binding takes care of sending this event.", ) ..addFlag('use-test-fonts', help: 'Enable (and default to) the "Ahem" font. This is a special font ' 'used in tests to remove any dependencies on the font metrics. It ' 'is enabled when you use "flutter test". Set this flag when running ' 'a test using "flutter run" for debugging purposes. This flag is ' 'only available when running in debug mode.', ) ..addFlag('build', defaultsTo: true, help: 'If necessary, build the app before running.', ) ..addOption('project-root', hide: !verboseHelp, help: 'Specify the project root directory.', ) ..addFlag('machine', hide: !verboseHelp, negatable: false, help: 'Handle machine structured JSON command input and provide output ' 'and progress in machine friendly format.', ) ..addFlag('hot', defaultsTo: kHotReloadDefault, help: 'Run with support for hot reloading. Only available for debug mode. Not available with "--trace-startup".', ) ..addFlag('resident', defaultsTo: true, hide: !verboseHelp, help: 'Stay resident after launching the application. Not available with "--trace-startup".', ) ..addOption('pid-file', help: 'Specify a file to write the process ID to. ' 'You can send SIGUSR1 to trigger a hot reload ' 'and SIGUSR2 to trigger a hot restart. ' 'The file is created when the signal handlers ' 'are hooked and deleted when they are removed.', )..addFlag( 'report-ready', help: 'Print "ready" to the console after handling a keyboard command.\n' 'This is primarily useful for tests and other automation, but consider ' 'using "--machine" instead.', hide: !verboseHelp, )..addFlag('benchmark', negatable: false, hide: !verboseHelp, help: 'Enable a benchmarking mode. This will run the given application, ' 'measure the startup time and the app restart time, write the ' 'results out to "refresh_benchmark.json", and exit. This flag is ' 'intended for use in generating automated flutter benchmarks.', ) // TODO(zanderso): Off by default with investigating whether this // is slower for certain use cases. // See: https://github.com/flutter/flutter/issues/49499 ..addFlag('fast-start', help: 'Whether to quickly bootstrap applications with a minimal app. ' 'Currently this is only supported on Android devices. This option ' 'cannot be paired with "--${FlutterOptions.kUseApplicationBinary}".', hide: !verboseHelp, ); } final HotRunnerNativeAssetsBuilder? _nativeAssetsBuilder; @override final String name = 'run'; @override DeprecationBehavior get deprecationBehavior => boolArg('ignore-deprecation') ? DeprecationBehavior.ignore : _deviceDeprecationBehavior; DeprecationBehavior _deviceDeprecationBehavior = DeprecationBehavior.none; @override final String description = 'Run your Flutter app on an attached device.'; @override String get category => FlutterCommandCategory.project; List<Device>? devices; bool webMode = false; String? get userIdentifier => stringArg(FlutterOptions.kDeviceUser); @override bool get startPausedDefault => false; @override Future<String?> get usagePath async { final String? command = await super.usagePath; if (devices == null) { return command; } if (devices!.length > 1) { return '$command/all'; } return '$command/${getNameForTargetPlatform(await devices![0].targetPlatform)}'; } @override Future<CustomDimensions> get usageValues async { final AnalyticsUsageValuesRecord record = await _sharedAnalyticsUsageValues; return CustomDimensions( commandRunIsEmulator: record.runIsEmulator, commandRunTargetName: record.runTargetName, commandRunTargetOsVersion: record.runTargetOsVersion, commandRunModeName: record.runModeName, commandRunProjectModule: record.runProjectModule, commandRunProjectHostLanguage: record.runProjectHostLanguage, commandRunAndroidEmbeddingVersion: record.runAndroidEmbeddingVersion, commandRunEnableImpeller: record.runEnableImpeller, commandRunIOSInterfaceType: record.runIOSInterfaceType, commandRunIsTest: record.runIsTest, ); } @override Future<analytics.Event> unifiedAnalyticsUsageValues(String commandPath) async { final AnalyticsUsageValuesRecord record = await _sharedAnalyticsUsageValues; return analytics.Event.commandUsageValues( workflow: commandPath, commandHasTerminal: hasTerminal, runIsEmulator: record.runIsEmulator, runTargetName: record.runTargetName, runTargetOsVersion: record.runTargetOsVersion, runModeName: record.runModeName, runProjectModule: record.runProjectModule, runProjectHostLanguage: record.runProjectHostLanguage, runAndroidEmbeddingVersion: record.runAndroidEmbeddingVersion, runEnableImpeller: record.runEnableImpeller, runIOSInterfaceType: record.runIOSInterfaceType, runIsTest: record.runIsTest, ); } late final Future<AnalyticsUsageValuesRecord> _sharedAnalyticsUsageValues = (() async { String deviceType, deviceOsVersion; bool isEmulator; bool anyAndroidDevices = false; bool anyIOSDevices = false; bool anyWirelessIOSDevices = false; if (devices == null || devices!.isEmpty) { deviceType = 'none'; deviceOsVersion = 'none'; isEmulator = false; } else if (devices!.length == 1) { final Device device = devices![0]; final TargetPlatform platform = await device.targetPlatform; anyAndroidDevices = platform == TargetPlatform.android; anyIOSDevices = platform == TargetPlatform.ios; if (device is IOSDevice && device.isWirelesslyConnected) { anyWirelessIOSDevices = true; } deviceType = getNameForTargetPlatform(platform); deviceOsVersion = await device.sdkNameAndVersion; isEmulator = await device.isLocalEmulator; } else { deviceType = 'multiple'; deviceOsVersion = 'multiple'; isEmulator = false; for (final Device device in devices!) { final TargetPlatform platform = await device.targetPlatform; anyAndroidDevices = anyAndroidDevices || (platform == TargetPlatform.android); anyIOSDevices = anyIOSDevices || (platform == TargetPlatform.ios); if (device is IOSDevice && device.isWirelesslyConnected) { anyWirelessIOSDevices = true; } if (anyAndroidDevices && anyIOSDevices) { break; } } } String? iOSInterfaceType; if (anyIOSDevices) { iOSInterfaceType = anyWirelessIOSDevices ? 'wireless' : 'usb'; } String? androidEmbeddingVersion; final List<String> hostLanguage = <String>[]; if (anyAndroidDevices) { final AndroidProject androidProject = FlutterProject.current().android; if (androidProject.existsSync()) { hostLanguage.add(androidProject.isKotlin ? 'kotlin' : 'java'); androidEmbeddingVersion = androidProject.getEmbeddingVersion().toString().split('.').last; } } if (anyIOSDevices) { final IosProject iosProject = FlutterProject.current().ios; if (iosProject.exists) { final Iterable<File> swiftFiles = iosProject.hostAppRoot .listSync(recursive: true, followLinks: false) .whereType<File>() .where((File file) => globals.fs.path.extension(file.path) == '.swift'); hostLanguage.add(swiftFiles.isNotEmpty ? 'swift' : 'objc'); } } final BuildInfo buildInfo = await getBuildInfo(); final String modeName = buildInfo.modeName; return ( runIsEmulator: isEmulator, runTargetName: deviceType, runTargetOsVersion: deviceOsVersion, runModeName: modeName, runProjectModule: FlutterProject.current().isModule, runProjectHostLanguage: hostLanguage.join(','), runAndroidEmbeddingVersion: androidEmbeddingVersion, runEnableImpeller: enableImpeller.asBool, runIOSInterfaceType: iOSInterfaceType, runIsTest: targetFile.endsWith('_test.dart'), ); })(); @override bool get shouldRunPub { // If we are running with a prebuilt application, do not run pub. if (runningWithPrebuiltApplication) { return false; } return super.shouldRunPub; } bool shouldUseHotMode(BuildInfo buildInfo) { final bool hotArg = boolArg('hot'); final bool shouldUseHotMode = hotArg && !traceStartup; return buildInfo.isDebug && shouldUseHotMode; } bool get stayResident => boolArg('resident'); bool get awaitFirstFrameWhenTracing => boolArg('await-first-frame-when-tracing'); @override Future<void> validateCommand() async { // When running with a prebuilt application, no command validation is // necessary. if (!runningWithPrebuiltApplication) { await super.validateCommand(); } devices = await findAllTargetDevices(); if (devices == null) { throwToolExit(null); } if (devices!.length == 1 && devices!.first is MacOSDesignedForIPadDevice) { throwToolExit('Mac Designed for iPad is currently not supported for flutter run -d.'); } if (globals.deviceManager!.hasSpecifiedAllDevices) { devices?.removeWhere((Device device) => device is MacOSDesignedForIPadDevice); } if (globals.deviceManager!.hasSpecifiedAllDevices && runningWithPrebuiltApplication) { throwToolExit('Using "-d all" with "--${FlutterOptions.kUseApplicationBinary}" is not supported'); } if (userIdentifier != null && devices!.every((Device device) => device.platformType != PlatformType.android)) { throwToolExit( '--${FlutterOptions.kDeviceUser} is only supported for Android. At least one Android device is required.' ); } if (devices!.any((Device device) => device is AndroidDevice)) { _deviceDeprecationBehavior = DeprecationBehavior.exit; } // Only support "web mode" with a single web device due to resident runner // refactoring required otherwise. webMode = featureFlags.isWebEnabled && devices!.length == 1 && await devices!.single.targetPlatform == TargetPlatform.web_javascript; final String? flavor = stringArg('flavor'); final bool flavorsSupportedOnEveryDevice = devices! .every((Device device) => device.supportsFlavors); if (flavor != null && !flavorsSupportedOnEveryDevice) { globals.printWarning( '--flavor is only supported for Android, macOS, and iOS devices. ' 'Flavor-related features may not function properly and could ' 'behave differently in a future release.' ); } } @visibleForTesting Future<ResidentRunner> createRunner({ required bool hotMode, required List<FlutterDevice> flutterDevices, required String? applicationBinaryPath, required FlutterProject flutterProject, }) async { if (hotMode && !webMode) { return HotRunner( flutterDevices, target: targetFile, debuggingOptions: await createDebuggingOptions(webMode), benchmarkMode: boolArg('benchmark'), applicationBinary: applicationBinaryPath == null ? null : globals.fs.file(applicationBinaryPath), projectRootPath: stringArg('project-root'), dillOutputPath: stringArg('output-dill'), stayResident: stayResident, ipv6: ipv6 ?? false, analytics: globals.analytics, nativeAssetsYamlFile: stringArg(FlutterOptions.kNativeAssetsYamlFile), nativeAssetsBuilder: _nativeAssetsBuilder, ); } else if (webMode) { return webRunnerFactory!.createWebRunner( flutterDevices.single, target: targetFile, flutterProject: flutterProject, ipv6: ipv6, debuggingOptions: await createDebuggingOptions(webMode), stayResident: stayResident, fileSystem: globals.fs, usage: globals.flutterUsage, analytics: globals.analytics, logger: globals.logger, systemClock: globals.systemClock, ); } return ColdRunner( flutterDevices, target: targetFile, debuggingOptions: await createDebuggingOptions(webMode), traceStartup: traceStartup, awaitFirstFrameWhenTracing: awaitFirstFrameWhenTracing, applicationBinary: applicationBinaryPath == null ? null : globals.fs.file(applicationBinaryPath), ipv6: ipv6 ?? false, stayResident: stayResident, ); } @visibleForTesting Daemon createMachineDaemon() { final Daemon daemon = Daemon( DaemonConnection( daemonStreams: DaemonStreams.fromStdio(globals.stdio, logger: globals.logger), logger: globals.logger, ), notifyingLogger: (globals.logger is NotifyingLogger) ? globals.logger as NotifyingLogger : NotifyingLogger(verbose: globals.logger.isVerbose, parent: globals.logger), logToStdout: true, ); return daemon; } @override Future<FlutterCommandResult> runCommand() async { // Enable hot mode by default if `--no-hot` was not passed and we are in // debug mode. final BuildInfo buildInfo = await getBuildInfo(); final bool hotMode = shouldUseHotMode(buildInfo); final String? applicationBinaryPath = stringArg(FlutterOptions.kUseApplicationBinary); if (boolArg('machine')) { if (devices!.length > 1) { throwToolExit('"--machine" does not support "-d all".'); } final Daemon daemon = createMachineDaemon(); late AppInstance app; try { app = await daemon.appDomain.startApp( devices!.first, globals.fs.currentDirectory.path, targetFile, route, await createDebuggingOptions(webMode), hotMode, applicationBinary: applicationBinaryPath == null ? null : globals.fs.file(applicationBinaryPath), trackWidgetCreation: trackWidgetCreation, projectRootPath: stringArg('project-root'), packagesFilePath: globalResults![FlutterGlobalOptions.kPackagesOption] as String?, dillOutputPath: stringArg('output-dill'), ipv6: ipv6 ?? false, userIdentifier: userIdentifier, enableDevTools: boolArg(FlutterCommand.kEnableDevTools), nativeAssetsBuilder: _nativeAssetsBuilder, ); } on Exception catch (error) { throwToolExit(error.toString()); } final DateTime appStartedTime = globals.systemClock.now(); final int result = await app.runner!.waitForAppToFinish(); if (result != 0) { throwToolExit(null, exitCode: result); } return FlutterCommandResult( ExitStatus.success, timingLabelParts: <String>['daemon'], endTimeOverride: appStartedTime, ); } globals.terminal.usesTerminalUi = true; final BuildMode buildMode = getBuildMode(); for (final Device device in devices!) { if (!await device.supportsRuntimeMode(buildMode)) { throwToolExit( '${sentenceCase(getFriendlyModeName(buildMode))} ' 'mode is not supported by ${device.name}.', ); } if (hotMode) { if (!device.supportsHotReload) { throwToolExit('Hot reload is not supported by ${device.name}. Run with "--no-hot".'); } } } List<String>? expFlags; if (argParser.options.containsKey(FlutterOptions.kEnableExperiment) && stringsArg(FlutterOptions.kEnableExperiment).isNotEmpty) { expFlags = stringsArg(FlutterOptions.kEnableExperiment); } final FlutterProject flutterProject = FlutterProject.current(); final List<FlutterDevice> flutterDevices = <FlutterDevice>[ for (final Device device in devices!) await FlutterDevice.create( device, experimentalFlags: expFlags, target: targetFile, buildInfo: buildInfo, userIdentifier: userIdentifier, platform: globals.platform, ), ]; final ResidentRunner runner = await createRunner( applicationBinaryPath: applicationBinaryPath, flutterDevices: flutterDevices, flutterProject: flutterProject, hotMode: hotMode, ); DateTime? appStartedTime; // Sync completer so the completing agent attaching to the resident doesn't // need to know about analytics. // // Do not add more operations to the future. final Completer<void> appStartedTimeRecorder = Completer<void>.sync(); TerminalHandler? handler; // This callback can't throw. unawaited(appStartedTimeRecorder.future.then<void>( (_) { appStartedTime = globals.systemClock.now(); if (stayResident) { handler = TerminalHandler( runner, logger: globals.logger, terminal: globals.terminal, signals: globals.signals, processInfo: globals.processInfo, reportReady: boolArg('report-ready'), pidFile: stringArg('pid-file'), ) ..registerSignalHandlers() ..setupTerminal(); } } )); try { final int? result = await runner.run( appStartedCompleter: appStartedTimeRecorder, enableDevTools: stayResident && boolArg(FlutterCommand.kEnableDevTools), route: route, ); handler?.stop(); if (result != 0) { throwToolExit(null, exitCode: result); } } on RPCError catch (error) { if (error.code == RPCErrorCodes.kServiceDisappeared) { throwToolExit('Lost connection to device.'); } rethrow; } finally { // However we exited from the runner, ensure the terminal has line mode // and echo mode enabled before we return the user to the shell. try { globals.terminal.singleCharMode = false; } on StdinException { // Do nothing, if the STDIN handle is no longer available, there is nothing actionable for us to do at this point } } return FlutterCommandResult( ExitStatus.success, timingLabelParts: <String?>[ if (hotMode) 'hot' else 'cold', getBuildMode().cliName, if (devices!.length == 1) getNameForTargetPlatform(await devices![0].targetPlatform) else 'multiple', if (devices!.length == 1 && await devices![0].isLocalEmulator) 'emulator' else null, ], endTimeOverride: appStartedTime, ); } } /// Schema for the usage values to send for analytics reporting. typedef AnalyticsUsageValuesRecord = ({ String? runAndroidEmbeddingVersion, bool? runEnableImpeller, String? runIOSInterfaceType, bool runIsEmulator, bool runIsTest, String runModeName, String runProjectHostLanguage, bool runProjectModule, String runTargetName, String runTargetOsVersion, });
flutter/packages/flutter_tools/lib/src/commands/run.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/commands/run.dart", "repo_id": "flutter", "token_count": 13878 }
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:async'; import 'dart:math' as math; import 'package:process/process.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../base/terminal.dart'; import '../base/utils.dart'; import '../convert.dart'; /// An interface to the Dart analysis server. class AnalysisServer { AnalysisServer( this.sdkPath, this.directories, { required FileSystem fileSystem, required ProcessManager processManager, required Logger logger, required Platform platform, required Terminal terminal, required this.suppressAnalytics, String? protocolTrafficLog, }) : _fileSystem = fileSystem, _processManager = processManager, _logger = logger, _platform = platform, _terminal = terminal, _protocolTrafficLog = protocolTrafficLog; final String sdkPath; final List<String> directories; final FileSystem _fileSystem; final ProcessManager _processManager; final Logger _logger; final Platform _platform; final Terminal _terminal; final String? _protocolTrafficLog; final bool suppressAnalytics; Process? _process; final StreamController<bool> _analyzingController = StreamController<bool>.broadcast(); final StreamController<FileAnalysisErrors> _errorsController = StreamController<FileAnalysisErrors>.broadcast(); bool _didServerErrorOccur = false; int _id = 0; Future<void> start() async { final String snapshot = _fileSystem.path.join( sdkPath, 'bin', 'snapshots', 'analysis_server.dart.snapshot', ); final List<String> command = <String>[ _fileSystem.path.join(sdkPath, 'bin', 'dart'), '--disable-dart-dev', snapshot, '--disable-server-feature-completion', '--disable-server-feature-search', '--sdk', sdkPath, if (suppressAnalytics) '--suppress-analytics', if (_protocolTrafficLog != null) '--protocol-traffic-log=$_protocolTrafficLog', ]; _logger.printTrace('dart ${command.skip(1).join(' ')}'); _process = await _processManager.start(command); // This callback hookup can't throw. unawaited(_process!.exitCode.whenComplete(() => _process = null)); final Stream<String> errorStream = _process!.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()); errorStream.listen(_handleError); final Stream<String> inStream = _process!.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()); inStream.listen(_handleServerResponse); _sendCommand('server.setSubscriptions', <String, dynamic>{ 'subscriptions': <String>['STATUS'], }); _sendCommand('analysis.setAnalysisRoots', <String, dynamic>{'included': directories, 'excluded': <String>[]}); } final List<String> _logs = <String>[]; /// Aggregated STDOUT and STDERR logs from the server. /// /// This can be surfaced to the user if the server crashes. If [tail] is null, /// returns all logs, else only the last [tail] lines. String getLogs([int? tail]) { if (tail == null) { return _logs.join('\n'); } // Since List doesn't implement a .tail() method, we reverse it then use // .take() final Iterable<String> reversedLogs = _logs.reversed; final List<String> firstTailLogs = reversedLogs.take(tail).toList(); return firstTailLogs.reversed.join('\n'); } void _handleError(String message) { _logs.add('[stderr] $message'); _logger.printError(message); } bool get didServerErrorOccur => _didServerErrorOccur; Stream<bool> get onAnalyzing => _analyzingController.stream; Stream<FileAnalysisErrors> get onErrors => _errorsController.stream; Future<int?> get onExit async => _process?.exitCode; void _sendCommand(String method, Map<String, dynamic> params) { final String message = json.encode(<String, dynamic>{ 'id': (++_id).toString(), 'method': method, 'params': params, }); _process?.stdin.writeln(message); _logger.printTrace('==> $message'); } void _handleServerResponse(String line) { _logs.add('[stdout] $line'); _logger.printTrace('<== $line'); final dynamic response = json.decode(line); if (response is Map<String, dynamic>) { if (response['event'] != null) { final String event = response['event'] as String; final dynamic params = response['params']; Map<String, dynamic>? paramsMap; if (params is Map<String, dynamic>) { paramsMap = castStringKeyedMap(params); } if (paramsMap != null) { switch (event) { case 'server.status': _handleStatus(paramsMap); case 'analysis.errors': _handleAnalysisIssues(paramsMap); case 'server.error': _handleServerError(paramsMap); } } } else if (response['error'] != null) { // Fields are 'code', 'message', and 'stackTrace'. final Map<String, dynamic> error = castStringKeyedMap(response['error'])!; _logger.printError( 'Error response from the server: ${error['code']} ${error['message']}'); if (error['stackTrace'] != null) { _logger.printError(error['stackTrace'] as String); } } } } void _handleStatus(Map<String, dynamic> statusInfo) { // {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}} if (statusInfo['analysis'] != null && !_analyzingController.isClosed) { final bool isAnalyzing = (statusInfo['analysis'] as Map<String, dynamic>)['isAnalyzing'] as bool; _analyzingController.add(isAnalyzing); } } void _handleServerError(Map<String, dynamic> error) { // Fields are 'isFatal', 'message', and 'stackTrace'. _logger.printError('Error from the analysis server: ${error['message']}'); if (error['stackTrace'] != null) { _logger.printError(error['stackTrace'] as String); } _didServerErrorOccur = true; } void _handleAnalysisIssues(Map<String, dynamic> issueInfo) { // {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}} final String file = issueInfo['file'] as String; final List<dynamic> errorsList = issueInfo['errors'] as List<dynamic>; final List<AnalysisError> errors = errorsList .map<Map<String, dynamic>>((dynamic e) => castStringKeyedMap(e) ?? <String, dynamic>{}) .map<AnalysisError>((Map<String, dynamic> json) { return AnalysisError(WrittenError.fromJson(json), fileSystem: _fileSystem, platform: _platform, terminal: _terminal, ); }) .toList(); if (!_errorsController.isClosed) { _errorsController.add(FileAnalysisErrors(file, errors)); } } Future<bool?> dispose() async { await _analyzingController.close(); await _errorsController.close(); return _process?.kill(); } } enum AnalysisSeverity { error, warning, info, none, } /// [AnalysisError] with command line style. class AnalysisError implements Comparable<AnalysisError> { AnalysisError( this.writtenError, { required Platform platform, required Terminal terminal, required FileSystem fileSystem, }) : _platform = platform, _terminal = terminal, _fileSystem = fileSystem; final WrittenError writtenError; final Platform _platform; final Terminal _terminal; final FileSystem _fileSystem; String get _separator => _platform.isWindows ? '-' : '•'; String get colorSeverity { switch (writtenError.severityLevel) { case AnalysisSeverity.error: return _terminal.color(writtenError.severity, TerminalColor.red); case AnalysisSeverity.warning: return _terminal.color(writtenError.severity, TerminalColor.yellow); case AnalysisSeverity.info: case AnalysisSeverity.none: return writtenError.severity; } } String get type => writtenError.type; String get code => writtenError.code; @override int compareTo(AnalysisError other) { // Sort in order of file path, error location, severity, and message. if (writtenError.file != other.writtenError.file) { return writtenError.file.compareTo(other.writtenError.file); } if (writtenError.offset != other.writtenError.offset) { return writtenError.offset - other.writtenError.offset; } final int diff = other.writtenError.severityLevel.index - writtenError.severityLevel.index; if (diff != 0) { return diff; } return writtenError.message.compareTo(other.writtenError.message); } @override String toString() { // Can't use "padLeft" because of ANSI color sequences in the colorized // severity. final String padding = ' ' * math.max(0, 7 - writtenError.severity.length); return '$padding${colorSeverity.toLowerCase()} $_separator ' '${writtenError.messageSentenceFragment} $_separator ' '${_fileSystem.path.relative(writtenError.file)}:${writtenError.startLine}:${writtenError.startColumn} $_separator ' '$code'; } String toLegacyString() { return writtenError.toString(); } } /// [AnalysisError] in plain text content. class WrittenError { WrittenError._({ required this.severity, required this.type, required this.message, required this.code, required this.file, required this.startLine, required this.startColumn, required this.offset, }); /// { /// "severity":"INFO", /// "type":"TODO", /// "location":{ /// "file":"/Users/.../lib/test.dart", /// "offset":362, /// "length":72, /// "startLine":15, /// "startColumn":4 /// }, /// "message":"...", /// "hasFix":false /// } static WrittenError fromJson(Map<String, dynamic> json) { final Map<String, dynamic> location = json['location'] as Map<String, dynamic>; return WrittenError._( severity: json['severity'] as String, type: json['type'] as String, message: json['message'] as String, code: json['code'] as String, file: location['file'] as String, startLine: location['startLine'] as int, startColumn: location['startColumn'] as int, offset: location['offset'] as int, ); } final String severity; final String type; final String message; final String code; final String file; final int startLine; final int startColumn; final int offset; static final Map<String, AnalysisSeverity> _severityMap = <String, AnalysisSeverity>{ 'INFO': AnalysisSeverity.info, 'WARNING': AnalysisSeverity.warning, 'ERROR': AnalysisSeverity.error, }; AnalysisSeverity get severityLevel => _severityMap[severity] ?? AnalysisSeverity.none; String get messageSentenceFragment { if (message.endsWith('.')) { return message.substring(0, message.length - 1); } return message; } @override String toString() { return '[${severity.toLowerCase()}] $messageSentenceFragment ($file:$startLine:$startColumn)'; } } class FileAnalysisErrors { FileAnalysisErrors(this.file, this.errors); final String file; final List<AnalysisError> errors; }
flutter/packages/flutter_tools/lib/src/dart/analysis.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/dart/analysis.dart", "repo_id": "flutter", "token_count": 4231 }
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 'dart:async'; import 'dart:math' as math; import 'package:meta/meta.dart'; import 'application_package.dart'; import 'base/context.dart'; import 'base/dds.dart'; import 'base/file_system.dart'; import 'base/logger.dart'; import 'base/utils.dart'; import 'build_info.dart'; import 'devfs.dart'; import 'device_port_forwarder.dart'; import 'project.dart'; import 'vmservice.dart'; import 'web/compile.dart'; DeviceManager? get deviceManager => context.get<DeviceManager>(); /// A description of the kind of workflow the device supports. enum Category { web._('web'), desktop._('desktop'), mobile._('mobile'); const Category._(this.value); final String value; @override String toString() => value; static Category? fromString(String category) { return const <String, Category>{ 'web': web, 'desktop': desktop, 'mobile': mobile, }[category]; } } /// The platform sub-folder that a device type supports. enum PlatformType { web, android, ios, linux, macos, windows, fuchsia, custom, windowsPreview; @override String toString() => name; static PlatformType? fromString(String platformType) => values.asNameMap()[platformType]; } /// A discovery mechanism for flutter-supported development devices. abstract class DeviceManager { DeviceManager({ required Logger logger, }) : _logger = logger; final Logger _logger; /// Constructing DeviceManagers is cheap; they only do expensive work if some /// of their methods are called. List<DeviceDiscovery> get deviceDiscoverers; String? _specifiedDeviceId; /// A user-specified device ID. String? get specifiedDeviceId { if (_specifiedDeviceId == null || _specifiedDeviceId == 'all') { return null; } return _specifiedDeviceId; } set specifiedDeviceId(String? id) { _specifiedDeviceId = id; } /// A minimum duration to use when discovering wireless iOS devices. static const Duration minimumWirelessDeviceDiscoveryTimeout = Duration( seconds: 5, ); /// True when the user has specified a single specific device. bool get hasSpecifiedDeviceId => specifiedDeviceId != null; /// True when the user has specified all devices by setting /// specifiedDeviceId = 'all'. bool get hasSpecifiedAllDevices => _specifiedDeviceId == 'all'; /// Get devices filtered by [filter] that match the given device id/name. /// /// If [filter] is not provided, a default filter that requires devices to be /// connected will be used. /// /// If an exact match is found, return it immediately. Otherwise wait for all /// discoverers to complete and return any partial matches. Future<List<Device>> getDevicesById( String deviceId, { DeviceDiscoveryFilter? filter, }) async { filter ??= DeviceDiscoveryFilter(); final String lowerDeviceId = deviceId.toLowerCase(); bool exactlyMatchesDeviceId(Device device) => device.id.toLowerCase() == lowerDeviceId || device.name.toLowerCase() == lowerDeviceId; bool startsWithDeviceId(Device device) => device.id.toLowerCase().startsWith(lowerDeviceId) || device.name.toLowerCase().startsWith(lowerDeviceId); // Some discoverers have hard-coded device IDs and return quickly, and others // shell out to other processes and can take longer. // If an ID was specified, first check if it was a "well-known" device id. final Set<String> wellKnownIds = _platformDiscoverers .expand((DeviceDiscovery discovery) => discovery.wellKnownIds) .toSet(); final bool hasWellKnownId = hasSpecifiedDeviceId && wellKnownIds.contains(specifiedDeviceId); // Process discoverers as they can return results, so if an exact match is // found quickly, we don't wait for all the discoverers to complete. final List<Device> prefixMatches = <Device>[]; final Completer<Device> exactMatchCompleter = Completer<Device>(); final List<Future<List<Device>?>> futureDevices = <Future<List<Device>?>>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) if (!hasWellKnownId || discoverer.wellKnownIds.contains(specifiedDeviceId)) discoverer .devices(filter: filter) .then((List<Device> devices) { for (final Device device in devices) { if (exactlyMatchesDeviceId(device)) { exactMatchCompleter.complete(device); return null; } if (startsWithDeviceId(device)) { prefixMatches.add(device); } } return null; }, onError: (dynamic error, StackTrace stackTrace) { // Return matches from other discoverers even if one fails. _logger.printTrace('Ignored error discovering $deviceId: $error'); }), ]; // Wait for an exact match, or for all discoverers to return results. await Future.any<Object>(<Future<Object>>[ exactMatchCompleter.future, Future.wait<List<Device>?>(futureDevices), ]); if (exactMatchCompleter.isCompleted) { return <Device>[await exactMatchCompleter.future]; } return prefixMatches; } /// Returns a list of devices filtered by the user-specified device /// id/name (if applicable) and [filter]. /// /// If [filter] is not provided, a default filter that requires devices to be /// connected will be used. Future<List<Device>> getDevices({ DeviceDiscoveryFilter? filter, }) { filter ??= DeviceDiscoveryFilter(); final String? id = specifiedDeviceId; if (id == null) { return getAllDevices(filter: filter); } return getDevicesById(id, filter: filter); } Iterable<DeviceDiscovery> get _platformDiscoverers { return deviceDiscoverers.where((DeviceDiscovery discoverer) => discoverer.supportsPlatform); } /// Returns a list of devices filtered by [filter]. /// /// If [filter] is not provided, a default filter that requires devices to be /// connected will be used. Future<List<Device>> getAllDevices({ DeviceDiscoveryFilter? filter, }) async { filter ??= DeviceDiscoveryFilter(); final List<List<Device>> devices = await Future.wait<List<Device>>(<Future<List<Device>>>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) discoverer.devices(filter: filter), ]); return devices.expand<Device>((List<Device> deviceList) => deviceList).toList(); } /// Returns a list of devices filtered by [filter]. Discards existing cache of devices. /// /// If [filter] is not provided, a default filter that requires devices to be /// connected will be used. /// /// Search for devices to populate the cache for no longer than [timeout]. Future<List<Device>> refreshAllDevices({ Duration? timeout, DeviceDiscoveryFilter? filter, }) async { filter ??= DeviceDiscoveryFilter(); final List<List<Device>> devices = await Future.wait<List<Device>>(<Future<List<Device>>>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) discoverer.discoverDevices(filter: filter, timeout: timeout), ]); return devices.expand<Device>((List<Device> deviceList) => deviceList).toList(); } /// Discard existing cache of discoverers that are known to take longer to /// discover wireless devices. /// /// Then, search for devices for those discoverers to populate the cache for /// no longer than [timeout]. Future<void> refreshExtendedWirelessDeviceDiscoverers({ Duration? timeout, DeviceDiscoveryFilter? filter, }) async { await Future.wait<List<Device>>(<Future<List<Device>>>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) if (discoverer.requiresExtendedWirelessDeviceDiscovery) discoverer.discoverDevices(timeout: timeout) ]); } /// Whether we're capable of listing any devices given the current environment configuration. bool get canListAnything { return _platformDiscoverers.any((DeviceDiscovery discoverer) => discoverer.canListAnything); } /// Get diagnostics about issues with any connected devices. Future<List<String>> getDeviceDiagnostics() async { return <String>[ for (final DeviceDiscovery discoverer in _platformDiscoverers) ...await discoverer.getDiagnostics(), ]; } /// Determines how to filter devices. /// /// By default, filters to only include devices that are supported by Flutter. /// /// If the user has not specified a device, filters to only include devices /// that are supported by Flutter and supported by the project. /// /// If the user has specified `--device all`, filters to only include devices /// that are supported by Flutter, supported by the project, and supported for `all`. /// /// If [includeDevicesUnsupportedByProject] is true, all devices will be /// considered supported by the project, regardless of user specifications. /// /// This also exists to allow the check to be overridden for google3 clients. DeviceDiscoverySupportFilter deviceSupportFilter({ bool includeDevicesUnsupportedByProject = false, }) { FlutterProject? flutterProject; if (!includeDevicesUnsupportedByProject) { flutterProject = FlutterProject.current(); } if (hasSpecifiedAllDevices) { return DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProjectOrAll( flutterProject: flutterProject, ); } else if (!hasSpecifiedDeviceId) { return DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProject( flutterProject: flutterProject, ); } else { return DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutter(); } } /// If the user did not specify to run all or a specific device, then attempt /// to prioritize ephemeral devices. /// /// If there is not exactly one ephemeral device return null. /// /// For example, if the user only typed 'flutter run' and both an Android /// device and desktop device are available, choose the Android device. /// /// Note: ephemeral is nullable for device types where this is not well /// defined. Device? getSingleEphemeralDevice(List<Device> devices){ if (!hasSpecifiedDeviceId) { try { return devices.singleWhere((Device device) => device.ephemeral); } on StateError { return null; } } return null; } } /// A class for determining how to filter devices based on if they are supported. class DeviceDiscoverySupportFilter { /// Filter devices to only include those supported by Flutter. DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutter() : _excludeDevicesNotSupportedByProject = false, _excludeDevicesNotSupportedByAll = false, _flutterProject = null; /// Filter devices to only include those supported by Flutter and the /// provided [flutterProject]. /// /// If [flutterProject] is null, all devices will be considered supported by /// the project. DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProject({ required FlutterProject? flutterProject, }) : _flutterProject = flutterProject, _excludeDevicesNotSupportedByProject = true, _excludeDevicesNotSupportedByAll = false; /// Filter devices to only include those supported by Flutter, the provided /// [flutterProject], and `--device all`. /// /// If [flutterProject] is null, all devices will be considered supported by /// the project. DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutterOrProjectOrAll({ required FlutterProject? flutterProject, }) : _flutterProject = flutterProject, _excludeDevicesNotSupportedByProject = true, _excludeDevicesNotSupportedByAll = true; final FlutterProject? _flutterProject; final bool _excludeDevicesNotSupportedByProject; final bool _excludeDevicesNotSupportedByAll; Future<bool> matchesRequirements(Device device) async { final bool meetsSupportByFlutterRequirement = device.isSupported(); final bool meetsSupportForProjectRequirement = !_excludeDevicesNotSupportedByProject || isDeviceSupportedForProject(device); final bool meetsSupportForAllRequirement = !_excludeDevicesNotSupportedByAll || await isDeviceSupportedForAll(device); return meetsSupportByFlutterRequirement && meetsSupportForProjectRequirement && meetsSupportForAllRequirement; } /// User has specified `--device all`. /// /// Always remove web and fuchsia devices from `all`. This setting /// currently requires devices to share a frontend_server and resident /// runner instance. Both web and fuchsia require differently configured /// compilers, and web requires an entirely different resident runner. Future<bool> isDeviceSupportedForAll(Device device) async { final TargetPlatform devicePlatform = await device.targetPlatform; return device.isSupported() && devicePlatform != TargetPlatform.fuchsia_arm64 && devicePlatform != TargetPlatform.fuchsia_x64 && devicePlatform != TargetPlatform.web_javascript && isDeviceSupportedForProject(device); } /// Returns whether the device is supported for the project. /// /// A device can be supported by Flutter but not supported for the project /// (e.g. when the user has removed the iOS directory from their project). /// /// This also exists to allow the check to be overridden for google3 clients. If /// [_flutterProject] is null then return true. bool isDeviceSupportedForProject(Device device) { if (!device.isSupported()) { return false; } if (_flutterProject == null) { return true; } return device.isSupportedForProject(_flutterProject); } } /// A class for filtering devices. /// /// If [excludeDisconnected] is true, only devices detected as connected will be included. /// /// If [supportFilter] is provided, only devices matching the requirements will be included. /// /// If [deviceConnectionInterface] is provided, only devices matching the DeviceConnectionInterface will be included. class DeviceDiscoveryFilter { DeviceDiscoveryFilter({ this.excludeDisconnected = true, this.supportFilter, this.deviceConnectionInterface, }); final bool excludeDisconnected; final DeviceDiscoverySupportFilter? supportFilter; final DeviceConnectionInterface? deviceConnectionInterface; Future<bool> matchesRequirements(Device device) async { final DeviceDiscoverySupportFilter? localSupportFilter = supportFilter; final bool meetsConnectionRequirement = !excludeDisconnected || device.isConnected; final bool meetsSupportRequirements = localSupportFilter == null || (await localSupportFilter.matchesRequirements(device)); final bool meetsConnectionInterfaceRequirement = matchesDeviceConnectionInterface(device, deviceConnectionInterface); return meetsConnectionRequirement && meetsSupportRequirements && meetsConnectionInterfaceRequirement; } Future<List<Device>> filterDevices(List<Device> devices) async { devices = <Device>[ for (final Device device in devices) if (await matchesRequirements(device)) device, ]; return devices; } bool matchesDeviceConnectionInterface( Device device, DeviceConnectionInterface? deviceConnectionInterface, ) { if (deviceConnectionInterface == null) { return true; } return device.connectionInterface == deviceConnectionInterface; } } /// An abstract class to discover and enumerate a specific type of devices. abstract class DeviceDiscovery { bool get supportsPlatform; /// Whether this device discovery is capable of listing any devices given the /// current environment configuration. bool get canListAnything; /// Whether this device discovery is known to take longer to discover /// wireless devices. bool get requiresExtendedWirelessDeviceDiscovery => false; /// Return all connected devices, cached on subsequent calls. Future<List<Device>> devices({DeviceDiscoveryFilter? filter}); /// Return all connected devices. Discards existing cache of devices. Future<List<Device>> discoverDevices({ Duration? timeout, DeviceDiscoveryFilter? filter, }); /// Gets a list of diagnostic messages pertaining to issues with any connected /// devices (will be an empty list if there are no issues). Future<List<String>> getDiagnostics() => Future<List<String>>.value(<String>[]); /// Hard-coded device IDs that the discoverer can produce. /// /// These values are used by the device discovery to determine if it can /// short-circuit the other detectors if a specific ID is provided. If a /// discoverer has no valid fixed IDs, these should be left empty. /// /// For example, 'windows' or 'linux'. List<String> get wellKnownIds; } /// A [DeviceDiscovery] implementation that uses polling to discover device adds /// and removals. abstract class PollingDeviceDiscovery extends DeviceDiscovery { PollingDeviceDiscovery(this.name); static const Duration _pollingInterval = Duration(seconds: 4); static const Duration _pollingTimeout = Duration(seconds: 30); final String name; @protected @visibleForTesting ItemListNotifier<Device>? deviceNotifier; Timer? _timer; Future<List<Device>> pollingGetDevices({Duration? timeout}); void startPolling() { if (_timer == null) { deviceNotifier ??= ItemListNotifier<Device>(); // Make initial population the default, fast polling timeout. _timer = _initTimer(null, initialCall: true); } } Timer _initTimer(Duration? pollingTimeout, {bool initialCall = false}) { // Poll for devices immediately on the initial call for faster initial population. return Timer(initialCall ? Duration.zero : _pollingInterval, () async { try { final List<Device> devices = await pollingGetDevices(timeout: pollingTimeout); deviceNotifier!.updateWithNewList(devices); } on TimeoutException { // Do nothing on a timeout. } // Subsequent timeouts after initial population should wait longer. _timer = _initTimer(_pollingTimeout); }); } void stopPolling() { _timer?.cancel(); _timer = null; } /// Get devices from cache filtered by [filter]. /// /// If the cache is empty, populate the cache. /// /// If [filter] is null, it may return devices that are not connected. @override Future<List<Device>> devices({DeviceDiscoveryFilter? filter}) { return _populateDevices(filter: filter); } /// Empty the cache and repopulate it before getting devices from cache filtered by [filter]. /// /// Search for devices to populate the cache for no longer than [timeout]. /// /// If [filter] is null, it may return devices that are not connected. @override Future<List<Device>> discoverDevices({ Duration? timeout, DeviceDiscoveryFilter? filter, }) { return _populateDevices(timeout: timeout, filter: filter, resetCache: true); } /// Get devices from cache filtered by [filter]. /// /// If the cache is empty or [resetCache] is true, populate the cache. /// /// Search for devices to populate the cache for no longer than [timeout]. Future<List<Device>> _populateDevices({ Duration? timeout, DeviceDiscoveryFilter? filter, bool resetCache = false, }) async { if (deviceNotifier == null || resetCache) { final List<Device> devices = await pollingGetDevices(timeout: timeout); // If the cache was populated while the polling was ongoing, do not // overwrite the cache unless it's explicitly refreshing the cache. if (resetCache) { deviceNotifier = ItemListNotifier<Device>.from(devices); } else { deviceNotifier ??= ItemListNotifier<Device>.from(devices); } } // If a filter is provided, filter cache to only return devices matching. if (filter != null) { return filter.filterDevices(deviceNotifier!.items); } return deviceNotifier!.items; } Stream<Device> get onAdded { deviceNotifier ??= ItemListNotifier<Device>(); return deviceNotifier!.onAdded; } Stream<Device> get onRemoved { deviceNotifier ??= ItemListNotifier<Device>(); return deviceNotifier!.onRemoved; } void dispose() => stopPolling(); @override String toString() => '$name device discovery'; } /// How a device is connected. enum DeviceConnectionInterface { attached, wireless, } /// Returns the `DeviceConnectionInterface` enum based on its string name. DeviceConnectionInterface getDeviceConnectionInterfaceForName(String name) { switch (name) { case 'attached': return DeviceConnectionInterface.attached; case 'wireless': return DeviceConnectionInterface.wireless; } throw Exception('Unsupported DeviceConnectionInterface name "$name"'); } /// Returns a `DeviceConnectionInterface`'s string name. String getNameForDeviceConnectionInterface(DeviceConnectionInterface connectionInterface) { switch (connectionInterface) { case DeviceConnectionInterface.attached: return 'attached'; case DeviceConnectionInterface.wireless: return 'wireless'; } } /// A device is a physical hardware that can run a Flutter application. /// /// This may correspond to a connected iOS or Android device, or represent /// the host operating system in the case of Flutter Desktop. abstract class Device { Device(this.id, { required this.category, required this.platformType, required this.ephemeral, }); final String id; /// The [Category] for this device type. final Category? category; /// The [PlatformType] for this device. final PlatformType? platformType; /// Whether this is an ephemeral device. final bool ephemeral; bool get isConnected => true; DeviceConnectionInterface get connectionInterface => DeviceConnectionInterface.attached; bool get isWirelesslyConnected => connectionInterface == DeviceConnectionInterface.wireless; String get name; bool get supportsStartPaused => true; /// Whether it is an emulated device running on localhost. /// /// This may return `true` for certain physical Android devices, and is /// generally only a best effort guess. Future<bool> get isLocalEmulator; /// The unique identifier for the emulator that corresponds to this device, or /// null if it is not an emulator. /// /// The ID returned matches that in the output of `flutter emulators`. Fetching /// this name may require connecting to the device and if an error occurs null /// will be returned. Future<String?> get emulatorId; /// Whether this device can run the provided [buildMode]. /// /// For example, some emulator architectures cannot run profile or /// release builds. FutureOr<bool> supportsRuntimeMode(BuildMode buildMode) => true; /// Whether the device is a simulator on a platform which supports hardware rendering. // This is soft-deprecated since the logic is not correct expect for iOS simulators. Future<bool> get supportsHardwareRendering async { return true; } /// Whether the device is supported for the current project directory. bool isSupportedForProject(FlutterProject flutterProject); /// Check if a version of the given app is already installed. /// /// Specify [userIdentifier] to check if installed for a particular user (Android only). Future<bool> isAppInstalled( ApplicationPackage app, { String? userIdentifier, }); /// Check if the latest build of the [app] is already installed. Future<bool> isLatestBuildInstalled(ApplicationPackage app); /// Install an app package on the current device. /// /// Specify [userIdentifier] to install for a particular user (Android only). Future<bool> installApp( ApplicationPackage app, { String? userIdentifier, }); /// Uninstall an app package from the current device. /// /// Specify [userIdentifier] to uninstall for a particular user, /// defaults to all users (Android only). Future<bool> uninstallApp( ApplicationPackage app, { String? userIdentifier, }); /// Check if the device is supported by Flutter. bool isSupported(); // String meant to be displayed to the user indicating if the device is // supported by Flutter, and, if not, why. String supportMessage() => isSupported() ? 'Supported' : 'Unsupported'; /// The device's platform. Future<TargetPlatform> get targetPlatform; /// Platform name for display only. Future<String> get targetPlatformDisplayName async => getNameForTargetPlatform(await targetPlatform); Future<String> get sdkNameAndVersion; /// Create a platform-specific [DevFSWriter] for the given [app], or /// null if the device does not support them. /// /// For example, the desktop device classes can use a writer which /// copies the files across the local file system. DevFSWriter? createDevFSWriter( ApplicationPackage? app, String? userIdentifier, ) { return null; } /// Get a log reader for this device. /// /// If `app` is specified, this will return a log reader specific to that /// application. Otherwise, a global log reader will be returned. /// /// If `includePastLogs` is true and the device type supports it, the log /// reader will also include log messages from before the invocation time. /// Defaults to false. FutureOr<DeviceLogReader> getLogReader({ ApplicationPackage? app, bool includePastLogs = false, }); /// Get the port forwarder for this device. DevicePortForwarder? get portForwarder; /// Get the DDS instance for this device. final DartDevelopmentService dds = DartDevelopmentService(); /// Clear the device's logs. void clearLogs(); /// Start an app package on the current device. /// /// [platformArgs] allows callers to pass platform-specific arguments to the /// start call. The build mode is not used by all platforms. Future<LaunchResult> startApp( covariant ApplicationPackage? package, { String? mainPath, String? route, required DebuggingOptions debuggingOptions, Map<String, Object?> platformArgs, bool prebuiltApplication = false, bool ipv6 = false, String? userIdentifier, }); /// Whether this device implements support for hot reload. bool get supportsHotReload => true; /// Whether this device implements support for hot restart. bool get supportsHotRestart => true; /// Whether Flutter applications running on this device can be terminated /// from the VM Service. bool get supportsFlutterExit => true; /// Whether the device supports taking screenshots of a running flutter /// application. bool get supportsScreenshot => false; /// Whether the device supports the '--fast-start' development mode. bool get supportsFastStart => false; /// Whether the Flavors feature ('--flavor') is supported for this device. bool get supportsFlavors => false; /// Stop an app package on the current device. /// /// Specify [userIdentifier] to stop app installed to a profile (Android only). Future<bool> stopApp( ApplicationPackage? app, { String? userIdentifier, }); /// Query the current application memory usage.. /// /// If the device does not support this callback, an empty map /// is returned. Future<MemoryInfo> queryMemoryInfo() { return Future<MemoryInfo>.value(const MemoryInfo.empty()); } Future<void> takeScreenshot(File outputFile) => Future<void>.error('unimplemented'); @nonVirtual @override // ignore: avoid_equals_and_hash_code_on_mutable_classes int get hashCode => id.hashCode; @nonVirtual @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { if (identical(this, other)) { return true; } return other is Device && other.id == id; } @override String toString() => name; static Future<List<String>> descriptions(List<Device> devices) async { if (devices.isEmpty) { return const <String>[]; } // Extract device information final List<List<String>> table = <List<String>>[]; for (final Device device in devices) { String supportIndicator = device.isSupported() ? '' : ' (unsupported)'; final TargetPlatform targetPlatform = await device.targetPlatform; if (await device.isLocalEmulator) { final String type = targetPlatform == TargetPlatform.ios ? 'simulator' : 'emulator'; supportIndicator += ' ($type)'; } table.add(<String>[ '${device.name} (${device.category})', device.id, await device.targetPlatformDisplayName, '${await device.sdkNameAndVersion}$supportIndicator', ]); } // Calculate column widths final List<int> indices = List<int>.generate(table[0].length - 1, (int i) => i); List<int> widths = indices.map<int>((int i) => 0).toList(); for (final List<String> row in table) { widths = indices.map<int>((int i) => math.max(widths[i], row[i].length)).toList(); } // Join columns into lines of text return <String>[ for (final List<String> row in table) indices.map<String>((int i) => row[i].padRight(widths[i])).followedBy(<String>[row.last]).join(' • '), ]; } static Future<void> printDevices(List<Device> devices, Logger logger, { String prefix = '' }) async { for (final String line in await descriptions(devices)) { logger.printStatus('$prefix$line'); } } static List<String> devicesPlatformTypes(List<Device> devices) { return devices .map( (Device d) => d.platformType.toString(), ).toSet().toList()..sort(); } /// Convert the Device object to a JSON representation suitable for serialization. Future<Map<String, Object>> toJson() async { final bool isLocalEmu = await isLocalEmulator; return <String, Object>{ 'name': name, 'id': id, 'isSupported': isSupported(), 'targetPlatform': getNameForTargetPlatform(await targetPlatform), 'emulator': isLocalEmu, 'sdk': await sdkNameAndVersion, 'capabilities': <String, Object>{ 'hotReload': supportsHotReload, 'hotRestart': supportsHotRestart, 'screenshot': supportsScreenshot, 'fastStart': supportsFastStart, 'flutterExit': supportsFlutterExit, 'hardwareRendering': isLocalEmu && await supportsHardwareRendering, 'startPaused': supportsStartPaused, }, }; } /// Clean up resources allocated by device. /// /// For example log readers or port forwarders. Future<void> dispose(); } /// Information about an application's memory usage. abstract class MemoryInfo { /// Const constructor to allow subclasses to be const. const MemoryInfo(); /// Create a [MemoryInfo] object with no information. const factory MemoryInfo.empty() = _NoMemoryInfo; /// Convert the object to a JSON representation suitable for serialization. Map<String, Object> toJson(); } class _NoMemoryInfo implements MemoryInfo { const _NoMemoryInfo(); @override Map<String, Object> toJson() => <String, Object>{}; } enum ImpellerStatus { platformDefault._(null), enabled._(true), disabled._(false); const ImpellerStatus._(this.asBool); factory ImpellerStatus.fromBool(bool? b) { if (b == null) { return platformDefault; } return b ? enabled : disabled; } final bool? asBool; } class DebuggingOptions { DebuggingOptions.enabled( this.buildInfo, { this.startPaused = false, this.disableServiceAuthCodes = false, this.enableDds = true, this.cacheStartupProfile = false, this.dartEntrypointArgs = const <String>[], this.dartFlags = '', this.enableSoftwareRendering = false, this.skiaDeterministicRendering = false, this.traceSkia = false, this.traceAllowlist, this.traceSkiaAllowlist, this.traceSystrace = false, this.traceToFile, this.endlessTraceBuffer = false, this.dumpSkpOnShaderCompilation = false, this.cacheSkSL = false, this.purgePersistentCache = false, this.useTestFonts = false, this.verboseSystemLogs = false, this.hostVmServicePort, this.disablePortPublication = false, this.deviceVmServicePort, this.ddsPort, this.devToolsServerAddress, this.hostname, this.port, this.tlsCertPath, this.tlsCertKeyPath, this.webEnableExposeUrl, this.webUseSseForDebugProxy = true, this.webUseSseForDebugBackend = true, this.webUseSseForInjectedClient = true, this.webRunHeadless = false, this.webBrowserDebugPort, this.webBrowserFlags = const <String>[], this.webEnableExpressionEvaluation = false, this.webHeaders = const <String, String>{}, this.webLaunchUrl, this.webRenderer = WebRendererMode.auto, this.vmserviceOutFile, this.fastStart = false, this.nullAssertions = false, this.nativeNullAssertions = false, this.enableImpeller = ImpellerStatus.platformDefault, this.enableVulkanValidation = false, this.uninstallFirst = false, this.serveObservatory = false, this.enableDartProfiling = true, this.enableEmbedderApi = false, this.usingCISystem = false, this.debugLogsDirectoryPath, }) : debuggingEnabled = true; DebuggingOptions.disabled(this.buildInfo, { this.dartEntrypointArgs = const <String>[], this.port, this.hostname, this.tlsCertPath, this.tlsCertKeyPath, this.webEnableExposeUrl, this.webUseSseForDebugProxy = true, this.webUseSseForDebugBackend = true, this.webUseSseForInjectedClient = true, this.webRunHeadless = false, this.webBrowserDebugPort, this.webBrowserFlags = const <String>[], this.webLaunchUrl, this.webHeaders = const <String, String>{}, this.webRenderer = WebRendererMode.auto, this.cacheSkSL = false, this.traceAllowlist, this.enableImpeller = ImpellerStatus.platformDefault, this.enableVulkanValidation = false, this.uninstallFirst = false, this.enableDartProfiling = true, this.enableEmbedderApi = false, this.usingCISystem = false, this.debugLogsDirectoryPath, }) : debuggingEnabled = false, useTestFonts = false, startPaused = false, dartFlags = '', disableServiceAuthCodes = false, enableDds = true, cacheStartupProfile = false, enableSoftwareRendering = false, skiaDeterministicRendering = false, traceSkia = false, traceSkiaAllowlist = null, traceSystrace = false, traceToFile = null, endlessTraceBuffer = false, dumpSkpOnShaderCompilation = false, purgePersistentCache = false, verboseSystemLogs = false, hostVmServicePort = null, disablePortPublication = false, deviceVmServicePort = null, ddsPort = null, devToolsServerAddress = null, vmserviceOutFile = null, fastStart = false, webEnableExpressionEvaluation = false, nullAssertions = false, nativeNullAssertions = false, serveObservatory = false; DebuggingOptions._({ required this.buildInfo, required this.debuggingEnabled, required this.startPaused, required this.dartFlags, required this.dartEntrypointArgs, required this.disableServiceAuthCodes, required this.enableDds, required this.cacheStartupProfile, required this.enableSoftwareRendering, required this.skiaDeterministicRendering, required this.traceSkia, required this.traceAllowlist, required this.traceSkiaAllowlist, required this.traceSystrace, required this.traceToFile, required this.endlessTraceBuffer, required this.dumpSkpOnShaderCompilation, required this.cacheSkSL, required this.purgePersistentCache, required this.useTestFonts, required this.verboseSystemLogs, required this.hostVmServicePort, required this.deviceVmServicePort, required this.disablePortPublication, required this.ddsPort, required this.devToolsServerAddress, required this.port, required this.hostname, required this.tlsCertPath, required this.tlsCertKeyPath, required this.webEnableExposeUrl, required this.webUseSseForDebugProxy, required this.webUseSseForDebugBackend, required this.webUseSseForInjectedClient, required this.webRunHeadless, required this.webBrowserDebugPort, required this.webBrowserFlags, required this.webEnableExpressionEvaluation, required this.webHeaders, required this.webLaunchUrl, required this.webRenderer, required this.vmserviceOutFile, required this.fastStart, required this.nullAssertions, required this.nativeNullAssertions, required this.enableImpeller, required this.enableVulkanValidation, required this.uninstallFirst, required this.serveObservatory, required this.enableDartProfiling, required this.enableEmbedderApi, required this.usingCISystem, required this.debugLogsDirectoryPath, }); final bool debuggingEnabled; final BuildInfo buildInfo; final bool startPaused; final String dartFlags; final List<String> dartEntrypointArgs; final bool disableServiceAuthCodes; final bool enableDds; final bool cacheStartupProfile; final bool enableSoftwareRendering; final bool skiaDeterministicRendering; final bool traceSkia; final String? traceAllowlist; final String? traceSkiaAllowlist; final bool traceSystrace; final String? traceToFile; final bool endlessTraceBuffer; final bool dumpSkpOnShaderCompilation; final bool cacheSkSL; final bool purgePersistentCache; final bool useTestFonts; final bool verboseSystemLogs; final int? hostVmServicePort; final int? deviceVmServicePort; final bool disablePortPublication; final int? ddsPort; final Uri? devToolsServerAddress; final String? port; final String? hostname; final String? tlsCertPath; final String? tlsCertKeyPath; final bool? webEnableExposeUrl; final bool webUseSseForDebugProxy; final bool webUseSseForDebugBackend; final bool webUseSseForInjectedClient; final ImpellerStatus enableImpeller; final bool enableVulkanValidation; final bool serveObservatory; final bool enableDartProfiling; final bool enableEmbedderApi; final bool usingCISystem; final String? debugLogsDirectoryPath; /// Whether the tool should try to uninstall a previously installed version of the app. /// /// This is not implemented for every platform. final bool uninstallFirst; /// Whether to run the browser in headless mode. /// /// Some CI environments do not provide a display and fail to launch the /// browser with full graphics stack. Some browsers provide a special /// "headless" mode that runs the browser with no graphics. final bool webRunHeadless; /// The port the browser should use for its debugging protocol. final int? webBrowserDebugPort; /// Arbitrary browser flags. final List<String> webBrowserFlags; /// Enable expression evaluation for web target. final bool webEnableExpressionEvaluation; /// Allow developers to customize the browser's launch URL final String? webLaunchUrl; /// Allow developers to add custom headers to web server final Map<String, String> webHeaders; /// Which web renderer to use for the debugging session final WebRendererMode webRenderer; /// A file where the VM Service URL should be written after the application is started. final String? vmserviceOutFile; final bool fastStart; final bool nullAssertions; /// Additional null runtime checks inserted for web applications. /// /// See also: /// * https://github.com/dart-lang/sdk/blob/main/sdk/lib/html/doc/NATIVE_NULL_ASSERTIONS.md final bool nativeNullAssertions; List<String> getIOSLaunchArguments( EnvironmentType environmentType, String? route, Map<String, Object?> platformArgs, { bool ipv6 = false, DeviceConnectionInterface interfaceType = DeviceConnectionInterface.attached, bool isCoreDevice = false, }) { final String dartVmFlags = computeDartVmFlags(this); return <String>[ if (enableDartProfiling) '--enable-dart-profiling', if (disableServiceAuthCodes) '--disable-service-auth-codes', if (disablePortPublication) '--disable-vm-service-publication', if (startPaused) '--start-paused', // Wrap dart flags in quotes for physical devices if (environmentType == EnvironmentType.physical && dartVmFlags.isNotEmpty) '--dart-flags="$dartVmFlags"', if (environmentType == EnvironmentType.simulator && dartVmFlags.isNotEmpty) '--dart-flags=$dartVmFlags', if (useTestFonts) '--use-test-fonts', // Core Devices (iOS 17 devices) are debugged through Xcode so don't // include these flags, which are used to check if the app was launched // via Flutter CLI and `ios-deploy`. if (debuggingEnabled && !isCoreDevice) ...<String>[ '--enable-checked-mode', '--verify-entry-points', ], if (enableSoftwareRendering) '--enable-software-rendering', if (traceSystrace) '--trace-systrace', if (traceToFile != null) '--trace-to-file="$traceToFile"', if (skiaDeterministicRendering) '--skia-deterministic-rendering', if (traceSkia) '--trace-skia', if (traceAllowlist != null) '--trace-allowlist="$traceAllowlist"', if (traceSkiaAllowlist != null) '--trace-skia-allowlist="$traceSkiaAllowlist"', if (endlessTraceBuffer) '--endless-trace-buffer', if (dumpSkpOnShaderCompilation) '--dump-skp-on-shader-compilation', if (verboseSystemLogs) '--verbose-logging', if (cacheSkSL) '--cache-sksl', if (purgePersistentCache) '--purge-persistent-cache', if (route != null) '--route=$route', if (platformArgs['trace-startup'] as bool? ?? false) '--trace-startup', if (enableImpeller == ImpellerStatus.enabled) '--enable-impeller=true', if (enableImpeller == ImpellerStatus.disabled) '--enable-impeller=false', if (environmentType == EnvironmentType.physical && deviceVmServicePort != null) '--vm-service-port=$deviceVmServicePort', // The simulator "device" is actually on the host machine so no ports will be forwarded. // Use the suggested host port. if (environmentType == EnvironmentType.simulator && hostVmServicePort != null) '--vm-service-port=$hostVmServicePort', // Tell the VM service to listen on all interfaces, don't restrict to the loopback. if (interfaceType == DeviceConnectionInterface.wireless) '--vm-service-host=${ipv6 ? '::0' : '0.0.0.0'}', if (enableEmbedderApi) '--enable-embedder-api', ]; } Map<String, Object?> toJson() => <String, Object?>{ 'debuggingEnabled': debuggingEnabled, 'startPaused': startPaused, 'dartFlags': dartFlags, 'dartEntrypointArgs': dartEntrypointArgs, 'disableServiceAuthCodes': disableServiceAuthCodes, 'enableDds': enableDds, 'cacheStartupProfile': cacheStartupProfile, 'enableSoftwareRendering': enableSoftwareRendering, 'skiaDeterministicRendering': skiaDeterministicRendering, 'traceSkia': traceSkia, 'traceAllowlist': traceAllowlist, 'traceSkiaAllowlist': traceSkiaAllowlist, 'traceSystrace': traceSystrace, 'traceToFile': traceToFile, 'endlessTraceBuffer': endlessTraceBuffer, 'dumpSkpOnShaderCompilation': dumpSkpOnShaderCompilation, 'cacheSkSL': cacheSkSL, 'purgePersistentCache': purgePersistentCache, 'useTestFonts': useTestFonts, 'verboseSystemLogs': verboseSystemLogs, 'hostVmServicePort': hostVmServicePort, 'deviceVmServicePort': deviceVmServicePort, 'disablePortPublication': disablePortPublication, 'ddsPort': ddsPort, 'devToolsServerAddress': devToolsServerAddress.toString(), 'port': port, 'hostname': hostname, 'tlsCertPath': tlsCertPath, 'tlsCertKeyPath': tlsCertKeyPath, 'webEnableExposeUrl': webEnableExposeUrl, 'webUseSseForDebugProxy': webUseSseForDebugProxy, 'webUseSseForDebugBackend': webUseSseForDebugBackend, 'webUseSseForInjectedClient': webUseSseForInjectedClient, 'webRunHeadless': webRunHeadless, 'webBrowserDebugPort': webBrowserDebugPort, 'webBrowserFlags': webBrowserFlags, 'webEnableExpressionEvaluation': webEnableExpressionEvaluation, 'webLaunchUrl': webLaunchUrl, 'webHeaders': webHeaders, 'webRenderer': webRenderer.name, 'vmserviceOutFile': vmserviceOutFile, 'fastStart': fastStart, 'nullAssertions': nullAssertions, 'nativeNullAssertions': nativeNullAssertions, 'enableImpeller': enableImpeller.asBool, 'enableVulkanValidation': enableVulkanValidation, 'serveObservatory': serveObservatory, 'enableDartProfiling': enableDartProfiling, 'enableEmbedderApi': enableEmbedderApi, 'usingCISystem': usingCISystem, 'debugLogsDirectoryPath': debugLogsDirectoryPath, }; static DebuggingOptions fromJson(Map<String, Object?> json, BuildInfo buildInfo) => DebuggingOptions._( buildInfo: buildInfo, debuggingEnabled: json['debuggingEnabled']! as bool, startPaused: json['startPaused']! as bool, dartFlags: json['dartFlags']! as String, dartEntrypointArgs: (json['dartEntrypointArgs']! as List<dynamic>).cast<String>(), disableServiceAuthCodes: json['disableServiceAuthCodes']! as bool, enableDds: json['enableDds']! as bool, cacheStartupProfile: json['cacheStartupProfile']! as bool, enableSoftwareRendering: json['enableSoftwareRendering']! as bool, skiaDeterministicRendering: json['skiaDeterministicRendering']! as bool, traceSkia: json['traceSkia']! as bool, traceAllowlist: json['traceAllowlist'] as String?, traceSkiaAllowlist: json['traceSkiaAllowlist'] as String?, traceSystrace: json['traceSystrace']! as bool, traceToFile: json['traceToFile'] as String?, endlessTraceBuffer: json['endlessTraceBuffer']! as bool, dumpSkpOnShaderCompilation: json['dumpSkpOnShaderCompilation']! as bool, cacheSkSL: json['cacheSkSL']! as bool, purgePersistentCache: json['purgePersistentCache']! as bool, useTestFonts: json['useTestFonts']! as bool, verboseSystemLogs: json['verboseSystemLogs']! as bool, hostVmServicePort: json['hostVmServicePort'] as int? , deviceVmServicePort: json['deviceVmServicePort'] as int?, disablePortPublication: json['disablePortPublication']! as bool, ddsPort: json['ddsPort'] as int?, devToolsServerAddress: json['devToolsServerAddress'] != null ? Uri.parse(json['devToolsServerAddress']! as String) : null, port: json['port'] as String?, hostname: json['hostname'] as String?, tlsCertPath: json['tlsCertPath'] as String?, tlsCertKeyPath: json['tlsCertKeyPath'] as String?, webEnableExposeUrl: json['webEnableExposeUrl'] as bool?, webUseSseForDebugProxy: json['webUseSseForDebugProxy']! as bool, webUseSseForDebugBackend: json['webUseSseForDebugBackend']! as bool, webUseSseForInjectedClient: json['webUseSseForInjectedClient']! as bool, webRunHeadless: json['webRunHeadless']! as bool, webBrowserDebugPort: json['webBrowserDebugPort'] as int?, webBrowserFlags: (json['webBrowserFlags']! as List<dynamic>).cast<String>(), webEnableExpressionEvaluation: json['webEnableExpressionEvaluation']! as bool, webHeaders: (json['webHeaders']! as Map<dynamic, dynamic>).cast<String, String>(), webLaunchUrl: json['webLaunchUrl'] as String?, webRenderer: WebRendererMode.values.byName(json['webRenderer']! as String), vmserviceOutFile: json['vmserviceOutFile'] as String?, fastStart: json['fastStart']! as bool, nullAssertions: json['nullAssertions']! as bool, nativeNullAssertions: json['nativeNullAssertions']! as bool, enableImpeller: ImpellerStatus.fromBool(json['enableImpeller'] as bool?), enableVulkanValidation: (json['enableVulkanValidation'] as bool?) ?? false, uninstallFirst: (json['uninstallFirst'] as bool?) ?? false, serveObservatory: (json['serveObservatory'] as bool?) ?? false, enableDartProfiling: (json['enableDartProfiling'] as bool?) ?? true, enableEmbedderApi: (json['enableEmbedderApi'] as bool?) ?? false, usingCISystem: (json['usingCISystem'] as bool?) ?? false, debugLogsDirectoryPath: json['debugLogsDirectoryPath'] as String?, ); } class LaunchResult { LaunchResult.succeeded({ Uri? vmServiceUri, Uri? observatoryUri }) : started = true, vmServiceUri = vmServiceUri ?? observatoryUri; LaunchResult.failed() : started = false, vmServiceUri = null; bool get hasVmService => vmServiceUri != null; final bool started; final Uri? vmServiceUri; @override String toString() { final StringBuffer buf = StringBuffer('started=$started'); if (vmServiceUri != null) { buf.write(', vmService=$vmServiceUri'); } return buf.toString(); } } /// Read the log for a particular device. abstract class DeviceLogReader { String get name; /// A broadcast stream where each element in the string is a line of log output. Stream<String> get logLines; /// Some logs can be obtained from a VM service stream. /// Set this after the VM services are connected. FlutterVmService? connectedVMService; @override String toString() => name; /// Process ID of the app on the device. int? appPid; // Clean up resources allocated by log reader e.g. subprocesses void dispose(); } /// Describes an app running on the device. class DiscoveredApp { DiscoveredApp(this.id, this.vmServicePort); final String id; final int vmServicePort; } // An empty device log reader class NoOpDeviceLogReader implements DeviceLogReader { NoOpDeviceLogReader(String? nameOrNull) : name = nameOrNull ?? ''; @override final String name; @override int? appPid; @override FlutterVmService? connectedVMService; @override Stream<String> get logLines => const Stream<String>.empty(); @override void dispose() { } } /// Append --null_assertions to any existing Dart VM flags if /// [debuggingOptions.nullAssertions] is true. String computeDartVmFlags(DebuggingOptions debuggingOptions) { return <String>[ if (debuggingOptions.dartFlags.isNotEmpty) debuggingOptions.dartFlags, if (debuggingOptions.nullAssertions) '--null_assertions', ].join(','); }
flutter/packages/flutter_tools/lib/src/device.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/device.dart", "repo_id": "flutter", "token_count": 16437 }
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 '../application_package.dart'; import '../base/file_system.dart'; import '../build_info.dart'; import '../globals.dart' as globals; import '../project.dart'; abstract class FuchsiaApp extends ApplicationPackage { FuchsiaApp({required String projectBundleId}) : super(id: projectBundleId); /// Creates a new [FuchsiaApp] from a fuchsia sub project. static FuchsiaApp? fromFuchsiaProject(FuchsiaProject project) { if (!project.existsSync()) { // If the project doesn't exist at all the current hint to run flutter // create is accurate. return null; } return BuildableFuchsiaApp( project: project, ); } /// Creates a new [FuchsiaApp] from an existing .far archive. /// /// [applicationBinary] is the path to the .far archive. static FuchsiaApp? fromPrebuiltApp(FileSystemEntity applicationBinary) { final FileSystemEntityType entityType = globals.fs.typeSync(applicationBinary.path); if (entityType != FileSystemEntityType.file) { globals.printError('File "${applicationBinary.path}" does not exist or is not a .far file. Use far archive.'); return null; } return PrebuiltFuchsiaApp( applicationPackage: applicationBinary, ); } @override String get displayName => id; /// The location of the 'far' archive containing the built app. File farArchive(BuildMode buildMode); } class PrebuiltFuchsiaApp extends FuchsiaApp implements PrebuiltApplicationPackage { PrebuiltFuchsiaApp({ required this.applicationPackage, }) : // TODO(zanderso): Extract the archive and extract the id from meta/package. super(projectBundleId: applicationPackage.path); @override File farArchive(BuildMode buildMode) => globals.fs.file(applicationPackage); @override String get name => applicationPackage.path; @override final FileSystemEntity applicationPackage; } class BuildableFuchsiaApp extends FuchsiaApp { BuildableFuchsiaApp({required this.project}) : super(projectBundleId: project.project.manifest.appName); final FuchsiaProject project; @override File farArchive(BuildMode buildMode) { // TODO(zanderso): Distinguish among build modes. final String outDir = getFuchsiaBuildDirectory(); final String pkgDir = globals.fs.path.join(outDir, 'pkg'); final String appName = project.project.manifest.appName; return globals.fs.file(globals.fs.path.join(pkgDir, '$appName-0.far')); } @override String get name => project.project.manifest.appName; }
flutter/packages/flutter_tools/lib/src/fuchsia/application_package.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/fuchsia/application_package.dart", "repo_id": "flutter", "token_count": 864 }
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 'dart:async'; import 'package:meta/meta.dart'; import 'package:process/process.dart'; import '../artifacts.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../base/process.dart'; import '../cache.dart'; import '../convert.dart'; import '../device.dart'; import 'code_signing.dart'; // Error message patterns from ios-deploy output const String noProvisioningProfileErrorOne = 'Error 0xe8008015'; const String noProvisioningProfileErrorTwo = 'Error 0xe8000067'; const String deviceLockedError = 'e80000e2'; const String deviceLockedErrorMessage = 'the device was not, or could not be, unlocked'; const String unknownAppLaunchError = 'Error 0xe8000022'; class IOSDeploy { IOSDeploy({ required Artifacts artifacts, required Cache cache, required Logger logger, required Platform platform, required ProcessManager processManager, }) : _platform = platform, _cache = cache, _processUtils = ProcessUtils(processManager: processManager, logger: logger), _logger = logger, _binaryPath = artifacts.getHostArtifact(HostArtifact.iosDeploy).path; final Cache _cache; final String _binaryPath; final Logger _logger; final Platform _platform; final ProcessUtils _processUtils; Map<String, String> get iosDeployEnv { // Push /usr/bin to the front of PATH to pick up default system python, package 'six'. // // ios-deploy transitively depends on LLDB.framework, which invokes a // Python script that uses package 'six'. LLDB.framework relies on the // python at the front of the path, which may not include package 'six'. // Ensure that we pick up the system install of python, which includes it. final Map<String, String> environment = Map<String, String>.of(_platform.environment); environment['PATH'] = '/usr/bin:${environment['PATH']}'; environment.addEntries(<MapEntry<String, String>>[_cache.dyLdLibEntry]); return environment; } /// Uninstalls the specified app bundle. /// /// Uses ios-deploy and returns the exit code. Future<int> uninstallApp({ required String deviceId, required String bundleId, }) async { final List<String> launchCommand = <String>[ _binaryPath, '--id', deviceId, '--uninstall_only', '--bundle_id', bundleId, ]; return _processUtils.stream( launchCommand, mapFunction: _monitorFailure, trace: true, environment: iosDeployEnv, ); } /// Installs the specified app bundle. /// /// Uses ios-deploy and returns the exit code. Future<int> installApp({ required String deviceId, required String bundlePath, required List<String>launchArguments, required DeviceConnectionInterface interfaceType, Directory? appDeltaDirectory, }) async { appDeltaDirectory?.createSync(recursive: true); final List<String> launchCommand = <String>[ _binaryPath, '--id', deviceId, '--bundle', bundlePath, if (appDeltaDirectory != null) ...<String>[ '--app_deltas', appDeltaDirectory.path, ], if (interfaceType != DeviceConnectionInterface.wireless) '--no-wifi', if (launchArguments.isNotEmpty) ...<String>[ '--args', launchArguments.join(' '), ], ]; return _processUtils.stream( launchCommand, mapFunction: _monitorFailure, trace: true, environment: iosDeployEnv, ); } /// Returns [IOSDeployDebugger] wrapping attached debugger logic. /// /// This method does not install the app. Call [IOSDeployDebugger.launchAndAttach()] /// to install and attach the debugger to the specified app bundle. IOSDeployDebugger prepareDebuggerForLaunch({ required String deviceId, required String bundlePath, required List<String> launchArguments, required DeviceConnectionInterface interfaceType, Directory? appDeltaDirectory, required bool uninstallFirst, bool skipInstall = false, }) { appDeltaDirectory?.createSync(recursive: true); // Interactive debug session to support sending the lldb detach command. final List<String> launchCommand = <String>[ 'script', '-t', '0', '/dev/null', _binaryPath, '--id', deviceId, '--bundle', bundlePath, if (appDeltaDirectory != null) ...<String>[ '--app_deltas', appDeltaDirectory.path, ], if (uninstallFirst) '--uninstall', if (skipInstall) '--noinstall', '--debug', if (interfaceType != DeviceConnectionInterface.wireless) '--no-wifi', if (launchArguments.isNotEmpty) ...<String>[ '--args', launchArguments.join(' '), ], ]; return IOSDeployDebugger( launchCommand: launchCommand, logger: _logger, processUtils: _processUtils, iosDeployEnv: iosDeployEnv, ); } /// Installs and then runs the specified app bundle. /// /// Uses ios-deploy and returns the exit code. Future<int> launchApp({ required String deviceId, required String bundlePath, required List<String> launchArguments, required DeviceConnectionInterface interfaceType, required bool uninstallFirst, Directory? appDeltaDirectory, }) async { appDeltaDirectory?.createSync(recursive: true); final List<String> launchCommand = <String>[ _binaryPath, '--id', deviceId, '--bundle', bundlePath, if (appDeltaDirectory != null) ...<String>[ '--app_deltas', appDeltaDirectory.path, ], if (interfaceType != DeviceConnectionInterface.wireless) '--no-wifi', if (uninstallFirst) '--uninstall', '--justlaunch', if (launchArguments.isNotEmpty) ...<String>[ '--args', launchArguments.join(' '), ], ]; return _processUtils.stream( launchCommand, mapFunction: _monitorFailure, trace: true, environment: iosDeployEnv, ); } Future<bool> isAppInstalled({ required String bundleId, required String deviceId, }) async { final List<String> launchCommand = <String>[ _binaryPath, '--id', deviceId, '--exists', '--timeout', // If the device is not connected, ios-deploy will wait forever. '10', '--bundle_id', bundleId, ]; final RunResult result = await _processUtils.run( launchCommand, environment: iosDeployEnv, ); // Device successfully connected, but app not installed. if (result.exitCode == 255) { _logger.printTrace('$bundleId not installed on $deviceId'); return false; } if (result.exitCode != 0) { _logger.printTrace('App install check failed: ${result.stderr}'); return false; } return true; } String _monitorFailure(String stdout) => _monitorIOSDeployFailure(stdout, _logger); } /// lldb attach state flow. enum _IOSDeployDebuggerState { detached, launching, attached, } /// Wrapper to launch app and attach the debugger with ios-deploy. class IOSDeployDebugger { IOSDeployDebugger({ required Logger logger, required ProcessUtils processUtils, required List<String> launchCommand, required Map<String, String> iosDeployEnv, }) : _processUtils = processUtils, _logger = logger, _launchCommand = launchCommand, _iosDeployEnv = iosDeployEnv, _debuggerState = _IOSDeployDebuggerState.detached; /// Create a [IOSDeployDebugger] for testing. /// /// Sets the command to "ios-deploy" and environment to an empty map. @visibleForTesting factory IOSDeployDebugger.test({ required ProcessManager processManager, Logger? logger, }) { final Logger debugLogger = logger ?? BufferLogger.test(); return IOSDeployDebugger( logger: debugLogger, processUtils: ProcessUtils(logger: debugLogger, processManager: processManager), launchCommand: <String>['ios-deploy'], iosDeployEnv: <String, String>{}, ); } final Logger _logger; final ProcessUtils _processUtils; final List<String> _launchCommand; final Map<String, String> _iosDeployEnv; Process? _iosDeployProcess; Stream<String> get logLines => _debuggerOutput.stream; final StreamController<String> _debuggerOutput = StreamController<String>.broadcast(); bool get debuggerAttached => _debuggerState == _IOSDeployDebuggerState.attached; _IOSDeployDebuggerState _debuggerState; @visibleForTesting String? symbolsDirectoryPath; // (lldb) platform select remote-'ios' --sysroot // https://github.com/ios-control/ios-deploy/blob/1.11.2-beta.1/src/ios-deploy/ios-deploy.m#L33 // This regex is to get the configurable lldb prompt. By default this prompt will be "lldb". static final RegExp _lldbPlatformSelect = RegExp(r"\s*platform select remote-'ios' --sysroot"); // (lldb) run // https://github.com/ios-control/ios-deploy/blob/1.11.2-beta.1/src/ios-deploy/ios-deploy.m#L51 static final RegExp _lldbProcessExit = RegExp(r'Process \d* exited with status ='); // (lldb) Process 6152 stopped static final RegExp _lldbProcessStopped = RegExp(r'Process \d* stopped'); // (lldb) Process 6152 detached static final RegExp _lldbProcessDetached = RegExp(r'Process \d* detached'); // (lldb) Process 6152 resuming static final RegExp _lldbProcessResuming = RegExp(r'Process \d+ resuming'); // Symbol Path: /Users/swarming/Library/Developer/Xcode/iOS DeviceSupport/16.2 (20C65) arm64e/Symbols static final RegExp _symbolsPathPattern = RegExp(r'.*Symbol Path: '); // Send signal to stop (pause) the app. Used before a backtrace dump. static const String _signalStop = 'process signal SIGSTOP'; static const String _signalStopError = 'Failed to send signal 17'; static const String _processResume = 'process continue'; static const String _processInterrupt = 'process interrupt'; // Print backtrace for all threads while app is stopped. static const String _backTraceAll = 'thread backtrace all'; /// If this is non-null, then the app process is paused and awaiting backtrace logging. /// /// The future should be completed once the backtraces are logged. Completer<void>? _processResumeCompleter; // Process 525 exited with status = -1 (0xffffffff) lost connection static final RegExp _lostConnectionPattern = RegExp(r'exited with status = -1 \(0xffffffff\) lost connection'); /// Whether ios-deploy received a message matching [_lostConnectionPattern], /// indicating that it lost connection to the device. bool get lostConnection => _lostConnection; bool _lostConnection = false; /// Launch the app on the device, and attach the debugger. /// /// Returns whether or not the debugger successfully attached. Future<bool> launchAndAttach() async { // Return when the debugger attaches, or the ios-deploy process exits. // (lldb) run // https://github.com/ios-control/ios-deploy/blob/1.11.2-beta.1/src/ios-deploy/ios-deploy.m#L51 RegExp lldbRun = RegExp(r'\(lldb\)\s*run'); final Completer<bool> debuggerCompleter = Completer<bool>(); bool receivedLogs = false; try { _iosDeployProcess = await _processUtils.start( _launchCommand, environment: _iosDeployEnv, ); String? lastLineFromDebugger; final StreamSubscription<String> stdoutSubscription = _iosDeployProcess!.stdout .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { _monitorIOSDeployFailure(line, _logger); // (lldb) platform select remote-'ios' --sysroot // Use the configurable custom lldb prompt in the regex. The developer can set this prompt to anything. // For example `settings set prompt "(mylldb)"` in ~/.lldbinit results in: // "(mylldb) platform select remote-'ios' --sysroot" if (_lldbPlatformSelect.hasMatch(line)) { final String platformSelect = _lldbPlatformSelect.stringMatch(line) ?? ''; if (platformSelect.isEmpty) { return; } final int promptEndIndex = line.indexOf(platformSelect); if (promptEndIndex == -1) { return; } final String prompt = line.substring(0, promptEndIndex); lldbRun = RegExp(RegExp.escape(prompt) + r'\s*run'); _logger.printTrace(line); return; } // Symbol Path: /Users/swarming/Library/Developer/Xcode/iOS DeviceSupport/16.2 (20C65) arm64e/Symbols if (_symbolsPathPattern.hasMatch(line)) { _logger.printTrace('Detected path to iOS debug symbols: "$line"'); final String prefix = _symbolsPathPattern.stringMatch(line) ?? ''; if (prefix.isEmpty) { return; } symbolsDirectoryPath = line.substring(prefix.length); return; } // (lldb) run // success // 2020-09-15 13:42:25.185474-0700 Runner[477:181141] flutter: The Dart VM service is listening on http://127.0.0.1:57782/ if (lldbRun.hasMatch(line)) { _logger.printTrace(line); _debuggerState = _IOSDeployDebuggerState.launching; return; } // Next line after "run" must be "success", or the attach failed. // Example: "error: process launch failed" if (_debuggerState == _IOSDeployDebuggerState.launching) { _logger.printTrace(line); final bool attachSuccess = line == 'success'; _debuggerState = attachSuccess ? _IOSDeployDebuggerState.attached : _IOSDeployDebuggerState.detached; if (!debuggerCompleter.isCompleted) { debuggerCompleter.complete(attachSuccess); } return; } // (lldb) process signal SIGSTOP // or // process signal SIGSTOP if (line.contains(_signalStop)) { // The app is about to be stopped. Only show in verbose mode. _logger.printTrace(line); return; } // error: Failed to send signal 17: failed to send signal 17 if (line.contains(_signalStopError)) { // The stop signal failed, force exit. exit(); return; } if (line == _backTraceAll) { // The app is stopped and the backtrace for all threads will be printed. _logger.printTrace(line); // Even though we're not "detached", just stopped, mark as detached so the backtrace // is only show in verbose. _debuggerState = _IOSDeployDebuggerState.detached; // If we paused the app and are waiting to resume it, complete the completer final Completer<void>? processResumeCompleter = _processResumeCompleter; if (processResumeCompleter != null) { _processResumeCompleter = null; processResumeCompleter.complete(); } return; } if (line.contains('PROCESS_STOPPED') || _lldbProcessStopped.hasMatch(line)) { // The app has been stopped. Dump the backtrace, and detach. _logger.printTrace(line); _iosDeployProcess?.stdin.writeln(_backTraceAll); if (_processResumeCompleter == null) { detach(); } return; } if (line.contains('PROCESS_EXITED') || _lldbProcessExit.hasMatch(line)) { // The app exited or crashed, so exit. Continue passing debugging // messages to the log reader until it exits to capture crash dumps. _logger.printTrace(line); if (line.contains(_lostConnectionPattern)) { _lostConnection = true; } exit(); return; } if (_lldbProcessDetached.hasMatch(line)) { // The debugger has detached from the app, and there will be no more debugging messages. // Kill the ios-deploy process. _logger.printTrace(line); exit(); return; } if (_lldbProcessResuming.hasMatch(line)) { _logger.printTrace(line); // we marked this detached when we received [_backTraceAll] _debuggerState = _IOSDeployDebuggerState.attached; return; } if (_debuggerState != _IOSDeployDebuggerState.attached) { _logger.printTrace(line); return; } if (lastLineFromDebugger != null && lastLineFromDebugger!.isNotEmpty && line.isEmpty) { // The lldb console stream from ios-deploy is separated lines by an extra \r\n. // To avoid all lines being double spaced, if the last line from the // debugger was not an empty line, skip this empty line. // This will still cause "legit" logged newlines to be doubled... } else if (!_debuggerOutput.isClosed) { _debuggerOutput.add(line); // Sometimes the `ios-deploy` process does not return logs from the // application after attaching, such as the Dart VM url. In CI, // `idevicesyslog` is used as a fallback to get logs. Print a // message to indicate whether logs were received from `ios-deploy` // to help with debugging. if (!receivedLogs) { _logger.printTrace('Received logs from ios-deploy.'); receivedLogs = true; } } lastLineFromDebugger = line; }); final StreamSubscription<String> stderrSubscription = _iosDeployProcess!.stderr .transform<String>(utf8.decoder) .transform<String>(const LineSplitter()) .listen((String line) { _monitorIOSDeployFailure(line, _logger); _logger.printTrace(line); }); unawaited(_iosDeployProcess!.exitCode.then((int status) async { _logger.printTrace('ios-deploy exited with code $exitCode'); _debuggerState = _IOSDeployDebuggerState.detached; await stdoutSubscription.cancel(); await stderrSubscription.cancel(); }).whenComplete(() async { if (_debuggerOutput.hasListener) { // Tell listeners the process died. await _debuggerOutput.close(); } if (!debuggerCompleter.isCompleted) { debuggerCompleter.complete(false); } _iosDeployProcess = null; })); } on ProcessException catch (exception, stackTrace) { _logger.printTrace('ios-deploy failed: $exception'); _debuggerState = _IOSDeployDebuggerState.detached; if (!_debuggerOutput.isClosed) { _debuggerOutput.addError(exception, stackTrace); } } on ArgumentError catch (exception, stackTrace) { _logger.printTrace('ios-deploy failed: $exception'); _debuggerState = _IOSDeployDebuggerState.detached; if (!_debuggerOutput.isClosed) { _debuggerOutput.addError(exception, stackTrace); } } // Wait until the debugger attaches, or the attempt fails. return debuggerCompleter.future; } bool exit() { final bool success = (_iosDeployProcess == null) || _iosDeployProcess!.kill(); _iosDeployProcess = null; return success; } /// Pause app, dump backtrace for debugging, and resume. Future<void> pauseDumpBacktraceResume() async { if (!debuggerAttached) { return; } final Completer<void> completer = Completer<void>(); _processResumeCompleter = completer; try { // Stop the app, which will prompt the backtrace to be printed for all threads in the stdoutSubscription handler. _iosDeployProcess?.stdin.writeln(_processInterrupt); } on SocketException catch (error) { _logger.printTrace('Could not stop app from debugger: $error'); } // wait for backtrace to be dumped await completer.future; _iosDeployProcess?.stdin.writeln(_processResume); } /// Check what files are found in the device's iOS DeviceSupport directory. /// /// Expected files include Symbols (directory), Info.plist, and .finalized. /// /// If any of the expected files are missing or there are additional files /// (such as .copying_lock or .processing_lock), this may indicate the /// symbols may still be fetching or something went wrong when fetching them. /// /// Used for debugging test flakes: https://github.com/flutter/flutter/issues/121231 Future<void> checkForSymbolsFiles(FileSystem fileSystem) async { if (symbolsDirectoryPath == null) { _logger.printTrace('No path provided for Symbols directory.'); return; } final Directory symbolsDirectory = fileSystem.directory(symbolsDirectoryPath); if (!symbolsDirectory.existsSync()) { _logger.printTrace('Unable to find Symbols directory at $symbolsDirectoryPath'); return; } final Directory currentDeviceSupportDir = symbolsDirectory.parent; final List<FileSystemEntity> symbolStatusFiles = currentDeviceSupportDir.listSync(); _logger.printTrace('Symbol files:'); for (final FileSystemEntity file in symbolStatusFiles) { _logger.printTrace(' ${file.basename}'); } } Future<void> stopAndDumpBacktrace() async { if (!debuggerAttached) { return; } // Stop the app, which will prompt the backtrace to be printed for all // threads in the stdoutSubscription handler. await stdinWriteln( _signalStop, onError: (Object error, _) { _logger.printTrace('Could not stop the app: $error'); }, ); // Wait for logging to finish on process exit. return logLines.drain(); } Future<void>? _stdinWriteFuture; /// Queue write of [line] to STDIN of [_iosDeployProcess]. /// /// No-op if [_iosDeployProcess] is null. /// /// This write will not happen until the flush of any previous writes have /// completed, because calling [IOSink.flush()] before a previous flush has /// completed will throw a [StateError]. /// /// This method needs to keep track of the [_stdinWriteFuture] from previous /// calls because the future returned by [detach] is not always await-ed. Future<void> stdinWriteln(String line, {required void Function(Object, StackTrace) onError}) async { final Process? process = _iosDeployProcess; if (process == null) { return; } Future<void> writeln() { return ProcessUtils.writelnToStdinGuarded( stdin: process.stdin, line: line, onError: onError, ); } _stdinWriteFuture = _stdinWriteFuture?.then<void>((_) => writeln()) ?? writeln(); return _stdinWriteFuture; } Future<void> detach() async { if (!debuggerAttached) { return; } return stdinWriteln( 'process detach', onError: (Object error, _) { // Best effort, try to detach, but maybe the app already exited or already detached. _logger.printTrace('Could not detach from debugger: $error'); } ); } } // Maps stdout line stream. Must return original line. String _monitorIOSDeployFailure(String stdout, Logger logger) { // Installation issues. if (stdout.contains(noProvisioningProfileErrorOne) || stdout.contains(noProvisioningProfileErrorTwo)) { logger.printError(noProvisioningProfileInstruction, emphasis: true); // Launch issues. } else if (stdout.contains(deviceLockedError) || stdout.contains(deviceLockedErrorMessage)) { logger.printError(''' ═══════════════════════════════════════════════════════════════════════════════════ Your device is locked. Unlock your device first before running. ═══════════════════════════════════════════════════════════════════════════════════''', emphasis: true); } else if (stdout.contains(unknownAppLaunchError)) { logger.printError(''' ═══════════════════════════════════════════════════════════════════════════════════ Error launching app. Try launching from within Xcode via: open ios/Runner.xcworkspace Your Xcode version may be too old for your iOS version. ═══════════════════════════════════════════════════════════════════════════════════''', emphasis: true); } return stdout; }
flutter/packages/flutter_tools/lib/src/ios/ios_deploy.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/ios/ios_deploy.dart", "repo_id": "flutter", "token_count": 9205 }
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 '../application_package.dart'; import '../base/file_system.dart'; import '../build_info.dart'; import '../cmake.dart'; import '../cmake_project.dart'; import '../globals.dart' as globals; abstract class LinuxApp extends ApplicationPackage { LinuxApp({required String projectBundleId}) : super(id: projectBundleId); /// Creates a new [LinuxApp] from a linux sub project. factory LinuxApp.fromLinuxProject(LinuxProject project) { return BuildableLinuxApp( project: project, ); } /// Creates a new [LinuxApp] from an existing executable. /// /// `applicationBinary` is the path to the executable. factory LinuxApp.fromPrebuiltApp(FileSystemEntity applicationBinary) { return PrebuiltLinuxApp( executable: applicationBinary.path, ); } @override String get displayName => id; String executable(BuildMode buildMode); } class PrebuiltLinuxApp extends LinuxApp { PrebuiltLinuxApp({ required String executable, }) : _executable = executable, super(projectBundleId: executable); final String _executable; @override String executable(BuildMode buildMode) => _executable; @override String get name => _executable; } class BuildableLinuxApp extends LinuxApp { BuildableLinuxApp({required this.project}) : super(projectBundleId: project.parent.manifest.appName); final LinuxProject project; @override String executable(BuildMode buildMode) { final String? binaryName = getCmakeExecutableName(project); return globals.fs.path.join( getLinuxBuildDirectory(), buildMode.cliName, 'bundle', binaryName, ); } @override String get name => project.parent.manifest.appName; }
flutter/packages/flutter_tools/lib/src/linux/application_package.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/linux/application_package.dart", "repo_id": "flutter", "token_count": 593 }
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 'package:process/process.dart'; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/os.dart'; import '../base/platform.dart'; import '../build_info.dart'; import '../desktop_device.dart'; import '../device.dart'; import '../macos/application_package.dart'; import '../project.dart'; import 'build_macos.dart'; import 'macos_workflow.dart'; /// A device that represents a desktop MacOS target. class MacOSDevice extends DesktopDevice { MacOSDevice({ required ProcessManager processManager, required Logger logger, required FileSystem fileSystem, required OperatingSystemUtils operatingSystemUtils, }) : _processManager = processManager, _logger = logger, _operatingSystemUtils = operatingSystemUtils, super( 'macos', platformType: PlatformType.macos, ephemeral: false, processManager: processManager, logger: logger, fileSystem: fileSystem, operatingSystemUtils: operatingSystemUtils, ); final ProcessManager _processManager; final Logger _logger; final OperatingSystemUtils _operatingSystemUtils; @override bool isSupported() => true; @override String get name => 'macOS'; @override bool get supportsFlavors => true; @override Future<TargetPlatform> get targetPlatform async => TargetPlatform.darwin; @override Future<String> get targetPlatformDisplayName async { if (_operatingSystemUtils.hostPlatform == HostPlatform.darwin_arm64) { return 'darwin-arm64'; } return 'darwin-x64'; } @override bool isSupportedForProject(FlutterProject flutterProject) { return flutterProject.macos.existsSync(); } @override Future<void> buildForDevice({ required BuildInfo buildInfo, String? mainPath, }) async { await buildMacOS( flutterProject: FlutterProject.current(), buildInfo: buildInfo, targetOverride: mainPath, verboseLogging: _logger.isVerbose, ); } @override String? executablePathForDevice(covariant MacOSApp package, BuildInfo buildInfo) { return package.executable(buildInfo); } @override void onAttached(covariant MacOSApp package, BuildInfo buildInfo, Process process) { // Bring app to foreground. Ideally this would be done post-launch rather // than post-attach, since this won't run for release builds, but there's // no general-purpose way of knowing when a process is far enough along in // the launch process for 'open' to foreground it. final String? applicationBundle = package.applicationBundle(buildInfo); if (applicationBundle == null) { _logger.printError('Failed to foreground app; application bundle not found'); return; } _processManager.run(<String>[ 'open', applicationBundle, ]).then((ProcessResult result) { if (result.exitCode != 0) { _logger.printError('Failed to foreground app; open returned ${result.exitCode}'); } }); } } class MacOSDevices extends PollingDeviceDiscovery { MacOSDevices({ required Platform platform, required MacOSWorkflow macOSWorkflow, required ProcessManager processManager, required Logger logger, required FileSystem fileSystem, required OperatingSystemUtils operatingSystemUtils, }) : _logger = logger, _platform = platform, _macOSWorkflow = macOSWorkflow, _processManager = processManager, _fileSystem = fileSystem, _operatingSystemUtils = operatingSystemUtils, super('macOS devices'); final MacOSWorkflow _macOSWorkflow; final Platform _platform; final ProcessManager _processManager; final Logger _logger; final FileSystem _fileSystem; final OperatingSystemUtils _operatingSystemUtils; @override bool get supportsPlatform => _platform.isMacOS; @override bool get canListAnything => _macOSWorkflow.canListDevices; @override Future<List<Device>> pollingGetDevices({ Duration? timeout }) async { if (!canListAnything) { return const <Device>[]; } return <Device>[ MacOSDevice( processManager: _processManager, logger: _logger, fileSystem: _fileSystem, operatingSystemUtils: _operatingSystemUtils, ), ]; } @override Future<List<String>> getDiagnostics() async => const <String>[]; @override List<String> get wellKnownIds => const <String>['macos']; }
flutter/packages/flutter_tools/lib/src/macos/macos_device.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/macos/macos_device.dart", "repo_id": "flutter", "token_count": 1568 }
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 '../base/file_system.dart'; import '../base/project_migrator.dart'; import '../xcode_project.dart'; // Migrate Xcode Thin Binary build phase to depend on Info.plist from build directory // as an input file to ensure it has been created before inserting the NSBonjourServices key // to avoid an mDNS error. class XcodeThinBinaryBuildPhaseInputPathsMigration extends ProjectMigrator { XcodeThinBinaryBuildPhaseInputPathsMigration(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(); // Add Info.plist from build directory as an input file to Thin Binary build phase. // Path for the Info.plist is ${TARGET_BUILD_DIR}/\${INFOPLIST_PATH} // Example: // 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { // isa = PBXShellScriptBuildPhase; // alwaysOutOfDate = 1; // buildActionMask = 2147483647; // files = ( // ); // inputPaths = ( // ); String newProjectContents = originalProjectContents; const String thinBinaryBuildPhaseOriginal = ''' 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); '''; const String thinBinaryBuildPhaseReplacement = r''' 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); inputPaths = ( "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", ); '''; newProjectContents = newProjectContents.replaceAll(thinBinaryBuildPhaseOriginal, thinBinaryBuildPhaseReplacement); if (originalProjectContents != newProjectContents) { logger.printStatus('Adding input path to Thin Binary build phase.'); _xcodeProjectInfoFile.writeAsStringSync(newProjectContents); } } }
flutter/packages/flutter_tools/lib/src/migrations/xcode_thin_binary_build_phase_input_paths_migration.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/migrations/xcode_thin_binary_build_phase_input_paths_migration.dart", "repo_id": "flutter", "token_count": 828 }
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:file/file.dart'; import 'package:http/http.dart' as http; import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; import '../base/os.dart'; import '../base/platform.dart'; import '../doctor.dart'; import '../project.dart'; import 'github_template.dart'; import 'reporting.dart'; /// Tells crash backend that the error is from the Flutter CLI. const String _kProductId = 'Flutter_Tools'; /// Tells crash backend that this is a Dart error as opposed to, say, Java. const String _kDartTypeId = 'DartError'; /// Crash backend host. const String _kCrashServerHost = 'clients2.google.com'; /// Path to the crash servlet. const String _kCrashEndpointPath = '/cr/report'; /// The field corresponding to the multipart/form-data file attachment where /// crash backend expects to find the Dart stack trace. const String _kStackTraceFileField = 'DartError'; /// The name of the file attached as [_kStackTraceFileField]. /// /// The precise value is not important. It is ignored by the crash back end, but /// it must be supplied in the request. const String _kStackTraceFilename = 'stacktrace_file'; class CrashDetails { CrashDetails({ required this.command, required this.error, required this.stackTrace, required this.doctorText, }); final String command; final Object error; final StackTrace stackTrace; final DoctorText doctorText; } /// Reports information about the crash to the user. class CrashReporter { CrashReporter({ required FileSystem fileSystem, required Logger logger, required FlutterProjectFactory flutterProjectFactory, }) : _fileSystem = fileSystem, _logger = logger, _flutterProjectFactory = flutterProjectFactory; final FileSystem _fileSystem; final Logger _logger; final FlutterProjectFactory _flutterProjectFactory; /// Prints instructions for filing a bug about the crash. Future<void> informUser(CrashDetails details, File crashFile) async { _logger.printError('A crash report has been written to ${crashFile.path}'); _logger.printStatus('This crash may already be reported. Check GitHub for similar crashes.', emphasis: true); final String similarIssuesURL = GitHubTemplateCreator.toolCrashSimilarIssuesURL(details.error.toString()); _logger.printStatus('$similarIssuesURL\n', wrap: false); _logger.printStatus('To report your crash to the Flutter team, first read the guide to filing a bug.', emphasis: true); _logger.printStatus('https://flutter.dev/docs/resources/bug-reports\n', wrap: false); _logger.printStatus('Create a new GitHub issue by pasting this link into your browser and completing the issue template. Thank you!', emphasis: true); final GitHubTemplateCreator gitHubTemplateCreator = GitHubTemplateCreator( fileSystem: _fileSystem, logger: _logger, flutterProjectFactory: _flutterProjectFactory, ); final String gitHubTemplateURL = await gitHubTemplateCreator.toolCrashIssueTemplateGitHubURL( details.command, details.error, details.stackTrace, await details.doctorText.piiStrippedText, ); _logger.printStatus('$gitHubTemplateURL\n', wrap: false); } } /// Sends crash reports to Google. /// /// To override the behavior of this class, define a /// `FLUTTER_CRASH_SERVER_BASE_URL` environment variable that points to a custom /// crash reporting server. This is useful if your development environment is /// behind a firewall and unable to send crash reports to Google, or when you /// wish to use your own server for collecting crash reports from Flutter Tools. class CrashReportSender { CrashReportSender({ http.Client? client, required Usage usage, required Platform platform, required Logger logger, required OperatingSystemUtils operatingSystemUtils, }) : _client = client ?? http.Client(), _usage = usage, _platform = platform, _logger = logger, _operatingSystemUtils = operatingSystemUtils; final http.Client _client; final Usage _usage; final Platform _platform; final Logger _logger; final OperatingSystemUtils _operatingSystemUtils; bool _crashReportSent = false; Uri get _baseUrl { final String? overrideUrl = _platform.environment['FLUTTER_CRASH_SERVER_BASE_URL']; if (overrideUrl != null) { return Uri.parse(overrideUrl); } return Uri( scheme: 'https', host: _kCrashServerHost, port: 443, path: _kCrashEndpointPath, ); } /// Sends one crash report. /// /// The report is populated from data in [error] and [stackTrace]. Future<void> sendReport({ required Object error, required StackTrace stackTrace, required String Function() getFlutterVersion, required String command, }) async { // Only send one crash report per run. if (_crashReportSent) { return; } try { final String flutterVersion = getFlutterVersion(); // We don't need to report exceptions happening on user branches if (_usage.suppressAnalytics || RegExp(r'^\[user-branch\]\/').hasMatch(flutterVersion)) { return; } _logger.printTrace('Sending crash report to Google.'); final Uri uri = _baseUrl.replace( queryParameters: <String, String>{ 'product': _kProductId, 'version': flutterVersion, }, ); final http.MultipartRequest req = http.MultipartRequest('POST', uri); req.fields['uuid'] = _usage.clientId; req.fields['product'] = _kProductId; req.fields['version'] = flutterVersion; req.fields['osName'] = _platform.operatingSystem; req.fields['osVersion'] = _operatingSystemUtils.name; // this actually includes version req.fields['type'] = _kDartTypeId; req.fields['error_runtime_type'] = '${error.runtimeType}'; req.fields['error_message'] = '$error'; req.fields['comments'] = command; req.files.add(http.MultipartFile.fromString( _kStackTraceFileField, stackTrace.toString(), filename: _kStackTraceFilename, )); final http.StreamedResponse resp = await _client.send(req); if (resp.statusCode == HttpStatus.ok) { final String reportId = await http.ByteStream(resp.stream) .bytesToString(); _logger.printTrace('Crash report sent (report ID: $reportId)'); _crashReportSent = true; } else { _logger.printError('Failed to send crash report. Server responded with HTTP status code ${resp.statusCode}'); } // Catch all exceptions to print the message that makes clear that the // crash logger crashed. } catch (sendError, sendStackTrace) { // ignore: avoid_catches_without_on_clauses if (sendError is SocketException || sendError is HttpException || sendError is http.ClientException) { _logger.printError('Failed to send crash report due to a network error: $sendError'); } else { // If the sender itself crashes, just print. We did our best. _logger.printError('Crash report sender itself crashed: $sendError\n$sendStackTrace'); } } } }
flutter/packages/flutter_tools/lib/src/reporting/crash_reporting.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/reporting/crash_reporting.dart", "repo_id": "flutter", "token_count": 2449 }
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:meta/meta.dart'; import '../base/common.dart'; import '../base/logger.dart'; import '../base/platform.dart'; import '../base/terminal.dart'; import '../device.dart'; import '../globals.dart' as globals; import '../ios/devices.dart'; const String _checkingForWirelessDevicesMessage = 'Checking for wireless devices...'; const String _chooseOneMessage = 'Please choose one (or "q" to quit)'; const String _connectedDevicesMessage = 'Connected devices:'; const String _foundButUnsupportedDevicesMessage = 'The following devices were found, but are not supported by this project:'; const String _noAttachedCheckForWirelessMessage = 'No devices found yet. Checking for wireless devices...'; const String _noDevicesFoundMessage = 'No devices found.'; const String _noWirelessDevicesFoundMessage = 'No wireless devices were found.'; const String _wirelesslyConnectedDevicesMessage = 'Wirelessly connected devices:'; String _chooseDeviceOptionMessage(int option, String name, String deviceId) => '[$option]: $name ($deviceId)'; String _foundMultipleSpecifiedDevicesMessage(String deviceId) => 'Found multiple devices with name or id matching $deviceId:'; String _foundSpecifiedDevicesMessage(int count, String deviceId) => 'Found $count devices with name or id matching $deviceId:'; String _noMatchingDeviceMessage(String deviceId) => 'No supported devices found with name or id ' "matching '$deviceId'."; String flutterSpecifiedDeviceDevModeDisabled(String deviceName) => 'To use ' "'$deviceName' for development, enable Developer Mode in Settings → Privacy & Security."; String flutterSpecifiedDeviceUnpaired(String deviceName) => "'$deviceName' is not paired. " 'Open Xcode and trust this computer when prompted.'; /// This class handles functionality of finding and selecting target devices. /// /// Target devices are devices that are supported and selectable to run /// a flutter application on. class TargetDevices { factory TargetDevices({ required Platform platform, required DeviceManager deviceManager, required Logger logger, DeviceConnectionInterface? deviceConnectionInterface, }) { if (platform.isMacOS) { return TargetDevicesWithExtendedWirelessDeviceDiscovery( deviceManager: deviceManager, logger: logger, deviceConnectionInterface: deviceConnectionInterface, ); } return TargetDevices._private( deviceManager: deviceManager, logger: logger, deviceConnectionInterface: deviceConnectionInterface, ); } TargetDevices._private({ required DeviceManager deviceManager, required Logger logger, required this.deviceConnectionInterface, }) : _deviceManager = deviceManager, _logger = logger; final DeviceManager _deviceManager; final Logger _logger; final DeviceConnectionInterface? deviceConnectionInterface; bool get _includeAttachedDevices => deviceConnectionInterface == null || deviceConnectionInterface == DeviceConnectionInterface.attached; bool get _includeWirelessDevices => deviceConnectionInterface == null || deviceConnectionInterface == DeviceConnectionInterface.wireless; Future<List<Device>> _getAttachedDevices({ DeviceDiscoverySupportFilter? supportFilter, }) async { if (!_includeAttachedDevices) { return <Device>[]; } return _deviceManager.getDevices( filter: DeviceDiscoveryFilter( deviceConnectionInterface: DeviceConnectionInterface.attached, supportFilter: supportFilter, ), ); } Future<List<Device>> _getWirelessDevices({ DeviceDiscoverySupportFilter? supportFilter, }) async { if (!_includeWirelessDevices) { return <Device>[]; } return _deviceManager.getDevices( filter: DeviceDiscoveryFilter( deviceConnectionInterface: DeviceConnectionInterface.wireless, supportFilter: supportFilter, ), ); } Future<List<Device>> _getDeviceById({ bool includeDevicesUnsupportedByProject = false, bool includeDisconnected = false, }) async { return _deviceManager.getDevices( filter: DeviceDiscoveryFilter( excludeDisconnected: !includeDisconnected, supportFilter: _deviceManager.deviceSupportFilter( includeDevicesUnsupportedByProject: includeDevicesUnsupportedByProject, ), deviceConnectionInterface: deviceConnectionInterface, ), ); } DeviceDiscoverySupportFilter _defaultSupportFilter( bool includeDevicesUnsupportedByProject, ) { return _deviceManager.deviceSupportFilter( includeDevicesUnsupportedByProject: includeDevicesUnsupportedByProject, ); } void startExtendedWirelessDeviceDiscovery({ Duration? deviceDiscoveryTimeout, }) {} /// Find and return all target [Device]s based upon criteria entered by the /// user on the command line. /// /// When the user has specified `all` devices, return all devices meeting criteria. /// /// When the user has specified a device id/name, attempt to find an exact or /// partial match. If an exact match or a single partial match is found, /// return it immediately. /// /// When multiple devices are found and there is a terminal attached to /// stdin, allow the user to select which device to use. When a terminal /// with stdin is not available, print a list of available devices and /// return null. /// /// When no devices meet user specifications, print a list of unsupported /// devices and return null. Future<List<Device>?> findAllTargetDevices({ Duration? deviceDiscoveryTimeout, bool includeDevicesUnsupportedByProject = false, }) async { if (!globals.doctor!.canLaunchAnything) { _logger.printError(globals.userMessages.flutterNoDevelopmentDevice); return null; } if (deviceDiscoveryTimeout != null) { // Reset the cache with the specified timeout. await _deviceManager.refreshAllDevices(timeout: deviceDiscoveryTimeout); } if (_deviceManager.hasSpecifiedDeviceId) { // Must check for device match separately from `_getAttachedDevices` and // `_getWirelessDevices` because if an exact match is found in one // and a partial match is found in another, there is no way to distinguish // between them. final List<Device> devices = await _getDeviceById( includeDevicesUnsupportedByProject: includeDevicesUnsupportedByProject, ); if (devices.length == 1) { return devices; } } final List<Device> attachedDevices = await _getAttachedDevices( supportFilter: _defaultSupportFilter(includeDevicesUnsupportedByProject), ); final List<Device> wirelessDevices = await _getWirelessDevices( supportFilter: _defaultSupportFilter(includeDevicesUnsupportedByProject), ); final List<Device> allDevices = attachedDevices + wirelessDevices; if (allDevices.isEmpty) { return _handleNoDevices(); } else if (_deviceManager.hasSpecifiedAllDevices) { return allDevices; } else if (allDevices.length > 1) { return _handleMultipleDevices(attachedDevices, wirelessDevices); } return allDevices; } /// When no supported devices are found, display a message and list of /// unsupported devices found. Future<List<Device>?> _handleNoDevices() async { // Get connected devices from cache, including unsupported ones. final List<Device> unsupportedDevices = await _deviceManager.getAllDevices( filter: DeviceDiscoveryFilter( deviceConnectionInterface: deviceConnectionInterface, ) ); if (_deviceManager.hasSpecifiedDeviceId) { _logger.printStatus( _noMatchingDeviceMessage(_deviceManager.specifiedDeviceId!), ); if (unsupportedDevices.isNotEmpty) { _logger.printStatus(''); _logger.printStatus('The following devices were found:'); await Device.printDevices(unsupportedDevices, _logger); } return null; } _logger.printStatus(_deviceManager.hasSpecifiedAllDevices ? _noDevicesFoundMessage : globals.userMessages.flutterNoSupportedDevices); await _printUnsupportedDevice(unsupportedDevices); return null; } /// Determine which device to use when multiple found. /// /// If user has not specified a device id/name, attempt to prioritize /// ephemeral devices. If a single ephemeral device is found, return it /// immediately. /// /// Otherwise, prompt the user to select a device if there is a terminal /// with stdin. If there is not a terminal, display the list of devices with /// instructions to use a device selection flag. Future<List<Device>?> _handleMultipleDevices( List<Device> attachedDevices, List<Device> wirelessDevices, ) async { final List<Device> allDevices = attachedDevices + wirelessDevices; final Device? ephemeralDevice = _deviceManager.getSingleEphemeralDevice(allDevices); if (ephemeralDevice != null) { return <Device>[ephemeralDevice]; } if (globals.terminal.stdinHasTerminal) { return _selectFromMultipleDevices(attachedDevices, wirelessDevices); } else { return _printMultipleDevices(attachedDevices, wirelessDevices); } } /// Display a list of found devices. When the user has not specified the /// device id/name, display devices unsupported by the project as well and /// give instructions to use a device selection flag. Future<List<Device>?> _printMultipleDevices( List<Device> attachedDevices, List<Device> wirelessDevices, ) async { List<Device> supportedAttachedDevices = attachedDevices; List<Device> supportedWirelessDevices = wirelessDevices; if (_deviceManager.hasSpecifiedDeviceId) { final int allDeviceLength = supportedAttachedDevices.length + supportedWirelessDevices.length; _logger.printStatus(_foundSpecifiedDevicesMessage( allDeviceLength, _deviceManager.specifiedDeviceId!, )); } else { // Get connected devices from cache, including ones unsupported for the // project but still supported by Flutter. supportedAttachedDevices = await _getAttachedDevices( supportFilter: DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutter(), ); supportedWirelessDevices = await _getWirelessDevices( supportFilter: DeviceDiscoverySupportFilter.excludeDevicesUnsupportedByFlutter(), ); _logger.printStatus(globals.userMessages.flutterSpecifyDeviceWithAllOption); _logger.printStatus(''); } await Device.printDevices(supportedAttachedDevices, _logger); if (supportedWirelessDevices.isNotEmpty) { if (_deviceManager.hasSpecifiedDeviceId || supportedAttachedDevices.isNotEmpty) { _logger.printStatus(''); } _logger.printStatus(_wirelesslyConnectedDevicesMessage); await Device.printDevices(supportedWirelessDevices, _logger); } return null; } /// Display a list of selectable devices, prompt the user to choose one, and /// wait for the user to select a valid option. Future<List<Device>?> _selectFromMultipleDevices( List<Device> attachedDevices, List<Device> wirelessDevices, ) async { final List<Device> allDevices = attachedDevices + wirelessDevices; if (_deviceManager.hasSpecifiedDeviceId) { _logger.printStatus(_foundSpecifiedDevicesMessage( allDevices.length, _deviceManager.specifiedDeviceId!, )); } else { _logger.printStatus(_connectedDevicesMessage); } await Device.printDevices(attachedDevices, _logger); if (wirelessDevices.isNotEmpty) { _logger.printStatus(''); _logger.printStatus(_wirelesslyConnectedDevicesMessage); await Device.printDevices(wirelessDevices, _logger); _logger.printStatus(''); } final Device chosenDevice = await _chooseOneOfAvailableDevices(allDevices); // Update the [DeviceManager.specifiedDeviceId] so that the user will not // be prompted again. _deviceManager.specifiedDeviceId = chosenDevice.id; return <Device>[chosenDevice]; } Future<void> _printUnsupportedDevice(List<Device> unsupportedDevices) async { if (unsupportedDevices.isNotEmpty) { final StringBuffer result = StringBuffer(); result.writeln(); result.writeln(_foundButUnsupportedDevicesMessage); result.writeAll( (await Device.descriptions(unsupportedDevices)) .map((String desc) => desc) .toList(), '\n', ); result.writeln(); result.writeln(globals.userMessages.flutterMissPlatformProjects( Device.devicesPlatformTypes(unsupportedDevices), )); _logger.printStatus(result.toString(), newline: false); } } Future<Device> _chooseOneOfAvailableDevices(List<Device> devices) async { _displayDeviceOptions(devices); final String userInput = await _readUserInput(devices.length); if (userInput.toLowerCase() == 'q') { throwToolExit(''); } return devices[int.parse(userInput) - 1]; } void _displayDeviceOptions(List<Device> devices) { int count = 1; for (final Device device in devices) { _logger.printStatus(_chooseDeviceOptionMessage(count, device.name, device.id)); count++; } } Future<String> _readUserInput(int deviceCount) async { globals.terminal.usesTerminalUi = true; final String result = await globals.terminal.promptForCharInput( <String>[ for (int i = 0; i < deviceCount; i++) '${i + 1}', 'q', 'Q'], displayAcceptedCharacters: false, logger: _logger, prompt: _chooseOneMessage, ); return result; } } @visibleForTesting class TargetDevicesWithExtendedWirelessDeviceDiscovery extends TargetDevices { TargetDevicesWithExtendedWirelessDeviceDiscovery({ required super.deviceManager, required super.logger, super.deviceConnectionInterface, }) : super._private(); Future<void>? _wirelessDevicesRefresh; @visibleForTesting bool waitForWirelessBeforeInput = false; @visibleForTesting late final TargetDeviceSelection deviceSelection = TargetDeviceSelection(_logger); @override void startExtendedWirelessDeviceDiscovery({ Duration? deviceDiscoveryTimeout, }) { if (deviceDiscoveryTimeout == null && _includeWirelessDevices) { _wirelessDevicesRefresh ??= _deviceManager.refreshExtendedWirelessDeviceDiscoverers( timeout: DeviceManager.minimumWirelessDeviceDiscoveryTimeout, ); } return; } Future<List<Device>> _getRefreshedWirelessDevices({ bool includeDevicesUnsupportedByProject = false, }) async { if (!_includeWirelessDevices) { return <Device>[]; } startExtendedWirelessDeviceDiscovery(); return () async { await _wirelessDevicesRefresh; return _deviceManager.getDevices( filter: DeviceDiscoveryFilter( deviceConnectionInterface: DeviceConnectionInterface.wireless, supportFilter: _defaultSupportFilter(includeDevicesUnsupportedByProject), ), ); }(); } Future<Device?> _waitForIOSDeviceToConnect(IOSDevice device) async { for (final DeviceDiscovery discoverer in _deviceManager.deviceDiscoverers) { if (discoverer is IOSDevices) { _logger.printStatus('Waiting for ${device.name} to connect...'); final Status waitingStatus = _logger.startSpinner( timeout: const Duration(seconds: 30), warningColor: TerminalColor.red, slowWarningCallback: () { return 'The device was unable to connect after 30 seconds. Ensure the device is paired and unlocked.'; }, ); final Device? connectedDevice = await discoverer.waitForDeviceToConnect(device, _logger); waitingStatus.stop(); return connectedDevice; } } return null; } /// Find and return all target [Device]s based upon criteria entered by the /// user on the command line. /// /// When the user has specified `all` devices, return all devices meeting criteria. /// /// When the user has specified a device id/name, attempt to find an exact or /// partial match. If an exact match or a single partial match is found and /// the device is connected, return it immediately. If an exact match or a /// single partial match is found and the device is not connected and it's /// an iOS device, wait for it to connect. /// /// When multiple devices are found and there is a terminal attached to /// stdin, allow the user to select which device to use. When a terminal /// with stdin is not available, print a list of available devices and /// return null. /// /// When no devices meet user specifications, print a list of unsupported /// devices and return null. @override Future<List<Device>?> findAllTargetDevices({ Duration? deviceDiscoveryTimeout, bool includeDevicesUnsupportedByProject = false, }) async { if (!globals.doctor!.canLaunchAnything) { _logger.printError(globals.userMessages.flutterNoDevelopmentDevice); return null; } // When a user defines the timeout or filters to only attached devices, // use the super function that does not do longer wireless device // discovery and does not wait for devices to connect. if (deviceDiscoveryTimeout != null || deviceConnectionInterface == DeviceConnectionInterface.attached) { return super.findAllTargetDevices( deviceDiscoveryTimeout: deviceDiscoveryTimeout, includeDevicesUnsupportedByProject: includeDevicesUnsupportedByProject, ); } // Start polling for wireless devices that need longer to load if it hasn't // already been started. startExtendedWirelessDeviceDiscovery(); if (_deviceManager.hasSpecifiedDeviceId) { // Get devices matching the specified device regardless of whether they // are currently connected or not. // If there is a single matching connected device, return it immediately. // If the only device found is an iOS device that is not connected yet, // wait for it to connect. // If there are multiple matches, continue on to wait for all attached // and wireless devices to load so the user can select between all // connected matches. final List<Device> specifiedDevices = await _getDeviceById( includeDevicesUnsupportedByProject: includeDevicesUnsupportedByProject, includeDisconnected: true, ); if (specifiedDevices.length == 1) { Device? matchedDevice = specifiedDevices.first; if (matchedDevice is IOSDevice) { // If the only matching device is not paired, print a warning if (!matchedDevice.isPaired) { _logger.printStatus(flutterSpecifiedDeviceUnpaired(matchedDevice.name)); return null; } // If the only matching device does not have Developer Mode enabled, // print a warning if (!matchedDevice.devModeEnabled) { _logger.printStatus( flutterSpecifiedDeviceDevModeDisabled(matchedDevice.name) ); return null; } if (!matchedDevice.isConnected) { matchedDevice = await _waitForIOSDeviceToConnect(matchedDevice); } } if (matchedDevice != null && matchedDevice.isConnected) { return <Device>[matchedDevice]; } } else { for (final IOSDevice device in specifiedDevices.whereType<IOSDevice>()) { // Print warning for every matching unpaired device. if (!device.isPaired) { _logger.printStatus(flutterSpecifiedDeviceUnpaired(device.name)); } // Print warning for every matching device that does not have Developer Mode enabled. if (!device.devModeEnabled) { _logger.printStatus( flutterSpecifiedDeviceDevModeDisabled(device.name) ); } } } } final List<Device> attachedDevices = await _getAttachedDevices( supportFilter: _defaultSupportFilter(includeDevicesUnsupportedByProject), ); // _getRefreshedWirelessDevices must be run after _getAttachedDevices is // finished to prevent non-iOS discoverers from running simultaneously. // `AndroidDevices` may error if run simultaneously. final Future<List<Device>> futureWirelessDevices = _getRefreshedWirelessDevices( includeDevicesUnsupportedByProject: includeDevicesUnsupportedByProject, ); if (attachedDevices.isEmpty) { return _handleNoAttachedDevices(attachedDevices, futureWirelessDevices); } else if (_deviceManager.hasSpecifiedAllDevices) { return _handleAllDevices(attachedDevices, futureWirelessDevices); } // Even if there's only a single attached device, continue to // `_handleRemainingDevices` since there might be wireless devices // that are not loaded yet. return _handleRemainingDevices(attachedDevices, futureWirelessDevices); } /// When no supported attached devices are found, wait for wireless devices /// to load. /// /// If no wireless devices are found, continue to `_handleNoDevices`. /// /// If wireless devices are found, continue to `_handleMultipleDevices`. Future<List<Device>?> _handleNoAttachedDevices( List<Device> attachedDevices, Future<List<Device>> futureWirelessDevices, ) async { if (_includeAttachedDevices) { _logger.printStatus(_noAttachedCheckForWirelessMessage); } else { _logger.printStatus(_checkingForWirelessDevicesMessage); } final List<Device> wirelessDevices = await futureWirelessDevices; final List<Device> allDevices = attachedDevices + wirelessDevices; if (allDevices.isEmpty) { _logger.printStatus(''); return _handleNoDevices(); } else if (_deviceManager.hasSpecifiedAllDevices) { return allDevices; } else if (allDevices.length > 1) { _logger.printStatus(''); return _handleMultipleDevices(attachedDevices, wirelessDevices); } return allDevices; } /// Wait for wireless devices to load and then return all attached and /// wireless devices. Future<List<Device>?> _handleAllDevices( List<Device> devices, Future<List<Device>> futureWirelessDevices, ) async { _logger.printStatus(_checkingForWirelessDevicesMessage); final List<Device> wirelessDevices = await futureWirelessDevices; return devices + wirelessDevices; } /// Determine which device to use when one or more are found. /// /// If user has not specified a device id/name, attempt to prioritize /// ephemeral devices. If a single ephemeral device is found, return it /// immediately. /// /// Otherwise, prompt the user to select a device if there is a terminal /// with stdin. If there is not a terminal, display the list of devices with /// instructions to use a device selection flag. Future<List<Device>?> _handleRemainingDevices( List<Device> attachedDevices, Future<List<Device>> futureWirelessDevices, ) async { final Device? ephemeralDevice = _deviceManager.getSingleEphemeralDevice(attachedDevices); if (ephemeralDevice != null) { return <Device>[ephemeralDevice]; } if (!globals.terminal.stdinHasTerminal || !_logger.supportsColor) { _logger.printStatus(_checkingForWirelessDevicesMessage); final List<Device> wirelessDevices = await futureWirelessDevices; if (attachedDevices.length + wirelessDevices.length == 1) { return attachedDevices + wirelessDevices; } _logger.printStatus(''); // If the terminal has stdin but does not support color/ANSI (which is // needed to clear lines), fallback to standard selection of device. if (globals.terminal.stdinHasTerminal && !_logger.supportsColor) { return _handleMultipleDevices(attachedDevices, wirelessDevices); } // If terminal does not have stdin, print out device list. return _printMultipleDevices(attachedDevices, wirelessDevices); } return _selectFromDevicesAndCheckForWireless( attachedDevices, futureWirelessDevices, ); } /// Display a list of selectable attached devices and prompt the user to /// choose one. /// /// Also, display a message about waiting for wireless devices to load. Once /// wireless devices have loaded, update waiting message, device list, and /// selection options. /// /// Wait for the user to select a device. Future<List<Device>?> _selectFromDevicesAndCheckForWireless( List<Device> attachedDevices, Future<List<Device>> futureWirelessDevices, ) async { if (attachedDevices.length == 1 || !_deviceManager.hasSpecifiedDeviceId) { _logger.printStatus(_connectedDevicesMessage); } else if (_deviceManager.hasSpecifiedDeviceId) { // Multiple devices were found with part of the name/id provided. _logger.printStatus(_foundMultipleSpecifiedDevicesMessage( _deviceManager.specifiedDeviceId!, )); } // Display list of attached devices. await Device.printDevices(attachedDevices, _logger); // Display waiting message. _logger.printStatus(''); _logger.printStatus(_checkingForWirelessDevicesMessage); _logger.printStatus(''); // Start user device selection so user can select device while waiting // for wireless devices to load if they want. _displayDeviceOptions(attachedDevices); deviceSelection.devices = attachedDevices; final Future<Device> futureChosenDevice = deviceSelection.userSelectDevice(); Device? chosenDevice; // Once wireless devices are found, we clear out the waiting message (3), // device option list (attachedDevices.length), and device option prompt (1). int numLinesToClear = attachedDevices.length + 4; futureWirelessDevices = futureWirelessDevices.then((List<Device> wirelessDevices) async { // If device is already chosen, don't update terminal with // wireless device list. if (chosenDevice != null) { return wirelessDevices; } final List<Device> allDevices = attachedDevices + wirelessDevices; if (_logger.isVerbose) { await _verbosePrintWirelessDevices(attachedDevices, wirelessDevices); } else { // Also clear any invalid device selections. numLinesToClear += deviceSelection.invalidAttempts; await _printWirelessDevices(wirelessDevices, numLinesToClear); } _logger.printStatus(''); // Reprint device option list. _displayDeviceOptions(allDevices); deviceSelection.devices = allDevices; // Reprint device option prompt. _logger.printStatus( '$_chooseOneMessage: ', emphasis: true, newline: false, ); return wirelessDevices; }); // Used for testing. if (waitForWirelessBeforeInput) { await futureWirelessDevices; } // Wait for user to select a device. chosenDevice = await futureChosenDevice; // Update the [DeviceManager.specifiedDeviceId] so that the user will not // be prompted again. _deviceManager.specifiedDeviceId = chosenDevice.id; return <Device>[chosenDevice]; } /// Reprint list of attached devices before printing list of wireless devices. Future<void> _verbosePrintWirelessDevices( List<Device> attachedDevices, List<Device> wirelessDevices, ) async { if (wirelessDevices.isEmpty) { _logger.printStatus(_noWirelessDevicesFoundMessage); } // The iOS xcdevice outputs once wireless devices are done loading, so // reprint attached devices so they're grouped with the wireless ones. _logger.printStatus(_connectedDevicesMessage); await Device.printDevices(attachedDevices, _logger); if (wirelessDevices.isNotEmpty) { _logger.printStatus(''); _logger.printStatus(_wirelesslyConnectedDevicesMessage); await Device.printDevices(wirelessDevices, _logger); } } /// Clear [numLinesToClear] lines from terminal. Print message and list of /// wireless devices. Future<void> _printWirelessDevices( List<Device> wirelessDevices, int numLinesToClear, ) async { _logger.printStatus( globals.terminal.clearLines(numLinesToClear), newline: false, ); _logger.printStatus(''); if (wirelessDevices.isEmpty) { _logger.printStatus(_noWirelessDevicesFoundMessage); } else { _logger.printStatus(_wirelesslyConnectedDevicesMessage); await Device.printDevices(wirelessDevices, _logger); } } } @visibleForTesting class TargetDeviceSelection { TargetDeviceSelection(this._logger); List<Device> devices = <Device>[]; final Logger _logger; int invalidAttempts = 0; /// Prompt user to select a device and wait until they select a valid device. /// /// If the user selects `q`, exit the tool. /// /// If the user selects an invalid number, reprompt them and continue waiting. Future<Device> userSelectDevice() async { Device? chosenDevice; while (chosenDevice == null) { final String userInputString = await readUserInput(); if (userInputString.toLowerCase() == 'q') { throwToolExit(''); } final int deviceIndex = int.parse(userInputString) - 1; if (deviceIndex > -1 && deviceIndex < devices.length) { chosenDevice = devices[deviceIndex]; } } return chosenDevice; } /// Prompt user to select a device and wait until they select a valid /// character. /// /// Only allow input of a number or `q`. @visibleForTesting Future<String> readUserInput() async { final RegExp pattern = RegExp(r'\d+$|q', caseSensitive: false); String? choice; globals.terminal.singleCharMode = true; while (choice == null || choice.length > 1 || !pattern.hasMatch(choice)) { _logger.printStatus(_chooseOneMessage, emphasis: true, newline: false); // prompt ends with ': ' _logger.printStatus(': ', emphasis: true, newline: false); choice = (await globals.terminal.keystrokes.first).trim(); _logger.printStatus(choice); invalidAttempts++; } globals.terminal.singleCharMode = false; return choice; } }
flutter/packages/flutter_tools/lib/src/runner/target_devices.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/runner/target_devices.dart", "repo_id": "flutter", "token_count": 10107 }
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 'dart:async'; import 'package:test_core/src/executable.dart' as test; // ignore: implementation_imports import 'package:test_core/src/platform.dart' as hack show registerPlatformPlugin; // ignore: implementation_imports import 'package:test_core/src/platform.dart'; // ignore: implementation_imports export 'package:test_api/backend.dart' show Runtime; export 'package:test_core/src/platform.dart' show PlatformPlugin; abstract class TestWrapper { const factory TestWrapper() = _DefaultTestWrapper; Future<void> main(List<String> args); void registerPlatformPlugin(Iterable<Runtime> runtimes, FutureOr<PlatformPlugin> Function() platforms); } class _DefaultTestWrapper implements TestWrapper { const _DefaultTestWrapper(); @override Future<void> main(List<String> args) async { await test.main(args); } @override void registerPlatformPlugin(Iterable<Runtime> runtimes, FutureOr<PlatformPlugin> Function() platforms) { hack.registerPlatformPlugin(runtimes, platforms); } }
flutter/packages/flutter_tools/lib/src/test/test_wrapper.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/test/test_wrapper.dart", "repo_id": "flutter", "token_count": 345 }
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 'package:package_config/package_config.dart'; /// Generates the main.dart file. String generateMainDartFile(String appEntrypoint, { required String pluginRegistrantEntrypoint, LanguageVersion? languageVersion, }) { return <String>[ if (languageVersion != null) '// @dart=${languageVersion.major}.${languageVersion.minor}', '// Flutter web bootstrap script for $appEntrypoint.', '//', '// Generated file. Do not edit.', '//', '', '// ignore_for_file: type=lint', '', "import 'dart:ui_web' as ui_web;", "import 'dart:async';", '', "import '$appEntrypoint' as entrypoint;", "import '$pluginRegistrantEntrypoint' as pluginRegistrant;", '', 'typedef _UnaryFunction = dynamic Function(List<String> args);', 'typedef _NullaryFunction = dynamic Function();', '', 'Future<void> main() async {', ' await ui_web.bootstrapEngine(', ' runApp: () {', ' if (entrypoint.main is _UnaryFunction) {', ' return (entrypoint.main as _UnaryFunction)(<String>[]);', ' }', ' return (entrypoint.main as _NullaryFunction)();', ' },', ' registerPlugins: () {', ' pluginRegistrant.registerPlugins();', ' },', ' );', '}', '', ].join('\n'); }
flutter/packages/flutter_tools/lib/src/web/file_generators/main_dart.dart/0
{ "file_path": "flutter/packages/flutter_tools/lib/src/web/file_generators/main_dart.dart", "repo_id": "flutter", "token_count": 579 }
811