text stringlengths 6 1.82M | id stringlengths 12 200 | metadata dict | __index_level_0__ int64 0 784 |
|---|---|---|---|
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_api_samples/painting/linear_border/linear_border.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Smoke Test', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ExampleApp(),
);
expect(find.byType(example.Home), findsOneWidget);
// Scroll the interpolation example into view
await tester.scrollUntilVisible(
find.byIcon(Icons.play_arrow),
500.0,
scrollable: find.byType(Scrollable),
);
expect(find.byIcon(Icons.play_arrow), findsOneWidget);
// Run the interpolation example
await tester.tap(find.byIcon(Icons.play_arrow));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.play_arrow));
await tester.pumpAndSettle();
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('Interpolation')));
await gesture.moveTo(tester.getCenter(find.text('Hover')));
await tester.pumpAndSettle();
await gesture.moveTo(tester.getCenter(find.text('Interpolation')));
await tester.pumpAndSettle();
});
}
| flutter/examples/api/test/painting/linear_border/linear_border.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/painting/linear_border/linear_border.0_test.dart",
"repo_id": "flutter",
"token_count": 479
} | 200 |
// Copyright 2014 The Flutter Authors. 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_api_samples/widgets/app/widgets_app.widgets_app.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('WidgetsApp test', (WidgetTester tester) async {
await tester.pumpWidget(
const example.WidgetsAppExampleApp(),
);
expect(find.text('Hello World'), findsOneWidget);
});
}
| flutter/examples/api/test/widgets/app/widgets_app.widgets_app.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/app/widgets_app.widgets_app.0_test.dart",
"repo_id": "flutter",
"token_count": 179
} | 201 |
// Copyright 2014 The Flutter Authors. 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_api_samples/widgets/basic/expanded.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Expanded widget in a Column', (WidgetTester tester) async {
const double totalHeight = 600;
const double appBarHeight = 56.0;
const double columnWidth = 100.0;
const double columnHeight = totalHeight - appBarHeight;
const double containerOneHeight = 100;
const double containerTwoHeight = columnHeight - 200;
const double containerThreeHeight = 100;
await tester.pumpWidget(
const example.ExpandedApp(),
);
final Size column = tester.getSize(find.byType(Column));
expect(column, const Size(columnWidth, columnHeight));
final Size containerOne = tester.getSize(find.byType(Container).at(0));
expect(containerOne, const Size(columnWidth, containerOneHeight));
// This Container is wrapped in an Expanded widget, so it should take up
// the remaining space in the Column.
final Size containerTwo = tester.getSize(find.byType(Container).at(1));
expect(containerTwo, const Size(columnWidth, containerTwoHeight));
final Size containerThree = tester.getSize(find.byType(Container).at(2));
expect(containerThree, const Size(columnWidth, containerThreeHeight));
});
}
| flutter/examples/api/test/widgets/basic/expanded.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/basic/expanded.0_test.dart",
"repo_id": "flutter",
"token_count": 464
} | 202 |
// Copyright 2014 The Flutter Authors. 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_api_samples/widgets/drag_target/draggable.0.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
Finder findContainerWith({
required Finder child,
required Color color,
}) {
return find.ancestor(
of: child,
matching: find.byWidgetPredicate(
(Widget widget) => widget is Container && widget.color == color,
),
);
}
testWidgets('Verify initial state', (WidgetTester tester) async {
await tester.pumpWidget(
const example.DraggableExampleApp(),
);
expect(find.text('Draggable Sample'), findsOneWidget);
expect(
findContainerWith(
color: Colors.lightGreenAccent,
child: find.text('Draggable'),
),
findsOneWidget,
);
expect(
findContainerWith(
color: Colors.cyan,
child: find.text('Value is updated to: 0'),
),
findsOneWidget,
);
});
testWidgets('Verify correct containers are displayed while dragging', (WidgetTester tester) async {
await tester.pumpWidget(
const example.DraggableExampleApp(),
);
final Finder idleContainer = findContainerWith(
color: Colors.lightGreenAccent,
child: find.text('Draggable'),
);
final Finder draggingContainer = findContainerWith(
color: Colors.pinkAccent,
child: find.text('Child When Dragging'),
);
final Finder feedbackContainer = findContainerWith(
color: Colors.deepOrange,
child: find.byIcon(Icons.directions_run),
);
expect(idleContainer, findsOneWidget);
expect(draggingContainer, findsNothing);
expect(feedbackContainer, findsNothing);
final TestGesture gesture = await tester.startGesture(
tester.getCenter(idleContainer),
);
await tester.pump();
expect(idleContainer, findsNothing);
expect(draggingContainer, findsOneWidget);
expect(feedbackContainer, findsOneWidget);
await gesture.moveBy(const Offset(200, 0));
await tester.pump();
expect(idleContainer, findsNothing);
expect(draggingContainer, findsOneWidget);
expect(feedbackContainer, findsOneWidget);
await gesture.up();
await tester.pump();
expect(idleContainer, findsOneWidget);
expect(draggingContainer, findsNothing);
expect(feedbackContainer, findsNothing);
});
testWidgets('Dropping Draggable over DragTarget updates the counter', (WidgetTester tester) async {
await tester.pumpWidget(
const example.DraggableExampleApp(),
);
final Finder draggable = find.byType(Draggable<int>);
final Finder target = find.byType(DragTarget<int>);
int counter = 0;
for (int i = 0; i < 5; i++) {
final TestGesture gesture = await tester.startGesture(
tester.getCenter(draggable),
);
await gesture.moveTo(tester.getCenter(target));
await gesture.up();
await tester.pump();
counter += 10;
expect(
findContainerWith(
color: Colors.cyan,
child: find.text('Value is updated to: $counter'),
),
findsOneWidget,
);
}
});
}
| flutter/examples/api/test/widgets/drag_target/draggable.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/drag_target/draggable.0_test.dart",
"repo_id": "flutter",
"token_count": 1241
} | 203 |
// Copyright 2014 The Flutter Authors. 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_api_samples/widgets/heroes/hero.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Has Hero animation', (WidgetTester tester) async {
await tester.pumpWidget(
const example.HeroApp(),
);
expect(find.text('Hero Sample'), findsOneWidget);
await tester.tap(find.byType(Container));
await tester.pump();
Size heroSize = tester.getSize(find.byType(Container));
// Jump 25% into the transition (total length = 300ms)
await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
heroSize = tester.getSize(find.byType(Container));
expect(heroSize.width.roundToDouble(), 103.0);
expect(heroSize.height.roundToDouble(), 60.0);
// Jump to 50% into the transition.
await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
heroSize = tester.getSize(find.byType(Container));
expect(heroSize.width.roundToDouble(), 189.0);
expect(heroSize.height.roundToDouble(), 146.0);
// Jump to 75% into the transition.
await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
heroSize = tester.getSize(find.byType(Container));
expect(heroSize.width.roundToDouble(), 199.0);
expect(heroSize.height.roundToDouble(), 190.0);
// Jump to 100% into the transition.
await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
heroSize = tester.getSize(find.byType(Container));
expect(heroSize, const Size(200.0, 200.0));
expect(find.byIcon(Icons.arrow_back), findsOneWidget);
await tester.tap(find.byIcon(Icons.arrow_back));
await tester.pump();
// Jump 25% into the transition (total length = 300ms)
await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
heroSize = tester.getSize(find.byType(Container));
expect(heroSize.width.roundToDouble(), 199.0);
expect(heroSize.height.roundToDouble(), 190.0);
// Jump to 50% into the transition.
await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
heroSize = tester.getSize(find.byType(Container));
expect(heroSize.width.roundToDouble(), 189.0);
expect(heroSize.height.roundToDouble(), 146.0);
// Jump to 75% into the transition.
await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
heroSize = tester.getSize(find.byType(Container));
expect(heroSize.width.roundToDouble(), 103.0);
expect(heroSize.height.roundToDouble(), 60.0);
// Jump to 100% into the transition.
await tester.pump(const Duration(milliseconds: 75)); // 25% of 300ms
heroSize = tester.getSize(find.byType(Container));
expect(heroSize, const Size(50.0, 50.0));
});
}
| flutter/examples/api/test/widgets/heroes/hero.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/heroes/hero.0_test.dart",
"repo_id": "flutter",
"token_count": 1033
} | 204 |
// Copyright 2014 The Flutter Authors. 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_api_samples/widgets/navigator_pop_handler/navigator_pop_handler.1.dart' as example;
import 'package:flutter_test/flutter_test.dart';
import '../navigator_utils.dart';
void main() {
testWidgets("System back gesture operates on current tab's nested Navigator", (WidgetTester tester) async {
await tester.pumpWidget(
const example.NavigatorPopHandlerApp(),
);
expect(find.text('Bottom nav - tab Home Tab - route _TabPage.home'), findsOneWidget);
// Go to the next route in this tab.
await tester.tap(find.text('Go to another route in this nested Navigator'));
await tester.pumpAndSettle();
expect(find.text('Bottom nav - tab Home Tab - route _TabPage.one'), findsOneWidget);
// Go to another tab.
await tester.tap(find.text('Go to One'));
await tester.pumpAndSettle();
expect(find.text('Bottom nav - tab Tab One - route _TabPage.home'), findsOneWidget);
// Return to the home tab. The navigation state is preserved.
await tester.tap(find.text('Go to Home'));
await tester.pumpAndSettle();
expect(find.text('Bottom nav - tab Home Tab - route _TabPage.one'), findsOneWidget);
// A back pops the navigation stack of the current tab's nested Navigator.
await simulateSystemBack();
await tester.pumpAndSettle();
expect(find.text('Bottom nav - tab Home Tab - route _TabPage.home'), findsOneWidget);
});
}
| flutter/examples/api/test/widgets/navigator_pop_handler/navigator_pop_handler.1_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/navigator_pop_handler/navigator_pop_handler.1_test.dart",
"repo_id": "flutter",
"token_count": 511
} | 205 |
// Copyright 2014 The Flutter Authors. 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_api_samples/widgets/routes/route_observer.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('RouteObserver notifies RouteAware widget', (WidgetTester tester) async {
await tester.pumpWidget(
const example.RouteObserverApp(),
);
// Check the initial RouteObserver logs.
expect(find.text('didPush'), findsOneWidget);
// Tap on the button to push a new route.
await tester.tap(find.text('Go to next page'));
await tester.pumpAndSettle();
// Tap on the button to go back to the previous route.
await tester.tap(find.text('Go back to RouteAware page'));
await tester.pumpAndSettle();
// Check the RouteObserver logs after the route is popped.
expect(find.text('didPush'), findsOneWidget);
expect(find.text('didPopNext'), findsOneWidget);
// Tap on the button to push a new route again.
await tester.tap(find.text('Go to next page'));
await tester.pumpAndSettle();
// Tap on the button to go back to the previous route again.
await tester.tap(find.text('Go back to RouteAware page'));
await tester.pumpAndSettle();
// Check the RouteObserver logs after the route is popped again.
expect(find.text('didPush'), findsOneWidget);
expect(find.text('didPopNext'), findsNWidgets(2));
});
}
| flutter/examples/api/test/widgets/routes/route_observer.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/routes/route_observer.0_test.dart",
"repo_id": "flutter",
"token_count": 507
} | 206 |
// Copyright 2014 The Flutter Authors. 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_api_samples/widgets/shortcuts/shortcuts.0.dart'
as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Verify correct labels are displayed', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ShortcutsExampleApp(),
);
expect(find.text('Shortcuts Sample'), findsOneWidget);
expect(
find.text('Add to the counter by pressing the up arrow key'),
findsOneWidget,
);
expect(
find.text('Subtract from the counter by pressing the down arrow key'),
findsOneWidget,
);
expect(find.text('count: 0'), findsOneWidget);
});
testWidgets('Up and down arrow press updates counter', (WidgetTester tester) async {
await tester.pumpWidget(
const example.ShortcutsExampleApp(),
);
int counter = 0;
while (counter < 10) {
expect(find.text('count: $counter'), findsOneWidget);
// Increment the counter.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
counter++;
}
while (counter >= 0) {
expect(find.text('count: $counter'), findsOneWidget);
// Decrement the counter.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
counter--;
}
});
}
| flutter/examples/api/test/widgets/shortcuts/shortcuts.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/shortcuts/shortcuts.0_test.dart",
"repo_id": "flutter",
"token_count": 548
} | 207 |
// Copyright 2014 The Flutter Authors. 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_api_samples/widgets/table/table.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Table has expected arrangement', (WidgetTester tester) async {
await tester.pumpWidget(const example.TableExampleApp());
final Table table = tester.widget<Table>(find.byType(Table));
// Check the defined columnWidths.
expect(table.columnWidths, const <int, TableColumnWidth>{
0: IntrinsicColumnWidth(),
1: FlexColumnWidth(),
2: FixedColumnWidth(64),
});
// The table has two rows.
expect(table.children.length, 2);
for (int i = 0; i < table.children.length; i++) {
// Each row has three containers.
expect(table.children[i].children.length, 3);
// Returns the width of given widget.
double getWidgetWidth(Widget widget) {
return tester.getSize(find.byWidget(widget)).width;
}
// Check table row container width.
expect(getWidgetWidth(table.children[i].children.first), equals(128));
expect(getWidgetWidth(table.children[i].children[2]), equals(64));
}
});
}
| flutter/examples/api/test/widgets/table/table.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/table/table.0_test.dart",
"repo_id": "flutter",
"token_count": 463
} | 208 |
// Copyright 2014 The Flutter Authors. 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_api_samples/widgets/transitions/relative_positioned_transition.0.dart' as example;
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Shows flutter logo in transition', (WidgetTester tester) async {
await tester.pumpWidget(const example.RelativePositionedTransitionExampleApp());
expect(find.byType(FlutterLogo), findsOneWidget);
expect(find.byType(Padding), findsAtLeast(1));
expect(find.byType(RelativePositionedTransition), findsOneWidget);
});
testWidgets('Animates repeatedly every 2 seconds', (WidgetTester tester) async {
await tester.pumpWidget(const example.RelativePositionedTransitionExampleApp());
expect(tester.getSize(find.byType(FlutterLogo)), const Size(200.0 - 2.0 * 8.0, 200.0 - 2.0 * 8.0));
expect(tester.getTopLeft(find.byType(FlutterLogo)), const Offset(8.0, 8.0));
await tester.pump(const Duration(seconds: 2));
await tester.pump();
final Size canvasSize = tester.getSize(find.byType(LayoutBuilder));
expect(tester.getSize(find.byType(FlutterLogo)), const Size(100.0 - 2.0 * 8.0, 100.0 - 2.0 * 8.0));
expect(tester.getBottomRight(find.byType(FlutterLogo)), Offset(canvasSize.width - 8.0, canvasSize.height - 8.0));
await tester.pump(const Duration(seconds: 2));
await tester.pump();
expect(tester.getSize(find.byType(FlutterLogo)), const Size(200.0 - 2.0 * 8.0, 200.0 - 2.0 * 8.0));
expect(tester.getTopLeft(find.byType(FlutterLogo)), const Offset(8.0, 8.0));
await tester.pump(const Duration(seconds: 2));
await tester.pump();
expect(tester.getSize(find.byType(FlutterLogo)), const Size(100.0 - 2.0 * 8.0, 100.0 - 2.0 * 8.0));
expect(tester.getBottomRight(find.byType(FlutterLogo)), Offset(canvasSize.width - 8.0, canvasSize.height - 8.0));
});
}
| flutter/examples/api/test/widgets/transitions/relative_positioned_transition.0_test.dart/0 | {
"file_path": "flutter/examples/api/test/widgets/transitions/relative_positioned_transition.0_test.dart",
"repo_id": "flutter",
"token_count": 746
} | 209 |
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@3x.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@3x.png",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@3x.png",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "20x20",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@1x.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@1x.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@2x.png",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "Icon-App-83.5x83.5@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@1x.png",
"scale" : "1x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@1x.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@3x.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
} | flutter/examples/flutter_view/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json/0 | {
"file_path": "flutter/examples/flutter_view/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json",
"repo_id": "flutter",
"token_count": 1595
} | 210 |
#include "ephemeral/Flutter-Generated.xcconfig"
| flutter/examples/hello_world/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "flutter/examples/hello_world/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "flutter",
"token_count": 19
} | 211 |
// Application-level settings for the Runner target.
//
// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the
// future. If not, the values below would default to using the project name when this becomes a
// 'flutter create' template.
// The application's name. By default this is also the title of the Flutter window.
PRODUCT_NAME = hello_world
// The application's bundle identifier
PRODUCT_BUNDLE_IDENTIFIER = io.flutter.examples.helloWorld
// The copyright displayed in application information
PRODUCT_COPYRIGHT = Copyright Β© 2021 io.flutter.examples. All rights reserved.
| flutter/examples/hello_world/macos/Runner/Configs/AppInfo.xcconfig/0 | {
"file_path": "flutter/examples/hello_world/macos/Runner/Configs/AppInfo.xcconfig",
"repo_id": "flutter",
"token_count": 163
} | 212 |
#include "ephemeral/Flutter-Generated.xcconfig"
| flutter/examples/layers/macos/Flutter/Flutter-Release.xcconfig/0 | {
"file_path": "flutter/examples/layers/macos/Flutter/Flutter-Release.xcconfig",
"repo_id": "flutter",
"token_count": 19
} | 213 |
// Copyright 2014 The Flutter Authors. 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:isolate';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
typedef OnProgressListener = void Function(double completed, double total);
typedef OnResultListener = void Function(String result);
// An encapsulation of a large amount of synchronous processing.
//
// The choice of JSON parsing here is meant as an example that might surface
// in real-world applications.
class Calculator {
Calculator({ required this.onProgressListener, required this.onResultListener, String? data })
: _data = _replicateJson(data, 10000);
final OnProgressListener onProgressListener;
final OnResultListener onResultListener;
final String _data;
// This example assumes that the number of objects to parse is known in
// advance. In a real-world situation, this might not be true; in that case,
// the app might choose to display an indeterminate progress indicator.
static const int _NUM_ITEMS = 110000;
static const int _NOTIFY_INTERVAL = 1000;
// Run the computation associated with this Calculator.
void run() {
int i = 0;
final JsonDecoder decoder = JsonDecoder(
(dynamic key, dynamic value) {
if (key is int && i++ % _NOTIFY_INTERVAL == 0) {
onProgressListener(i.toDouble(), _NUM_ITEMS.toDouble());
}
return value;
},
);
try {
final List<dynamic> result = decoder.convert(_data) as List<dynamic>;
final int n = result.length;
onResultListener('Decoded $n results');
} on FormatException catch (e, stack) {
debugPrint('Invalid JSON file: $e');
debugPrint('$stack');
}
}
static String _replicateJson(String? data, int count) {
final StringBuffer buffer = StringBuffer()..write('[');
for (int i = 0; i < count; i++) {
buffer.write(data);
if (i < count - 1) {
buffer.write(',');
}
}
buffer.write(']');
return buffer.toString();
}
}
// The current state of the calculation.
enum CalculationState {
idle,
loading,
calculating
}
// Structured message to initialize the spawned isolate.
class CalculationMessage {
CalculationMessage(this.data, this.sendPort);
String data;
SendPort sendPort;
}
// A manager for the connection to a spawned isolate.
//
// Isolates communicate with each other via ReceivePorts and SendPorts.
// This class manages these ports and maintains state related to the
// progress of the background computation.
class CalculationManager {
CalculationManager({ required this.onProgressListener, required this.onResultListener })
: _receivePort = ReceivePort() {
_receivePort.listen(_handleMessage);
}
CalculationState _state = CalculationState.idle;
CalculationState get state => _state;
bool get isRunning => _state != CalculationState.idle;
double _completed = 0.0;
double _total = 1.0;
final OnProgressListener onProgressListener;
final OnResultListener onResultListener;
// Start the background computation.
//
// Does nothing if the computation is already running.
void start() {
if (!isRunning) {
_state = CalculationState.loading;
_runCalculation();
}
}
// Stop the background computation.
//
// Kills the isolate immediately, if spawned. Does nothing if the
// computation is not running.
void stop() {
if (isRunning) {
_state = CalculationState.idle;
if (_isolate != null) {
_isolate!.kill(priority: Isolate.immediate);
_isolate = null;
_completed = 0.0;
_total = 1.0;
}
}
}
final ReceivePort _receivePort;
Isolate? _isolate;
void _runCalculation() {
// Load the JSON string. This is done in the main isolate because spawned
// isolates do not have access to the root bundle. However, the loading
// process is asynchronous, so the UI will not block while the file is
// loaded.
rootBundle.loadString('services/data.json').then<void>((String data) {
if (isRunning) {
final CalculationMessage message = CalculationMessage(data, _receivePort.sendPort);
// Spawn an isolate to JSON-parse the file contents. The JSON parsing
// is synchronous, so if done in the main isolate, the UI would block.
Isolate.spawn<CalculationMessage>(_calculate, message).then<void>((Isolate isolate) {
if (!isRunning) {
isolate.kill(priority: Isolate.immediate);
} else {
_state = CalculationState.calculating;
_isolate = isolate;
}
});
}
});
}
void _handleMessage(dynamic message) {
if (message is List<double>) {
_completed = message[0];
_total = message[1];
onProgressListener(_completed, _total);
} else if (message is String) {
_completed = 0.0;
_total = 1.0;
_isolate = null;
_state = CalculationState.idle;
onResultListener(message);
}
}
// Main entry point for the spawned isolate.
//
// This entry point must be static, and its (single) argument must match
// the message passed in Isolate.spawn above. Typically, some part of the
// message will contain a SendPort so that the spawned isolate can
// communicate back to the main isolate.
//
// Static and global variables are initialized anew in the spawned isolate,
// in a separate memory space.
static void _calculate(CalculationMessage message) {
final SendPort sender = message.sendPort;
final Calculator calculator = Calculator(
onProgressListener: (double completed, double total) {
sender.send(<double>[ completed, total ]);
},
onResultListener: sender.send,
data: message.data,
);
calculator.run();
}
}
// Main app widget.
//
// The app shows a simple UI that allows control of the background computation,
// as well as an animation to illustrate that the UI does not block while this
// computation is performed.
//
// This is a StatefulWidget in order to hold the CalculationManager and
// the AnimationController for the running animation.
class IsolateExampleWidget extends StatefulWidget {
const IsolateExampleWidget({super.key});
@override
IsolateExampleState createState() => IsolateExampleState();
}
// Main application state.
class IsolateExampleState extends State<StatefulWidget> with SingleTickerProviderStateMixin {
String _status = 'Idle';
String _label = 'Start';
String _result = ' ';
double _progress = 0.0;
late final AnimationController _animation = AnimationController(
duration: const Duration(milliseconds: 3600),
vsync: this,
)..repeat();
late final CalculationManager _calculationManager = CalculationManager(
onProgressListener: _handleProgressUpdate,
onResultListener: _handleResult,
);
@override
void dispose() {
_animation.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Material(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
RotationTransition(
turns: _animation,
child: Container(
width: 120.0,
height: 120.0,
color: const Color(0xFF882222),
),
),
Opacity(
opacity: _calculationManager.isRunning ? 1.0 : 0.0,
child: CircularProgressIndicator(
value: _progress,
),
),
Text(_status),
Center(
child: ElevatedButton(
onPressed: _handleButtonPressed,
child: Text(_label),
),
),
Text(_result),
],
),
);
}
void _handleProgressUpdate(double completed, double total) {
_updateState(' ', completed / total);
}
void _handleResult(String result) {
_updateState(result, 0.0);
}
void _handleButtonPressed() {
if (_calculationManager.isRunning) {
_calculationManager.stop();
} else {
_calculationManager.start();
}
_updateState(' ', 0.0);
}
String _getStatus(CalculationState state) {
return switch (state) {
CalculationState.loading => 'Loading...',
CalculationState.calculating => 'In Progress',
CalculationState.idle => 'Idle',
};
}
void _updateState(String result, double progress) {
setState(() {
_result = result;
_progress = progress;
_label = _calculationManager.isRunning ? 'Stop' : 'Start';
_status = _getStatus(_calculationManager.state);
});
}
}
void main() {
runApp(const MaterialApp(home: IsolateExampleWidget()));
}
| flutter/examples/layers/services/isolate.dart/0 | {
"file_path": "flutter/examples/layers/services/isolate.dart",
"repo_id": "flutter",
"token_count": 3103
} | 214 |
// Copyright 2014 The Flutter Authors. 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 '../rendering/src/solid_color_box.dart';
// Solid color, RenderObject version
void addFlexChildSolidColor(RenderFlex parent, Color backgroundColor, { int flex = 0 }) {
final RenderSolidColorBox child = RenderSolidColorBox(backgroundColor);
parent.add(child);
final FlexParentData childParentData = child.parentData! as FlexParentData;
childParentData.flex = flex;
}
// Solid color, Widget version
class Rectangle extends StatelessWidget {
const Rectangle(this.color, { super.key });
final Color color;
@override
Widget build(BuildContext context) {
return Expanded(
child: Container(
color: color,
),
);
}
}
double? value;
RenderObjectToWidgetElement<RenderBox>? element;
void attachWidgetTreeToRenderTree(RenderProxyBox container) {
element = RenderObjectToWidgetAdapter<RenderBox>(
container: container,
child: Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
height: 300.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
const Rectangle(Color(0xFF00FFFF)),
Material(
child: Container(
padding: const EdgeInsets.all(10.0),
margin: const EdgeInsets.all(10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
ElevatedButton(
child: const Row(
children: <Widget>[
FlutterLogo(),
Text('PRESS ME'),
],
),
onPressed: () {
value = value == null ? 0.1 : (value! + 0.1) % 1.0;
attachWidgetTreeToRenderTree(container);
},
),
CircularProgressIndicator(value: value),
],
),
),
),
const Rectangle(Color(0xFFFFFF00)),
],
),
),
),
).attachToRenderTree(WidgetsBinding.instance.buildOwner!, element);
}
Duration? timeBase;
late RenderTransform transformBox;
void rotate(Duration timeStamp) {
timeBase ??= timeStamp;
final double delta = (timeStamp - timeBase!).inMicroseconds.toDouble() / Duration.microsecondsPerSecond; // radians
transformBox.setIdentity();
transformBox.rotateZ(delta);
WidgetsBinding.instance.buildOwner!.buildScope(element!);
}
void main() {
final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized();
final RenderProxyBox proxy = RenderProxyBox();
attachWidgetTreeToRenderTree(proxy);
final RenderFlex flexRoot = RenderFlex(direction: Axis.vertical);
addFlexChildSolidColor(flexRoot, const Color(0xFFFF00FF), flex: 1);
flexRoot.add(proxy);
addFlexChildSolidColor(flexRoot, const Color(0xFF0000FF), flex: 1);
transformBox = RenderTransform(child: flexRoot, transform: Matrix4.identity(), alignment: Alignment.center);
final RenderPadding root = RenderPadding(padding: const EdgeInsets.all(80.0), child: transformBox);
// TODO(goderbauer): Create a window if embedder doesn't provide an implicit view to draw into.
assert(binding.platformDispatcher.implicitView != null);
final RenderView view = RenderView(
view: binding.platformDispatcher.implicitView!,
child: root,
);
final PipelineOwner pipelineOwner = PipelineOwner()..rootNode = view;
binding.rootPipelineOwner.adoptChild(pipelineOwner);
binding.addRenderView(view);
view.prepareInitialFrame();
binding.addPersistentFrameCallback(rotate);
}
| flutter/examples/layers/widgets/spinning_mixed.dart/0 | {
"file_path": "flutter/examples/layers/widgets/spinning_mixed.dart",
"repo_id": "flutter",
"token_count": 1591
} | 215 |
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
| flutter/examples/platform_channel/macos/Runner/Configs/Release.xcconfig/0 | {
"file_path": "flutter/examples/platform_channel/macos/Runner/Configs/Release.xcconfig",
"repo_id": "flutter",
"token_count": 32
} | 216 |
<!-- Copyright 2014 The Flutter Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<path
android:fillColor="#FF000000"
android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>
| flutter/examples/platform_view/android/app/src/main/res/drawable/ic_add_black_24dp.xml/0 | {
"file_path": "flutter/examples/platform_view/android/app/src/main/res/drawable/ic_add_black_24dp.xml",
"repo_id": "flutter",
"token_count": 206
} | 217 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "PlatformViewController.h"
#import <Foundation/Foundation.h>
@interface PlatformViewController ()
@property(weak, nonatomic) IBOutlet UILabel* countLabel;
@end
@implementation PlatformViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self updateCountLabelText];
}
- (IBAction)handleIncrement:(id)sender {
self.counter++;
[self updateCountLabelText];
}
- (IBAction)switchToFlutterView:(id)sender {
[self.delegate didUpdateCounter:self.counter];
[self dismissViewControllerAnimated:NO completion:nil];
}
- (void)updateCountLabelText {
NSString* text = [NSString stringWithFormat:@"Button tapped %d %@.", self.counter,
(self.counter == 1) ? @"time" : @"times"];
self.countLabel.text = text;
}
@end
| flutter/examples/platform_view/ios/Runner/PlatformViewController.m/0 | {
"file_path": "flutter/examples/platform_view/ios/Runner/PlatformViewController.m",
"repo_id": "flutter",
"token_count": 336
} | 218 |
# Flutter Texture
An example to show how to use custom Flutter textures.
| flutter/examples/texture/README.md/0 | {
"file_path": "flutter/examples/texture/README.md",
"repo_id": "flutter",
"token_count": 19
} | 219 |
targets:
$default:
sources:
exclude:
- "test/examples/sector_layout_test.dart"
| flutter/packages/flutter/build.yaml/0 | {
"file_path": "flutter/packages/flutter/build.yaml",
"repo_id": "flutter",
"token_count": 48
} | 220 |
# Copyright 2014 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# For details regarding the *Flutter Fix* feature, see
# https://flutter.dev/docs/development/tools/flutter-fix
# Please add new fixes to the top of the file, separated by one blank line
# from other fixes. In a comment, include a link to the PR where the change
# requiring the fix was made.
# Every fix must be tested. See the flutter/packages/flutter/test_fixes/README.md
# file for instructions on testing these data driven fixes.
# For documentation about this file format, see
# https://dart.dev/go/data-driven-fixes.
# * Fixes in this file are for the MaterialState enum and classes from the Material library. *
# For fixes to
# * AppBar: fix_app_bar.yaml
# * AppBarTheme: fix_app_bar_theme.yaml
# * ColorScheme: fix_color_scheme.yaml
# * Material (general): fix_material.yaml
# * SliverAppBar: fix_sliver_app_bar.yaml
# * TextTheme: fix_text_theme.yaml
# * ThemeDate: fix_theme_data.yaml
version: 1
transforms:
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetState'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
enum: 'MaterialState'
changes:
- kind: 'rename'
newName: 'WidgetState'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetPropertyResolver'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
typedef: 'MaterialPropertyResolver'
changes:
- kind: 'rename'
newName: 'WidgetPropertyResolver'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateColor'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateColor'
changes:
- kind: 'rename'
newName: 'WidgetStateColor'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateMouseCursor'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateMouseCursor'
changes:
- kind: 'rename'
newName: 'WidgetStateMouseCursor'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateBorderSide'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateBorderSide'
changes:
- kind: 'rename'
newName: 'WidgetStateBorderSide'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateOutlinedBorder'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateOutlinedBorder'
changes:
- kind: 'rename'
newName: 'WidgetStateOutlinedBorder'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateTextStyle'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateTextStyle'
changes:
- kind: 'rename'
newName: 'WidgetStateTextStyle'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStateProperty'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStateProperty'
changes:
- kind: 'rename'
newName: 'WidgetStateProperty'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStatePropertyAll'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStatePropertyAll'
changes:
- kind: 'rename'
newName: 'WidgetStatePropertyAll'
# Changes made in https://github.com/flutter/flutter/pull/142151
- title: "Replace with 'WidgetStatesController'"
date: 2024-02-01
element:
uris: [ 'material.dart', 'widgets.dart' ]
class: 'MaterialStatesController'
changes:
- kind: 'rename'
newName: 'WidgetStatesController'
# Before adding a new fix: read instructions at the top of this file.
| flutter/packages/flutter/lib/fix_data/fix_material/fix_widget_state.yaml/0 | {
"file_path": "flutter/packages/flutter/lib/fix_data/fix_material/fix_widget_state.yaml",
"repo_id": "flutter",
"token_count": 1660
} | 221 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Flutter widgets implementing Material Design.
///
/// To use, import `package:flutter/material.dart`.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=DL0Ix1lnC4w}
///
/// See also:
///
/// * [docs.flutter.dev/ui/widgets/material](https://docs.flutter.dev/ui/widgets/material)
/// for a catalog of commonly-used Material component widgets.
/// * [m3.material.io](https://m3.material.io/) for the Material 3 specification
/// * [m2.material.io](https://m2.material.io/) for the Material 2 specification
library material;
export 'src/material/about.dart';
export 'src/material/action_buttons.dart';
export 'src/material/action_chip.dart';
export 'src/material/action_icons_theme.dart';
export 'src/material/adaptive_text_selection_toolbar.dart';
export 'src/material/animated_icons.dart';
export 'src/material/app.dart';
export 'src/material/app_bar.dart';
export 'src/material/app_bar_theme.dart';
export 'src/material/arc.dart';
export 'src/material/autocomplete.dart';
export 'src/material/badge.dart';
export 'src/material/badge_theme.dart';
export 'src/material/banner.dart';
export 'src/material/banner_theme.dart';
export 'src/material/bottom_app_bar.dart';
export 'src/material/bottom_app_bar_theme.dart';
export 'src/material/bottom_navigation_bar.dart';
export 'src/material/bottom_navigation_bar_theme.dart';
export 'src/material/bottom_sheet.dart';
export 'src/material/bottom_sheet_theme.dart';
export 'src/material/button.dart';
export 'src/material/button_bar.dart';
export 'src/material/button_bar_theme.dart';
export 'src/material/button_style.dart';
export 'src/material/button_style_button.dart';
export 'src/material/button_theme.dart';
export 'src/material/calendar_date_picker.dart';
export 'src/material/card.dart';
export 'src/material/card_theme.dart';
export 'src/material/carousel.dart';
export 'src/material/checkbox.dart';
export 'src/material/checkbox_list_tile.dart';
export 'src/material/checkbox_theme.dart';
export 'src/material/chip.dart';
export 'src/material/chip_theme.dart';
export 'src/material/choice_chip.dart';
export 'src/material/circle_avatar.dart';
export 'src/material/color_scheme.dart';
export 'src/material/colors.dart';
export 'src/material/constants.dart';
export 'src/material/curves.dart';
export 'src/material/data_table.dart';
export 'src/material/data_table_source.dart';
export 'src/material/data_table_theme.dart';
export 'src/material/date.dart';
export 'src/material/date_picker.dart';
export 'src/material/date_picker_theme.dart';
export 'src/material/debug.dart';
export 'src/material/desktop_text_selection.dart';
export 'src/material/desktop_text_selection_toolbar.dart';
export 'src/material/desktop_text_selection_toolbar_button.dart';
export 'src/material/dialog.dart';
export 'src/material/dialog_theme.dart';
export 'src/material/divider.dart';
export 'src/material/divider_theme.dart';
export 'src/material/drawer.dart';
export 'src/material/drawer_header.dart';
export 'src/material/drawer_theme.dart';
export 'src/material/dropdown.dart';
export 'src/material/dropdown_menu.dart';
export 'src/material/dropdown_menu_theme.dart';
export 'src/material/elevated_button.dart';
export 'src/material/elevated_button_theme.dart';
export 'src/material/elevation_overlay.dart';
export 'src/material/expand_icon.dart';
export 'src/material/expansion_panel.dart';
export 'src/material/expansion_tile.dart';
export 'src/material/expansion_tile_theme.dart';
export 'src/material/filled_button.dart';
export 'src/material/filled_button_theme.dart';
export 'src/material/filter_chip.dart';
export 'src/material/flexible_space_bar.dart';
export 'src/material/floating_action_button.dart';
export 'src/material/floating_action_button_location.dart';
export 'src/material/floating_action_button_theme.dart';
export 'src/material/flutter_logo.dart';
export 'src/material/grid_tile.dart';
export 'src/material/grid_tile_bar.dart';
export 'src/material/icon_button.dart';
export 'src/material/icon_button_theme.dart';
export 'src/material/icons.dart';
export 'src/material/ink_decoration.dart';
export 'src/material/ink_highlight.dart';
export 'src/material/ink_ripple.dart';
export 'src/material/ink_sparkle.dart';
export 'src/material/ink_splash.dart';
export 'src/material/ink_well.dart';
export 'src/material/input_border.dart';
export 'src/material/input_chip.dart';
export 'src/material/input_date_picker_form_field.dart';
export 'src/material/input_decorator.dart';
export 'src/material/list_tile.dart';
export 'src/material/list_tile_theme.dart';
export 'src/material/magnifier.dart';
export 'src/material/material.dart';
export 'src/material/material_button.dart';
export 'src/material/material_localizations.dart';
export 'src/material/material_state.dart';
export 'src/material/material_state_mixin.dart';
export 'src/material/menu_anchor.dart';
export 'src/material/menu_bar_theme.dart';
export 'src/material/menu_button_theme.dart';
export 'src/material/menu_style.dart';
export 'src/material/menu_theme.dart';
export 'src/material/mergeable_material.dart';
export 'src/material/motion.dart';
export 'src/material/navigation_bar.dart';
export 'src/material/navigation_bar_theme.dart';
export 'src/material/navigation_drawer.dart';
export 'src/material/navigation_drawer_theme.dart';
export 'src/material/navigation_rail.dart';
export 'src/material/navigation_rail_theme.dart';
export 'src/material/no_splash.dart';
export 'src/material/outlined_button.dart';
export 'src/material/outlined_button_theme.dart';
export 'src/material/page.dart';
export 'src/material/page_transitions_theme.dart';
export 'src/material/paginated_data_table.dart';
export 'src/material/popup_menu.dart';
export 'src/material/popup_menu_theme.dart';
export 'src/material/predictive_back_page_transitions_builder.dart';
export 'src/material/progress_indicator.dart';
export 'src/material/progress_indicator_theme.dart';
export 'src/material/radio.dart';
export 'src/material/radio_list_tile.dart';
export 'src/material/radio_theme.dart';
export 'src/material/range_slider.dart';
export 'src/material/refresh_indicator.dart';
export 'src/material/reorderable_list.dart';
export 'src/material/scaffold.dart';
export 'src/material/scrollbar.dart';
export 'src/material/scrollbar_theme.dart';
export 'src/material/search.dart';
export 'src/material/search_anchor.dart';
export 'src/material/search_bar_theme.dart';
export 'src/material/search_view_theme.dart';
export 'src/material/segmented_button.dart';
export 'src/material/segmented_button_theme.dart';
export 'src/material/selectable_text.dart';
export 'src/material/selection_area.dart';
export 'src/material/shadows.dart';
export 'src/material/slider.dart';
export 'src/material/slider_theme.dart';
export 'src/material/snack_bar.dart';
export 'src/material/snack_bar_theme.dart';
export 'src/material/spell_check_suggestions_toolbar.dart';
export 'src/material/spell_check_suggestions_toolbar_layout_delegate.dart';
export 'src/material/stepper.dart';
export 'src/material/switch.dart';
export 'src/material/switch_list_tile.dart';
export 'src/material/switch_theme.dart';
export 'src/material/tab_bar_theme.dart';
export 'src/material/tab_controller.dart';
export 'src/material/tab_indicator.dart';
export 'src/material/tabs.dart';
export 'src/material/text_button.dart';
export 'src/material/text_button_theme.dart';
export 'src/material/text_field.dart';
export 'src/material/text_form_field.dart';
export 'src/material/text_selection.dart';
export 'src/material/text_selection_theme.dart';
export 'src/material/text_selection_toolbar.dart';
export 'src/material/text_selection_toolbar_text_button.dart';
export 'src/material/text_theme.dart';
export 'src/material/theme.dart';
export 'src/material/theme_data.dart';
export 'src/material/time.dart';
export 'src/material/time_picker.dart';
export 'src/material/time_picker_theme.dart';
export 'src/material/toggle_buttons.dart';
export 'src/material/toggle_buttons_theme.dart';
export 'src/material/tooltip.dart';
export 'src/material/tooltip_theme.dart';
export 'src/material/tooltip_visibility.dart';
export 'src/material/typography.dart';
export 'src/material/user_accounts_drawer_header.dart';
export 'widgets.dart';
| flutter/packages/flutter/lib/material.dart/0 | {
"file_path": "flutter/packages/flutter/lib/material.dart",
"repo_id": "flutter",
"token_count": 2917
} | 222 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show defaultTargetPlatform;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'desktop_text_selection_toolbar.dart';
import 'desktop_text_selection_toolbar_button.dart';
import 'text_selection_toolbar.dart';
import 'text_selection_toolbar_button.dart';
/// The default Cupertino context menu for text selection for the current
/// platform with the given children.
///
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.platforms}
/// Builds the mobile Cupertino context menu on all mobile platforms, not just
/// iOS, and builds the desktop Cupertino context menu on all desktop platforms,
/// not just MacOS. For a widget that builds the native-looking context menu for
/// all platforms, see [AdaptiveTextSelectionToolbar].
/// {@endtemplate}
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar], which does the same thing as this widget
/// but for all platforms, not just the Cupertino-styled platforms.
/// * [CupertinoAdaptiveTextSelectionToolbar.getAdaptiveButtons], which builds
/// the Cupertino button Widgets for the current platform given
/// [ContextMenuButtonItem]s.
class CupertinoAdaptiveTextSelectionToolbar extends StatelessWidget {
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the
/// given [children].
///
/// See also:
///
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.buttonItems}
/// * [CupertinoAdaptiveTextSelectionToolbar.buttonItems], which takes a list
/// of [ContextMenuButtonItem]s instead of [children] widgets.
/// {@endtemplate}
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editable}
/// * [CupertinoAdaptiveTextSelectionToolbar.editable], which builds the
/// default Cupertino children for an editable field.
/// {@endtemplate}
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editableText}
/// * [CupertinoAdaptiveTextSelectionToolbar.editableText], which builds the
/// default Cupertino children for an [EditableText].
/// {@endtemplate}
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.selectable}
/// * [CupertinoAdaptiveTextSelectionToolbar.selectable], which builds the
/// Cupertino children for content that is selectable but not editable.
/// {@endtemplate}
const CupertinoAdaptiveTextSelectionToolbar({
super.key,
required this.children,
required this.anchors,
}) : buttonItems = null;
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] whose
/// children will be built from the given [buttonItems].
///
/// See also:
///
/// {@template flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.new}
/// * [CupertinoAdaptiveTextSelectionToolbar.new], which takes the children
/// directly as a list of widgets.
/// {@endtemplate}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editableText}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.selectable}
const CupertinoAdaptiveTextSelectionToolbar.buttonItems({
super.key,
required this.buttonItems,
required this.anchors,
}) : children = null;
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the
/// default children for an editable field.
///
/// If a callback is null, then its corresponding button will not be built.
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar.editable], which is similar to this but
/// includes Material and Cupertino toolbars.
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.new}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editableText}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.selectable}
CupertinoAdaptiveTextSelectionToolbar.editable({
super.key,
required ClipboardStatus clipboardStatus,
required VoidCallback? onCopy,
required VoidCallback? onCut,
required VoidCallback? onPaste,
required VoidCallback? onSelectAll,
required VoidCallback? onLookUp,
required VoidCallback? onSearchWeb,
required VoidCallback? onShare,
required VoidCallback? onLiveTextInput,
required this.anchors,
}) : children = null,
buttonItems = EditableText.getEditableButtonItems(
clipboardStatus: clipboardStatus,
onCopy: onCopy,
onCut: onCut,
onPaste: onPaste,
onSelectAll: onSelectAll,
onLookUp: onLookUp,
onSearchWeb: onSearchWeb,
onShare: onShare,
onLiveTextInput: onLiveTextInput
);
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the
/// default children for an [EditableText].
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar.editableText], which is similar to this
/// but includes Material and Cupertino toolbars.
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.new}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.selectable}
CupertinoAdaptiveTextSelectionToolbar.editableText({
super.key,
required EditableTextState editableTextState,
}) : children = null,
buttonItems = editableTextState.contextMenuButtonItems,
anchors = editableTextState.contextMenuAnchors;
/// Create an instance of [CupertinoAdaptiveTextSelectionToolbar] with the
/// default children for selectable, but not editable, content.
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar.selectable], which is similar to this but
/// includes Material and Cupertino toolbars.
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.new}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.cupertino.CupertinoAdaptiveTextSelectionToolbar.editableText}
CupertinoAdaptiveTextSelectionToolbar.selectable({
super.key,
required VoidCallback onCopy,
required VoidCallback onSelectAll,
required SelectionGeometry selectionGeometry,
required this.anchors,
}) : children = null,
buttonItems = SelectableRegion.getSelectableButtonItems(
selectionGeometry: selectionGeometry,
onCopy: onCopy,
onSelectAll: onSelectAll,
onShare: null, // See https://github.com/flutter/flutter/issues/141775.
);
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.anchors}
final TextSelectionToolbarAnchors anchors;
/// The children of the toolbar, typically buttons.
final List<Widget>? children;
/// The [ContextMenuButtonItem]s that will be turned into the correct button
/// widgets for the current platform.
final List<ContextMenuButtonItem>? buttonItems;
/// Returns a List of Widgets generated by turning [buttonItems] into the
/// default context menu buttons for Cupertino on the current platform.
///
/// This is useful when building a text selection toolbar with the default
/// button appearance for the given platform, but where the toolbar and/or the
/// button actions and labels may be custom.
///
/// Does not build Material buttons. On non-Apple platforms, Cupertino buttons
/// will still be used, because the Cupertino library does not access the
/// Material library. To get the native-looking buttons on every platform,
/// use [AdaptiveTextSelectionToolbar.getAdaptiveButtons] in the Material
/// library.
///
/// See also:
///
/// * [AdaptiveTextSelectionToolbar.getAdaptiveButtons], which is the Material
/// equivalent of this class and builds only the Material buttons. It
/// includes a live example of using `getAdaptiveButtons`.
static Iterable<Widget> getAdaptiveButtons(BuildContext context, List<ContextMenuButtonItem> buttonItems) {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.iOS:
return buttonItems.map((ContextMenuButtonItem buttonItem) {
return CupertinoTextSelectionToolbarButton.buttonItem(
buttonItem: buttonItem,
);
});
case TargetPlatform.linux:
case TargetPlatform.windows:
case TargetPlatform.macOS:
return buttonItems.map((ContextMenuButtonItem buttonItem) {
return CupertinoDesktopTextSelectionToolbarButton.buttonItem(
buttonItem: buttonItem,
);
});
}
}
@override
Widget build(BuildContext context) {
// If there aren't any buttons to build, build an empty toolbar.
if ((children?.isEmpty ?? false) || (buttonItems?.isEmpty ?? false)) {
return const SizedBox.shrink();
}
final List<Widget> resultChildren = children
?? getAdaptiveButtons(context, buttonItems!).toList();
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.iOS:
case TargetPlatform.fuchsia:
return CupertinoTextSelectionToolbar(
anchorAbove: anchors.primaryAnchor,
anchorBelow: anchors.secondaryAnchor ?? anchors.primaryAnchor,
children: resultChildren,
);
case TargetPlatform.linux:
case TargetPlatform.windows:
case TargetPlatform.macOS:
return CupertinoDesktopTextSelectionToolbar(
anchor: anchors.primaryAnchor,
children: resultChildren,
);
}
}
}
| flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/adaptive_text_selection_toolbar.dart",
"repo_id": "flutter",
"token_count": 3229
} | 223 |
// Copyright 2014 The Flutter Authors. 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 'colors.dart';
import 'list_section.dart';
// Used for iOS "Inset Grouped" margin, determined from SwiftUI's Forms in
// iOS 14.2 SDK.
const EdgeInsetsDirectional _kFormDefaultInsetGroupedRowsMargin = EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 20.0, 10.0);
/// An iOS-style form section.
///
/// The base constructor for [CupertinoFormSection] constructs an
/// edge-to-edge style section which includes an iOS-style header, rows,
/// the dividers between rows, and borders on top and bottom of the rows.
///
/// The [CupertinoFormSection.insetGrouped] constructor creates a round-edged and
/// padded section that is commonly seen in notched-displays like iPhone X and
/// beyond. Creates an iOS-style header, rows, and the dividers
/// between rows. Does not create borders on top and bottom of the rows.
///
/// The [header] parameter sets the form section header. The section header lies
/// above the [children] rows, with margins that match the iOS style.
///
/// The [footer] parameter sets the form section footer. The section footer
/// lies below the [children] rows.
///
/// The [children] parameter is required and sets the list of rows shown in
/// the section. The [children] parameter takes a list, as opposed to a more
/// efficient builder function that lazy builds, because forms are intended to
/// be short in row count. It is recommended that only [CupertinoFormRow] and
/// [CupertinoTextFormFieldRow] widgets be included in the [children] list in
/// order to retain the iOS look.
///
/// The [margin] parameter sets the spacing around the content area of the
/// section encapsulating [children].
///
/// The [decoration] parameter sets the decoration around [children].
/// If null, defaults to [CupertinoColors.secondarySystemGroupedBackground].
/// If null, defaults to 10.0 circular radius when constructing with
/// [CupertinoFormSection.insetGrouped]. Defaults to zero radius for the
/// standard [CupertinoFormSection] constructor.
///
/// The [backgroundColor] parameter sets the background color behind the section.
/// If null, defaults to [CupertinoColors.systemGroupedBackground].
///
/// {@macro flutter.material.Material.clipBehavior}
///
/// See also:
///
/// * [CupertinoFormRow], an iOS-style list tile, a typical child of
/// [CupertinoFormSection].
/// * [CupertinoListSection], an iOS-style list section.
class CupertinoFormSection extends StatelessWidget {
/// Creates a section that mimics standard iOS forms.
///
/// The base constructor for [CupertinoFormSection] constructs an
/// edge-to-edge style section which includes an iOS-style header,
/// rows, the dividers between rows, and borders on top and bottom of the rows.
///
/// The [header] parameter sets the form section header. The section header
/// lies above the [children] rows, with margins that match the iOS style.
///
/// The [footer] parameter sets the form section footer. The section footer
/// lies below the [children] rows.
///
/// The [children] parameter is required and sets the list of rows shown in
/// the section. The [children] parameter takes a list, as opposed to a more
/// efficient builder function that lazy builds, because forms are intended to
/// be short in row count. It is recommended that only [CupertinoFormRow] and
/// [CupertinoTextFormFieldRow] widgets be included in the [children] list in
/// order to retain the iOS look.
///
/// The [margin] parameter sets the spacing around the content area of the
/// section encapsulating [children], and defaults to zero padding.
///
/// The [decoration] parameter sets the decoration around [children].
/// If null, defaults to [CupertinoColors.secondarySystemGroupedBackground].
/// If null, defaults to 10.0 circular radius when constructing with
/// [CupertinoFormSection.insetGrouped]. Defaults to zero radius for the
/// standard [CupertinoFormSection] constructor.
///
/// The [backgroundColor] parameter sets the background color behind the
/// section. If null, defaults to [CupertinoColors.systemGroupedBackground].
///
/// {@macro flutter.material.Material.clipBehavior}
const CupertinoFormSection({
super.key,
required this.children,
this.header,
this.footer,
this.margin = EdgeInsets.zero,
this.backgroundColor = CupertinoColors.systemGroupedBackground,
this.decoration,
this.clipBehavior = Clip.none,
}) : _type = CupertinoListSectionType.base,
assert(children.length > 0);
/// Creates a section that mimics standard "Inset Grouped" iOS forms.
///
/// The [CupertinoFormSection.insetGrouped] constructor creates a round-edged and
/// padded section that is commonly seen in notched-displays like iPhone X and
/// beyond. Creates an iOS-style header, rows, and the dividers
/// between rows. Does not create borders on top and bottom of the rows.
///
/// The [header] parameter sets the form section header. The section header
/// lies above the [children] rows, with margins that match the iOS style.
///
/// The [footer] parameter sets the form section footer. The section footer
/// lies below the [children] rows.
///
/// The [children] parameter is required and sets the list of rows shown in
/// the section. The [children] parameter takes a list, as opposed to a more
/// efficient builder function that lazy builds, because forms are intended to
/// be short in row count. It is recommended that only [CupertinoFormRow] and
/// [CupertinoTextFormFieldRow] widgets be included in the [children] list in
/// order to retain the iOS look.
///
/// The [margin] parameter sets the spacing around the content area of the
/// section encapsulating [children], and defaults to the standard
/// notched-style iOS form padding.
///
/// The [decoration] parameter sets the decoration around [children].
/// If null, defaults to [CupertinoColors.secondarySystemGroupedBackground].
/// If null, defaults to 10.0 circular radius when constructing with
/// [CupertinoFormSection.insetGrouped]. Defaults to zero radius for the
/// standard [CupertinoFormSection] constructor.
///
/// The [backgroundColor] parameter sets the background color behind the
/// section. If null, defaults to [CupertinoColors.systemGroupedBackground].
///
/// {@macro flutter.material.Material.clipBehavior}
const CupertinoFormSection.insetGrouped({
super.key,
required this.children,
this.header,
this.footer,
this.margin = _kFormDefaultInsetGroupedRowsMargin,
this.backgroundColor = CupertinoColors.systemGroupedBackground,
this.decoration,
this.clipBehavior = Clip.none,
}) : _type = CupertinoListSectionType.insetGrouped,
assert(children.length > 0);
final CupertinoListSectionType _type;
/// Sets the form section header. The section header lies above the
/// [children] rows.
final Widget? header;
/// Sets the form section footer. The section footer lies below the
/// [children] rows.
final Widget? footer;
/// Margin around the content area of the section encapsulating [children].
///
/// Defaults to zero padding if constructed with standard
/// [CupertinoFormSection] constructor. Defaults to the standard notched-style
/// iOS margin when constructing with [CupertinoFormSection.insetGrouped].
final EdgeInsetsGeometry margin;
/// The list of rows in the section.
///
/// This takes a list, as opposed to a more efficient builder function that
/// lazy builds, because forms are intended to be short in row count. It is
/// recommended that only [CupertinoFormRow] and [CupertinoTextFormFieldRow]
/// widgets be included in the [children] list in order to retain the iOS look.
final List<Widget> children;
/// Sets the decoration around [children].
///
/// If null, background color defaults to
/// [CupertinoColors.secondarySystemGroupedBackground].
///
/// If null, border radius defaults to 10.0 circular radius when constructing
/// with [CupertinoFormSection.insetGrouped]. Defaults to zero radius for the
/// standard [CupertinoFormSection] constructor.
final BoxDecoration? decoration;
/// Sets the background color behind the section.
///
/// Defaults to [CupertinoColors.systemGroupedBackground].
final Color backgroundColor;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
@override
Widget build(BuildContext context) {
final Widget? headerWidget = header == null
? null
: DefaultTextStyle(
style: TextStyle(
fontSize: 13.0,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
),
child: header!);
final Widget? footerWidget = footer == null
? null
: DefaultTextStyle(
style: TextStyle(
fontSize: 13.0,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
),
child: footer!);
switch (_type) {
case CupertinoListSectionType.base:
return CupertinoListSection(
header: headerWidget,
footer: footerWidget,
margin: margin,
backgroundColor: backgroundColor,
decoration: decoration,
clipBehavior: clipBehavior,
hasLeading: false,
children: children,
);
case CupertinoListSectionType.insetGrouped:
return CupertinoListSection.insetGrouped(
header: headerWidget,
footer: footerWidget,
margin: margin,
backgroundColor: backgroundColor,
decoration: decoration,
clipBehavior: clipBehavior,
hasLeading: false,
children: children,
);
}
}
}
| flutter/packages/flutter/lib/src/cupertino/form_section.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/form_section.dart",
"repo_id": "flutter",
"token_count": 3001
} | 224 |
// Copyright 2014 The Flutter Authors. 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:collection';
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'theme.dart';
// Minimum padding from edges of the segmented control to edges of
// encompassing widget.
const EdgeInsetsGeometry _kHorizontalItemPadding = EdgeInsets.symmetric(horizontal: 16.0);
// Minimum height of the segmented control.
const double _kMinSegmentedControlHeight = 28.0;
// The duration of the fade animation used to transition when a new widget
// is selected.
const Duration _kFadeDuration = Duration(milliseconds: 165);
/// An iOS-style segmented control.
///
/// Displays the widgets provided in the [Map] of [children] in a
/// horizontal list. Used to select between a number of mutually exclusive
/// options. When one option in the segmented control is selected, the other
/// options in the segmented control cease to be selected.
///
/// A segmented control can feature any [Widget] as one of the values in its
/// [Map] of [children]. The type T is the type of the keys used
/// to identify each widget and determine which widget is selected. As
/// required by the [Map] class, keys must be of consistent types
/// and must be comparable. The ordering of the keys will determine the order
/// of the widgets in the segmented control.
///
/// When the state of the segmented control changes, the widget calls the
/// [onValueChanged] callback. The map key associated with the newly selected
/// widget is returned in the [onValueChanged] callback. Typically, widgets
/// that use a segmented control will listen for the [onValueChanged] callback
/// and rebuild the segmented control with a new [groupValue] to update which
/// option is currently selected.
///
/// The [children] will be displayed in the order of the keys in the [Map].
/// The height of the segmented control is determined by the height of the
/// tallest widget provided as a value in the [Map] of [children].
/// The width of each child in the segmented control will be equal to the width
/// of widest child, unless the combined width of the children is wider than
/// the available horizontal space. In this case, the available horizontal space
/// is divided by the number of provided [children] to determine the width of
/// each widget. The selection area for each of the widgets in the [Map] of
/// [children] will then be expanded to fill the calculated space, so each
/// widget will appear to have the same dimensions.
///
/// A segmented control may optionally be created with custom colors. The
/// [unselectedColor], [selectedColor], [borderColor], and [pressedColor]
/// arguments can be used to override the segmented control's colors from
/// [CupertinoTheme] defaults.
///
/// {@tool dartpad}
/// This example shows a [CupertinoSegmentedControl] with an enum type.
///
/// The callback provided to [onValueChanged] should update the state of
/// the parent [StatefulWidget] using the [State.setState] method, so that
/// the parent gets rebuilt; for example:
///
/// ** See code in examples/api/lib/cupertino/segmented_control/cupertino_segmented_control.0.dart **
/// {@end-tool}
/// See also:
///
/// * [CupertinoSegmentedControl], a segmented control widget in the style used
/// up until iOS 13.
/// * <https://developer.apple.com/design/human-interface-guidelines/ios/controls/segmented-controls/>
class CupertinoSegmentedControl<T extends Object> extends StatefulWidget {
/// Creates an iOS-style segmented control bar.
///
/// The [children] argument must be an ordered [Map] such as a
/// [LinkedHashMap]. Further, the length of the [children] list must be
/// greater than one.
///
/// Each widget value in the map of [children] must have an associated key
/// that uniquely identifies this widget. This key is what will be returned
/// in the [onValueChanged] callback when a new value from the [children] map
/// is selected.
///
/// The [groupValue] is the currently selected value for the segmented control.
/// If no [groupValue] is provided, or the [groupValue] is null, no widget will
/// appear as selected. The [groupValue] must be either null or one of the keys
/// in the [children] map.
CupertinoSegmentedControl({
super.key,
required this.children,
required this.onValueChanged,
this.groupValue,
this.unselectedColor,
this.selectedColor,
this.borderColor,
this.pressedColor,
this.padding,
}) : assert(children.length >= 2),
assert(
groupValue == null || children.keys.any((T child) => child == groupValue),
'The groupValue must be either null or one of the keys in the children map.',
);
/// The identifying keys and corresponding widget values in the
/// segmented control.
///
/// The map must have more than one entry.
/// This attribute must be an ordered [Map] such as a [LinkedHashMap].
final Map<T, Widget> children;
/// The identifier of the widget that is currently selected.
///
/// This must be one of the keys in the [Map] of [children].
/// If this attribute is null, no widget will be initially selected.
final T? groupValue;
/// The callback that is called when a new option is tapped.
///
/// The segmented control passes the newly selected widget's associated key
/// to the callback but does not actually change state until the parent
/// widget rebuilds the segmented control with the new [groupValue].
final ValueChanged<T> onValueChanged;
/// The color used to fill the backgrounds of unselected widgets and as the
/// text color of the selected widget.
///
/// Defaults to [CupertinoTheme]'s `primaryContrastingColor` if null.
final Color? unselectedColor;
/// The color used to fill the background of the selected widget and as the text
/// color of unselected widgets.
///
/// Defaults to [CupertinoTheme]'s `primaryColor` if null.
final Color? selectedColor;
/// The color used as the border around each widget.
///
/// Defaults to [CupertinoTheme]'s `primaryColor` if null.
final Color? borderColor;
/// The color used to fill the background of the widget the user is
/// temporarily interacting with through a long press or drag.
///
/// Defaults to the selectedColor at 20% opacity if null.
final Color? pressedColor;
/// The CupertinoSegmentedControl will be placed inside this padding.
///
/// Defaults to EdgeInsets.symmetric(horizontal: 16.0)
final EdgeInsetsGeometry? padding;
@override
State<CupertinoSegmentedControl<T>> createState() => _SegmentedControlState<T>();
}
class _SegmentedControlState<T extends Object> extends State<CupertinoSegmentedControl<T>>
with TickerProviderStateMixin<CupertinoSegmentedControl<T>> {
T? _pressedKey;
final List<AnimationController> _selectionControllers = <AnimationController>[];
final List<ColorTween> _childTweens = <ColorTween>[];
late ColorTween _forwardBackgroundColorTween;
late ColorTween _reverseBackgroundColorTween;
late ColorTween _textColorTween;
Color? _selectedColor;
Color? _unselectedColor;
Color? _borderColor;
Color? _pressedColor;
AnimationController createAnimationController() {
return AnimationController(
duration: _kFadeDuration,
vsync: this,
)..addListener(() {
setState(() {
// State of background/text colors has changed
});
});
}
bool _updateColors() {
assert(mounted, 'This should only be called after didUpdateDependencies');
bool changed = false;
final Color selectedColor = widget.selectedColor ?? CupertinoTheme.of(context).primaryColor;
if (_selectedColor != selectedColor) {
changed = true;
_selectedColor = selectedColor;
}
final Color unselectedColor = widget.unselectedColor ?? CupertinoTheme.of(context).primaryContrastingColor;
if (_unselectedColor != unselectedColor) {
changed = true;
_unselectedColor = unselectedColor;
}
final Color borderColor = widget.borderColor ?? CupertinoTheme.of(context).primaryColor;
if (_borderColor != borderColor) {
changed = true;
_borderColor = borderColor;
}
final Color pressedColor = widget.pressedColor ?? CupertinoTheme.of(context).primaryColor.withOpacity(0.2);
if (_pressedColor != pressedColor) {
changed = true;
_pressedColor = pressedColor;
}
_forwardBackgroundColorTween = ColorTween(
begin: _pressedColor,
end: _selectedColor,
);
_reverseBackgroundColorTween = ColorTween(
begin: _unselectedColor,
end: _selectedColor,
);
_textColorTween = ColorTween(
begin: _selectedColor,
end: _unselectedColor,
);
return changed;
}
void _updateAnimationControllers() {
assert(mounted, 'This should only be called after didUpdateDependencies');
for (final AnimationController controller in _selectionControllers) {
controller.dispose();
}
_selectionControllers.clear();
_childTweens.clear();
for (final T key in widget.children.keys) {
final AnimationController animationController = createAnimationController();
if (widget.groupValue == key) {
_childTweens.add(_reverseBackgroundColorTween);
animationController.value = 1.0;
} else {
_childTweens.add(_forwardBackgroundColorTween);
}
_selectionControllers.add(animationController);
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_updateColors()) {
_updateAnimationControllers();
}
}
@override
void didUpdateWidget(CupertinoSegmentedControl<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (_updateColors() || oldWidget.children.length != widget.children.length) {
_updateAnimationControllers();
}
if (oldWidget.groupValue != widget.groupValue) {
int index = 0;
for (final T key in widget.children.keys) {
if (widget.groupValue == key) {
_childTweens[index] = _forwardBackgroundColorTween;
_selectionControllers[index].forward();
} else {
_childTweens[index] = _reverseBackgroundColorTween;
_selectionControllers[index].reverse();
}
index += 1;
}
}
}
@override
void dispose() {
for (final AnimationController animationController in _selectionControllers) {
animationController.dispose();
}
super.dispose();
}
void _onTapDown(T currentKey) {
if (_pressedKey == null && currentKey != widget.groupValue) {
setState(() {
_pressedKey = currentKey;
});
}
}
void _onTapCancel() {
setState(() {
_pressedKey = null;
});
}
void _onTap(T currentKey) {
if (currentKey != _pressedKey) {
return;
}
if (currentKey != widget.groupValue) {
widget.onValueChanged(currentKey);
}
_pressedKey = null;
}
Color? getTextColor(int index, T currentKey) {
if (_selectionControllers[index].isAnimating) {
return _textColorTween.evaluate(_selectionControllers[index]);
}
if (widget.groupValue == currentKey) {
return _unselectedColor;
}
return _selectedColor;
}
Color? getBackgroundColor(int index, T currentKey) {
if (_selectionControllers[index].isAnimating) {
return _childTweens[index].evaluate(_selectionControllers[index]);
}
if (widget.groupValue == currentKey) {
return _selectedColor;
}
if (_pressedKey == currentKey) {
return _pressedColor;
}
return _unselectedColor;
}
@override
Widget build(BuildContext context) {
final List<Widget> gestureChildren = <Widget>[];
final List<Color> backgroundColors = <Color>[];
int index = 0;
int? selectedIndex;
int? pressedIndex;
for (final T currentKey in widget.children.keys) {
selectedIndex = (widget.groupValue == currentKey) ? index : selectedIndex;
pressedIndex = (_pressedKey == currentKey) ? index : pressedIndex;
final TextStyle textStyle = DefaultTextStyle.of(context).style.copyWith(
color: getTextColor(index, currentKey),
);
final IconThemeData iconTheme = IconThemeData(
color: getTextColor(index, currentKey),
);
Widget child = Center(
child: widget.children[currentKey],
);
child = MouseRegion(
cursor: kIsWeb ? SystemMouseCursors.click : MouseCursor.defer,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (TapDownDetails event) {
_onTapDown(currentKey);
},
onTapCancel: _onTapCancel,
onTap: () {
_onTap(currentKey);
},
child: IconTheme(
data: iconTheme,
child: DefaultTextStyle(
style: textStyle,
child: Semantics(
button: true,
inMutuallyExclusiveGroup: true,
selected: widget.groupValue == currentKey,
child: child,
),
),
),
),
);
backgroundColors.add(getBackgroundColor(index, currentKey)!);
gestureChildren.add(child);
index += 1;
}
final Widget box = _SegmentedControlRenderWidget<T>(
selectedIndex: selectedIndex,
pressedIndex: pressedIndex,
backgroundColors: backgroundColors,
borderColor: _borderColor!,
children: gestureChildren,
);
return Padding(
padding: widget.padding ?? _kHorizontalItemPadding,
child: UnconstrainedBox(
constrainedAxis: Axis.horizontal,
child: box,
),
);
}
}
class _SegmentedControlRenderWidget<T> extends MultiChildRenderObjectWidget {
const _SegmentedControlRenderWidget({
super.key,
super.children,
required this.selectedIndex,
required this.pressedIndex,
required this.backgroundColors,
required this.borderColor,
});
final int? selectedIndex;
final int? pressedIndex;
final List<Color> backgroundColors;
final Color borderColor;
@override
RenderObject createRenderObject(BuildContext context) {
return _RenderSegmentedControl<T>(
textDirection: Directionality.of(context),
selectedIndex: selectedIndex,
pressedIndex: pressedIndex,
backgroundColors: backgroundColors,
borderColor: borderColor,
);
}
@override
void updateRenderObject(BuildContext context, _RenderSegmentedControl<T> renderObject) {
renderObject
..textDirection = Directionality.of(context)
..selectedIndex = selectedIndex
..pressedIndex = pressedIndex
..backgroundColors = backgroundColors
..borderColor = borderColor;
}
}
class _SegmentedControlContainerBoxParentData extends ContainerBoxParentData<RenderBox> {
RRect? surroundingRect;
}
typedef _NextChild = RenderBox? Function(RenderBox child);
class _RenderSegmentedControl<T> extends RenderBox
with ContainerRenderObjectMixin<RenderBox, ContainerBoxParentData<RenderBox>>,
RenderBoxContainerDefaultsMixin<RenderBox, ContainerBoxParentData<RenderBox>> {
_RenderSegmentedControl({
required int? selectedIndex,
required int? pressedIndex,
required TextDirection textDirection,
required List<Color> backgroundColors,
required Color borderColor,
}) : _textDirection = textDirection,
_selectedIndex = selectedIndex,
_pressedIndex = pressedIndex,
_backgroundColors = backgroundColors,
_borderColor = borderColor;
int? get selectedIndex => _selectedIndex;
int? _selectedIndex;
set selectedIndex(int? value) {
if (_selectedIndex == value) {
return;
}
_selectedIndex = value;
markNeedsPaint();
}
int? get pressedIndex => _pressedIndex;
int? _pressedIndex;
set pressedIndex(int? value) {
if (_pressedIndex == value) {
return;
}
_pressedIndex = value;
markNeedsPaint();
}
TextDirection get textDirection => _textDirection;
TextDirection _textDirection;
set textDirection(TextDirection value) {
if (_textDirection == value) {
return;
}
_textDirection = value;
markNeedsLayout();
}
List<Color> get backgroundColors => _backgroundColors;
List<Color> _backgroundColors;
set backgroundColors(List<Color> value) {
if (_backgroundColors == value) {
return;
}
_backgroundColors = value;
markNeedsPaint();
}
Color get borderColor => _borderColor;
Color _borderColor;
set borderColor(Color value) {
if (_borderColor == value) {
return;
}
_borderColor = value;
markNeedsPaint();
}
@override
double computeMinIntrinsicWidth(double height) {
RenderBox? child = firstChild;
double minWidth = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final double childWidth = child.getMinIntrinsicWidth(height);
minWidth = math.max(minWidth, childWidth);
child = childParentData.nextSibling;
}
return minWidth * childCount;
}
@override
double computeMaxIntrinsicWidth(double height) {
RenderBox? child = firstChild;
double maxWidth = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final double childWidth = child.getMaxIntrinsicWidth(height);
maxWidth = math.max(maxWidth, childWidth);
child = childParentData.nextSibling;
}
return maxWidth * childCount;
}
@override
double computeMinIntrinsicHeight(double width) {
RenderBox? child = firstChild;
double minHeight = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final double childHeight = child.getMinIntrinsicHeight(width);
minHeight = math.max(minHeight, childHeight);
child = childParentData.nextSibling;
}
return minHeight;
}
@override
double computeMaxIntrinsicHeight(double width) {
RenderBox? child = firstChild;
double maxHeight = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final double childHeight = child.getMaxIntrinsicHeight(width);
maxHeight = math.max(maxHeight, childHeight);
child = childParentData.nextSibling;
}
return maxHeight;
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
return defaultComputeDistanceToHighestActualBaseline(baseline);
}
@override
void setupParentData(RenderBox child) {
if (child.parentData is! _SegmentedControlContainerBoxParentData) {
child.parentData = _SegmentedControlContainerBoxParentData();
}
}
void _layoutRects(_NextChild nextChild, RenderBox? leftChild, RenderBox? rightChild) {
RenderBox? child = leftChild;
double start = 0.0;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
final Offset childOffset = Offset(start, 0.0);
childParentData.offset = childOffset;
final Rect childRect = Rect.fromLTWH(start, 0.0, child.size.width, child.size.height);
final RRect rChildRect;
if (child == leftChild) {
rChildRect = RRect.fromRectAndCorners(
childRect,
topLeft: const Radius.circular(3.0),
bottomLeft: const Radius.circular(3.0),
);
} else if (child == rightChild) {
rChildRect = RRect.fromRectAndCorners(
childRect,
topRight: const Radius.circular(3.0),
bottomRight: const Radius.circular(3.0),
);
} else {
rChildRect = RRect.fromRectAndCorners(childRect);
}
childParentData.surroundingRect = rChildRect;
start += child.size.width;
child = nextChild(child);
}
}
Size _calculateChildSize(BoxConstraints constraints) {
double maxHeight = _kMinSegmentedControlHeight;
double childWidth = constraints.minWidth / childCount;
RenderBox? child = firstChild;
while (child != null) {
childWidth = math.max(childWidth, child.getMaxIntrinsicWidth(double.infinity));
child = childAfter(child);
}
childWidth = math.min(childWidth, constraints.maxWidth / childCount);
child = firstChild;
while (child != null) {
final double boxHeight = child.getMaxIntrinsicHeight(childWidth);
maxHeight = math.max(maxHeight, boxHeight);
child = childAfter(child);
}
return Size(childWidth, maxHeight);
}
Size _computeOverallSizeFromChildSize(Size childSize) {
return constraints.constrain(Size(childSize.width * childCount, childSize.height));
}
@override
double? computeDryBaseline(covariant BoxConstraints constraints, TextBaseline baseline) {
final Size childSize = _calculateChildSize(constraints);
final BoxConstraints childConstraints = BoxConstraints.tight(childSize);
BaselineOffset baselineOffset = BaselineOffset.noBaseline;
for (RenderBox? child = firstChild; child != null; child = childAfter(child)) {
baselineOffset = baselineOffset.minOf(BaselineOffset(child.getDryBaseline(childConstraints, baseline)));
}
return baselineOffset.offset;
}
@override
Size computeDryLayout(BoxConstraints constraints) {
final Size childSize = _calculateChildSize(constraints);
return _computeOverallSizeFromChildSize(childSize);
}
@override
void performLayout() {
final BoxConstraints constraints = this.constraints;
final Size childSize = _calculateChildSize(constraints);
final BoxConstraints childConstraints = BoxConstraints.tightFor(
width: childSize.width,
height: childSize.height,
);
RenderBox? child = firstChild;
while (child != null) {
child.layout(childConstraints, parentUsesSize: true);
child = childAfter(child);
}
switch (textDirection) {
case TextDirection.rtl:
_layoutRects(
childBefore,
lastChild,
firstChild,
);
case TextDirection.ltr:
_layoutRects(
childAfter,
firstChild,
lastChild,
);
}
size = _computeOverallSizeFromChildSize(childSize);
}
@override
void paint(PaintingContext context, Offset offset) {
RenderBox? child = firstChild;
int index = 0;
while (child != null) {
_paintChild(context, offset, child, index);
child = childAfter(child);
index += 1;
}
}
void _paintChild(PaintingContext context, Offset offset, RenderBox child, int childIndex) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
context.canvas.drawRRect(
childParentData.surroundingRect!.shift(offset),
Paint()
..color = backgroundColors[childIndex]
..style = PaintingStyle.fill,
);
context.canvas.drawRRect(
childParentData.surroundingRect!.shift(offset),
Paint()
..color = borderColor
..strokeWidth = 1.0
..style = PaintingStyle.stroke,
);
context.paintChild(child, childParentData.offset + offset);
}
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
RenderBox? child = lastChild;
while (child != null) {
final _SegmentedControlContainerBoxParentData childParentData = child.parentData! as _SegmentedControlContainerBoxParentData;
if (childParentData.surroundingRect!.contains(position)) {
return result.addWithPaintOffset(
offset: childParentData.offset,
position: position,
hitTest: (BoxHitTestResult result, Offset localOffset) {
assert(localOffset == position - childParentData.offset);
return child!.hitTest(result, position: localOffset);
},
);
}
child = childParentData.previousSibling;
}
return false;
}
}
| flutter/packages/flutter/lib/src/cupertino/segmented_control.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/segmented_control.dart",
"repo_id": "flutter",
"token_count": 8301
} | 225 |
The rule for packages in this directory is that they can depend on
nothing but core Dart packages. They can't depend on `dart:ui`, they
can't depend on any `package:`, and they can't depend on anything
outside this directory.
Currently they do depend on dart:ui, but only for `VoidCallback` and
`clampDouble` (and maybe one day `lerpDouble`), which are all intended
to be moved out of `dart:ui` and into `dart:core`.
There is currently also an unfortunate dependency on the platform
dispatcher logic (SingletonFlutterWindow, Brightness,
PlatformDispatcher, window), though that should probably move to the
'services' library.
See also:
* https://github.com/dart-lang/sdk/issues/25217
| flutter/packages/flutter/lib/src/foundation/README.md/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/README.md",
"repo_id": "flutter",
"token_count": 190
} | 226 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import '_capabilities_io.dart'
if (dart.library.js_util) '_capabilities_web.dart' as capabilities;
/// Returns true if the application is using CanvasKit.
///
/// Only to be used for web.
bool get isCanvasKit => capabilities.isCanvasKit;
/// Returns true if the application is using Skwasm.
///
/// Only to be used for web.
bool get isSkwasm => capabilities.isSkwasm;
/// Returns true if the application is using CanvasKit or Skwasm.
///
/// Only to be used for web.
bool get isSkiaWeb => isCanvasKit || isSkwasm;
| flutter/packages/flutter/lib/src/foundation/capabilities.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/capabilities.dart",
"repo_id": "flutter",
"token_count": 207
} | 227 |
// Copyright 2014 The Flutter 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 implements debugPrint in terms of print, so avoiding
// calling "print" is sort of a non-starter here...
// ignore_for_file: avoid_print
import 'dart:async';
import 'dart:collection';
/// Signature for [debugPrint] implementations.
///
/// If a [wrapWidth] is provided, each line of the [message] is word-wrapped to
/// that width. (Lines may be separated by newline characters, as in '\n'.)
///
/// By default, this function very crudely attempts to throttle the rate at
/// which messages are sent to avoid data loss on Android. This means that
/// interleaving calls to this function (directly or indirectly via, e.g.,
/// [debugDumpRenderTree] or [debugDumpApp]) and to the Dart [print] method can
/// result in out-of-order messages in the logs.
///
/// The implementation of this function can be replaced by setting the
/// [debugPrint] variable to a new implementation that matches the
/// [DebugPrintCallback] signature. For example, flutter_test does this.
///
/// The default value is [debugPrintThrottled]. For a version that acts
/// identically but does not throttle, use [debugPrintSynchronously].
typedef DebugPrintCallback = void Function(String? message, { int? wrapWidth });
/// Prints a message to the console, which you can access using the "flutter"
/// tool's "logs" command ("flutter logs").
///
/// The [debugPrint] function logs to console even in [release mode](https://docs.flutter.dev/testing/build-modes#release).
/// As per convention, calls to [debugPrint] should be within a debug mode check or an assert:
/// ```dart
/// if (kDebugMode) {
/// debugPrint('A useful message');
/// }
/// ```
///
/// See also:
///
/// * [DebugPrintCallback], for function parameters and usage details.
/// * [debugPrintThrottled], the default implementation.
DebugPrintCallback debugPrint = debugPrintThrottled;
/// Alternative implementation of [debugPrint] that does not throttle.
/// Used by tests.
void debugPrintSynchronously(String? message, { int? wrapWidth }) {
if (message != null && wrapWidth != null) {
print(message.split('\n').expand<String>((String line) => debugWordWrap(line, wrapWidth)).join('\n'));
} else {
print(message);
}
}
/// Implementation of [debugPrint] that throttles messages. This avoids dropping
/// messages on platforms that rate-limit their logging (for example, Android).
///
/// If `wrapWidth` is not null, the message is wrapped using [debugWordWrap].
void debugPrintThrottled(String? message, { int? wrapWidth }) {
final List<String> messageLines = message?.split('\n') ?? <String>['null'];
if (wrapWidth != null) {
_debugPrintBuffer.addAll(messageLines.expand<String>((String line) => debugWordWrap(line, wrapWidth)));
} else {
_debugPrintBuffer.addAll(messageLines);
}
if (!_debugPrintScheduled) {
_debugPrintTask();
}
}
int _debugPrintedCharacters = 0;
const int _kDebugPrintCapacity = 12 * 1024;
const Duration _kDebugPrintPauseTime = Duration(seconds: 1);
final Queue<String> _debugPrintBuffer = Queue<String>();
final Stopwatch _debugPrintStopwatch = Stopwatch(); // flutter_ignore: stopwatch (see analyze.dart)
// Ignore context: This is not used in tests, only for throttled logging.
Completer<void>? _debugPrintCompleter;
bool _debugPrintScheduled = false;
void _debugPrintTask() {
_debugPrintScheduled = false;
if (_debugPrintStopwatch.elapsed > _kDebugPrintPauseTime) {
_debugPrintStopwatch.stop();
_debugPrintStopwatch.reset();
_debugPrintedCharacters = 0;
}
while (_debugPrintedCharacters < _kDebugPrintCapacity && _debugPrintBuffer.isNotEmpty) {
final String line = _debugPrintBuffer.removeFirst();
_debugPrintedCharacters += line.length; // TODO(ianh): Use the UTF-8 byte length instead
print(line);
}
if (_debugPrintBuffer.isNotEmpty) {
_debugPrintScheduled = true;
_debugPrintedCharacters = 0;
Timer(_kDebugPrintPauseTime, _debugPrintTask);
_debugPrintCompleter ??= Completer<void>();
} else {
_debugPrintStopwatch.start();
_debugPrintCompleter?.complete();
_debugPrintCompleter = null;
}
}
/// A Future that resolves when there is no longer any buffered content being
/// printed by [debugPrintThrottled] (which is the default implementation for
/// [debugPrint], which is used to report errors to the console).
Future<void> get debugPrintDone => _debugPrintCompleter?.future ?? Future<void>.value();
final RegExp _indentPattern = RegExp('^ *(?:[-+*] |[0-9]+[.):] )?');
enum _WordWrapParseMode { inSpace, inWord, atBreak }
/// Wraps the given string at the given width.
///
/// The `message` should not contain newlines (`\n`, U+000A). Strings that may
/// contain newlines should be [String.split] before being wrapped.
///
/// Wrapping occurs at space characters (U+0020). Lines that start with an
/// octothorpe ("#", U+0023) are not wrapped (so for example, Dart stack traces
/// won't be wrapped).
///
/// Subsequent lines attempt to duplicate the indentation of the first line, for
/// example if the first line starts with multiple spaces. In addition, if a
/// `wrapIndent` argument is provided, each line after the first is prefixed by
/// that string.
///
/// This is not suitable for use with arbitrary Unicode text. For example, it
/// doesn't implement UAX #14, can't handle ideographic text, doesn't hyphenate,
/// and so forth. It is only intended for formatting error messages.
///
/// The default [debugPrint] implementation uses this for its line wrapping.
Iterable<String> debugWordWrap(String message, int width, { String wrapIndent = '' }) {
if (message.length < width || message.trimLeft()[0] == '#') {
return <String>[message];
}
final List<String> wrapped = <String>[];
final Match prefixMatch = _indentPattern.matchAsPrefix(message)!;
final String prefix = wrapIndent + ' ' * prefixMatch.group(0)!.length;
int start = 0;
int startForLengthCalculations = 0;
bool addPrefix = false;
int index = prefix.length;
_WordWrapParseMode mode = _WordWrapParseMode.inSpace;
late int lastWordStart;
int? lastWordEnd;
while (true) {
switch (mode) {
case _WordWrapParseMode.inSpace: // at start of break point (or start of line); can't break until next break
while ((index < message.length) && (message[index] == ' ')) {
index += 1;
}
lastWordStart = index;
mode = _WordWrapParseMode.inWord;
case _WordWrapParseMode.inWord: // looking for a good break point
while ((index < message.length) && (message[index] != ' ')) {
index += 1;
}
mode = _WordWrapParseMode.atBreak;
case _WordWrapParseMode.atBreak: // at start of break point
if ((index - startForLengthCalculations > width) || (index == message.length)) {
// we are over the width line, so break
if ((index - startForLengthCalculations <= width) || (lastWordEnd == null)) {
// we should use this point, because either it doesn't actually go over the
// end (last line), or it does, but there was no earlier break point
lastWordEnd = index;
}
if (addPrefix) {
wrapped.add(prefix + message.substring(start, lastWordEnd));
} else {
wrapped.add(message.substring(start, lastWordEnd));
addPrefix = true;
}
if (lastWordEnd >= message.length) {
return wrapped;
}
// just yielded a line
if (lastWordEnd == index) {
// we broke at current position
// eat all the spaces, then set our start point
while ((index < message.length) && (message[index] == ' ')) {
index += 1;
}
start = index;
mode = _WordWrapParseMode.inWord;
} else {
// we broke at the previous break point, and we're at the start of a new one
assert(lastWordStart > lastWordEnd);
start = lastWordStart;
mode = _WordWrapParseMode.atBreak;
}
startForLengthCalculations = start - prefix.length;
assert(addPrefix);
lastWordEnd = null;
} else {
// save this break point, we're not yet over the line width
lastWordEnd = index;
// skip to the end of this break point
mode = _WordWrapParseMode.inSpace;
}
}
}
}
| flutter/packages/flutter/lib/src/foundation/print.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/print.dart",
"repo_id": "flutter",
"token_count": 2893
} | 228 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart' show clampDouble;
import 'events.dart';
import 'recognizer.dart';
export 'dart:ui' show Offset, PointerDeviceKind;
export 'events.dart' show PointerDownEvent, PointerEvent;
enum _ForceState {
// No pointer has touched down and the detector is ready for a pointer down to occur.
ready,
// A pointer has touched down, but a force press gesture has not yet been detected.
possible,
// A pointer is down and a force press gesture has been detected. However, if
// the ForcePressGestureRecognizer is the only recognizer in the arena, thus
// accepted as soon as the gesture state is possible, the gesture will not
// yet have started.
accepted,
// A pointer is down and the gesture has started, ie. the pressure of the pointer
// has just become greater than the ForcePressGestureRecognizer.startPressure.
started,
// A pointer is down and the pressure of the pointer has just become greater
// than the ForcePressGestureRecognizer.peakPressure. Even after a pointer
// crosses this threshold, onUpdate callbacks will still be sent.
peaked,
}
/// Details object for callbacks that use [GestureForcePressStartCallback],
/// [GestureForcePressPeakCallback], [GestureForcePressEndCallback] or
/// [GestureForcePressUpdateCallback].
///
/// See also:
///
/// * [ForcePressGestureRecognizer.onStart], [ForcePressGestureRecognizer.onPeak],
/// [ForcePressGestureRecognizer.onEnd], and [ForcePressGestureRecognizer.onUpdate]
/// which use [ForcePressDetails].
class ForcePressDetails {
/// Creates details for a [GestureForcePressStartCallback],
/// [GestureForcePressPeakCallback] or [GestureForcePressEndCallback].
ForcePressDetails({
required this.globalPosition,
Offset? localPosition,
required this.pressure,
}) : localPosition = localPosition ?? globalPosition;
/// The global position at which the function was called.
final Offset globalPosition;
/// The local position at which the function was called.
final Offset localPosition;
/// The pressure of the pointer on the screen.
final double pressure;
}
/// Signature used by a [ForcePressGestureRecognizer] for when a pointer has
/// pressed with at least [ForcePressGestureRecognizer.startPressure].
typedef GestureForcePressStartCallback = void Function(ForcePressDetails details);
/// Signature used by [ForcePressGestureRecognizer] for when a pointer that has
/// pressed with at least [ForcePressGestureRecognizer.peakPressure].
typedef GestureForcePressPeakCallback = void Function(ForcePressDetails details);
/// Signature used by [ForcePressGestureRecognizer] during the frames
/// after the triggering of a [ForcePressGestureRecognizer.onStart] callback.
typedef GestureForcePressUpdateCallback = void Function(ForcePressDetails details);
/// Signature for when the pointer that previously triggered a
/// [ForcePressGestureRecognizer.onStart] callback is no longer in contact
/// with the screen.
typedef GestureForcePressEndCallback = void Function(ForcePressDetails details);
/// Signature used by [ForcePressGestureRecognizer] for interpolating the raw
/// device pressure to a value in the range `[0, 1]` given the device's pressure
/// min and pressure max.
typedef GestureForceInterpolation = double Function(double pressureMin, double pressureMax, double pressure);
/// Recognizes a force press on devices that have force sensors.
///
/// Only the force from a single pointer is used to invoke events. A tap
/// recognizer will win against this recognizer on pointer up as long as the
/// pointer has not pressed with a force greater than
/// [ForcePressGestureRecognizer.startPressure]. A long press recognizer will
/// win when the press down time exceeds the threshold time as long as the
/// pointer's pressure was never greater than
/// [ForcePressGestureRecognizer.startPressure] in that duration.
///
/// As of November, 2018 iPhone devices of generation 6S and higher have
/// force touch functionality, with the exception of the iPhone XR. In addition,
/// a small handful of Android devices have this functionality as well.
///
/// Devices with faux screen pressure sensors like the Pixel 2 and 3 will not
/// send any force press related callbacks.
///
/// Reported pressure will always be in the range 0.0 to 1.0, where 1.0 is
/// maximum pressure and 0.0 is minimum pressure. If using a custom
/// [interpolation] callback, the pressure reported will correspond to that
/// custom curve.
class ForcePressGestureRecognizer extends OneSequenceGestureRecognizer {
/// Creates a force press gesture recognizer.
///
/// The [startPressure] defaults to 0.4, and [peakPressure] defaults to 0.85
/// where a value of 0.0 is no pressure and a value of 1.0 is maximum pressure.
///
/// The [startPressure], [peakPressure] and [interpolation] arguments must not
/// be null. The [peakPressure] argument must be greater than [startPressure].
/// The [interpolation] callback must always return a value in the range 0.0
/// to 1.0 for values of `pressure` that are between `pressureMin` and
/// `pressureMax`.
///
/// {@macro flutter.gestures.GestureRecognizer.supportedDevices}
ForcePressGestureRecognizer({
this.startPressure = 0.4,
this.peakPressure = 0.85,
this.interpolation = _inverseLerp,
super.debugOwner,
super.supportedDevices,
super.allowedButtonsFilter,
}) : assert(peakPressure > startPressure);
/// A pointer is in contact with the screen and has just pressed with a force
/// exceeding the [startPressure]. Consequently, if there were other gesture
/// detectors, only the force press gesture will be detected and all others
/// will be rejected.
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [ForcePressDetails] object.
GestureForcePressStartCallback? onStart;
/// A pointer is in contact with the screen and is either moving on the plane
/// of the screen, pressing the screen with varying forces or both
/// simultaneously.
///
/// This callback will be invoked for every pointer event after the invocation
/// of [onStart] and/or [onPeak] and before the invocation of [onEnd], no
/// matter what the pressure is during this time period. The position and
/// pressure of the pointer is provided in the callback's `details` argument,
/// which is a [ForcePressDetails] object.
GestureForcePressUpdateCallback? onUpdate;
/// A pointer is in contact with the screen and has just pressed with a force
/// exceeding the [peakPressure]. This is an arbitrary second level action
/// threshold and isn't necessarily the maximum possible device pressure
/// (which is 1.0).
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [ForcePressDetails] object.
GestureForcePressPeakCallback? onPeak;
/// A pointer is no longer in contact with the screen.
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [ForcePressDetails] object.
GestureForcePressEndCallback? onEnd;
/// The pressure of the press required to initiate a force press.
///
/// A value of 0.0 is no pressure, and 1.0 is maximum pressure.
final double startPressure;
/// The pressure of the press required to peak a force press.
///
/// A value of 0.0 is no pressure, and 1.0 is maximum pressure. This value
/// must be greater than [startPressure].
final double peakPressure;
/// The function used to convert the raw device pressure values into a value
/// in the range 0.0 to 1.0.
///
/// The function takes in the device's minimum, maximum and raw touch pressure
/// and returns a value in the range 0.0 to 1.0 denoting the interpolated
/// touch pressure.
///
/// This function must always return values in the range 0.0 to 1.0 given a
/// pressure that is between the minimum and maximum pressures. It may return
/// `double.NaN` for values that it does not want to support.
///
/// By default, the function is a linear interpolation; however, changing the
/// function could be useful to accommodate variations in the way different
/// devices respond to pressure, or to change how animations from pressure
/// feedback are rendered.
///
/// For example, an ease-in curve can be used to determine the interpolated
/// value:
///
/// ```dart
/// double interpolateWithEasing(double min, double max, double t) {
/// final double lerp = (t - min) / (max - min);
/// return Curves.easeIn.transform(lerp);
/// }
/// ```
final GestureForceInterpolation interpolation;
late OffsetPair _lastPosition;
late double _lastPressure;
_ForceState _state = _ForceState.ready;
@override
void addAllowedPointer(PointerDownEvent event) {
// If the device has a maximum pressure of less than or equal to 1, it
// doesn't have touch pressure sensing capabilities. Do not participate
// in the gesture arena.
if (event.pressureMax <= 1.0) {
resolve(GestureDisposition.rejected);
} else {
super.addAllowedPointer(event);
if (_state == _ForceState.ready) {
_state = _ForceState.possible;
_lastPosition = OffsetPair.fromEventPosition(event);
}
}
}
@override
void handleEvent(PointerEvent event) {
assert(_state != _ForceState.ready);
// A static pointer with changes in pressure creates PointerMoveEvent events.
if (event is PointerMoveEvent || event is PointerDownEvent) {
final double pressure = interpolation(event.pressureMin, event.pressureMax, event.pressure);
assert(
(pressure >= 0.0 && pressure <= 1.0) || // Interpolated pressure must be between 1.0 and 0.0...
pressure.isNaN, // and interpolation may return NaN for values it doesn't want to support...
);
_lastPosition = OffsetPair.fromEventPosition(event);
_lastPressure = pressure;
if (_state == _ForceState.possible) {
if (pressure > startPressure) {
_state = _ForceState.started;
resolve(GestureDisposition.accepted);
} else if (event.delta.distanceSquared > computeHitSlop(event.kind, gestureSettings)) {
resolve(GestureDisposition.rejected);
}
}
// In case this is the only gesture detector we still don't want to start
// the gesture until the pressure is greater than the startPressure.
if (pressure > startPressure && _state == _ForceState.accepted) {
_state = _ForceState.started;
if (onStart != null) {
invokeCallback<void>('onStart', () => onStart!(ForcePressDetails(
pressure: pressure,
globalPosition: _lastPosition.global,
localPosition: _lastPosition.local,
)));
}
}
if (onPeak != null && pressure > peakPressure &&
(_state == _ForceState.started)) {
_state = _ForceState.peaked;
if (onPeak != null) {
invokeCallback<void>('onPeak', () => onPeak!(ForcePressDetails(
pressure: pressure,
globalPosition: event.position,
localPosition: event.localPosition,
)));
}
}
if (onUpdate != null && !pressure.isNaN &&
(_state == _ForceState.started || _state == _ForceState.peaked)) {
if (onUpdate != null) {
invokeCallback<void>('onUpdate', () => onUpdate!(ForcePressDetails(
pressure: pressure,
globalPosition: event.position,
localPosition: event.localPosition,
)));
}
}
}
stopTrackingIfPointerNoLongerDown(event);
}
@override
void acceptGesture(int pointer) {
if (_state == _ForceState.possible) {
_state = _ForceState.accepted;
}
if (onStart != null && _state == _ForceState.started) {
invokeCallback<void>('onStart', () => onStart!(ForcePressDetails(
pressure: _lastPressure,
globalPosition: _lastPosition.global,
localPosition: _lastPosition.local,
)));
}
}
@override
void didStopTrackingLastPointer(int pointer) {
final bool wasAccepted = _state == _ForceState.started || _state == _ForceState.peaked;
if (_state == _ForceState.possible) {
resolve(GestureDisposition.rejected);
return;
}
if (wasAccepted && onEnd != null) {
if (onEnd != null) {
invokeCallback<void>('onEnd', () => onEnd!(ForcePressDetails(
pressure: 0.0,
globalPosition: _lastPosition.global,
localPosition: _lastPosition.local,
)));
}
}
_state = _ForceState.ready;
}
@override
void rejectGesture(int pointer) {
stopTrackingPointer(pointer);
didStopTrackingLastPointer(pointer);
}
static double _inverseLerp(double min, double max, double t) {
assert(min <= max);
double value = (t - min) / (max - min);
// If the device incorrectly reports a pressure outside of pressureMin
// and pressureMax, we still want this recognizer to respond normally.
if (!value.isNaN) {
value = clampDouble(value, 0.0, 1.0);
}
return value;
}
@override
String get debugDescription => 'force press';
}
| flutter/packages/flutter/lib/src/gestures/force_press.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/gestures/force_press.dart",
"repo_id": "flutter",
"token_count": 4173
} | 229 |
// Copyright 2014 The Flutter Authors. 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 'binding.dart';
import 'events.dart';
import 'lsq_solver.dart';
export 'dart:ui' show Offset, PointerDeviceKind;
/// A velocity in two dimensions.
@immutable
class Velocity {
/// Creates a [Velocity].
const Velocity({
required this.pixelsPerSecond,
});
/// A velocity that isn't moving at all.
static const Velocity zero = Velocity(pixelsPerSecond: Offset.zero);
/// The number of pixels per second of velocity in the x and y directions.
final Offset pixelsPerSecond;
/// Return the negation of a velocity.
Velocity operator -() => Velocity(pixelsPerSecond: -pixelsPerSecond);
/// Return the difference of two velocities.
Velocity operator -(Velocity other) {
return Velocity(pixelsPerSecond: pixelsPerSecond - other.pixelsPerSecond);
}
/// Return the sum of two velocities.
Velocity operator +(Velocity other) {
return Velocity(pixelsPerSecond: pixelsPerSecond + other.pixelsPerSecond);
}
/// Return a velocity whose magnitude has been clamped to [minValue]
/// and [maxValue].
///
/// If the magnitude of this Velocity is less than minValue then return a new
/// Velocity with the same direction and with magnitude [minValue]. Similarly,
/// if the magnitude of this Velocity is greater than maxValue then return a
/// new Velocity with the same direction and magnitude [maxValue].
///
/// If the magnitude of this Velocity is within the specified bounds then
/// just return this.
Velocity clampMagnitude(double minValue, double maxValue) {
assert(minValue >= 0.0);
assert(maxValue >= 0.0 && maxValue >= minValue);
final double valueSquared = pixelsPerSecond.distanceSquared;
if (valueSquared > maxValue * maxValue) {
return Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * maxValue);
}
if (valueSquared < minValue * minValue) {
return Velocity(pixelsPerSecond: (pixelsPerSecond / pixelsPerSecond.distance) * minValue);
}
return this;
}
@override
bool operator ==(Object other) {
return other is Velocity
&& other.pixelsPerSecond == pixelsPerSecond;
}
@override
int get hashCode => pixelsPerSecond.hashCode;
@override
String toString() => 'Velocity(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)})';
}
/// A two dimensional velocity estimate.
///
/// VelocityEstimates are computed by [VelocityTracker.getVelocityEstimate]. An
/// estimate's [confidence] measures how well the velocity tracker's position
/// data fit a straight line, [duration] is the time that elapsed between the
/// first and last position sample used to compute the velocity, and [offset]
/// is similarly the difference between the first and last positions.
///
/// See also:
///
/// * [VelocityTracker], which computes [VelocityEstimate]s.
/// * [Velocity], which encapsulates (just) a velocity vector and provides some
/// useful velocity operations.
class VelocityEstimate {
/// Creates a dimensional velocity estimate.
const VelocityEstimate({
required this.pixelsPerSecond,
required this.confidence,
required this.duration,
required this.offset,
});
/// The number of pixels per second of velocity in the x and y directions.
final Offset pixelsPerSecond;
/// A value between 0.0 and 1.0 that indicates how well [VelocityTracker]
/// was able to fit a straight line to its position data.
///
/// The value of this property is 1.0 for a perfect fit, 0.0 for a poor fit.
final double confidence;
/// The time that elapsed between the first and last position sample used
/// to compute [pixelsPerSecond].
final Duration duration;
/// The difference between the first and last position sample used
/// to compute [pixelsPerSecond].
final Offset offset;
@override
String toString() => 'VelocityEstimate(${pixelsPerSecond.dx.toStringAsFixed(1)}, ${pixelsPerSecond.dy.toStringAsFixed(1)}; offset: $offset, duration: $duration, confidence: ${confidence.toStringAsFixed(1)})';
}
class _PointAtTime {
const _PointAtTime(this.point, this.time);
final Duration time;
final Offset point;
@override
String toString() => '_PointAtTime($point at $time)';
}
/// Computes a pointer's velocity based on data from [PointerMoveEvent]s.
///
/// The input data is provided by calling [addPosition]. Adding data is cheap.
///
/// To obtain a velocity, call [getVelocity] or [getVelocityEstimate]. This will
/// compute the velocity based on the data added so far. Only call these when
/// you need to use the velocity, as they are comparatively expensive.
///
/// The quality of the velocity estimation will be better if more data points
/// have been received.
class VelocityTracker {
/// Create a new velocity tracker for a pointer [kind].
VelocityTracker.withKind(this.kind);
static const int _assumePointerMoveStoppedMilliseconds = 40;
static const int _historySize = 20;
static const int _horizonMilliseconds = 100;
static const int _minSampleSize = 3;
/// The kind of pointer this tracker is for.
final PointerDeviceKind kind;
// Time difference since the last sample was added
Stopwatch get _sinceLastSample {
_stopwatch ??= GestureBinding.instance.samplingClock.stopwatch();
return _stopwatch!;
}
Stopwatch? _stopwatch;
// Circular buffer; current sample at _index.
final List<_PointAtTime?> _samples = List<_PointAtTime?>.filled(_historySize, null);
int _index = 0;
/// Adds a position as the given time to the tracker.
void addPosition(Duration time, Offset position) {
_sinceLastSample.start();
_sinceLastSample.reset();
_index += 1;
if (_index == _historySize) {
_index = 0;
}
_samples[_index] = _PointAtTime(position, time);
}
/// Returns an estimate of the velocity of the object being tracked by the
/// tracker given the current information available to the tracker.
///
/// Information is added using [addPosition].
///
/// Returns null if there is no data on which to base an estimate.
VelocityEstimate? getVelocityEstimate() {
// Has user recently moved since last sample?
if (_sinceLastSample.elapsedMilliseconds > _assumePointerMoveStoppedMilliseconds) {
return const VelocityEstimate(
pixelsPerSecond: Offset.zero,
confidence: 1.0,
duration: Duration.zero,
offset: Offset.zero,
);
}
final List<double> x = <double>[];
final List<double> y = <double>[];
final List<double> w = <double>[];
final List<double> time = <double>[];
int sampleCount = 0;
int index = _index;
final _PointAtTime? newestSample = _samples[index];
if (newestSample == null) {
return null;
}
_PointAtTime previousSample = newestSample;
_PointAtTime oldestSample = newestSample;
// Starting with the most recent PointAtTime sample, iterate backwards while
// the samples represent continuous motion.
do {
final _PointAtTime? sample = _samples[index];
if (sample == null) {
break;
}
final double age = (newestSample.time - sample.time).inMicroseconds.toDouble() / 1000;
final double delta = (sample.time - previousSample.time).inMicroseconds.abs().toDouble() / 1000;
previousSample = sample;
if (age > _horizonMilliseconds || delta > _assumePointerMoveStoppedMilliseconds) {
break;
}
oldestSample = sample;
final Offset position = sample.point;
x.add(position.dx);
y.add(position.dy);
w.add(1.0);
time.add(-age);
index = (index == 0 ? _historySize : index) - 1;
sampleCount += 1;
} while (sampleCount < _historySize);
if (sampleCount >= _minSampleSize) {
final LeastSquaresSolver xSolver = LeastSquaresSolver(time, x, w);
final PolynomialFit? xFit = xSolver.solve(2);
if (xFit != null) {
final LeastSquaresSolver ySolver = LeastSquaresSolver(time, y, w);
final PolynomialFit? yFit = ySolver.solve(2);
if (yFit != null) {
return VelocityEstimate( // convert from pixels/ms to pixels/s
pixelsPerSecond: Offset(xFit.coefficients[1] * 1000, yFit.coefficients[1] * 1000),
confidence: xFit.confidence * yFit.confidence,
duration: newestSample.time - oldestSample.time,
offset: newestSample.point - oldestSample.point,
);
}
}
}
// We're unable to make a velocity estimate but we did have at least one
// valid pointer position.
return VelocityEstimate(
pixelsPerSecond: Offset.zero,
confidence: 1.0,
duration: newestSample.time - oldestSample.time,
offset: newestSample.point - oldestSample.point,
);
}
/// Computes the velocity of the pointer at the time of the last
/// provided data point.
///
/// This can be expensive. Only call this when you need the velocity.
///
/// Returns [Velocity.zero] if there is no data from which to compute an
/// estimate or if the estimated velocity is zero.
Velocity getVelocity() {
final VelocityEstimate? estimate = getVelocityEstimate();
if (estimate == null || estimate.pixelsPerSecond == Offset.zero) {
return Velocity.zero;
}
return Velocity(pixelsPerSecond: estimate.pixelsPerSecond);
}
}
/// A [VelocityTracker] subclass that provides a close approximation of iOS
/// scroll view's velocity estimation strategy.
///
/// The estimated velocity reported by this class is a close approximation of
/// the velocity an iOS scroll view would report with the same
/// [PointerMoveEvent]s, when the touch that initiates a fling is released.
///
/// This class differs from the [VelocityTracker] class in that it uses weighted
/// average of the latest few velocity samples of the tracked pointer, instead
/// of doing a linear regression on a relatively large amount of data points, to
/// estimate the velocity of the tracked pointer. Adding data points and
/// estimating the velocity are both cheap.
///
/// To obtain a velocity, call [getVelocity] or [getVelocityEstimate]. The
/// estimated velocity is typically used as the initial flinging velocity of a
/// `Scrollable`, when its drag gesture ends.
///
/// See also:
///
/// * [scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)](https://developer.apple.com/documentation/uikit/uiscrollviewdelegate/1619385-scrollviewwillenddragging),
/// the iOS method that reports the fling velocity when the touch is released.
class IOSScrollViewFlingVelocityTracker extends VelocityTracker {
/// Create a new IOSScrollViewFlingVelocityTracker.
IOSScrollViewFlingVelocityTracker(super.kind) : super.withKind();
/// The velocity estimation uses at most 4 `_PointAtTime` samples. The extra
/// samples are there to make the `VelocityEstimate.offset` sufficiently large
/// to be recognized as a fling. See
/// `VerticalDragGestureRecognizer.isFlingGesture`.
static const int _sampleSize = 20;
final List<_PointAtTime?> _touchSamples = List<_PointAtTime?>.filled(_sampleSize, null);
@override
void addPosition(Duration time, Offset position) {
_sinceLastSample.start();
_sinceLastSample.reset();
assert(() {
final _PointAtTime? previousPoint = _touchSamples[_index];
if (previousPoint == null || previousPoint.time <= time) {
return true;
}
throw FlutterError(
'The position being added ($position) has a smaller timestamp ($time) '
'than its predecessor: $previousPoint.',
);
}());
_index = (_index + 1) % _sampleSize;
_touchSamples[_index] = _PointAtTime(position, time);
}
// Computes the velocity using 2 adjacent points in history. When index = 0,
// it uses the latest point recorded and the point recorded immediately before
// it. The smaller index is, the earlier in history the points used are.
Offset _previousVelocityAt(int index) {
final int endIndex = (_index + index) % _sampleSize;
final int startIndex = (_index + index - 1) % _sampleSize;
final _PointAtTime? end = _touchSamples[endIndex];
final _PointAtTime? start = _touchSamples[startIndex];
if (end == null || start == null) {
return Offset.zero;
}
final int dt = (end.time - start.time).inMicroseconds;
assert(dt >= 0);
return dt > 0
// Convert dt to milliseconds to preserve floating point precision.
? (end.point - start.point) * 1000 / (dt.toDouble() / 1000)
: Offset.zero;
}
@override
VelocityEstimate getVelocityEstimate() {
// Has user recently moved since last sample?
if (_sinceLastSample.elapsedMilliseconds > VelocityTracker._assumePointerMoveStoppedMilliseconds) {
return const VelocityEstimate(
pixelsPerSecond: Offset.zero,
confidence: 1.0,
duration: Duration.zero,
offset: Offset.zero,
);
}
// The velocity estimated using this expression is an approximation of the
// scroll velocity of an iOS scroll view at the moment the user touch was
// released, not the final velocity of the iOS pan gesture recognizer
// installed on the scroll view would report. Typically in an iOS scroll
// view the velocity values are different between the two, because the
// scroll view usually slows down when the touch is released.
final Offset estimatedVelocity = _previousVelocityAt(-2) * 0.6
+ _previousVelocityAt(-1) * 0.35
+ _previousVelocityAt(0) * 0.05;
final _PointAtTime? newestSample = _touchSamples[_index];
_PointAtTime? oldestNonNullSample;
for (int i = 1; i <= _sampleSize; i += 1) {
oldestNonNullSample = _touchSamples[(_index + i) % _sampleSize];
if (oldestNonNullSample != null) {
break;
}
}
if (oldestNonNullSample == null || newestSample == null) {
assert(false, 'There must be at least 1 point in _touchSamples: $_touchSamples');
return const VelocityEstimate(
pixelsPerSecond: Offset.zero,
confidence: 0.0,
duration: Duration.zero,
offset: Offset.zero,
);
} else {
return VelocityEstimate(
pixelsPerSecond: estimatedVelocity,
confidence: 1.0,
duration: newestSample.time - oldestNonNullSample.time,
offset: newestSample.point - oldestNonNullSample.point,
);
}
}
}
/// A [VelocityTracker] subclass that provides a close approximation of macOS
/// scroll view's velocity estimation strategy.
///
/// The estimated velocity reported by this class is a close approximation of
/// the velocity a macOS scroll view would report with the same
/// [PointerMoveEvent]s, when the touch that initiates a fling is released.
///
/// This class differs from the [VelocityTracker] class in that it uses weighted
/// average of the latest few velocity samples of the tracked pointer, instead
/// of doing a linear regression on a relatively large amount of data points, to
/// estimate the velocity of the tracked pointer. Adding data points and
/// estimating the velocity are both cheap.
///
/// To obtain a velocity, call [getVelocity] or [getVelocityEstimate]. The
/// estimated velocity is typically used as the initial flinging velocity of a
/// `Scrollable`, when its drag gesture ends.
class MacOSScrollViewFlingVelocityTracker extends IOSScrollViewFlingVelocityTracker {
/// Create a new MacOSScrollViewFlingVelocityTracker.
MacOSScrollViewFlingVelocityTracker(super.kind);
@override
VelocityEstimate getVelocityEstimate() {
// Has user recently moved since last sample?
if (_sinceLastSample.elapsedMilliseconds > VelocityTracker._assumePointerMoveStoppedMilliseconds) {
return const VelocityEstimate(
pixelsPerSecond: Offset.zero,
confidence: 1.0,
duration: Duration.zero,
offset: Offset.zero,
);
}
// The velocity estimated using this expression is an approximation of the
// scroll velocity of a macOS scroll view at the moment the user touch was
// released.
final Offset estimatedVelocity = _previousVelocityAt(-2) * 0.15
+ _previousVelocityAt(-1) * 0.65
+ _previousVelocityAt(0) * 0.2;
final _PointAtTime? newestSample = _touchSamples[_index];
_PointAtTime? oldestNonNullSample;
for (int i = 1; i <= IOSScrollViewFlingVelocityTracker._sampleSize; i += 1) {
oldestNonNullSample = _touchSamples[(_index + i) % IOSScrollViewFlingVelocityTracker._sampleSize];
if (oldestNonNullSample != null) {
break;
}
}
if (oldestNonNullSample == null || newestSample == null) {
assert(false, 'There must be at least 1 point in _touchSamples: $_touchSamples');
return const VelocityEstimate(
pixelsPerSecond: Offset.zero,
confidence: 0.0,
duration: Duration.zero,
offset: Offset.zero,
);
} else {
return VelocityEstimate(
pixelsPerSecond: estimatedVelocity,
confidence: 1.0,
duration: newestSample.time - oldestNonNullSample.time,
offset: newestSample.point - oldestNonNullSample.point,
);
}
}
}
| flutter/packages/flutter/lib/src/gestures/velocity_tracker.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/gestures/velocity_tracker.dart",
"repo_id": "flutter",
"token_count": 5649
} | 230 |
// Copyright 2014 The Flutter Authors. 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 lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// Defines the visual properties of [MaterialBanner] widgets.
///
/// Descendant widgets obtain the current [MaterialBannerThemeData] object using
/// `MaterialBannerTheme.of(context)`. Instances of [MaterialBannerThemeData]
/// can be customized with [MaterialBannerThemeData.copyWith].
///
/// Typically a [MaterialBannerThemeData] is specified as part of the overall
/// [Theme] with [ThemeData.bannerTheme].
///
/// All [MaterialBannerThemeData] properties are `null` by default. When null,
/// the [MaterialBanner] will provide its own defaults.
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
@immutable
class MaterialBannerThemeData with Diagnosticable {
/// Creates a theme that can be used for [MaterialBannerTheme] or
/// [ThemeData.bannerTheme].
const MaterialBannerThemeData({
this.backgroundColor,
this.surfaceTintColor,
this.shadowColor,
this.dividerColor,
this.contentTextStyle,
this.elevation,
this.padding,
this.leadingPadding,
});
/// The background color of a [MaterialBanner].
final Color? backgroundColor;
/// Overrides the default value of [MaterialBanner.surfaceTintColor].
final Color? surfaceTintColor;
/// Overrides the default value of [MaterialBanner.shadowColor].
final Color? shadowColor;
/// Overrides the default value of [MaterialBanner.dividerColor].
final Color? dividerColor;
/// Used to configure the [DefaultTextStyle] for the [MaterialBanner.content]
/// widget.
final TextStyle? contentTextStyle;
/// Default value for [MaterialBanner.elevation].
//
// If null, MaterialBanner uses a default of 0.0.
final double? elevation;
/// The amount of space by which to inset [MaterialBanner.content].
final EdgeInsetsGeometry? padding;
/// The amount of space by which to inset [MaterialBanner.leading].
final EdgeInsetsGeometry? leadingPadding;
/// Creates a copy of this object with the given fields replaced with the
/// new values.
MaterialBannerThemeData copyWith({
Color? backgroundColor,
Color? surfaceTintColor,
Color? shadowColor,
Color? dividerColor,
TextStyle? contentTextStyle,
double? elevation,
EdgeInsetsGeometry? padding,
EdgeInsetsGeometry? leadingPadding,
}) {
return MaterialBannerThemeData(
backgroundColor: backgroundColor ?? this.backgroundColor,
surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor,
shadowColor: shadowColor ?? this.shadowColor,
dividerColor: dividerColor ?? this.dividerColor,
contentTextStyle: contentTextStyle ?? this.contentTextStyle,
elevation: elevation ?? this.elevation,
padding: padding ?? this.padding,
leadingPadding: leadingPadding ?? this.leadingPadding,
);
}
/// Linearly interpolate between two Banner themes.
///
/// {@macro dart.ui.shadow.lerp}
static MaterialBannerThemeData lerp(MaterialBannerThemeData? a, MaterialBannerThemeData? b, double t) {
return MaterialBannerThemeData(
backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t),
surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t),
shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t),
dividerColor: Color.lerp(a?.dividerColor, b?.dividerColor, t),
contentTextStyle: TextStyle.lerp(a?.contentTextStyle, b?.contentTextStyle, t),
elevation: lerpDouble(a?.elevation, b?.elevation, t),
padding: EdgeInsetsGeometry.lerp(a?.padding, b?.padding, t),
leadingPadding: EdgeInsetsGeometry.lerp(a?.leadingPadding, b?.leadingPadding, t),
);
}
@override
int get hashCode => Object.hash(
backgroundColor,
surfaceTintColor,
shadowColor,
dividerColor,
contentTextStyle,
elevation,
padding,
leadingPadding,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is MaterialBannerThemeData
&& other.backgroundColor == backgroundColor
&& other.surfaceTintColor == surfaceTintColor
&& other.shadowColor == shadowColor
&& other.dividerColor == dividerColor
&& other.contentTextStyle == contentTextStyle
&& other.elevation == elevation
&& other.padding == padding
&& other.leadingPadding == leadingPadding;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null));
properties.add(ColorProperty('surfaceTintColor', surfaceTintColor, defaultValue: null));
properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null));
properties.add(ColorProperty('dividerColor', dividerColor, defaultValue: null));
properties.add(DiagnosticsProperty<TextStyle>('contentTextStyle', contentTextStyle, defaultValue: null));
properties.add(DoubleProperty('elevation', elevation, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('leadingPadding', leadingPadding, defaultValue: null));
}
}
/// An inherited widget that defines the configuration for
/// [MaterialBanner]s in this widget's subtree.
///
/// Values specified here are used for [MaterialBanner] properties that are not
/// given an explicit non-null value.
class MaterialBannerTheme extends InheritedTheme {
/// Creates a banner theme that controls the configurations for
/// [MaterialBanner]s in its widget subtree.
const MaterialBannerTheme({
super.key,
this.data,
required super.child,
});
/// The properties for descendant [MaterialBanner] widgets.
final MaterialBannerThemeData? data;
/// The closest instance of this class's [data] value that encloses the given
/// context.
///
/// If there is no ancestor, it returns [ThemeData.bannerTheme]. Applications
/// can assume that the returned value will not be null.
///
/// Typical usage is as follows:
///
/// ```dart
/// MaterialBannerThemeData theme = MaterialBannerTheme.of(context);
/// ```
static MaterialBannerThemeData of(BuildContext context) {
final MaterialBannerTheme? bannerTheme = context.dependOnInheritedWidgetOfExactType<MaterialBannerTheme>();
return bannerTheme?.data ?? Theme.of(context).bannerTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return MaterialBannerTheme(data: data, child: child);
}
@override
bool updateShouldNotify(MaterialBannerTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/banner_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/banner_theme.dart",
"repo_id": "flutter",
"token_count": 2218
} | 231 |
// Copyright 2014 The Flutter Authors. 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/rendering.dart';
import 'package:flutter/widgets.dart';
import 'colors.dart';
import 'ink_well.dart';
import 'material.dart';
import 'theme.dart';
/// A Material Design carousel widget.
///
/// The [CarouselView] present a scrollable list of items, each of which can dynamically
/// change size based on the chosen layout.
///
/// This widget supports uncontained carousel layout. It shows items that scroll
/// to the edge of the container, behaving similarly to a [ListView] where all
/// children are a uniform size.
///
/// The [CarouselController] is used to control the [CarouselController.initialItem].
///
/// The [CarouselView.itemExtent] property must be non-null and defines the base
/// size of items. While items typically maintain this size, the first and last
/// visible items may be slightly compressed during scrolling. The [shrinkExtent]
/// property controls the minimum allowable size for these compressed items.
///
/// {@tool dartpad}
/// Here is an example of [CarouselView] to show the uncontained layout. Each carousel
/// item has the same size but can be "squished" to the [shrinkExtent] when they
/// are show on the view and out of view.
///
/// ** See code in examples/api/lib/material/carousel/carousel.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [CarouselController], which controls the first visible item in the carousel.
/// * [PageView], which is a scrollable list that works page by page.
class CarouselView extends StatefulWidget {
/// Creates a Material Design carousel.
const CarouselView({
super.key,
this.padding,
this.backgroundColor,
this.elevation,
this.shape,
this.overlayColor,
this.itemSnapping = false,
this.shrinkExtent = 0.0,
this.controller,
this.scrollDirection = Axis.horizontal,
this.reverse = false,
this.onTap,
required this.itemExtent,
required this.children,
});
/// The amount of space to surround each carousel item with.
///
/// Defaults to [EdgeInsets.all] of 4 pixels.
final EdgeInsets? padding;
/// The background color for each carousel item.
///
/// Defaults to [ColorScheme.surface].
final Color? backgroundColor;
/// The z-coordinate of each carousel item.
///
/// Defaults to 0.0.
final double? elevation;
/// The shape of each carousel item's [Material].
///
/// Defines each item's [Material.shape].
///
/// Defaults to a [RoundedRectangleBorder] with a circular corner radius
/// of 28.0.
final ShapeBorder? shape;
/// The highlight color to indicate the carousel items are in pressed, hovered
/// or focused states.
///
/// The default values are:
/// * [WidgetState.pressed] - [ColorScheme.onSurface] with an opacity of 0.1
/// * [WidgetState.hovered] - [ColorScheme.onSurface] with an opacity of 0.08
/// * [WidgetState.focused] - [ColorScheme.onSurface] with an opacity of 0.1
final WidgetStateProperty<Color?>? overlayColor;
/// The minimum allowable extent (size) in the main axis for carousel items
/// during scrolling transitions.
///
/// As the carousel scrolls, the first visible item is pinned and gradually
/// shrinks until it reaches this minimum extent before scrolling off-screen.
/// Similarly, the last visible item enters the viewport at this minimum size
/// and expands to its full [itemExtent].
///
/// In cases where the remaining viewport space for the last visible item is
/// larger than the defined [shrinkExtent], the [shrinkExtent] is dynamically
/// adjusted to match this remaining space, ensuring a smooth size transition.
///
/// Defaults to 0.0. Setting to 0.0 allows items to shrink/expand completely,
/// transitioning between 0.0 and the full [itemExtent]. In cases where the
/// remaining viewport space for the last visible item is larger than the
/// defined [shrinkExtent], the [shrinkExtent] is dynamically adjusted to match
/// this remaining space, ensuring a smooth size transition.
final double shrinkExtent;
/// Whether the carousel should keep scrolling to the next/previous items to
/// maintain the original layout.
///
/// Defaults to false.
final bool itemSnapping;
/// An object that can be used to control the position to which this scroll
/// view is scrolled.
final CarouselController? controller;
/// The [Axis] along which the scroll view's offset increases with each item.
///
/// Defaults to [Axis.horizontal].
final Axis scrollDirection;
/// Whether the carousel list scrolls in the reading direction.
///
/// For example, if the reading direction is left-to-right and
/// [scrollDirection] is [Axis.horizontal], then the carousel scrolls from
/// left to right when [reverse] is false and from right to left when
/// [reverse] is true.
///
/// Similarly, if [scrollDirection] is [Axis.vertical], then the carousel view
/// scrolls from top to bottom when [reverse] is false and from bottom to top
/// when [reverse] is true.
///
/// Defaults to false.
final bool reverse;
/// Called when one of the [children] is tapped.
final ValueChanged<int>? onTap;
/// The extent the children are forced to have in the main axis.
///
/// The item extent should not exceed the available space that the carousel
/// occupies to ensure at least one item is fully visible.
///
/// This must be non-null.
final double itemExtent;
/// The child widgets for the carousel.
final List<Widget> children;
@override
State<CarouselView> createState() => _CarouselViewState();
}
class _CarouselViewState extends State<CarouselView> {
late double _itemExtent;
CarouselController? _internalController;
CarouselController get _controller => widget.controller ?? _internalController!;
@override
void initState() {
super.initState();
if (widget.controller == null) {
_internalController = CarouselController();
}
_controller._attach(this);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_itemExtent = widget.itemExtent;
}
@override
void didUpdateWidget(covariant CarouselView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller != oldWidget.controller) {
oldWidget.controller?._detach(this);
if (widget.controller != null) {
_internalController?._detach(this);
_internalController = null;
widget.controller?._attach(this);
} else { // widget.controller == null && oldWidget.controller != null
assert(_internalController == null);
_internalController = CarouselController();
_controller._attach(this);
}
}
if (widget.itemExtent != oldWidget.itemExtent) {
_itemExtent = widget.itemExtent;
}
}
@override
void dispose() {
_controller._detach(this);
_internalController?.dispose();
super.dispose();
}
AxisDirection _getDirection(BuildContext context) {
switch (widget.scrollDirection) {
case Axis.horizontal:
assert(debugCheckHasDirectionality(context));
final TextDirection textDirection = Directionality.of(context);
final AxisDirection axisDirection = textDirectionToAxisDirection(textDirection);
return widget.reverse ? flipAxisDirection(axisDirection) : axisDirection;
case Axis.vertical:
return widget.reverse ? AxisDirection.up : AxisDirection.down;
}
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final AxisDirection axisDirection = _getDirection(context);
final ScrollPhysics physics = widget.itemSnapping
? const CarouselScrollPhysics()
: ScrollConfiguration.of(context).getScrollPhysics(context);
final EdgeInsets effectivePadding = widget.padding ?? const EdgeInsets.all(4.0);
final Color effectiveBackgroundColor = widget.backgroundColor ?? Theme.of(context).colorScheme.surface;
final double effectiveElevation = widget.elevation ?? 0.0;
final ShapeBorder effectiveShape = widget.shape
?? const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(28.0))
);
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final double mainAxisExtent = switch (widget.scrollDirection) {
Axis.horizontal => constraints.maxWidth,
Axis.vertical => constraints.maxHeight,
};
_itemExtent = clampDouble(_itemExtent, 0, mainAxisExtent);
return Scrollable(
axisDirection: axisDirection,
controller: _controller,
physics: physics,
viewportBuilder: (BuildContext context, ViewportOffset position) {
return Viewport(
cacheExtent: 0.0,
cacheExtentStyle: CacheExtentStyle.viewport,
axisDirection: axisDirection,
offset: position,
clipBehavior: Clip.antiAlias,
slivers: <Widget>[
_SliverFixedExtentCarousel(
itemExtent: _itemExtent,
minExtent: widget.shrinkExtent,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Padding(
padding: effectivePadding,
child: Material(
clipBehavior: Clip.antiAlias,
color: effectiveBackgroundColor,
elevation: effectiveElevation,
shape: effectiveShape,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
widget.children.elementAt(index),
Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
widget.onTap?.call(index);
},
overlayColor: widget.overlayColor ?? WidgetStateProperty.resolveWith((Set<WidgetState> states) {
if (states.contains(WidgetState.pressed)) {
return theme.colorScheme.onSurface.withOpacity(0.1);
}
if (states.contains(WidgetState.hovered)) {
return theme.colorScheme.onSurface.withOpacity(0.08);
}
if (states.contains(WidgetState.focused)) {
return theme.colorScheme.onSurface.withOpacity(0.1);
}
return null;
}),
),
),
],
),
),
);
},
childCount: widget.children.length,
),
),
],
);
},
);
}
);
}
}
/// A sliver that displays its box children in a linear array with a fixed extent
/// per item.
///
/// _To learn more about slivers, see [CustomScrollView.slivers]._
///
/// This sliver list arranges its children in a line along the main axis starting
/// at offset zero and without gaps. Each child is constrained to a fixed extent
/// along the main axis and the [SliverConstraints.crossAxisExtent]
/// along the cross axis. The difference between this and a list view with a fixed
/// extent is the first item and last item can be squished a little during scrolling
/// transition. This compression is controlled by the `minExtent` property and
/// aligns with the [Material Design Carousel specifications]
/// (https://m3.material.io/components/carousel/guidelines#96c5c157-fe5b-4ee3-a9b4-72bf8efab7e9).
class _SliverFixedExtentCarousel extends SliverMultiBoxAdaptorWidget {
const _SliverFixedExtentCarousel({
required super.delegate,
required this.minExtent,
required this.itemExtent,
});
final double itemExtent;
final double minExtent;
@override
RenderSliverFixedExtentBoxAdaptor createRenderObject(BuildContext context) {
final SliverMultiBoxAdaptorElement element = context as SliverMultiBoxAdaptorElement;
return _RenderSliverFixedExtentCarousel(
childManager: element,
minExtent: minExtent,
maxExtent: itemExtent,
);
}
@override
void updateRenderObject(BuildContext context, _RenderSliverFixedExtentCarousel renderObject) {
renderObject.maxExtent = itemExtent;
renderObject.minExtent = itemExtent;
}
}
class _RenderSliverFixedExtentCarousel extends RenderSliverFixedExtentBoxAdaptor {
_RenderSliverFixedExtentCarousel({
required super.childManager,
required double maxExtent,
required double minExtent,
}) : _maxExtent = maxExtent,
_minExtent = minExtent;
double get maxExtent => _maxExtent;
double _maxExtent;
set maxExtent(double value) {
if (_maxExtent == value) {
return;
}
_maxExtent = value;
markNeedsLayout();
}
double get minExtent => _minExtent;
double _minExtent;
set minExtent(double value) {
if (_minExtent == value) {
return;
}
_minExtent = value;
markNeedsLayout();
}
// This implements the [itemExtentBuilder] callback.
double _buildItemExtent(int index, SliverLayoutDimensions currentLayoutDimensions) {
final int firstVisibleIndex = (constraints.scrollOffset / maxExtent).floor();
// Calculate how many items have been completely scroll off screen.
final int offscreenItems = (constraints.scrollOffset / maxExtent).floor();
// If an item is partially off screen and partially on screen,
// `constraints.scrollOffset` must be greater than
// `offscreenItems * maxExtent`, so the difference between these two is how
// much the current first visible item is off screen.
final double offscreenExtent = constraints.scrollOffset - offscreenItems * maxExtent;
// If there is not enough space to place the last visible item but the remaining
// space is larger than `minExtent`, the extent for last item should be at
// least the remaining extent to ensure a smooth size transition.
final double effectiveMinExtent = math.max(constraints.remainingPaintExtent % maxExtent, minExtent);
// Two special cases are the first and last visible items. Other items' extent
// should all return `maxExtent`.
if (index == firstVisibleIndex) {
final double effectiveExtent = maxExtent - offscreenExtent;
return math.max(effectiveExtent, effectiveMinExtent);
}
final double scrollOffsetForLastIndex = constraints.scrollOffset + constraints.remainingPaintExtent;
if (index == getMaxChildIndexForScrollOffset(scrollOffsetForLastIndex, maxExtent)) {
return clampDouble(scrollOffsetForLastIndex - maxExtent * index, effectiveMinExtent, maxExtent);
}
return maxExtent;
}
late SliverLayoutDimensions _currentLayoutDimensions;
@override
void performLayout() {
_currentLayoutDimensions = SliverLayoutDimensions(
scrollOffset: constraints.scrollOffset,
precedingScrollExtent: constraints.precedingScrollExtent,
viewportMainAxisExtent: constraints.viewportMainAxisExtent,
crossAxisExtent: constraints.crossAxisExtent,
);
super.performLayout();
}
/// The layout offset for the child with the given index.
@override
double indexToLayoutOffset(
@Deprecated(
'The itemExtent is already available within the scope of this function. '
'This feature was deprecated after v3.20.0-7.0.pre.'
)
double itemExtent,
int index,
) {
final int firstVisibleIndex = (constraints.scrollOffset / maxExtent).floor();
// If there is not enough space to place the last visible item but the remaining
// space is larger than `minExtent`, the extent for last item should be at
// least the remaining extent to make sure a smooth size transition.
final double effectiveMinExtent = math.max(constraints.remainingPaintExtent % maxExtent, minExtent);
if (index == firstVisibleIndex) {
final double firstVisibleItemExtent = _buildItemExtent(index, _currentLayoutDimensions);
// If the first item is squished to be less than `effectievMinExtent`,
// then it should stop changinng its size and should start to scroll off screen.
if (firstVisibleItemExtent <= effectiveMinExtent) {
return maxExtent * index - effectiveMinExtent + maxExtent;
}
return constraints.scrollOffset;
}
return maxExtent * index;
}
/// The minimum child index that is visible at the given scroll offset.
@override
int getMinChildIndexForScrollOffset(
double scrollOffset,
@Deprecated(
'The itemExtent is already available within the scope of this function. '
'This feature was deprecated after v3.20.0-7.0.pre.'
)
double itemExtent,
) {
final int firstVisibleIndex = (constraints.scrollOffset / maxExtent).floor();
return math.max(firstVisibleIndex, 0);
}
/// The maximum child index that is visible at the given scroll offset.
@override
int getMaxChildIndexForScrollOffset(
double scrollOffset,
@Deprecated(
'The itemExtent is already available within the scope of this function. '
'This feature was deprecated after v3.20.0-7.0.pre.'
)
double itemExtent,
) {
if (maxExtent > 0.0) {
final double actual = scrollOffset / maxExtent - 1;
final int round = actual.round();
if ((actual * maxExtent - round * maxExtent).abs() < precisionErrorTolerance) {
return math.max(0, round);
}
return math.max(0, actual.ceil());
}
return 0;
}
@override
double? get itemExtent => null;
@override
ItemExtentBuilder? get itemExtentBuilder => _buildItemExtent;
}
/// Scroll physics used by a [CarouselView].
///
/// These physics cause the carousel item to snap to item boundaries.
///
/// See also:
///
/// * [ScrollPhysics], the base class which defines the API for scrolling
/// physics.
/// * [PageScrollPhysics], scroll physics used by a [PageView].
class CarouselScrollPhysics extends ScrollPhysics {
/// Creates physics for a [CarouselView].
const CarouselScrollPhysics({super.parent});
@override
CarouselScrollPhysics applyTo(ScrollPhysics? ancestor) {
return CarouselScrollPhysics(parent: buildParent(ancestor));
}
double _getTargetPixels(
_CarouselPosition position,
Tolerance tolerance,
double velocity,
) {
double fraction;
fraction = position.itemExtent! / position.viewportDimension;
final double itemWidth = position.viewportDimension * fraction;
final double actual = math.max(0.0, position.pixels) / itemWidth;
final double round = actual.roundToDouble();
double item;
if ((actual - round).abs() < precisionErrorTolerance) {
item = round;
} else {
item = actual;
}
if (velocity < -tolerance.velocity) {
item -= 0.5;
} else if (velocity > tolerance.velocity) {
item += 0.5;
}
return item.roundToDouble() * itemWidth;
}
@override
Simulation? createBallisticSimulation(
ScrollMetrics position,
double velocity,
) {
assert(
position is _CarouselPosition,
'CarouselScrollPhysics can only be used with Scrollables that uses '
'the CarouselController',
);
final _CarouselPosition metrics = position as _CarouselPosition;
if ((velocity <= 0.0 && metrics.pixels <= metrics.minScrollExtent) ||
(velocity >= 0.0 && metrics.pixels >= metrics.maxScrollExtent)) {
return super.createBallisticSimulation(metrics, velocity);
}
final Tolerance tolerance = toleranceFor(metrics);
final double target = _getTargetPixels(metrics, tolerance, velocity);
if (target != metrics.pixels) {
return ScrollSpringSimulation(
spring,
metrics.pixels,
target,
velocity,
tolerance: tolerance,
);
}
return null;
}
@override
bool get allowImplicitScrolling => true;
}
/// Metrics for a [CarouselView].
class _CarouselMetrics extends FixedScrollMetrics {
/// Creates an immutable snapshot of values associated with a [CarouselView].
_CarouselMetrics({
required super.minScrollExtent,
required super.maxScrollExtent,
required super.pixels,
required super.viewportDimension,
required super.axisDirection,
this.itemExtent,
required super.devicePixelRatio,
});
/// Extent for the carousel item.
///
/// Used to compute the first item from the current [pixels].
final double? itemExtent;
@override
_CarouselMetrics copyWith({
double? minScrollExtent,
double? maxScrollExtent,
double? pixels,
double? viewportDimension,
AxisDirection? axisDirection,
double? itemExtent,
double? devicePixelRatio,
}) {
return _CarouselMetrics(
minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null),
maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null),
pixels: pixels ?? (hasPixels ? this.pixels : null),
viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null),
axisDirection: axisDirection ?? this.axisDirection,
itemExtent: itemExtent ?? this.itemExtent,
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
);
}
}
class _CarouselPosition extends ScrollPositionWithSingleContext implements _CarouselMetrics {
_CarouselPosition({
required super.physics,
required super.context,
this.initialItem = 0,
required this.itemExtent,
super.oldPosition,
}) : _itemToShowOnStartup = initialItem.toDouble(),
super(
initialPixels: null
);
final int initialItem;
final double _itemToShowOnStartup;
// When the viewport has a zero-size, the item can not
// be retrieved by `getItemFromPixels`, so we need to cache the item
// for use when resizing the viewport to non-zero next time.
double? _cachedItem;
@override
double? itemExtent;
double getItemFromPixels(double pixels, double viewportDimension) {
assert(viewportDimension > 0.0);
final double fraction = itemExtent! / viewportDimension;
final double actual = math.max(0.0, pixels) / (viewportDimension * fraction);
final double round = actual.roundToDouble();
if ((actual - round).abs() < precisionErrorTolerance) {
return round;
}
return actual;
}
double getPixelsFromItem(double item) {
final double fraction = itemExtent! / viewportDimension;
return item * viewportDimension * fraction;
}
@override
bool applyViewportDimension(double viewportDimension) {
final double? oldViewportDimensions = hasViewportDimension ? this.viewportDimension : null;
if (viewportDimension == oldViewportDimensions) {
return true;
}
final bool result = super.applyViewportDimension(viewportDimension);
final double? oldPixels = hasPixels ? pixels : null;
double item;
if (oldPixels == null) {
item = _itemToShowOnStartup;
} else if (oldViewportDimensions == 0.0) {
// If resize from zero, we should use the _cachedItem to recover the state.
item = _cachedItem!;
} else {
item = getItemFromPixels(oldPixels, oldViewportDimensions!);
}
final double newPixels = getPixelsFromItem(item);
// If the viewportDimension is zero, cache the item
// in case the viewport is resized to be non-zero.
_cachedItem = (viewportDimension == 0.0) ? item : null;
if (newPixels != oldPixels) {
correctPixels(newPixels);
return false;
}
return result;
}
@override
_CarouselMetrics copyWith({
double? minScrollExtent,
double? maxScrollExtent,
double? pixels,
double? viewportDimension,
AxisDirection? axisDirection,
double? itemExtent,
List<int>? layoutWeights,
double? devicePixelRatio,
}) {
return _CarouselMetrics(
minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null),
maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null),
pixels: pixels ?? (hasPixels ? this.pixels : null),
viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null),
axisDirection: axisDirection ?? this.axisDirection,
itemExtent: itemExtent ?? this.itemExtent,
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
);
}
}
/// A controller for [CarouselView].
///
/// Using a carousel controller helps to show the first visible item on the
/// carousel list.
class CarouselController extends ScrollController {
/// Creates a carousel controller.
CarouselController({
this.initialItem = 0,
});
/// The item that expands to the maximum size when first creating the [CarouselView].
final int initialItem;
_CarouselViewState? _carouselState;
// ignore: use_setters_to_change_properties
void _attach(_CarouselViewState anchor) {
_carouselState = anchor;
}
void _detach(_CarouselViewState anchor) {
if (_carouselState == anchor) {
_carouselState = null;
}
}
@override
ScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) {
assert(_carouselState != null);
final double itemExtent = _carouselState!._itemExtent;
return _CarouselPosition(
physics: physics,
context: context,
initialItem: initialItem,
itemExtent: itemExtent,
oldPosition: oldPosition,
);
}
@override
void attach(ScrollPosition position) {
super.attach(position);
final _CarouselPosition carouselPosition = position as _CarouselPosition;
carouselPosition.itemExtent = _carouselState!._itemExtent;
}
}
| flutter/packages/flutter/lib/src/material/carousel.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/carousel.dart",
"repo_id": "flutter",
"token_count": 9440
} | 232 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'app_bar.dart';
import 'back_button.dart';
import 'button_style.dart';
import 'calendar_date_picker.dart';
import 'color_scheme.dart';
import 'date.dart';
import 'date_picker_theme.dart';
import 'debug.dart';
import 'dialog.dart';
import 'dialog_theme.dart';
import 'divider.dart';
import 'icon_button.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'input_border.dart';
import 'input_date_picker_form_field.dart';
import 'input_decorator.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'material_state.dart';
import 'scaffold.dart';
import 'text_button.dart';
import 'text_field.dart';
import 'text_theme.dart';
import 'theme.dart';
// The M3 sizes are coming from the tokens, but are hand coded,
// as the current token DB does not contain landscape versions.
const Size _calendarPortraitDialogSizeM2 = Size(330.0, 518.0);
const Size _calendarPortraitDialogSizeM3 = Size(328.0, 512.0);
const Size _calendarLandscapeDialogSize = Size(496.0, 346.0);
const Size _inputPortraitDialogSizeM2 = Size(330.0, 270.0);
const Size _inputPortraitDialogSizeM3 = Size(328.0, 270.0);
const Size _inputLandscapeDialogSize = Size(496, 160.0);
const Size _inputRangeLandscapeDialogSize = Size(496, 164.0);
const Duration _dialogSizeAnimationDuration = Duration(milliseconds: 200);
const double _inputFormPortraitHeight = 98.0;
const double _inputFormLandscapeHeight = 108.0;
const double _kMaxTextScaleFactor = 1.3;
/// Shows a dialog containing a Material Design date picker.
///
/// The returned [Future] resolves to the date selected by the user when the
/// user confirms the dialog. If the user cancels the dialog, null is returned.
///
/// When the date picker is first displayed, if [initialDate] is not null, it
/// will show the month of [initialDate], with [initialDate] selected. Otherwise
/// it will show the [currentDate]'s month.
///
/// The [firstDate] is the earliest allowable date. The [lastDate] is the latest
/// allowable date. If [initialDate] is not null, it must either fall between
/// these dates, or be equal to one of them. For each of these [DateTime]
/// parameters, only their dates are considered. Their time fields are ignored.
/// They must all be non-null.
///
/// The [currentDate] represents the current day (i.e. today). This
/// date will be highlighted in the day grid. If null, the date of
/// [DateTime.now] will be used.
///
/// An optional [initialEntryMode] argument can be used to display the date
/// picker in the [DatePickerEntryMode.calendar] (a calendar month grid)
/// or [DatePickerEntryMode.input] (a text input field) mode.
/// It defaults to [DatePickerEntryMode.calendar].
///
/// {@template flutter.material.date_picker.switchToInputEntryModeIcon}
/// An optional [switchToInputEntryModeIcon] argument can be used to
/// display a custom Icon in the corner of the dialog
/// when [DatePickerEntryMode] is [DatePickerEntryMode.calendar]. Clicking on
/// icon changes the [DatePickerEntryMode] to [DatePickerEntryMode.input].
/// If null, `Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit)` is used.
/// {@endtemplate}
///
/// {@template flutter.material.date_picker.switchToCalendarEntryModeIcon}
/// An optional [switchToCalendarEntryModeIcon] argument can be used to
/// display a custom Icon in the corner of the dialog
/// when [DatePickerEntryMode] is [DatePickerEntryMode.input]. Clicking on
/// icon changes the [DatePickerEntryMode] to [DatePickerEntryMode.calendar].
/// If null, `Icon(Icons.calendar_today)` is used.
/// {@endtemplate}
///
/// An optional [selectableDayPredicate] function can be passed in to only allow
/// certain days for selection. If provided, only the days that
/// [selectableDayPredicate] returns true for will be selectable. For example,
/// this can be used to only allow weekdays for selection. If provided, it must
/// return true for [initialDate].
///
/// The following optional string parameters allow you to override the default
/// text used for various parts of the dialog:
///
/// * [helpText], label displayed at the top of the dialog.
/// * [cancelText], label on the cancel button.
/// * [confirmText], label on the ok button.
/// * [errorFormatText], message used when the input text isn't in a proper date format.
/// * [errorInvalidText], message used when the input text isn't a selectable date.
/// * [fieldHintText], text used to prompt the user when no text has been entered in the field.
/// * [fieldLabelText], label for the date text input field.
///
/// An optional [locale] argument can be used to set the locale for the date
/// picker. It defaults to the ambient locale provided by [Localizations].
///
/// An optional [textDirection] argument can be used to set the text direction
/// ([TextDirection.ltr] or [TextDirection.rtl]) for the date picker. It
/// defaults to the ambient text direction provided by [Directionality]. If both
/// [locale] and [textDirection] are non-null, [textDirection] overrides the
/// direction chosen for the [locale].
///
/// The [context], [barrierDismissible], [barrierColor], [barrierLabel],
/// [useRootNavigator] and [routeSettings] arguments are passed to [showDialog],
/// the documentation for which discusses how it is used.
///
/// The [builder] parameter can be used to wrap the dialog widget
/// to add inherited widgets like [Theme].
///
/// An optional [initialDatePickerMode] argument can be used to have the
/// calendar date picker initially appear in the [DatePickerMode.year] or
/// [DatePickerMode.day] mode. It defaults to [DatePickerMode.day].
///
/// {@macro flutter.widgets.RawDialogRoute}
///
/// ### State Restoration
///
/// Using this method will not enable state restoration for the date picker.
/// In order to enable state restoration for a date picker, use
/// [Navigator.restorablePush] or [Navigator.restorablePushNamed] with
/// [DatePickerDialog].
///
/// For more information about state restoration, see [RestorationManager].
///
/// {@macro flutter.widgets.RestorationManager}
///
/// {@tool dartpad}
/// This sample demonstrates how to create a restorable Material date picker.
/// This is accomplished by enabling state restoration by specifying
/// [MaterialApp.restorationScopeId] and using [Navigator.restorablePush] to
/// push [DatePickerDialog] when the button is tapped.
///
/// ** See code in examples/api/lib/material/date_picker/show_date_picker.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [showDateRangePicker], which shows a Material Design date range picker
/// used to select a range of dates.
/// * [CalendarDatePicker], which provides the calendar grid used by the date picker dialog.
/// * [InputDatePickerFormField], which provides a text input field for entering dates.
/// * [DisplayFeatureSubScreen], which documents the specifics of how
/// [DisplayFeature]s can split the screen into sub-screens.
/// * [showTimePicker], which shows a dialog that contains a Material Design time picker.
Future<DateTime?> showDatePicker({
required BuildContext context,
DateTime? initialDate,
required DateTime firstDate,
required DateTime lastDate,
DateTime? currentDate,
DatePickerEntryMode initialEntryMode = DatePickerEntryMode.calendar,
SelectableDayPredicate? selectableDayPredicate,
String? helpText,
String? cancelText,
String? confirmText,
Locale? locale,
bool barrierDismissible = true,
Color? barrierColor,
String? barrierLabel,
bool useRootNavigator = true,
RouteSettings? routeSettings,
TextDirection? textDirection,
TransitionBuilder? builder,
DatePickerMode initialDatePickerMode = DatePickerMode.day,
String? errorFormatText,
String? errorInvalidText,
String? fieldHintText,
String? fieldLabelText,
TextInputType? keyboardType,
Offset? anchorPoint,
final ValueChanged<DatePickerEntryMode>? onDatePickerModeChange,
final Icon? switchToInputEntryModeIcon,
final Icon? switchToCalendarEntryModeIcon,
}) async {
initialDate = initialDate == null ? null : DateUtils.dateOnly(initialDate);
firstDate = DateUtils.dateOnly(firstDate);
lastDate = DateUtils.dateOnly(lastDate);
assert(
!lastDate.isBefore(firstDate),
'lastDate $lastDate must be on or after firstDate $firstDate.',
);
assert(
initialDate == null || !initialDate.isBefore(firstDate),
'initialDate $initialDate must be on or after firstDate $firstDate.',
);
assert(
initialDate == null || !initialDate.isAfter(lastDate),
'initialDate $initialDate must be on or before lastDate $lastDate.',
);
assert(
selectableDayPredicate == null || initialDate == null || selectableDayPredicate(initialDate),
'Provided initialDate $initialDate must satisfy provided selectableDayPredicate.',
);
assert(debugCheckHasMaterialLocalizations(context));
Widget dialog = DatePickerDialog(
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
currentDate: currentDate,
initialEntryMode: initialEntryMode,
selectableDayPredicate: selectableDayPredicate,
helpText: helpText,
cancelText: cancelText,
confirmText: confirmText,
initialCalendarMode: initialDatePickerMode,
errorFormatText: errorFormatText,
errorInvalidText: errorInvalidText,
fieldHintText: fieldHintText,
fieldLabelText: fieldLabelText,
keyboardType: keyboardType,
onDatePickerModeChange: onDatePickerModeChange,
switchToInputEntryModeIcon: switchToInputEntryModeIcon,
switchToCalendarEntryModeIcon: switchToCalendarEntryModeIcon,
);
if (textDirection != null) {
dialog = Directionality(
textDirection: textDirection,
child: dialog,
);
}
if (locale != null) {
dialog = Localizations.override(
context: context,
locale: locale,
child: dialog,
);
} else {
final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context);
if (datePickerTheme.locale != null) {
dialog = Localizations.override(
context: context,
locale: datePickerTheme.locale,
child: dialog,
);
}
}
return showDialog<DateTime>(
context: context,
barrierDismissible: barrierDismissible,
barrierColor: barrierColor,
barrierLabel: barrierLabel,
useRootNavigator: useRootNavigator,
routeSettings: routeSettings,
builder: (BuildContext context) {
return builder == null ? dialog : builder(context, dialog);
},
anchorPoint: anchorPoint,
);
}
/// A Material-style date picker dialog.
///
/// It is used internally by [showDatePicker] or can be directly pushed
/// onto the [Navigator] stack to enable state restoration. See
/// [showDatePicker] for a state restoration app example.
///
/// See also:
///
/// * [showDatePicker], which is a way to display the date picker.
class DatePickerDialog extends StatefulWidget {
/// A Material-style date picker dialog.
DatePickerDialog({
super.key,
DateTime? initialDate,
required DateTime firstDate,
required DateTime lastDate,
DateTime? currentDate,
this.initialEntryMode = DatePickerEntryMode.calendar,
this.selectableDayPredicate,
this.cancelText,
this.confirmText,
this.helpText,
this.initialCalendarMode = DatePickerMode.day,
this.errorFormatText,
this.errorInvalidText,
this.fieldHintText,
this.fieldLabelText,
this.keyboardType,
this.restorationId,
this.onDatePickerModeChange,
this.switchToInputEntryModeIcon,
this.switchToCalendarEntryModeIcon,
}) : initialDate = initialDate == null ? null : DateUtils.dateOnly(initialDate),
firstDate = DateUtils.dateOnly(firstDate),
lastDate = DateUtils.dateOnly(lastDate),
currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()) {
assert(
!this.lastDate.isBefore(this.firstDate),
'lastDate ${this.lastDate} must be on or after firstDate ${this.firstDate}.',
);
assert(
initialDate == null || !this.initialDate!.isBefore(this.firstDate),
'initialDate ${this.initialDate} must be on or after firstDate ${this.firstDate}.',
);
assert(
initialDate == null || !this.initialDate!.isAfter(this.lastDate),
'initialDate ${this.initialDate} must be on or before lastDate ${this.lastDate}.',
);
assert(
selectableDayPredicate == null || initialDate == null || selectableDayPredicate!(this.initialDate!),
'Provided initialDate ${this.initialDate} must satisfy provided selectableDayPredicate',
);
}
/// The initially selected [DateTime] that the picker should display.
///
/// If this is null, there is no selected date. A date must be selected to
/// submit the dialog.
final DateTime? initialDate;
/// The earliest allowable [DateTime] that the user can select.
final DateTime firstDate;
/// The latest allowable [DateTime] that the user can select.
final DateTime lastDate;
/// The [DateTime] representing today. It will be highlighted in the day grid.
final DateTime currentDate;
/// The initial mode of date entry method for the date picker dialog.
///
/// See [DatePickerEntryMode] for more details on the different data entry
/// modes available.
final DatePickerEntryMode initialEntryMode;
/// Function to provide full control over which [DateTime] can be selected.
final SelectableDayPredicate? selectableDayPredicate;
/// The text that is displayed on the cancel button.
final String? cancelText;
/// The text that is displayed on the confirm button.
final String? confirmText;
/// The text that is displayed at the top of the header.
///
/// This is used to indicate to the user what they are selecting a date for.
final String? helpText;
/// The initial display of the calendar picker.
final DatePickerMode initialCalendarMode;
/// The error text displayed if the entered date is not in the correct format.
final String? errorFormatText;
/// The error text displayed if the date is not valid.
///
/// A date is not valid if it is earlier than [firstDate], later than
/// [lastDate], or doesn't pass the [selectableDayPredicate].
final String? errorInvalidText;
/// The hint text displayed in the [TextField].
///
/// If this is null, it will default to the date format string. For example,
/// 'mm/dd/yyyy' for en_US.
final String? fieldHintText;
/// The label text displayed in the [TextField].
///
/// If this is null, it will default to the words representing the date format
/// string. For example, 'Month, Day, Year' for en_US.
final String? fieldLabelText;
/// {@template flutter.material.datePickerDialog}
/// The keyboard type of the [TextField].
///
/// If this is null, it will default to [TextInputType.datetime]
/// {@endtemplate}
final TextInputType? keyboardType;
/// Restoration ID to save and restore the state of the [DatePickerDialog].
///
/// If it is non-null, the date picker will persist and restore the
/// date selected on the dialog.
///
/// The state of this widget is persisted in a [RestorationBucket] claimed
/// from the surrounding [RestorationScope] using the provided restoration ID.
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
final String? restorationId;
/// Called when the [DatePickerDialog] is toggled between
/// [DatePickerEntryMode.calendar],[DatePickerEntryMode.input].
///
/// An example of how this callback might be used is an app that saves the
/// user's preferred entry mode and uses it to initialize the
/// `initialEntryMode` parameter the next time the date picker is shown.
final ValueChanged<DatePickerEntryMode>? onDatePickerModeChange;
/// {@macro flutter.material.date_picker.switchToInputEntryModeIcon}
final Icon? switchToInputEntryModeIcon;
/// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon}
final Icon? switchToCalendarEntryModeIcon;
@override
State<DatePickerDialog> createState() => _DatePickerDialogState();
}
class _DatePickerDialogState extends State<DatePickerDialog> with RestorationMixin {
late final RestorableDateTimeN _selectedDate = RestorableDateTimeN(widget.initialDate);
late final _RestorableDatePickerEntryMode _entryMode = _RestorableDatePickerEntryMode(widget.initialEntryMode);
final _RestorableAutovalidateMode _autovalidateMode = _RestorableAutovalidateMode(AutovalidateMode.disabled);
@override
void dispose() {
_selectedDate.dispose();
_entryMode.dispose();
_autovalidateMode.dispose();
super.dispose();
}
@override
String? get restorationId => widget.restorationId;
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_selectedDate, 'selected_date');
registerForRestoration(_autovalidateMode, 'autovalidateMode');
registerForRestoration(_entryMode, 'calendar_entry_mode');
}
final GlobalKey _calendarPickerKey = GlobalKey();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
void _handleOk() {
if (_entryMode.value == DatePickerEntryMode.input || _entryMode.value == DatePickerEntryMode.inputOnly) {
final FormState form = _formKey.currentState!;
if (!form.validate()) {
setState(() => _autovalidateMode.value = AutovalidateMode.always);
return;
}
form.save();
}
Navigator.pop(context, _selectedDate.value);
}
void _handleCancel() {
Navigator.pop(context);
}
void _handleOnDatePickerModeChange() {
widget.onDatePickerModeChange?.call(_entryMode.value);
}
void _handleEntryModeToggle() {
setState(() {
switch (_entryMode.value) {
case DatePickerEntryMode.calendar:
_autovalidateMode.value = AutovalidateMode.disabled;
_entryMode.value = DatePickerEntryMode.input;
_handleOnDatePickerModeChange();
case DatePickerEntryMode.input:
_formKey.currentState!.save();
_entryMode.value = DatePickerEntryMode.calendar;
_handleOnDatePickerModeChange();
case DatePickerEntryMode.calendarOnly:
case DatePickerEntryMode.inputOnly:
assert(false, 'Can not change entry mode from ${_entryMode.value}');
}
});
}
void _handleDateChanged(DateTime date) {
setState(() {
_selectedDate.value = date;
});
}
Size _dialogSize(BuildContext context) {
final bool useMaterial3 = Theme.of(context).useMaterial3;
final bool isCalendar = switch (_entryMode.value) {
DatePickerEntryMode.calendar || DatePickerEntryMode.calendarOnly => true,
DatePickerEntryMode.input || DatePickerEntryMode.inputOnly => false,
};
final Orientation orientation = MediaQuery.orientationOf(context);
return switch ((isCalendar, orientation)) {
(true, Orientation.portrait) when useMaterial3 => _calendarPortraitDialogSizeM3,
(false, Orientation.portrait) when useMaterial3 => _inputPortraitDialogSizeM3,
(true, Orientation.portrait) => _calendarPortraitDialogSizeM2,
(false, Orientation.portrait) => _inputPortraitDialogSizeM2,
(true, Orientation.landscape) => _calendarLandscapeDialogSize,
(false, Orientation.landscape) => _inputLandscapeDialogSize,
};
}
static const Map<ShortcutActivator, Intent> _formShortcutMap = <ShortcutActivator, Intent>{
// Pressing enter on the field will move focus to the next field or control.
SingleActivator(LogicalKeyboardKey.enter): NextFocusIntent(),
};
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final bool useMaterial3 = theme.useMaterial3;
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final Orientation orientation = MediaQuery.orientationOf(context);
final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context);
final DatePickerThemeData defaults = DatePickerTheme.defaults(context);
final TextTheme textTheme = theme.textTheme;
// There's no M3 spec for a landscape layout input (not calendar)
// date picker. To ensure that the date displayed in the input
// date picker's header fits in landscape mode, we override the M3
// default here.
TextStyle? headlineStyle;
if (useMaterial3) {
headlineStyle = datePickerTheme.headerHeadlineStyle ?? defaults.headerHeadlineStyle;
switch (_entryMode.value) {
case DatePickerEntryMode.input:
case DatePickerEntryMode.inputOnly:
if (orientation == Orientation.landscape) {
headlineStyle = textTheme.headlineSmall;
}
case DatePickerEntryMode.calendar:
case DatePickerEntryMode.calendarOnly:
// M3 default is OK.
}
} else {
headlineStyle = orientation == Orientation.landscape ? textTheme.headlineSmall : textTheme.headlineMedium;
}
final Color? headerForegroundColor = datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor;
headlineStyle = headlineStyle?.copyWith(color: headerForegroundColor);
final Widget actions = ConstrainedBox(
constraints: const BoxConstraints(minHeight: 52.0),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: OverflowBar(
spacing: 8,
children: <Widget>[
TextButton(
style: datePickerTheme.cancelButtonStyle ?? defaults.cancelButtonStyle,
onPressed: _handleCancel,
child: Text(widget.cancelText ?? (
useMaterial3
? localizations.cancelButtonLabel
: localizations.cancelButtonLabel.toUpperCase()
)),
),
TextButton(
style: datePickerTheme.confirmButtonStyle ?? defaults.confirmButtonStyle,
onPressed: _handleOk,
child: Text(widget.confirmText ?? localizations.okButtonLabel),
),
],
),
),
),
);
CalendarDatePicker calendarDatePicker() {
return CalendarDatePicker(
key: _calendarPickerKey,
initialDate: _selectedDate.value,
firstDate: widget.firstDate,
lastDate: widget.lastDate,
currentDate: widget.currentDate,
onDateChanged: _handleDateChanged,
selectableDayPredicate: widget.selectableDayPredicate,
initialCalendarMode: widget.initialCalendarMode,
);
}
Form inputDatePicker() {
return Form(
key: _formKey,
autovalidateMode: _autovalidateMode.value,
child: SizedBox(
height: orientation == Orientation.portrait ? _inputFormPortraitHeight : _inputFormLandscapeHeight,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Shortcuts(
shortcuts: _formShortcutMap,
child: Column(
children: <Widget>[
const Spacer(),
InputDatePickerFormField(
initialDate: _selectedDate.value,
firstDate: widget.firstDate,
lastDate: widget.lastDate,
onDateSubmitted: _handleDateChanged,
onDateSaved: _handleDateChanged,
selectableDayPredicate: widget.selectableDayPredicate,
errorFormatText: widget.errorFormatText,
errorInvalidText: widget.errorInvalidText,
fieldHintText: widget.fieldHintText,
fieldLabelText: widget.fieldLabelText,
keyboardType: widget.keyboardType,
autofocus: true,
),
const Spacer(),
],
),
),
),
),
);
}
final Widget picker;
final Widget? entryModeButton;
switch (_entryMode.value) {
case DatePickerEntryMode.calendar:
picker = calendarDatePicker();
entryModeButton = IconButton(
icon: widget.switchToInputEntryModeIcon ?? Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit),
color: headerForegroundColor,
tooltip: localizations.inputDateModeButtonLabel,
onPressed: _handleEntryModeToggle,
);
case DatePickerEntryMode.calendarOnly:
picker = calendarDatePicker();
entryModeButton = null;
case DatePickerEntryMode.input:
picker = inputDatePicker();
entryModeButton = IconButton(
icon: widget.switchToCalendarEntryModeIcon ?? const Icon(Icons.calendar_today),
color: headerForegroundColor,
tooltip: localizations.calendarModeButtonLabel,
onPressed: _handleEntryModeToggle,
);
case DatePickerEntryMode.inputOnly:
picker = inputDatePicker();
entryModeButton = null;
}
final Widget header = _DatePickerHeader(
helpText: widget.helpText ?? (
useMaterial3
? localizations.datePickerHelpText
: localizations.datePickerHelpText.toUpperCase()
),
titleText: _selectedDate.value == null ? '' : localizations.formatMediumDate(_selectedDate.value!),
titleStyle: headlineStyle,
orientation: orientation,
isShort: orientation == Orientation.landscape,
entryModeButton: entryModeButton,
);
// Constrain the textScaleFactor to the largest supported value to prevent
// layout issues.
// 14 is a common font size used to compute the effective text scale.
const double fontSizeToScale = 14.0;
final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: _kMaxTextScaleFactor).scale(fontSizeToScale) / fontSizeToScale;
final Size dialogSize = _dialogSize(context) * textScaleFactor;
final DialogTheme dialogTheme = theme.dialogTheme;
return Dialog(
backgroundColor: datePickerTheme.backgroundColor ?? defaults.backgroundColor,
elevation: useMaterial3
? datePickerTheme.elevation ?? defaults.elevation!
: datePickerTheme.elevation ?? dialogTheme.elevation ?? 24,
shadowColor: datePickerTheme.shadowColor ?? defaults.shadowColor,
surfaceTintColor: datePickerTheme.surfaceTintColor ?? defaults.surfaceTintColor,
shape: useMaterial3
? datePickerTheme.shape ?? defaults.shape
: datePickerTheme.shape ?? dialogTheme.shape ?? defaults.shape,
insetPadding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0),
clipBehavior: Clip.antiAlias,
child: AnimatedContainer(
width: dialogSize.width,
height: dialogSize.height,
duration: _dialogSizeAnimationDuration,
curve: Curves.easeIn,
child: MediaQuery.withClampedTextScaling(
// Constrain the textScaleFactor to the largest supported value to prevent
// layout issues.
maxScaleFactor: _kMaxTextScaleFactor,
child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
final Size portraitDialogSize = useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2;
// Make sure the portrait dialog can fit the contents comfortably when
// resized from the landscape dialog.
final bool isFullyPortrait = constraints.maxHeight >= math.min(dialogSize.height, portraitDialogSize.height);
switch (orientation) {
case Orientation.portrait:
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
header,
if (useMaterial3) Divider(height: 0, color: datePickerTheme.dividerColor),
if (isFullyPortrait) ...<Widget>[
Expanded(child: picker),
actions,
],
],
);
case Orientation.landscape:
return Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
header,
if (useMaterial3) VerticalDivider(width: 0, color: datePickerTheme.dividerColor),
Flexible(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(child: picker),
actions,
],
),
),
],
);
}
}),
),
),
);
}
}
// A restorable [DatePickerEntryMode] value.
//
// This serializes each entry as a unique `int` value.
class _RestorableDatePickerEntryMode extends RestorableValue<DatePickerEntryMode> {
_RestorableDatePickerEntryMode(
DatePickerEntryMode defaultValue,
) : _defaultValue = defaultValue;
final DatePickerEntryMode _defaultValue;
@override
DatePickerEntryMode createDefaultValue() => _defaultValue;
@override
void didUpdateValue(DatePickerEntryMode? oldValue) {
assert(debugIsSerializableForRestoration(value.index));
notifyListeners();
}
@override
DatePickerEntryMode fromPrimitives(Object? data) => DatePickerEntryMode.values[data! as int];
@override
Object? toPrimitives() => value.index;
}
// A restorable [AutovalidateMode] value.
//
// This serializes each entry as a unique `int` value.
class _RestorableAutovalidateMode extends RestorableValue<AutovalidateMode> {
_RestorableAutovalidateMode(
AutovalidateMode defaultValue,
) : _defaultValue = defaultValue;
final AutovalidateMode _defaultValue;
@override
AutovalidateMode createDefaultValue() => _defaultValue;
@override
void didUpdateValue(AutovalidateMode? oldValue) {
assert(debugIsSerializableForRestoration(value.index));
notifyListeners();
}
@override
AutovalidateMode fromPrimitives(Object? data) => AutovalidateMode.values[data! as int];
@override
Object? toPrimitives() => value.index;
}
/// Re-usable widget that displays the selected date (in large font) and the
/// help text above it.
///
/// These types include:
///
/// * Single Date picker with calendar mode.
/// * Single Date picker with text input mode.
/// * Date Range picker with text input mode.
///
/// [helpText], [orientation], [icon], [onIconPressed] are required and must be
/// non-null.
class _DatePickerHeader extends StatelessWidget {
/// Creates a header for use in a date picker dialog.
const _DatePickerHeader({
required this.helpText,
required this.titleText,
this.titleSemanticsLabel,
required this.titleStyle,
required this.orientation,
this.isShort = false,
this.entryModeButton,
});
static const double _datePickerHeaderLandscapeWidth = 152.0;
static const double _datePickerHeaderPortraitHeight = 120.0;
static const double _headerPaddingLandscape = 16.0;
/// The text that is displayed at the top of the header.
///
/// This is used to indicate to the user what they are selecting a date for.
final String helpText;
/// The text that is displayed at the center of the header.
final String titleText;
/// The semantic label associated with the [titleText].
final String? titleSemanticsLabel;
/// The [TextStyle] that the title text is displayed with.
final TextStyle? titleStyle;
/// The orientation is used to decide how to layout its children.
final Orientation orientation;
/// Indicates the header is being displayed in a shorter/narrower context.
///
/// This will be used to tighten up the space between the help text and date
/// text if `true`. Additionally, it will use a smaller typography style if
/// `true`.
///
/// This is necessary for displaying the manual input mode in
/// landscape orientation, in order to account for the keyboard height.
final bool isShort;
final Widget? entryModeButton;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context);
final DatePickerThemeData defaults = DatePickerTheme.defaults(context);
final Color? backgroundColor = datePickerTheme.headerBackgroundColor ?? defaults.headerBackgroundColor;
final Color? foregroundColor = datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor;
final TextStyle? helpStyle = (datePickerTheme.headerHelpStyle ?? defaults.headerHelpStyle)?.copyWith(
color: foregroundColor,
);
final Text help = Text(
helpText,
style: helpStyle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
final Text title = Text(
titleText,
semanticsLabel: titleSemanticsLabel ?? titleText,
style: titleStyle,
maxLines: orientation == Orientation.portrait ? 1 : 2,
overflow: TextOverflow.ellipsis,
);
switch (orientation) {
case Orientation.portrait:
return Semantics(
container: true,
child: SizedBox(
height: _datePickerHeaderPortraitHeight,
child: Material(
color: backgroundColor,
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: 24,
end: 12,
bottom: 12,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(height: 16),
help,
const Flexible(child: SizedBox(height: 38)),
Row(
children: <Widget>[
Expanded(child: title),
if (entryModeButton != null)
Semantics(
container: true,
child: entryModeButton,
),
],
),
],
),
),
),
),
);
case Orientation.landscape:
return Semantics(
container: true,
child:SizedBox(
width: _datePickerHeaderLandscapeWidth,
child: Material(
color: backgroundColor,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
const SizedBox(height: 16),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: _headerPaddingLandscape,
),
child: help,
),
SizedBox(height: isShort ? 16 : 56),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: _headerPaddingLandscape,
),
child: title,
),
),
if (entryModeButton != null)
Padding(
padding: theme.useMaterial3
// TODO(TahaTesser): This is an eye-balled M3 entry mode button padding
// from https://m3.material.io/components/date-pickers/specs#c16c142b-4706-47f3-9400-3cde654b9aa8.
// Update this value to use tokens when available.
? const EdgeInsetsDirectional.only(
start: 8.0,
end: 4.0,
bottom: 6.0,
)
: const EdgeInsets.symmetric(horizontal: 4),
child: Semantics(
container: true,
child: entryModeButton,
),
),
],
),
),
),
);
}
}
}
/// Shows a full screen modal dialog containing a Material Design date range
/// picker.
///
/// The returned [Future] resolves to the [DateTimeRange] selected by the user
/// when the user saves their selection. If the user cancels the dialog, null is
/// returned.
///
/// If [initialDateRange] is non-null, then it will be used as the initially
/// selected date range. If it is provided, `initialDateRange.start` must be
/// before or on `initialDateRange.end`.
///
/// The [firstDate] is the earliest allowable date. The [lastDate] is the latest
/// allowable date.
///
/// If an initial date range is provided, `initialDateRange.start`
/// and `initialDateRange.end` must both fall between or on [firstDate] and
/// [lastDate]. For all of these [DateTime] values, only their dates are
/// considered. Their time fields are ignored.
///
/// The [currentDate] represents the current day (i.e. today). This
/// date will be highlighted in the day grid. If null, the date of
/// `DateTime.now()` will be used.
///
/// An optional [initialEntryMode] argument can be used to display the date
/// picker in the [DatePickerEntryMode.calendar] (a scrollable calendar month
/// grid) or [DatePickerEntryMode.input] (two text input fields) mode.
/// It defaults to [DatePickerEntryMode.calendar].
///
/// {@macro flutter.material.date_picker.switchToInputEntryModeIcon}
///
/// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon}
///
/// The following optional string parameters allow you to override the default
/// text used for various parts of the dialog:
///
/// * [helpText], the label displayed at the top of the dialog.
/// * [cancelText], the label on the cancel button for the text input mode.
/// * [confirmText],the label on the ok button for the text input mode.
/// * [saveText], the label on the save button for the fullscreen calendar
/// mode.
/// * [errorFormatText], the message used when an input text isn't in a proper
/// date format.
/// * [errorInvalidText], the message used when an input text isn't a
/// selectable date.
/// * [errorInvalidRangeText], the message used when the date range is
/// invalid (e.g. start date is after end date).
/// * [fieldStartHintText], the text used to prompt the user when no text has
/// been entered in the start field.
/// * [fieldEndHintText], the text used to prompt the user when no text has
/// been entered in the end field.
/// * [fieldStartLabelText], the label for the start date text input field.
/// * [fieldEndLabelText], the label for the end date text input field.
///
/// An optional [locale] argument can be used to set the locale for the date
/// picker. It defaults to the ambient locale provided by [Localizations].
///
/// An optional [textDirection] argument can be used to set the text direction
/// ([TextDirection.ltr] or [TextDirection.rtl]) for the date picker. It
/// defaults to the ambient text direction provided by [Directionality]. If both
/// [locale] and [textDirection] are non-null, [textDirection] overrides the
/// direction chosen for the [locale].
///
/// The [context], [barrierDismissible], [barrierColor], [barrierLabel],
/// [useRootNavigator] and [routeSettings] arguments are passed to [showDialog],
/// the documentation for which discusses how it is used.
///
/// The [builder] parameter can be used to wrap the dialog widget
/// to add inherited widgets like [Theme].
///
/// {@macro flutter.widgets.RawDialogRoute}
///
/// ### State Restoration
///
/// Using this method will not enable state restoration for the date range picker.
/// In order to enable state restoration for a date range picker, use
/// [Navigator.restorablePush] or [Navigator.restorablePushNamed] with
/// [DateRangePickerDialog].
///
/// For more information about state restoration, see [RestorationManager].
///
/// {@macro flutter.widgets.RestorationManager}
///
/// {@tool dartpad}
/// This sample demonstrates how to create a restorable Material date range picker.
/// This is accomplished by enabling state restoration by specifying
/// [MaterialApp.restorationScopeId] and using [Navigator.restorablePush] to
/// push [DateRangePickerDialog] when the button is tapped.
///
/// ** See code in examples/api/lib/material/date_picker/show_date_range_picker.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [showDatePicker], which shows a Material Design date picker used to
/// select a single date.
/// * [DateTimeRange], which is used to describe a date range.
/// * [DisplayFeatureSubScreen], which documents the specifics of how
/// [DisplayFeature]s can split the screen into sub-screens.
Future<DateTimeRange?> showDateRangePicker({
required BuildContext context,
DateTimeRange? initialDateRange,
required DateTime firstDate,
required DateTime lastDate,
DateTime? currentDate,
DatePickerEntryMode initialEntryMode = DatePickerEntryMode.calendar,
String? helpText,
String? cancelText,
String? confirmText,
String? saveText,
String? errorFormatText,
String? errorInvalidText,
String? errorInvalidRangeText,
String? fieldStartHintText,
String? fieldEndHintText,
String? fieldStartLabelText,
String? fieldEndLabelText,
Locale? locale,
bool barrierDismissible = true,
Color? barrierColor,
String? barrierLabel,
bool useRootNavigator = true,
RouteSettings? routeSettings,
TextDirection? textDirection,
TransitionBuilder? builder,
Offset? anchorPoint,
TextInputType keyboardType = TextInputType.datetime,
final Icon? switchToInputEntryModeIcon,
final Icon? switchToCalendarEntryModeIcon,
}) async {
assert(
initialDateRange == null || !initialDateRange.start.isAfter(initialDateRange.end),
"initialDateRange's start date must not be after it's end date.",
);
initialDateRange = initialDateRange == null ? null : DateUtils.datesOnly(initialDateRange);
firstDate = DateUtils.dateOnly(firstDate);
lastDate = DateUtils.dateOnly(lastDate);
assert(
!lastDate.isBefore(firstDate),
'lastDate $lastDate must be on or after firstDate $firstDate.',
);
assert(
initialDateRange == null || !initialDateRange.start.isBefore(firstDate),
"initialDateRange's start date must be on or after firstDate $firstDate.",
);
assert(
initialDateRange == null || !initialDateRange.end.isBefore(firstDate),
"initialDateRange's end date must be on or after firstDate $firstDate.",
);
assert(
initialDateRange == null || !initialDateRange.start.isAfter(lastDate),
"initialDateRange's start date must be on or before lastDate $lastDate.",
);
assert(
initialDateRange == null || !initialDateRange.end.isAfter(lastDate),
"initialDateRange's end date must be on or before lastDate $lastDate.",
);
currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now());
assert(debugCheckHasMaterialLocalizations(context));
Widget dialog = DateRangePickerDialog(
initialDateRange: initialDateRange,
firstDate: firstDate,
lastDate: lastDate,
currentDate: currentDate,
initialEntryMode: initialEntryMode,
helpText: helpText,
cancelText: cancelText,
confirmText: confirmText,
saveText: saveText,
errorFormatText: errorFormatText,
errorInvalidText: errorInvalidText,
errorInvalidRangeText: errorInvalidRangeText,
fieldStartHintText: fieldStartHintText,
fieldEndHintText: fieldEndHintText,
fieldStartLabelText: fieldStartLabelText,
fieldEndLabelText: fieldEndLabelText,
keyboardType: keyboardType,
switchToInputEntryModeIcon: switchToInputEntryModeIcon,
switchToCalendarEntryModeIcon: switchToCalendarEntryModeIcon,
);
if (textDirection != null) {
dialog = Directionality(
textDirection: textDirection,
child: dialog,
);
}
if (locale != null) {
dialog = Localizations.override(
context: context,
locale: locale,
child: dialog,
);
}
return showDialog<DateTimeRange>(
context: context,
barrierDismissible: barrierDismissible,
barrierColor: barrierColor,
barrierLabel: barrierLabel,
useRootNavigator: useRootNavigator,
routeSettings: routeSettings,
useSafeArea: false,
builder: (BuildContext context) {
return builder == null ? dialog : builder(context, dialog);
},
anchorPoint: anchorPoint,
);
}
/// Returns a locale-appropriate string to describe the start of a date range.
///
/// If `startDate` is null, then it defaults to 'Start Date', otherwise if it
/// is in the same year as the `endDate` then it will use the short month
/// day format (i.e. 'Jan 21'). Otherwise it will return the short date format
/// (i.e. 'Jan 21, 2020').
String _formatRangeStartDate(MaterialLocalizations localizations, DateTime? startDate, DateTime? endDate) {
return startDate == null
? localizations.dateRangeStartLabel
: (endDate == null || startDate.year == endDate.year)
? localizations.formatShortMonthDay(startDate)
: localizations.formatShortDate(startDate);
}
/// Returns an locale-appropriate string to describe the end of a date range.
///
/// If `endDate` is null, then it defaults to 'End Date', otherwise if it
/// is in the same year as the `startDate` and the `currentDate` then it will
/// just use the short month day format (i.e. 'Jan 21'), otherwise it will
/// include the year (i.e. 'Jan 21, 2020').
String _formatRangeEndDate(MaterialLocalizations localizations, DateTime? startDate, DateTime? endDate, DateTime currentDate) {
return endDate == null
? localizations.dateRangeEndLabel
: (startDate != null && startDate.year == endDate.year && startDate.year == currentDate.year)
? localizations.formatShortMonthDay(endDate)
: localizations.formatShortDate(endDate);
}
/// A Material-style date range picker dialog.
///
/// It is used internally by [showDateRangePicker] or can be directly pushed
/// onto the [Navigator] stack to enable state restoration. See
/// [showDateRangePicker] for a state restoration app example.
///
/// See also:
///
/// * [showDateRangePicker], which is a way to display the date picker.
class DateRangePickerDialog extends StatefulWidget {
/// A Material-style date range picker dialog.
const DateRangePickerDialog({
super.key,
this.initialDateRange,
required this.firstDate,
required this.lastDate,
this.currentDate,
this.initialEntryMode = DatePickerEntryMode.calendar,
this.helpText,
this.cancelText,
this.confirmText,
this.saveText,
this.errorInvalidRangeText,
this.errorFormatText,
this.errorInvalidText,
this.fieldStartHintText,
this.fieldEndHintText,
this.fieldStartLabelText,
this.fieldEndLabelText,
this.keyboardType = TextInputType.datetime,
this.restorationId,
this.switchToInputEntryModeIcon,
this.switchToCalendarEntryModeIcon,
});
/// The date range that the date range picker starts with when it opens.
///
/// If an initial date range is provided, `initialDateRange.start`
/// and `initialDateRange.end` must both fall between or on [firstDate] and
/// [lastDate]. For all of these [DateTime] values, only their dates are
/// considered. Their time fields are ignored.
///
/// If [initialDateRange] is non-null, then it will be used as the initially
/// selected date range. If it is provided, `initialDateRange.start` must be
/// before or on `initialDateRange.end`.
final DateTimeRange? initialDateRange;
/// The earliest allowable date on the date range.
final DateTime firstDate;
/// The latest allowable date on the date range.
final DateTime lastDate;
/// The [currentDate] represents the current day (i.e. today).
///
/// This date will be highlighted in the day grid.
///
/// If `null`, the date of `DateTime.now()` will be used.
final DateTime? currentDate;
/// The initial date range picker entry mode.
///
/// The date range has two main modes: [DatePickerEntryMode.calendar] (a
/// scrollable calendar month grid) or [DatePickerEntryMode.input] (two text
/// input fields) mode.
///
/// It defaults to [DatePickerEntryMode.calendar].
final DatePickerEntryMode initialEntryMode;
/// The label on the cancel button for the text input mode.
///
/// If null, the localized value of
/// [MaterialLocalizations.cancelButtonLabel] is used.
final String? cancelText;
/// The label on the "OK" button for the text input mode.
///
/// If null, the localized value of
/// [MaterialLocalizations.okButtonLabel] is used.
final String? confirmText;
/// The label on the save button for the fullscreen calendar mode.
///
/// If null, the localized value of
/// [MaterialLocalizations.saveButtonLabel] is used.
final String? saveText;
/// The label displayed at the top of the dialog.
///
/// If null, the localized value of
/// [MaterialLocalizations.dateRangePickerHelpText] is used.
final String? helpText;
/// The message used when the date range is invalid (e.g. start date is after
/// end date).
///
/// If null, the localized value of
/// [MaterialLocalizations.invalidDateRangeLabel] is used.
final String? errorInvalidRangeText;
/// The message used when an input text isn't in a proper date format.
///
/// If null, the localized value of
/// [MaterialLocalizations.invalidDateFormatLabel] is used.
final String? errorFormatText;
/// The message used when an input text isn't a selectable date.
///
/// If null, the localized value of
/// [MaterialLocalizations.dateOutOfRangeLabel] is used.
final String? errorInvalidText;
/// The text used to prompt the user when no text has been entered in the
/// start field.
///
/// If null, the localized value of
/// [MaterialLocalizations.dateHelpText] is used.
final String? fieldStartHintText;
/// The text used to prompt the user when no text has been entered in the
/// end field.
///
/// If null, the localized value of [MaterialLocalizations.dateHelpText] is
/// used.
final String? fieldEndHintText;
/// The label for the start date text input field.
///
/// If null, the localized value of [MaterialLocalizations.dateRangeStartLabel]
/// is used.
final String? fieldStartLabelText;
/// The label for the end date text input field.
///
/// If null, the localized value of [MaterialLocalizations.dateRangeEndLabel]
/// is used.
final String? fieldEndLabelText;
/// {@macro flutter.material.datePickerDialog}
final TextInputType keyboardType;
/// Restoration ID to save and restore the state of the [DateRangePickerDialog].
///
/// If it is non-null, the date range picker will persist and restore the
/// date range selected on the dialog.
///
/// The state of this widget is persisted in a [RestorationBucket] claimed
/// from the surrounding [RestorationScope] using the provided restoration ID.
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
final String? restorationId;
/// {@macro flutter.material.date_picker.switchToInputEntryModeIcon}
final Icon? switchToInputEntryModeIcon;
/// {@macro flutter.material.date_picker.switchToCalendarEntryModeIcon}
final Icon? switchToCalendarEntryModeIcon;
@override
State<DateRangePickerDialog> createState() => _DateRangePickerDialogState();
}
class _DateRangePickerDialogState extends State<DateRangePickerDialog> with RestorationMixin {
late final _RestorableDatePickerEntryMode _entryMode = _RestorableDatePickerEntryMode(widget.initialEntryMode);
late final RestorableDateTimeN _selectedStart = RestorableDateTimeN(widget.initialDateRange?.start);
late final RestorableDateTimeN _selectedEnd = RestorableDateTimeN(widget.initialDateRange?.end);
final RestorableBool _autoValidate = RestorableBool(false);
final GlobalKey _calendarPickerKey = GlobalKey();
final GlobalKey<_InputDateRangePickerState> _inputPickerKey = GlobalKey<_InputDateRangePickerState>();
@override
String? get restorationId => widget.restorationId;
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_entryMode, 'entry_mode');
registerForRestoration(_selectedStart, 'selected_start');
registerForRestoration(_selectedEnd, 'selected_end');
registerForRestoration(_autoValidate, 'autovalidate');
}
@override
void dispose() {
_entryMode.dispose();
_selectedStart.dispose();
_selectedEnd.dispose();
_autoValidate.dispose();
super.dispose();
}
void _handleOk() {
if (_entryMode.value == DatePickerEntryMode.input || _entryMode.value == DatePickerEntryMode.inputOnly) {
final _InputDateRangePickerState picker = _inputPickerKey.currentState!;
if (!picker.validate()) {
setState(() {
_autoValidate.value = true;
});
return;
}
}
final DateTimeRange? selectedRange = _hasSelectedDateRange
? DateTimeRange(start: _selectedStart.value!, end: _selectedEnd.value!)
: null;
Navigator.pop(context, selectedRange);
}
void _handleCancel() {
Navigator.pop(context);
}
void _handleEntryModeToggle() {
setState(() {
switch (_entryMode.value) {
case DatePickerEntryMode.calendar:
_autoValidate.value = false;
_entryMode.value = DatePickerEntryMode.input;
case DatePickerEntryMode.input:
// Validate the range dates
if (_selectedStart.value != null &&
(_selectedStart.value!.isBefore(widget.firstDate) || _selectedStart.value!.isAfter(widget.lastDate))) {
_selectedStart.value = null;
// With no valid start date, having an end date makes no sense for the UI.
_selectedEnd.value = null;
}
if (_selectedEnd.value != null &&
(_selectedEnd.value!.isBefore(widget.firstDate) || _selectedEnd.value!.isAfter(widget.lastDate))) {
_selectedEnd.value = null;
}
// If invalid range (start after end), then just use the start date
if (_selectedStart.value != null && _selectedEnd.value != null && _selectedStart.value!.isAfter(_selectedEnd.value!)) {
_selectedEnd.value = null;
}
_entryMode.value = DatePickerEntryMode.calendar;
case DatePickerEntryMode.calendarOnly:
case DatePickerEntryMode.inputOnly:
assert(false, 'Can not change entry mode from $_entryMode');
}
});
}
void _handleStartDateChanged(DateTime? date) {
setState(() => _selectedStart.value = date);
}
void _handleEndDateChanged(DateTime? date) {
setState(() => _selectedEnd.value = date);
}
bool get _hasSelectedDateRange => _selectedStart.value != null && _selectedEnd.value != null;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final bool useMaterial3 = theme.useMaterial3;
final Orientation orientation = MediaQuery.orientationOf(context);
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context);
final DatePickerThemeData defaults = DatePickerTheme.defaults(context);
final Widget contents;
final Size size;
final double? elevation;
final Color? shadowColor;
final Color? surfaceTintColor;
final ShapeBorder? shape;
final EdgeInsets insetPadding;
final bool showEntryModeButton =
_entryMode.value == DatePickerEntryMode.calendar ||
_entryMode.value == DatePickerEntryMode.input;
switch (_entryMode.value) {
case DatePickerEntryMode.calendar:
case DatePickerEntryMode.calendarOnly:
contents = _CalendarRangePickerDialog(
key: _calendarPickerKey,
selectedStartDate: _selectedStart.value,
selectedEndDate: _selectedEnd.value,
firstDate: widget.firstDate,
lastDate: widget.lastDate,
currentDate: widget.currentDate,
onStartDateChanged: _handleStartDateChanged,
onEndDateChanged: _handleEndDateChanged,
onConfirm: _hasSelectedDateRange ? _handleOk : null,
onCancel: _handleCancel,
entryModeButton: showEntryModeButton
? IconButton(
icon: widget.switchToInputEntryModeIcon ?? Icon(useMaterial3 ? Icons.edit_outlined : Icons.edit),
padding: EdgeInsets.zero,
tooltip: localizations.inputDateModeButtonLabel,
onPressed: _handleEntryModeToggle,
)
: null,
confirmText: widget.saveText ?? (
useMaterial3
? localizations.saveButtonLabel
: localizations.saveButtonLabel.toUpperCase()
),
helpText: widget.helpText ?? (
useMaterial3
? localizations.dateRangePickerHelpText
: localizations.dateRangePickerHelpText.toUpperCase()
),
);
size = MediaQuery.sizeOf(context);
insetPadding = EdgeInsets.zero;
elevation = datePickerTheme.rangePickerElevation ?? defaults.rangePickerElevation!;
shadowColor = datePickerTheme.rangePickerShadowColor ?? defaults.rangePickerShadowColor!;
surfaceTintColor = datePickerTheme.rangePickerSurfaceTintColor ?? defaults.rangePickerSurfaceTintColor!;
shape = datePickerTheme.rangePickerShape ?? defaults.rangePickerShape;
case DatePickerEntryMode.input:
case DatePickerEntryMode.inputOnly:
contents = _InputDateRangePickerDialog(
selectedStartDate: _selectedStart.value,
selectedEndDate: _selectedEnd.value,
currentDate: widget.currentDate,
picker: SizedBox(
height: orientation == Orientation.portrait
? _inputFormPortraitHeight
: _inputFormLandscapeHeight,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
children: <Widget>[
const Spacer(),
_InputDateRangePicker(
key: _inputPickerKey,
initialStartDate: _selectedStart.value,
initialEndDate: _selectedEnd.value,
firstDate: widget.firstDate,
lastDate: widget.lastDate,
onStartDateChanged: _handleStartDateChanged,
onEndDateChanged: _handleEndDateChanged,
autofocus: true,
autovalidate: _autoValidate.value,
helpText: widget.helpText,
errorInvalidRangeText: widget.errorInvalidRangeText,
errorFormatText: widget.errorFormatText,
errorInvalidText: widget.errorInvalidText,
fieldStartHintText: widget.fieldStartHintText,
fieldEndHintText: widget.fieldEndHintText,
fieldStartLabelText: widget.fieldStartLabelText,
fieldEndLabelText: widget.fieldEndLabelText,
keyboardType: widget.keyboardType,
),
const Spacer(),
],
),
),
),
onConfirm: _handleOk,
onCancel: _handleCancel,
entryModeButton: showEntryModeButton
? IconButton(
icon: widget.switchToCalendarEntryModeIcon ?? const Icon(Icons.calendar_today),
padding: EdgeInsets.zero,
tooltip: localizations.calendarModeButtonLabel,
onPressed: _handleEntryModeToggle,
)
: null,
confirmText: widget.confirmText ?? localizations.okButtonLabel,
cancelText: widget.cancelText ?? (
useMaterial3
? localizations.cancelButtonLabel
: localizations.cancelButtonLabel.toUpperCase()
),
helpText: widget.helpText ?? (
useMaterial3
? localizations.dateRangePickerHelpText
: localizations.dateRangePickerHelpText.toUpperCase()
),
);
final DialogTheme dialogTheme = theme.dialogTheme;
size = orientation == Orientation.portrait
? (useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2)
: _inputRangeLandscapeDialogSize;
elevation = useMaterial3
? datePickerTheme.elevation ?? defaults.elevation!
: datePickerTheme.elevation ?? dialogTheme.elevation ?? 24;
shadowColor = datePickerTheme.shadowColor ?? defaults.shadowColor;
surfaceTintColor = datePickerTheme.surfaceTintColor ?? defaults.surfaceTintColor;
shape = useMaterial3
? datePickerTheme.shape ?? defaults.shape
: datePickerTheme.shape ?? dialogTheme.shape ?? defaults.shape;
insetPadding = const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0);
}
return Dialog(
insetPadding: insetPadding,
backgroundColor: datePickerTheme.backgroundColor ?? defaults.backgroundColor,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
shape: shape,
clipBehavior: Clip.antiAlias,
child: AnimatedContainer(
width: size.width,
height: size.height,
duration: _dialogSizeAnimationDuration,
curve: Curves.easeIn,
child: MediaQuery.withClampedTextScaling(
maxScaleFactor: _kMaxTextScaleFactor,
child: Builder(builder: (BuildContext context) {
return contents;
}),
),
),
);
}
}
class _CalendarRangePickerDialog extends StatelessWidget {
const _CalendarRangePickerDialog({
super.key,
required this.selectedStartDate,
required this.selectedEndDate,
required this.firstDate,
required this.lastDate,
required this.currentDate,
required this.onStartDateChanged,
required this.onEndDateChanged,
required this.onConfirm,
required this.onCancel,
required this.confirmText,
required this.helpText,
this.entryModeButton,
});
final DateTime? selectedStartDate;
final DateTime? selectedEndDate;
final DateTime firstDate;
final DateTime lastDate;
final DateTime? currentDate;
final ValueChanged<DateTime> onStartDateChanged;
final ValueChanged<DateTime?> onEndDateChanged;
final VoidCallback? onConfirm;
final VoidCallback? onCancel;
final String confirmText;
final String helpText;
final Widget? entryModeButton;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final bool useMaterial3 = theme.useMaterial3;
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final Orientation orientation = MediaQuery.orientationOf(context);
final DatePickerThemeData themeData = DatePickerTheme.of(context);
final DatePickerThemeData defaults = DatePickerTheme.defaults(context);
final Color? dialogBackground = themeData.rangePickerBackgroundColor ?? defaults.rangePickerBackgroundColor;
final Color? headerBackground = themeData.rangePickerHeaderBackgroundColor ?? defaults.rangePickerHeaderBackgroundColor;
final Color? headerForeground = themeData.rangePickerHeaderForegroundColor ?? defaults.rangePickerHeaderForegroundColor;
final Color? headerDisabledForeground = headerForeground?.withOpacity(0.38);
final TextStyle? headlineStyle = themeData.rangePickerHeaderHeadlineStyle ?? defaults.rangePickerHeaderHeadlineStyle;
final TextStyle? headlineHelpStyle = (themeData.rangePickerHeaderHelpStyle ?? defaults.rangePickerHeaderHelpStyle)?.apply(color: headerForeground);
final String startDateText = _formatRangeStartDate(localizations, selectedStartDate, selectedEndDate);
final String endDateText = _formatRangeEndDate(localizations, selectedStartDate, selectedEndDate, DateTime.now());
final TextStyle? startDateStyle = headlineStyle?.apply(
color: selectedStartDate != null ? headerForeground : headerDisabledForeground,
);
final TextStyle? endDateStyle = headlineStyle?.apply(
color: selectedEndDate != null ? headerForeground : headerDisabledForeground,
);
final ButtonStyle buttonStyle = TextButton.styleFrom(
foregroundColor: headerForeground,
disabledForegroundColor: headerDisabledForeground
);
final IconThemeData iconTheme = IconThemeData(color: headerForeground);
return SafeArea(
top: false,
left: false,
right: false,
child: Scaffold(
appBar: AppBar(
iconTheme: iconTheme,
actionsIconTheme: iconTheme,
elevation: useMaterial3 ? 0 : null,
scrolledUnderElevation: useMaterial3 ? 0 : null,
backgroundColor: headerBackground,
leading: CloseButton(
onPressed: onCancel,
),
actions: <Widget>[
if (orientation == Orientation.landscape && entryModeButton != null)
entryModeButton!,
TextButton(
style: buttonStyle,
onPressed: onConfirm,
child: Text(confirmText),
),
const SizedBox(width: 8),
],
bottom: PreferredSize(
preferredSize: const Size(double.infinity, 64),
child: Row(children: <Widget>[
SizedBox(width: MediaQuery.sizeOf(context).width < 360 ? 42 : 72),
Expanded(
child: Semantics(
label: '$helpText $startDateText to $endDateText',
excludeSemantics: true,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
helpText,
style: headlineHelpStyle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 8),
Row(
children: <Widget>[
Text(
startDateText,
style: startDateStyle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
Text(' β ', style: startDateStyle,
),
Flexible(
child: Text(
endDateText,
style: endDateStyle,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
const SizedBox(height: 16),
],
),
),
),
if (orientation == Orientation.portrait && entryModeButton != null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: IconTheme(
data: iconTheme,
child: entryModeButton!,
),
),
]),
),
),
backgroundColor: dialogBackground,
body: _CalendarDateRangePicker(
initialStartDate: selectedStartDate,
initialEndDate: selectedEndDate,
firstDate: firstDate,
lastDate: lastDate,
currentDate: currentDate,
onStartDateChanged: onStartDateChanged,
onEndDateChanged: onEndDateChanged,
),
),
);
}
}
const Duration _monthScrollDuration = Duration(milliseconds: 200);
const double _monthItemHeaderHeight = 58.0;
const double _monthItemFooterHeight = 12.0;
const double _monthItemRowHeight = 42.0;
const double _monthItemSpaceBetweenRows = 8.0;
const double _horizontalPadding = 8.0;
const double _maxCalendarWidthLandscape = 384.0;
const double _maxCalendarWidthPortrait = 480.0;
/// Displays a scrollable calendar grid that allows a user to select a range
/// of dates.
class _CalendarDateRangePicker extends StatefulWidget {
/// Creates a scrollable calendar grid for picking date ranges.
_CalendarDateRangePicker({
DateTime? initialStartDate,
DateTime? initialEndDate,
required DateTime firstDate,
required DateTime lastDate,
DateTime? currentDate,
required this.onStartDateChanged,
required this.onEndDateChanged,
}) : initialStartDate = initialStartDate != null ? DateUtils.dateOnly(initialStartDate) : null,
initialEndDate = initialEndDate != null ? DateUtils.dateOnly(initialEndDate) : null,
firstDate = DateUtils.dateOnly(firstDate),
lastDate = DateUtils.dateOnly(lastDate),
currentDate = DateUtils.dateOnly(currentDate ?? DateTime.now()) {
assert(
this.initialStartDate == null || this.initialEndDate == null || !this.initialStartDate!.isAfter(initialEndDate!),
'initialStartDate must be on or before initialEndDate.',
);
assert(
!this.lastDate.isBefore(this.firstDate),
'firstDate must be on or before lastDate.',
);
}
/// The [DateTime] that represents the start of the initial date range selection.
final DateTime? initialStartDate;
/// The [DateTime] that represents the end of the initial date range selection.
final DateTime? initialEndDate;
/// The earliest allowable [DateTime] that the user can select.
final DateTime firstDate;
/// The latest allowable [DateTime] that the user can select.
final DateTime lastDate;
/// The [DateTime] representing today. It will be highlighted in the day grid.
final DateTime currentDate;
/// Called when the user changes the start date of the selected range.
final ValueChanged<DateTime>? onStartDateChanged;
/// Called when the user changes the end date of the selected range.
final ValueChanged<DateTime?>? onEndDateChanged;
@override
_CalendarDateRangePickerState createState() => _CalendarDateRangePickerState();
}
class _CalendarDateRangePickerState extends State<_CalendarDateRangePicker> {
final GlobalKey _scrollViewKey = GlobalKey();
DateTime? _startDate;
DateTime? _endDate;
int _initialMonthIndex = 0;
late ScrollController _controller;
late bool _showWeekBottomDivider;
@override
void initState() {
super.initState();
_controller = ScrollController();
_controller.addListener(_scrollListener);
_startDate = widget.initialStartDate;
_endDate = widget.initialEndDate;
// Calculate the index for the initially displayed month. This is needed to
// divide the list of months into two `SliverList`s.
final DateTime initialDate = widget.initialStartDate ?? widget.currentDate;
if (!initialDate.isBefore(widget.firstDate) &&
!initialDate.isAfter(widget.lastDate)) {
_initialMonthIndex = DateUtils.monthDelta(widget.firstDate, initialDate);
}
_showWeekBottomDivider = _initialMonthIndex != 0;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _scrollListener() {
if (_controller.offset <= _controller.position.minScrollExtent) {
setState(() {
_showWeekBottomDivider = false;
});
} else if (!_showWeekBottomDivider) {
setState(() {
_showWeekBottomDivider = true;
});
}
}
int get _numberOfMonths => DateUtils.monthDelta(widget.firstDate, widget.lastDate) + 1;
void _vibrate() {
switch (Theme.of(context).platform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
HapticFeedback.vibrate();
case TargetPlatform.iOS:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
break;
}
}
// This updates the selected date range using this logic:
//
// * From the unselected state, selecting one date creates the start date.
// * If the next selection is before the start date, reset date range and
// set the start date to that selection.
// * If the next selection is on or after the start date, set the end date
// to that selection.
// * After both start and end dates are selected, any subsequent selection
// resets the date range and sets start date to that selection.
void _updateSelection(DateTime date) {
_vibrate();
setState(() {
if (_startDate != null && _endDate == null && !date.isBefore(_startDate!)) {
_endDate = date;
widget.onEndDateChanged?.call(_endDate);
} else {
_startDate = date;
widget.onStartDateChanged?.call(_startDate!);
if (_endDate != null) {
_endDate = null;
widget.onEndDateChanged?.call(_endDate);
}
}
});
}
Widget _buildMonthItem(BuildContext context, int index, bool beforeInitialMonth) {
final int monthIndex = beforeInitialMonth
? _initialMonthIndex - index - 1
: _initialMonthIndex + index;
final DateTime month = DateUtils.addMonthsToMonthDate(widget.firstDate, monthIndex);
return _MonthItem(
selectedDateStart: _startDate,
selectedDateEnd: _endDate,
currentDate: widget.currentDate,
firstDate: widget.firstDate,
lastDate: widget.lastDate,
displayedMonth: month,
onChanged: _updateSelection,
);
}
@override
Widget build(BuildContext context) {
const Key sliverAfterKey = Key('sliverAfterKey');
return Column(
children: <Widget>[
const _DayHeaders(),
if (_showWeekBottomDivider) const Divider(height: 0),
Expanded(
child: _CalendarKeyboardNavigator(
firstDate: widget.firstDate,
lastDate: widget.lastDate,
initialFocusedDay: _startDate ?? widget.initialStartDate ?? widget.currentDate,
// In order to prevent performance issues when displaying the
// correct initial month, 2 `SliverList`s are used to split the
// months. The first item in the second SliverList is the initial
// month to be displayed.
child: CustomScrollView(
key: _scrollViewKey,
controller: _controller,
center: sliverAfterKey,
slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) => _buildMonthItem(context, index, true),
childCount: _initialMonthIndex,
),
),
SliverList(
key: sliverAfterKey,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) => _buildMonthItem(context, index, false),
childCount: _numberOfMonths - _initialMonthIndex,
),
),
],
),
),
),
],
);
}
}
class _CalendarKeyboardNavigator extends StatefulWidget {
const _CalendarKeyboardNavigator({
required this.child,
required this.firstDate,
required this.lastDate,
required this.initialFocusedDay,
});
final Widget child;
final DateTime firstDate;
final DateTime lastDate;
final DateTime initialFocusedDay;
@override
_CalendarKeyboardNavigatorState createState() => _CalendarKeyboardNavigatorState();
}
class _CalendarKeyboardNavigatorState extends State<_CalendarKeyboardNavigator> {
final Map<ShortcutActivator, Intent> _shortcutMap = const <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left),
SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right),
SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down),
SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up),
};
late Map<Type, Action<Intent>> _actionMap;
late FocusNode _dayGridFocus;
TraversalDirection? _dayTraversalDirection;
DateTime? _focusedDay;
@override
void initState() {
super.initState();
_actionMap = <Type, Action<Intent>>{
NextFocusIntent: CallbackAction<NextFocusIntent>(onInvoke: _handleGridNextFocus),
PreviousFocusIntent: CallbackAction<PreviousFocusIntent>(onInvoke: _handleGridPreviousFocus),
DirectionalFocusIntent: CallbackAction<DirectionalFocusIntent>(onInvoke: _handleDirectionFocus),
};
_dayGridFocus = FocusNode(debugLabel: 'Day Grid');
}
@override
void dispose() {
_dayGridFocus.dispose();
super.dispose();
}
void _handleGridFocusChange(bool focused) {
setState(() {
if (focused) {
_focusedDay ??= widget.initialFocusedDay;
}
});
}
/// Move focus to the next element after the day grid.
void _handleGridNextFocus(NextFocusIntent intent) {
_dayGridFocus.requestFocus();
_dayGridFocus.nextFocus();
}
/// Move focus to the previous element before the day grid.
void _handleGridPreviousFocus(PreviousFocusIntent intent) {
_dayGridFocus.requestFocus();
_dayGridFocus.previousFocus();
}
/// Move the internal focus date in the direction of the given intent.
///
/// This will attempt to move the focused day to the next selectable day in
/// the given direction. If the new date is not in the current month, then
/// the page view will be scrolled to show the new date's month.
///
/// For horizontal directions, it will move forward or backward a day (depending
/// on the current [TextDirection]). For vertical directions it will move up and
/// down a week at a time.
void _handleDirectionFocus(DirectionalFocusIntent intent) {
assert(_focusedDay != null);
setState(() {
final DateTime? nextDate = _nextDateInDirection(_focusedDay!, intent.direction);
if (nextDate != null) {
_focusedDay = nextDate;
_dayTraversalDirection = intent.direction;
}
});
}
static const Map<TraversalDirection, int> _directionOffset = <TraversalDirection, int>{
TraversalDirection.up: -DateTime.daysPerWeek,
TraversalDirection.right: 1,
TraversalDirection.down: DateTime.daysPerWeek,
TraversalDirection.left: -1,
};
int _dayDirectionOffset(TraversalDirection traversalDirection, TextDirection textDirection) {
// Swap left and right if the text direction if RTL
if (textDirection == TextDirection.rtl) {
if (traversalDirection == TraversalDirection.left) {
traversalDirection = TraversalDirection.right;
} else if (traversalDirection == TraversalDirection.right) {
traversalDirection = TraversalDirection.left;
}
}
return _directionOffset[traversalDirection]!;
}
DateTime? _nextDateInDirection(DateTime date, TraversalDirection direction) {
final TextDirection textDirection = Directionality.of(context);
final DateTime nextDate = DateUtils.addDaysToDate(date, _dayDirectionOffset(direction, textDirection));
if (!nextDate.isBefore(widget.firstDate) && !nextDate.isAfter(widget.lastDate)) {
return nextDate;
}
return null;
}
@override
Widget build(BuildContext context) {
return FocusableActionDetector(
shortcuts: _shortcutMap,
actions: _actionMap,
focusNode: _dayGridFocus,
onFocusChange: _handleGridFocusChange,
child: _FocusedDate(
date: _dayGridFocus.hasFocus ? _focusedDay : null,
scrollDirection: _dayGridFocus.hasFocus ? _dayTraversalDirection : null,
child: widget.child,
),
);
}
}
/// InheritedWidget indicating what the current focused date is for its children.
///
/// This is used by the [_MonthPicker] to let its children [_DayPicker]s know
/// what the currently focused date (if any) should be.
class _FocusedDate extends InheritedWidget {
const _FocusedDate({
required super.child,
this.date,
this.scrollDirection,
});
final DateTime? date;
final TraversalDirection? scrollDirection;
@override
bool updateShouldNotify(_FocusedDate oldWidget) {
return !DateUtils.isSameDay(date, oldWidget.date) || scrollDirection != oldWidget.scrollDirection;
}
static _FocusedDate? maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<_FocusedDate>();
}
}
class _DayHeaders extends StatelessWidget {
const _DayHeaders();
/// Builds widgets showing abbreviated days of week. The first widget in the
/// returned list corresponds to the first day of week for the current locale.
///
/// Examples:
///
/// β Sunday is the first day of week in the US (en_US)
/// |
/// S M T W T F S β the returned list contains these widgets
/// _ _ _ _ _ 1 2
/// 3 4 5 6 7 8 9
///
/// β But it's Monday in the UK (en_GB)
/// |
/// M T W T F S S β the returned list contains these widgets
/// _ _ _ _ 1 2 3
/// 4 5 6 7 8 9 10
///
List<Widget> _getDayHeaders(TextStyle headerStyle, MaterialLocalizations localizations) {
final List<Widget> result = <Widget>[];
for (int i = localizations.firstDayOfWeekIndex; result.length < DateTime.daysPerWeek; i = (i + 1) % DateTime.daysPerWeek) {
final String weekday = localizations.narrowWeekdays[i];
result.add(ExcludeSemantics(
child: Center(child: Text(weekday, style: headerStyle)),
));
}
return result;
}
@override
Widget build(BuildContext context) {
final ThemeData themeData = Theme.of(context);
final ColorScheme colorScheme = themeData.colorScheme;
final TextStyle textStyle = themeData.textTheme.titleSmall!.apply(color: colorScheme.onSurface);
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final List<Widget> labels = _getDayHeaders(textStyle, localizations);
// Add leading and trailing boxes for edges of the custom grid layout.
labels.insert(0, const SizedBox.shrink());
labels.add(const SizedBox.shrink());
return ConstrainedBox(
constraints: BoxConstraints(
maxWidth: MediaQuery.orientationOf(context) == Orientation.landscape
? _maxCalendarWidthLandscape
: _maxCalendarWidthPortrait,
maxHeight: _monthItemRowHeight,
),
child: GridView.custom(
shrinkWrap: true,
gridDelegate: _monthItemGridDelegate,
childrenDelegate: SliverChildListDelegate(
labels,
addRepaintBoundaries: false,
),
),
);
}
}
class _MonthItemGridDelegate extends SliverGridDelegate {
const _MonthItemGridDelegate();
@override
SliverGridLayout getLayout(SliverConstraints constraints) {
final double tileWidth = (constraints.crossAxisExtent - 2 * _horizontalPadding) / DateTime.daysPerWeek;
return _MonthSliverGridLayout(
crossAxisCount: DateTime.daysPerWeek + 2,
dayChildWidth: tileWidth,
edgeChildWidth: _horizontalPadding,
reverseCrossAxis: axisDirectionIsReversed(constraints.crossAxisDirection),
);
}
@override
bool shouldRelayout(_MonthItemGridDelegate oldDelegate) => false;
}
const _MonthItemGridDelegate _monthItemGridDelegate = _MonthItemGridDelegate();
class _MonthSliverGridLayout extends SliverGridLayout {
/// Creates a layout that uses equally sized and spaced tiles for each day of
/// the week and an additional edge tile for padding at the start and end of
/// each row.
///
/// This is necessary to facilitate the painting of the range highlight
/// correctly.
const _MonthSliverGridLayout({
required this.crossAxisCount,
required this.dayChildWidth,
required this.edgeChildWidth,
required this.reverseCrossAxis,
}) : assert(crossAxisCount > 0),
assert(dayChildWidth >= 0),
assert(edgeChildWidth >= 0);
/// The number of children in the cross axis.
final int crossAxisCount;
/// The width in logical pixels of the day child widgets.
final double dayChildWidth;
/// The width in logical pixels of the edge child widgets.
final double edgeChildWidth;
/// Whether the children should be placed in the opposite order of increasing
/// coordinates in the cross axis.
///
/// For example, if the cross axis is horizontal, the children are placed from
/// left to right when [reverseCrossAxis] is false and from right to left when
/// [reverseCrossAxis] is true.
///
/// Typically set to the return value of [axisDirectionIsReversed] applied to
/// the [SliverConstraints.crossAxisDirection].
final bool reverseCrossAxis;
/// The number of logical pixels from the leading edge of one row to the
/// leading edge of the next row.
double get _rowHeight {
return _monthItemRowHeight + _monthItemSpaceBetweenRows;
}
/// The height in logical pixels of the children widgets.
double get _childHeight {
return _monthItemRowHeight;
}
@override
int getMinChildIndexForScrollOffset(double scrollOffset) {
return crossAxisCount * (scrollOffset ~/ _rowHeight);
}
@override
int getMaxChildIndexForScrollOffset(double scrollOffset) {
final int mainAxisCount = (scrollOffset / _rowHeight).ceil();
return math.max(0, crossAxisCount * mainAxisCount - 1);
}
double _getCrossAxisOffset(double crossAxisStart, bool isPadding) {
if (reverseCrossAxis) {
return
((crossAxisCount - 2) * dayChildWidth + 2 * edgeChildWidth) -
crossAxisStart -
(isPadding ? edgeChildWidth : dayChildWidth);
}
return crossAxisStart;
}
@override
SliverGridGeometry getGeometryForChildIndex(int index) {
final int adjustedIndex = index % crossAxisCount;
final bool isEdge = adjustedIndex == 0 || adjustedIndex == crossAxisCount - 1;
final double crossAxisStart = math.max(0, (adjustedIndex - 1) * dayChildWidth + edgeChildWidth);
return SliverGridGeometry(
scrollOffset: (index ~/ crossAxisCount) * _rowHeight,
crossAxisOffset: _getCrossAxisOffset(crossAxisStart, isEdge),
mainAxisExtent: _childHeight,
crossAxisExtent: isEdge ? edgeChildWidth : dayChildWidth,
);
}
@override
double computeMaxScrollOffset(int childCount) {
assert(childCount >= 0);
final int mainAxisCount = ((childCount - 1) ~/ crossAxisCount) + 1;
final double mainAxisSpacing = _rowHeight - _childHeight;
return _rowHeight * mainAxisCount - mainAxisSpacing;
}
}
/// Displays the days of a given month and allows choosing a date range.
///
/// The days are arranged in a rectangular grid with one column for each day of
/// the week.
class _MonthItem extends StatefulWidget {
/// Creates a month item.
_MonthItem({
required this.selectedDateStart,
required this.selectedDateEnd,
required this.currentDate,
required this.onChanged,
required this.firstDate,
required this.lastDate,
required this.displayedMonth,
}) : assert(!firstDate.isAfter(lastDate)),
assert(selectedDateStart == null || !selectedDateStart.isBefore(firstDate)),
assert(selectedDateEnd == null || !selectedDateEnd.isBefore(firstDate)),
assert(selectedDateStart == null || !selectedDateStart.isAfter(lastDate)),
assert(selectedDateEnd == null || !selectedDateEnd.isAfter(lastDate)),
assert(selectedDateStart == null || selectedDateEnd == null || !selectedDateStart.isAfter(selectedDateEnd));
/// The currently selected start date.
///
/// This date is highlighted in the picker.
final DateTime? selectedDateStart;
/// The currently selected end date.
///
/// This date is highlighted in the picker.
final DateTime? selectedDateEnd;
/// The current date at the time the picker is displayed.
final DateTime currentDate;
/// Called when the user picks a day.
final ValueChanged<DateTime> onChanged;
/// The earliest date the user is permitted to pick.
final DateTime firstDate;
/// The latest date the user is permitted to pick.
final DateTime lastDate;
/// The month whose days are displayed by this picker.
final DateTime displayedMonth;
@override
_MonthItemState createState() => _MonthItemState();
}
class _MonthItemState extends State<_MonthItem> {
/// List of [FocusNode]s, one for each day of the month.
late List<FocusNode> _dayFocusNodes;
@override
void initState() {
super.initState();
final int daysInMonth = DateUtils.getDaysInMonth(widget.displayedMonth.year, widget.displayedMonth.month);
_dayFocusNodes = List<FocusNode>.generate(
daysInMonth,
(int index) => FocusNode(skipTraversal: true, debugLabel: 'Day ${index + 1}'),
);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Check to see if the focused date is in this month, if so focus it.
final DateTime? focusedDate = _FocusedDate.maybeOf(context)?.date;
if (focusedDate != null && DateUtils.isSameMonth(widget.displayedMonth, focusedDate)) {
_dayFocusNodes[focusedDate.day - 1].requestFocus();
}
}
@override
void dispose() {
for (final FocusNode node in _dayFocusNodes) {
node.dispose();
}
super.dispose();
}
Color _highlightColor(BuildContext context) {
return DatePickerTheme.of(context).rangeSelectionBackgroundColor
?? DatePickerTheme.defaults(context).rangeSelectionBackgroundColor!;
}
void _dayFocusChanged(bool focused) {
if (focused) {
final TraversalDirection? focusDirection = _FocusedDate.maybeOf(context)?.scrollDirection;
if (focusDirection != null) {
ScrollPositionAlignmentPolicy policy = ScrollPositionAlignmentPolicy.explicit;
switch (focusDirection) {
case TraversalDirection.up:
case TraversalDirection.left:
policy = ScrollPositionAlignmentPolicy.keepVisibleAtStart;
case TraversalDirection.right:
case TraversalDirection.down:
policy = ScrollPositionAlignmentPolicy.keepVisibleAtEnd;
}
Scrollable.ensureVisible(primaryFocus!.context!,
duration: _monthScrollDuration,
alignmentPolicy: policy,
);
}
}
}
Widget _buildDayItem(BuildContext context, DateTime dayToBuild, int firstDayOffset, int daysInMonth) {
final int day = dayToBuild.day;
final bool isDisabled = dayToBuild.isAfter(widget.lastDate) || dayToBuild.isBefore(widget.firstDate);
final bool isRangeSelected = widget.selectedDateStart != null && widget.selectedDateEnd != null;
final bool isSelectedDayStart = widget.selectedDateStart != null && dayToBuild.isAtSameMomentAs(widget.selectedDateStart!);
final bool isSelectedDayEnd = widget.selectedDateEnd != null && dayToBuild.isAtSameMomentAs(widget.selectedDateEnd!);
final bool isInRange = isRangeSelected &&
dayToBuild.isAfter(widget.selectedDateStart!) &&
dayToBuild.isBefore(widget.selectedDateEnd!);
final bool isOneDayRange = isRangeSelected && widget.selectedDateStart == widget.selectedDateEnd;
final bool isToday = DateUtils.isSameDay(widget.currentDate, dayToBuild);
return _DayItem(
day: dayToBuild,
focusNode: _dayFocusNodes[day - 1],
onChanged: widget.onChanged,
onFocusChange: _dayFocusChanged,
highlightColor: _highlightColor(context),
isDisabled: isDisabled,
isRangeSelected: isRangeSelected,
isSelectedDayStart: isSelectedDayStart,
isSelectedDayEnd: isSelectedDayEnd,
isInRange: isInRange,
isOneDayRange: isOneDayRange,
isToday: isToday,
);
}
Widget _buildEdgeBox(BuildContext context, bool isHighlighted) {
const Widget empty = LimitedBox(maxWidth: 0.0, maxHeight: 0.0, child: SizedBox.expand());
return isHighlighted ? ColoredBox(color: _highlightColor(context), child: empty) : empty;
}
@override
Widget build(BuildContext context) {
final ThemeData themeData = Theme.of(context);
final TextTheme textTheme = themeData.textTheme;
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final int year = widget.displayedMonth.year;
final int month = widget.displayedMonth.month;
final int daysInMonth = DateUtils.getDaysInMonth(year, month);
final int dayOffset = DateUtils.firstDayOffset(year, month, localizations);
final int weeks = ((daysInMonth + dayOffset) / DateTime.daysPerWeek).ceil();
final double gridHeight = weeks * _monthItemRowHeight + (weeks - 1) * _monthItemSpaceBetweenRows;
final List<Widget> dayItems = <Widget>[];
// 1-based day of month, e.g. 1-31 for January, and 1-29 for February on
// a leap year.
for (int day = 0 - dayOffset + 1; day <= daysInMonth; day += 1) {
if (day < 1) {
dayItems.add(const LimitedBox(maxWidth: 0.0, maxHeight: 0.0, child: SizedBox.expand()));
} else {
final DateTime dayToBuild = DateTime(year, month, day);
final Widget dayItem = _buildDayItem(
context,
dayToBuild,
dayOffset,
daysInMonth,
);
dayItems.add(dayItem);
}
}
// Add the leading/trailing edge containers to each week in order to
// correctly extend the range highlight.
final List<Widget> paddedDayItems = <Widget>[];
for (int i = 0; i < weeks; i++) {
final int start = i * DateTime.daysPerWeek;
final int end = math.min(
start + DateTime.daysPerWeek,
dayItems.length,
);
final List<Widget> weekList = dayItems.sublist(start, end);
final DateTime dateAfterLeadingPadding = DateTime(year, month, start - dayOffset + 1);
// Only color the edge container if it is after the start date and
// on/before the end date.
final bool isLeadingInRange =
!(dayOffset > 0 && i == 0) &&
widget.selectedDateStart != null &&
widget.selectedDateEnd != null &&
dateAfterLeadingPadding.isAfter(widget.selectedDateStart!) &&
!dateAfterLeadingPadding.isAfter(widget.selectedDateEnd!);
weekList.insert(0, _buildEdgeBox(context, isLeadingInRange));
// Only add a trailing edge container if it is for a full week and not a
// partial week.
if (end < dayItems.length || (end == dayItems.length && dayItems.length % DateTime.daysPerWeek == 0)) {
final DateTime dateBeforeTrailingPadding =
DateTime(year, month, end - dayOffset);
// Only color the edge container if it is on/after the start date and
// before the end date.
final bool isTrailingInRange =
widget.selectedDateStart != null &&
widget.selectedDateEnd != null &&
!dateBeforeTrailingPadding.isBefore(widget.selectedDateStart!) &&
dateBeforeTrailingPadding.isBefore(widget.selectedDateEnd!);
weekList.add(_buildEdgeBox(context, isTrailingInRange));
}
paddedDayItems.addAll(weekList);
}
final double maxWidth = MediaQuery.orientationOf(context) == Orientation.landscape
? _maxCalendarWidthLandscape
: _maxCalendarWidthPortrait;
return Column(
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints(maxWidth: maxWidth).tighten(height: _monthItemHeaderHeight),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: ExcludeSemantics(
child: Text(
localizations.formatMonthYear(widget.displayedMonth),
style: textTheme.bodyMedium!.apply(color: themeData.colorScheme.onSurface),
),
),
),
),
),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: maxWidth,
maxHeight: gridHeight,
),
child: GridView.custom(
physics: const NeverScrollableScrollPhysics(),
gridDelegate: _monthItemGridDelegate,
childrenDelegate: SliverChildListDelegate(
paddedDayItems,
addRepaintBoundaries: false,
),
),
),
const SizedBox(height: _monthItemFooterHeight),
],
);
}
}
class _DayItem extends StatefulWidget {
const _DayItem({
required this.day,
required this.focusNode,
required this.onChanged,
required this.onFocusChange,
required this.highlightColor,
required this.isDisabled,
required this.isRangeSelected,
required this.isSelectedDayStart,
required this.isSelectedDayEnd,
required this.isInRange,
required this.isOneDayRange,
required this.isToday,
});
final DateTime day;
final FocusNode focusNode;
final ValueChanged<DateTime> onChanged;
final ValueChanged<bool> onFocusChange;
final Color highlightColor;
final bool isDisabled;
final bool isRangeSelected;
final bool isSelectedDayStart;
final bool isSelectedDayEnd;
final bool isInRange;
final bool isOneDayRange;
final bool isToday;
@override
State<_DayItem> createState() => _DayItemState();
}
class _DayItemState extends State<_DayItem> {
final MaterialStatesController _statesController = MaterialStatesController();
@override
void dispose() {
_statesController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme;
final TextTheme textTheme = theme.textTheme;
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context);
final DatePickerThemeData defaults = DatePickerTheme.defaults(context);
final TextDirection textDirection = Directionality.of(context);
final Color highlightColor = widget.highlightColor;
BoxDecoration? decoration;
TextStyle? itemStyle = textTheme.bodyMedium;
T? effectiveValue<T>(T? Function(DatePickerThemeData? theme) getProperty) {
return getProperty(datePickerTheme) ?? getProperty(defaults);
}
T? resolve<T>(MaterialStateProperty<T>? Function(DatePickerThemeData? theme) getProperty, Set<MaterialState> states) {
return effectiveValue(
(DatePickerThemeData? theme) {
return getProperty(theme)?.resolve(states);
},
);
}
final Set<MaterialState> states = <MaterialState>{
if (widget.isDisabled) MaterialState.disabled,
if (widget.isSelectedDayStart || widget.isSelectedDayEnd) MaterialState.selected,
};
_statesController.value = states;
final Color? dayForegroundColor = resolve<Color?>((DatePickerThemeData? theme) => theme?.dayForegroundColor, states);
final Color? dayBackgroundColor = resolve<Color?>((DatePickerThemeData? theme) => theme?.dayBackgroundColor, states);
final MaterialStateProperty<Color?> dayOverlayColor = MaterialStateProperty.resolveWith<Color?>(
(Set<MaterialState> states) => effectiveValue(
(DatePickerThemeData? theme) => widget.isInRange
? theme?.rangeSelectionOverlayColor?.resolve(states)
: theme?.dayOverlayColor?.resolve(states),
)
);
_HighlightPainter? highlightPainter;
if (widget.isSelectedDayStart || widget.isSelectedDayEnd) {
// The selected start and end dates gets a circle background
// highlight, and a contrasting text color.
itemStyle = textTheme.bodyMedium?.apply(color: dayForegroundColor);
decoration = BoxDecoration(
color: dayBackgroundColor,
shape: BoxShape.circle,
);
if (widget.isRangeSelected && !widget.isOneDayRange) {
final _HighlightPainterStyle style = widget.isSelectedDayStart
? _HighlightPainterStyle.highlightTrailing
: _HighlightPainterStyle.highlightLeading;
highlightPainter = _HighlightPainter(
color: highlightColor,
style: style,
textDirection: textDirection,
);
}
} else if (widget.isInRange) {
// The days within the range get a light background highlight.
highlightPainter = _HighlightPainter(
color: highlightColor,
style: _HighlightPainterStyle.highlightAll,
textDirection: textDirection,
);
} else if (widget.isDisabled) {
itemStyle = textTheme.bodyMedium?.apply(color: colorScheme.onSurface.withOpacity(0.38));
} else if (widget.isToday) {
// The current day gets a different text color and a circle stroke
// border.
itemStyle = textTheme.bodyMedium?.apply(color: colorScheme.primary);
decoration = BoxDecoration(
border: Border.all(color: colorScheme.primary),
shape: BoxShape.circle,
);
}
final String dayText = localizations.formatDecimal(widget.day.day);
// We want the day of month to be spoken first irrespective of the
// locale-specific preferences or TextDirection. This is because
// an accessibility user is more likely to be interested in the
// day of month before the rest of the date, as they are looking
// for the day of month. To do that we prepend day of month to the
// formatted full date.
final String semanticLabelSuffix = widget.isToday ? ', ${localizations.currentDateLabel}' : '';
String semanticLabel = '$dayText, ${localizations.formatFullDate(widget.day)}$semanticLabelSuffix';
if (widget.isSelectedDayStart) {
semanticLabel = localizations.dateRangeStartDateSemanticLabel(semanticLabel);
} else if (widget.isSelectedDayEnd) {
semanticLabel = localizations.dateRangeEndDateSemanticLabel(semanticLabel);
}
Widget dayWidget = Container(
decoration: decoration,
alignment: Alignment.center,
child: Semantics(
label: semanticLabel,
selected: widget.isSelectedDayStart || widget.isSelectedDayEnd,
child: ExcludeSemantics(
child: Text(dayText, style: itemStyle),
),
),
);
if (highlightPainter != null) {
dayWidget = CustomPaint(
painter: highlightPainter,
child: dayWidget,
);
}
if (!widget.isDisabled) {
dayWidget = InkResponse(
focusNode: widget.focusNode,
onTap: () => widget.onChanged(widget.day),
radius: _monthItemRowHeight / 2 + 4,
statesController: _statesController,
overlayColor: dayOverlayColor,
onFocusChange: widget.onFocusChange,
child: dayWidget,
);
}
return dayWidget;
}
}
/// Determines which style to use to paint the highlight.
enum _HighlightPainterStyle {
/// Paints nothing.
none,
/// Paints a rectangle that occupies the leading half of the space.
highlightLeading,
/// Paints a rectangle that occupies the trailing half of the space.
highlightTrailing,
/// Paints a rectangle that occupies all available space.
highlightAll,
}
/// This custom painter will add a background highlight to its child.
///
/// This highlight will be drawn depending on the [style], [color], and
/// [textDirection] supplied. It will either paint a rectangle on the
/// left/right, a full rectangle, or nothing at all. This logic is determined by
/// a combination of the [style] and [textDirection].
class _HighlightPainter extends CustomPainter {
_HighlightPainter({
required this.color,
this.style = _HighlightPainterStyle.none,
this.textDirection,
});
final Color color;
final _HighlightPainterStyle style;
final TextDirection? textDirection;
@override
void paint(Canvas canvas, Size size) {
if (style == _HighlightPainterStyle.none) {
return;
}
final Paint paint = Paint()
..color = color
..style = PaintingStyle.fill;
final bool rtl = switch (textDirection) {
TextDirection.rtl || null => true,
TextDirection.ltr => false,
};
switch (style) {
case _HighlightPainterStyle.highlightLeading when rtl:
case _HighlightPainterStyle.highlightTrailing when !rtl:
canvas.drawRect(Rect.fromLTWH(size.width / 2, 0, size.width / 2, size.height), paint);
case _HighlightPainterStyle.highlightLeading:
case _HighlightPainterStyle.highlightTrailing:
canvas.drawRect(Rect.fromLTWH(0, 0, size.width / 2, size.height), paint);
case _HighlightPainterStyle.highlightAll:
canvas.drawRect(Rect.fromLTWH(0, 0, size.width, size.height), paint);
case _HighlightPainterStyle.none:
break;
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => false;
}
class _InputDateRangePickerDialog extends StatelessWidget {
const _InputDateRangePickerDialog({
required this.selectedStartDate,
required this.selectedEndDate,
required this.currentDate,
required this.picker,
required this.onConfirm,
required this.onCancel,
required this.confirmText,
required this.cancelText,
required this.helpText,
required this.entryModeButton,
});
final DateTime? selectedStartDate;
final DateTime? selectedEndDate;
final DateTime? currentDate;
final Widget picker;
final VoidCallback onConfirm;
final VoidCallback onCancel;
final String? confirmText;
final String? cancelText;
final String? helpText;
final Widget? entryModeButton;
String _formatDateRange(BuildContext context, DateTime? start, DateTime? end, DateTime now) {
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final String startText = _formatRangeStartDate(localizations, start, end);
final String endText = _formatRangeEndDate(localizations, start, end, now);
if (start == null || end == null) {
return localizations.unspecifiedDateRange;
}
return switch (Directionality.of(context)) {
TextDirection.rtl => '$endText β $startText',
TextDirection.ltr => '$startText β $endText',
};
}
@override
Widget build(BuildContext context) {
final bool useMaterial3 = Theme.of(context).useMaterial3;
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final Orientation orientation = MediaQuery.orientationOf(context);
final DatePickerThemeData datePickerTheme = DatePickerTheme.of(context);
final DatePickerThemeData defaults = DatePickerTheme.defaults(context);
// There's no M3 spec for a landscape layout input (not calendar)
// date range picker. To ensure that the date range displayed in the
// input date range picker's header fits in landscape mode, we override
// the M3 default here.
TextStyle? headlineStyle = (orientation == Orientation.portrait)
? datePickerTheme.headerHeadlineStyle ?? defaults.headerHeadlineStyle
: Theme.of(context).textTheme.headlineSmall;
final Color? headerForegroundColor = datePickerTheme.headerForegroundColor ?? defaults.headerForegroundColor;
headlineStyle = headlineStyle?.copyWith(color: headerForegroundColor);
final String dateText = _formatDateRange(context, selectedStartDate, selectedEndDate, currentDate!);
final String semanticDateText = selectedStartDate != null && selectedEndDate != null
? '${localizations.formatMediumDate(selectedStartDate!)} β ${localizations.formatMediumDate(selectedEndDate!)}'
: '';
final Widget header = _DatePickerHeader(
helpText: helpText ?? (
useMaterial3
? localizations.dateRangePickerHelpText
: localizations.dateRangePickerHelpText.toUpperCase()
),
titleText: dateText,
titleSemanticsLabel: semanticDateText,
titleStyle: headlineStyle,
orientation: orientation,
isShort: orientation == Orientation.landscape,
entryModeButton: entryModeButton,
);
final Widget actions = ConstrainedBox(
constraints: const BoxConstraints(minHeight: 52.0),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: OverflowBar(
spacing: 8,
children: <Widget>[
TextButton(
onPressed: onCancel,
child: Text(cancelText ?? (
useMaterial3
? localizations.cancelButtonLabel
: localizations.cancelButtonLabel.toUpperCase()
)),
),
TextButton(
onPressed: onConfirm,
child: Text(confirmText ?? localizations.okButtonLabel),
),
],
),
),
),
);
// 14 is a common font size used to compute the effective text scale.
const double fontSizeToScale = 14.0;
final double textScaleFactor = MediaQuery.textScalerOf(context).clamp(maxScaleFactor: _kMaxTextScaleFactor).scale(fontSizeToScale) / fontSizeToScale;
final Size dialogSize = (useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2) * textScaleFactor;
switch (orientation) {
case Orientation.portrait:
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final Size portraitDialogSize = useMaterial3 ? _inputPortraitDialogSizeM3 : _inputPortraitDialogSizeM2;
// Make sure the portrait dialog can fit the contents comfortably when
// resized from the landscape dialog.
final bool isFullyPortrait = constraints.maxHeight >= math.min(dialogSize.height, portraitDialogSize.height);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
header,
if (isFullyPortrait) ...<Widget>[
Expanded(child: picker),
actions,
],
],
);
}
);
case Orientation.landscape:
return Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
header,
Flexible(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(child: picker),
actions,
],
),
),
],
);
}
}
}
/// Provides a pair of text fields that allow the user to enter the start and
/// end dates that represent a range of dates.
class _InputDateRangePicker extends StatefulWidget {
/// Creates a row with two text fields configured to accept the start and end dates
/// of a date range.
_InputDateRangePicker({
super.key,
DateTime? initialStartDate,
DateTime? initialEndDate,
required DateTime firstDate,
required DateTime lastDate,
required this.onStartDateChanged,
required this.onEndDateChanged,
this.helpText,
this.errorFormatText,
this.errorInvalidText,
this.errorInvalidRangeText,
this.fieldStartHintText,
this.fieldEndHintText,
this.fieldStartLabelText,
this.fieldEndLabelText,
this.autofocus = false,
this.autovalidate = false,
this.keyboardType = TextInputType.datetime,
}) : initialStartDate = initialStartDate == null ? null : DateUtils.dateOnly(initialStartDate),
initialEndDate = initialEndDate == null ? null : DateUtils.dateOnly(initialEndDate),
firstDate = DateUtils.dateOnly(firstDate),
lastDate = DateUtils.dateOnly(lastDate);
/// The [DateTime] that represents the start of the initial date range selection.
final DateTime? initialStartDate;
/// The [DateTime] that represents the end of the initial date range selection.
final DateTime? initialEndDate;
/// The earliest allowable [DateTime] that the user can select.
final DateTime firstDate;
/// The latest allowable [DateTime] that the user can select.
final DateTime lastDate;
/// Called when the user changes the start date of the selected range.
final ValueChanged<DateTime?>? onStartDateChanged;
/// Called when the user changes the end date of the selected range.
final ValueChanged<DateTime?>? onEndDateChanged;
/// The text that is displayed at the top of the header.
///
/// This is used to indicate to the user what they are selecting a date for.
final String? helpText;
/// Error text used to indicate the text in a field is not a valid date.
final String? errorFormatText;
/// Error text used to indicate the date in a field is not in the valid range
/// of [firstDate] - [lastDate].
final String? errorInvalidText;
/// Error text used to indicate the dates given don't form a valid date
/// range (i.e. the start date is after the end date).
final String? errorInvalidRangeText;
/// Hint text shown when the start date field is empty.
final String? fieldStartHintText;
/// Hint text shown when the end date field is empty.
final String? fieldEndHintText;
/// Label used for the start date field.
final String? fieldStartLabelText;
/// Label used for the end date field.
final String? fieldEndLabelText;
/// {@macro flutter.widgets.editableText.autofocus}
final bool autofocus;
/// If true, the date fields will validate and update their error text
/// immediately after every change. Otherwise, you must call
/// [_InputDateRangePickerState.validate] to validate.
final bool autovalidate;
/// {@macro flutter.material.datePickerDialog}
final TextInputType keyboardType;
@override
_InputDateRangePickerState createState() => _InputDateRangePickerState();
}
/// The current state of an [_InputDateRangePicker]. Can be used to
/// [validate] the date field entries.
class _InputDateRangePickerState extends State<_InputDateRangePicker> {
late String _startInputText;
late String _endInputText;
DateTime? _startDate;
DateTime? _endDate;
late TextEditingController _startController;
late TextEditingController _endController;
String? _startErrorText;
String? _endErrorText;
bool _autoSelected = false;
@override
void initState() {
super.initState();
_startDate = widget.initialStartDate;
_startController = TextEditingController();
_endDate = widget.initialEndDate;
_endController = TextEditingController();
}
@override
void dispose() {
_startController.dispose();
_endController.dispose();
super.dispose();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
if (_startDate != null) {
_startInputText = localizations.formatCompactDate(_startDate!);
final bool selectText = widget.autofocus && !_autoSelected;
_updateController(_startController, _startInputText, selectText);
_autoSelected = selectText;
}
if (_endDate != null) {
_endInputText = localizations.formatCompactDate(_endDate!);
_updateController(_endController, _endInputText, false);
}
}
/// Validates that the text in the start and end fields represent a valid
/// date range.
///
/// Will return true if the range is valid. If not, it will
/// return false and display an appropriate error message under one of the
/// text fields.
bool validate() {
String? startError = _validateDate(_startDate);
final String? endError = _validateDate(_endDate);
if (startError == null && endError == null) {
if (_startDate!.isAfter(_endDate!)) {
startError = widget.errorInvalidRangeText ?? MaterialLocalizations.of(context).invalidDateRangeLabel;
}
}
setState(() {
_startErrorText = startError;
_endErrorText = endError;
});
return startError == null && endError == null;
}
DateTime? _parseDate(String? text) {
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
return localizations.parseCompactDate(text);
}
String? _validateDate(DateTime? date) {
if (date == null) {
return widget.errorFormatText ?? MaterialLocalizations.of(context).invalidDateFormatLabel;
} else if (date.isBefore(widget.firstDate) || date.isAfter(widget.lastDate)) {
return widget.errorInvalidText ?? MaterialLocalizations.of(context).dateOutOfRangeLabel;
}
return null;
}
void _updateController(TextEditingController controller, String text, bool selectText) {
TextEditingValue textEditingValue = controller.value.copyWith(text: text);
if (selectText) {
textEditingValue = textEditingValue.copyWith(selection: TextSelection(
baseOffset: 0,
extentOffset: text.length,
));
}
controller.value = textEditingValue;
}
void _handleStartChanged(String text) {
setState(() {
_startInputText = text;
_startDate = _parseDate(text);
widget.onStartDateChanged?.call(_startDate);
});
if (widget.autovalidate) {
validate();
}
}
void _handleEndChanged(String text) {
setState(() {
_endInputText = text;
_endDate = _parseDate(text);
widget.onEndDateChanged?.call(_endDate);
});
if (widget.autovalidate) {
validate();
}
}
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final bool useMaterial3 = theme.useMaterial3;
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final InputDecorationTheme inputTheme = theme.inputDecorationTheme;
final InputBorder inputBorder = inputTheme.border
?? (useMaterial3 ? const OutlineInputBorder() : const UnderlineInputBorder());
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: TextField(
controller: _startController,
decoration: InputDecoration(
border: inputBorder,
filled: inputTheme.filled,
hintText: widget.fieldStartHintText ?? localizations.dateHelpText,
labelText: widget.fieldStartLabelText ?? localizations.dateRangeStartLabel,
errorText: _startErrorText,
),
keyboardType: widget.keyboardType,
onChanged: _handleStartChanged,
autofocus: widget.autofocus,
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _endController,
decoration: InputDecoration(
border: inputBorder,
filled: inputTheme.filled,
hintText: widget.fieldEndHintText ?? localizations.dateHelpText,
labelText: widget.fieldEndLabelText ?? localizations.dateRangeEndLabel,
errorText: _endErrorText,
),
keyboardType: widget.keyboardType,
onChanged: _handleEndChanged,
),
),
],
);
}
}
| flutter/packages/flutter/lib/src/material/date_picker.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/date_picker.dart",
"repo_id": "flutter",
"token_count": 43705
} | 233 |
// Copyright 2014 The Flutter Authors. 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 lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'button_style_button.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'elevated_button_theme.dart';
import 'ink_ripple.dart';
import 'ink_well.dart';
import 'material_state.dart';
import 'theme.dart';
import 'theme_data.dart';
/// A Material Design "elevated button".
///
/// Use elevated buttons to add dimension to otherwise mostly flat
/// layouts, e.g. in long busy lists of content, or in wide
/// spaces. Avoid using elevated buttons on already-elevated content
/// such as dialogs or cards.
///
/// An elevated button is a label [child] displayed on a [Material]
/// widget whose [Material.elevation] increases when the button is
/// pressed. The label's [Text] and [Icon] widgets are displayed in
/// [style]'s [ButtonStyle.foregroundColor] and the button's filled
/// background is the [ButtonStyle.backgroundColor].
///
/// The elevated button's default style is defined by
/// [defaultStyleOf]. The style of this elevated button can be
/// overridden with its [style] parameter. The style of all elevated
/// buttons in a subtree can be overridden with the
/// [ElevatedButtonTheme], and the style of all of the elevated
/// buttons in an app can be overridden with the [Theme]'s
/// [ThemeData.elevatedButtonTheme] property.
///
/// The static [styleFrom] method is a convenient way to create a
/// elevated button [ButtonStyle] from simple values.
///
/// If [onPressed] and [onLongPress] callbacks are null, then the
/// button will be disabled.
///
/// {@tool dartpad}
/// This sample produces an enabled and a disabled ElevatedButton.
///
/// ** See code in examples/api/lib/material/elevated_button/elevated_button.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [FilledButton], a filled button that doesn't elevate when pressed.
/// * [FilledButton.tonal], a filled button variant that uses a secondary fill color.
/// * [OutlinedButton], a button with an outlined border and no fill color.
/// * [TextButton], a button with no outline or fill color.
/// * <https://material.io/design/components/buttons.html>
/// * <https://m3.material.io/components/buttons>
class ElevatedButton extends ButtonStyleButton {
/// Create an ElevatedButton.
const ElevatedButton({
super.key,
required super.onPressed,
super.onLongPress,
super.onHover,
super.onFocusChange,
super.style,
super.focusNode,
super.autofocus = false,
super.clipBehavior,
super.statesController,
required super.child,
super.iconAlignment,
});
/// Create an elevated button from a pair of widgets that serve as the button's
/// [icon] and [label].
///
/// The icon and label are arranged in a row and padded by 12 logical pixels
/// at the start, and 16 at the end, with an 8 pixel gap in between.
///
/// If [icon] is null, will create an [ElevatedButton] instead.
///
/// {@macro flutter.material.ButtonStyleButton.iconAlignment}
///
factory ElevatedButton.icon({
Key? key,
required VoidCallback? onPressed,
VoidCallback? onLongPress,
ValueChanged<bool>? onHover,
ValueChanged<bool>? onFocusChange,
ButtonStyle? style,
FocusNode? focusNode,
bool? autofocus,
Clip? clipBehavior,
MaterialStatesController? statesController,
Widget? icon,
required Widget label,
IconAlignment iconAlignment = IconAlignment.start,
}) {
if (icon == null) {
return ElevatedButton(
key: key,
onPressed: onPressed,
onLongPress: onLongPress,
onHover: onHover,
onFocusChange: onFocusChange,
style: style,
focusNode: focusNode,
autofocus: autofocus ?? false,
clipBehavior: clipBehavior ?? Clip.none,
statesController: statesController,
child: label,
);
}
return _ElevatedButtonWithIcon(
key: key,
onPressed: onPressed,
onLongPress: onLongPress,
onHover: onHover,
onFocusChange: onFocusChange,
style: style,
focusNode: focusNode,
autofocus: autofocus ?? false,
clipBehavior: clipBehavior ?? Clip.none,
statesController: statesController,
icon: icon,
label: label,
iconAlignment: iconAlignment,
);
}
/// A static convenience method that constructs an elevated button
/// [ButtonStyle] given simple values.
///
/// The [foregroundColor] and [disabledForegroundColor] colors are used
/// to create a [MaterialStateProperty] [ButtonStyle.foregroundColor], and
/// a derived [ButtonStyle.overlayColor] if [overlayColor] isn't specified.
///
/// If [overlayColor] is specified and its value is [Colors.transparent]
/// then the pressed/focused/hovered highlights are effectively defeated.
/// Otherwise a [MaterialStateProperty] with the same opacities as the
/// default is created.
///
/// The [backgroundColor] and [disabledBackgroundColor] colors are
/// used to create a [MaterialStateProperty] [ButtonStyle.backgroundColor].
///
/// Similarly, the [enabledMouseCursor] and [disabledMouseCursor]
/// parameters are used to construct [ButtonStyle.mouseCursor] and
/// [iconColor], [disabledIconColor] are used to construct
/// [ButtonStyle.iconColor].
///
/// The button's elevations are defined relative to the [elevation]
/// parameter. The disabled elevation is the same as the parameter
/// value, [elevation] + 2 is used when the button is hovered
/// or focused, and elevation + 6 is used when the button is pressed.
///
/// All of the other parameters are either used directly or used to
/// create a [MaterialStateProperty] with a single value for all
/// states.
///
/// All parameters default to null, by default this method returns
/// a [ButtonStyle] that doesn't override anything.
///
/// For example, to override the default text and icon colors for a
/// [ElevatedButton], as well as its overlay color, with all of the
/// standard opacity adjustments for the pressed, focused, and
/// hovered states, one could write:
///
/// ```dart
/// ElevatedButton(
/// style: ElevatedButton.styleFrom(foregroundColor: Colors.green),
/// onPressed: () {
/// // ...
/// },
/// child: const Text('Jump'),
/// ),
/// ```
///
/// And to change the fill color:
///
/// ```dart
/// ElevatedButton(
/// style: ElevatedButton.styleFrom(backgroundColor: Colors.green),
/// onPressed: () {
/// // ...
/// },
/// child: const Text('Meow'),
/// ),
/// ```
///
static ButtonStyle styleFrom({
Color? foregroundColor,
Color? backgroundColor,
Color? disabledForegroundColor,
Color? disabledBackgroundColor,
Color? shadowColor,
Color? surfaceTintColor,
Color? iconColor,
Color? disabledIconColor,
Color? overlayColor,
double? elevation,
TextStyle? textStyle,
EdgeInsetsGeometry? padding,
Size? minimumSize,
Size? fixedSize,
Size? maximumSize,
BorderSide? side,
OutlinedBorder? shape,
MouseCursor? enabledMouseCursor,
MouseCursor? disabledMouseCursor,
VisualDensity? visualDensity,
MaterialTapTargetSize? tapTargetSize,
Duration? animationDuration,
bool? enableFeedback,
AlignmentGeometry? alignment,
InteractiveInkFeatureFactory? splashFactory,
ButtonLayerBuilder? backgroundBuilder,
ButtonLayerBuilder? foregroundBuilder,
}) {
final MaterialStateProperty<Color?>? foregroundColorProp = switch ((foregroundColor, disabledForegroundColor)) {
(null, null) => null,
(_, _) => _ElevatedButtonDefaultColor(foregroundColor, disabledForegroundColor),
};
final MaterialStateProperty<Color?>? backgroundColorProp = switch ((backgroundColor, disabledBackgroundColor)) {
(null, null) => null,
(_, _) => _ElevatedButtonDefaultColor(backgroundColor, disabledBackgroundColor),
};
final MaterialStateProperty<Color?>? iconColorProp = switch ((iconColor, disabledIconColor)) {
(null, null) => null,
(_, _) => _ElevatedButtonDefaultColor(iconColor, disabledIconColor),
};
final MaterialStateProperty<Color?>? overlayColorProp = switch ((foregroundColor, overlayColor)) {
(null, null) => null,
(_, final Color overlayColor) when overlayColor.value == 0 => const MaterialStatePropertyAll<Color?>(Colors.transparent),
(_, _) => _ElevatedButtonDefaultOverlay((overlayColor ?? foregroundColor)!),
};
final MaterialStateProperty<double>? elevationValue = switch (elevation) {
null => null,
_ => _ElevatedButtonDefaultElevation(elevation),
};
final MaterialStateProperty<MouseCursor?> mouseCursor = _ElevatedButtonDefaultMouseCursor(enabledMouseCursor, disabledMouseCursor);
return ButtonStyle(
textStyle: MaterialStatePropertyAll<TextStyle?>(textStyle),
backgroundColor: backgroundColorProp,
foregroundColor: foregroundColorProp,
overlayColor: overlayColorProp,
shadowColor: ButtonStyleButton.allOrNull<Color>(shadowColor),
surfaceTintColor: ButtonStyleButton.allOrNull<Color>(surfaceTintColor),
iconColor: iconColorProp,
elevation: elevationValue,
padding: ButtonStyleButton.allOrNull<EdgeInsetsGeometry>(padding),
minimumSize: ButtonStyleButton.allOrNull<Size>(minimumSize),
fixedSize: ButtonStyleButton.allOrNull<Size>(fixedSize),
maximumSize: ButtonStyleButton.allOrNull<Size>(maximumSize),
side: ButtonStyleButton.allOrNull<BorderSide>(side),
shape: ButtonStyleButton.allOrNull<OutlinedBorder>(shape),
mouseCursor: mouseCursor,
visualDensity: visualDensity,
tapTargetSize: tapTargetSize,
animationDuration: animationDuration,
enableFeedback: enableFeedback,
alignment: alignment,
splashFactory: splashFactory,
backgroundBuilder: backgroundBuilder,
foregroundBuilder: foregroundBuilder,
);
}
/// Defines the button's default appearance.
///
/// The button [child]'s [Text] and [Icon] widgets are rendered with
/// the [ButtonStyle]'s foreground color. The button's [InkWell] adds
/// the style's overlay color when the button is focused, hovered
/// or pressed. The button's background color becomes its [Material]
/// color.
///
/// All of the ButtonStyle's defaults appear below. In this list
/// "Theme.foo" is shorthand for `Theme.of(context).foo`. Color
/// scheme values like "onSurface(0.38)" are shorthand for
/// `onSurface.withOpacity(0.38)`. [MaterialStateProperty] valued
/// properties that are not followed by a sublist have the same
/// value for all states, otherwise the values are as specified for
/// each state, and "others" means all other states.
///
/// {@template flutter.material.elevated_button.default_font_size}
/// The "default font size" below refers to the font size specified in the
/// [defaultStyleOf] method (or 14.0 if unspecified), scaled by the
/// `MediaQuery.textScalerOf(context).scale` method. The names of the
/// EdgeInsets constructors and `EdgeInsetsGeometry.lerp` have been abbreviated
/// for readability.
/// {@endtemplate}
///
/// The color of the [ButtonStyle.textStyle] is not used, the
/// [ButtonStyle.foregroundColor] color is used instead.
///
/// ## Material 2 defaults
///
/// * `textStyle` - Theme.textTheme.button
/// * `backgroundColor`
/// * disabled - Theme.colorScheme.onSurface(0.12)
/// * others - Theme.colorScheme.primary
/// * `foregroundColor`
/// * disabled - Theme.colorScheme.onSurface(0.38)
/// * others - Theme.colorScheme.onPrimary
/// * `overlayColor`
/// * hovered - Theme.colorScheme.onPrimary(0.08)
/// * focused or pressed - Theme.colorScheme.onPrimary(0.12)
/// * `shadowColor` - Theme.shadowColor
/// * `elevation`
/// * disabled - 0
/// * default - 2
/// * hovered or focused - 4
/// * pressed - 8
/// * `padding`
/// * `default font size <= 14` - horizontal(16)
/// * `14 < default font size <= 28` - lerp(horizontal(16), horizontal(8))
/// * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4))
/// * `36 < default font size` - horizontal(4)
/// * `minimumSize` - Size(64, 36)
/// * `fixedSize` - null
/// * `maximumSize` - Size.infinite
/// * `side` - null
/// * `shape` - RoundedRectangleBorder(borderRadius: BorderRadius.circular(4))
/// * `mouseCursor`
/// * disabled - SystemMouseCursors.basic
/// * others - SystemMouseCursors.click
/// * `visualDensity` - theme.visualDensity
/// * `tapTargetSize` - theme.materialTapTargetSize
/// * `animationDuration` - kThemeChangeDuration
/// * `enableFeedback` - true
/// * `alignment` - Alignment.center
/// * `splashFactory` - InkRipple.splashFactory
///
/// The default padding values for the [ElevatedButton.icon] factory are slightly different:
///
/// * `padding`
/// * `default font size <= 14` - start(12) end(16)
/// * `14 < default font size <= 28` - lerp(start(12) end(16), horizontal(8))
/// * `28 < default font size <= 36` - lerp(horizontal(8), horizontal(4))
/// * `36 < default font size` - horizontal(4)
///
/// The default value for `side`, which defines the appearance of the button's
/// outline, is null. That means that the outline is defined by the button
/// shape's [OutlinedBorder.side]. Typically the default value of an
/// [OutlinedBorder]'s side is [BorderSide.none], so an outline is not drawn.
///
/// ## Material 3 defaults
///
/// If [ThemeData.useMaterial3] is set to true the following defaults will
/// be used:
///
/// * `textStyle` - Theme.textTheme.labelLarge
/// * `backgroundColor`
/// * disabled - Theme.colorScheme.onSurface(0.12)
/// * others - Theme.colorScheme.surfaceContainerLow
/// * `foregroundColor`
/// * disabled - Theme.colorScheme.onSurface(0.38)
/// * others - Theme.colorScheme.primary
/// * `overlayColor`
/// * hovered - Theme.colorScheme.primary(0.08)
/// * focused or pressed - Theme.colorScheme.primary(0.1)
/// * `shadowColor` - Theme.colorScheme.shadow
/// * `surfaceTintColor` - Colors.transparent
/// * `elevation`
/// * disabled - 0
/// * default - 1
/// * hovered - 3
/// * focused or pressed - 1
/// * `padding`
/// * `default font size <= 14` - horizontal(24)
/// * `14 < default font size <= 28` - lerp(horizontal(24), horizontal(12))
/// * `28 < default font size <= 36` - lerp(horizontal(12), horizontal(6))
/// * `36 < default font size` - horizontal(6)
/// * `minimumSize` - Size(64, 40)
/// * `fixedSize` - null
/// * `maximumSize` - Size.infinite
/// * `side` - null
/// * `shape` - StadiumBorder()
/// * `mouseCursor`
/// * disabled - SystemMouseCursors.basic
/// * others - SystemMouseCursors.click
/// * `visualDensity` - Theme.visualDensity
/// * `tapTargetSize` - Theme.materialTapTargetSize
/// * `animationDuration` - kThemeChangeDuration
/// * `enableFeedback` - true
/// * `alignment` - Alignment.center
/// * `splashFactory` - Theme.splashFactory
///
/// For the [ElevatedButton.icon] factory, the start (generally the left) value of
/// [padding] is reduced from 24 to 16.
@override
ButtonStyle defaultStyleOf(BuildContext context) {
final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme;
return Theme.of(context).useMaterial3
? _ElevatedButtonDefaultsM3(context)
: styleFrom(
backgroundColor: colorScheme.primary,
foregroundColor: colorScheme.onPrimary,
disabledBackgroundColor: colorScheme.onSurface.withOpacity(0.12),
disabledForegroundColor: colorScheme.onSurface.withOpacity(0.38),
shadowColor: theme.shadowColor,
elevation: 2,
textStyle: theme.textTheme.labelLarge,
padding: _scaledPadding(context),
minimumSize: const Size(64, 36),
maximumSize: Size.infinite,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4))),
enabledMouseCursor: SystemMouseCursors.click,
disabledMouseCursor: SystemMouseCursors.basic,
visualDensity: theme.visualDensity,
tapTargetSize: theme.materialTapTargetSize,
animationDuration: kThemeChangeDuration,
enableFeedback: true,
alignment: Alignment.center,
splashFactory: InkRipple.splashFactory,
);
}
/// Returns the [ElevatedButtonThemeData.style] of the closest
/// [ElevatedButtonTheme] ancestor.
@override
ButtonStyle? themeStyleOf(BuildContext context) {
return ElevatedButtonTheme.of(context).style;
}
}
EdgeInsetsGeometry _scaledPadding(BuildContext context) {
final ThemeData theme = Theme.of(context);
final double padding1x = theme.useMaterial3 ? 24.0 : 16.0;
final double defaultFontSize = theme.textTheme.labelLarge?.fontSize ?? 14.0;
final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0;
return ButtonStyleButton.scaledPadding(
EdgeInsets.symmetric(horizontal: padding1x),
EdgeInsets.symmetric(horizontal: padding1x / 2),
EdgeInsets.symmetric(horizontal: padding1x / 2 / 2),
effectiveTextScale,
);
}
@immutable
class _ElevatedButtonDefaultColor extends MaterialStateProperty<Color?> with Diagnosticable {
_ElevatedButtonDefaultColor(this.color, this.disabled);
final Color? color;
final Color? disabled;
@override
Color? resolve(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return disabled;
}
return color;
}
}
@immutable
class _ElevatedButtonDefaultOverlay extends MaterialStateProperty<Color?> with Diagnosticable {
_ElevatedButtonDefaultOverlay(this.overlay);
final Color overlay;
@override
Color? resolve(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return overlay.withOpacity(0.1);
}
if (states.contains(MaterialState.hovered)) {
return overlay.withOpacity(0.08);
}
if (states.contains(MaterialState.focused)) {
return overlay.withOpacity(0.1);
}
return null;
}
}
@immutable
class _ElevatedButtonDefaultElevation extends MaterialStateProperty<double> with Diagnosticable {
_ElevatedButtonDefaultElevation(this.elevation);
final double elevation;
@override
double resolve(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return 0;
}
if (states.contains(MaterialState.pressed)) {
return elevation + 6;
}
if (states.contains(MaterialState.hovered)) {
return elevation + 2;
}
if (states.contains(MaterialState.focused)) {
return elevation + 2;
}
return elevation;
}
}
@immutable
class _ElevatedButtonDefaultMouseCursor extends MaterialStateProperty<MouseCursor?> with Diagnosticable {
_ElevatedButtonDefaultMouseCursor(this.enabledCursor, this.disabledCursor);
final MouseCursor? enabledCursor;
final MouseCursor? disabledCursor;
@override
MouseCursor? resolve(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return disabledCursor;
}
return enabledCursor;
}
}
class _ElevatedButtonWithIcon extends ElevatedButton {
_ElevatedButtonWithIcon({
super.key,
required super.onPressed,
super.onLongPress,
super.onHover,
super.onFocusChange,
super.style,
super.focusNode,
bool? autofocus,
super.clipBehavior,
super.statesController,
required Widget icon,
required Widget label,
super.iconAlignment,
}) : super(
autofocus: autofocus ?? false,
child: _ElevatedButtonWithIconChild(
icon: icon,
label: label,
buttonStyle: style,
iconAlignment: iconAlignment,
),
);
@override
ButtonStyle defaultStyleOf(BuildContext context) {
final bool useMaterial3 = Theme.of(context).useMaterial3;
final ButtonStyle buttonStyle = super.defaultStyleOf(context);
final double defaultFontSize = buttonStyle.textStyle?.resolve(const <MaterialState>{})?.fontSize ?? 14.0;
final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0;
final EdgeInsetsGeometry scaledPadding = useMaterial3
? ButtonStyleButton.scaledPadding(
const EdgeInsetsDirectional.fromSTEB(16, 0, 24, 0),
const EdgeInsetsDirectional.fromSTEB(8, 0, 12, 0),
const EdgeInsetsDirectional.fromSTEB(4, 0, 6, 0),
effectiveTextScale,
) : ButtonStyleButton.scaledPadding(
const EdgeInsetsDirectional.fromSTEB(12, 0, 16, 0),
const EdgeInsets.symmetric(horizontal: 8),
const EdgeInsetsDirectional.fromSTEB(8, 0, 4, 0),
effectiveTextScale,
);
return buttonStyle.copyWith(
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(scaledPadding),
);
}
}
class _ElevatedButtonWithIconChild extends StatelessWidget {
const _ElevatedButtonWithIconChild({
required this.label,
required this.icon,
required this.buttonStyle,
required this.iconAlignment,
});
final Widget label;
final Widget icon;
final ButtonStyle? buttonStyle;
final IconAlignment iconAlignment;
@override
Widget build(BuildContext context) {
final double defaultFontSize = buttonStyle?.textStyle?.resolve(const <MaterialState>{})?.fontSize ?? 14.0;
final double scale = clampDouble(MediaQuery.textScalerOf(context).scale(defaultFontSize) / 14.0, 1.0, 2.0) - 1.0;
final double gap = lerpDouble(8, 4, scale)!;
return Row(
mainAxisSize: MainAxisSize.min,
children: iconAlignment == IconAlignment.start
? <Widget>[icon, SizedBox(width: gap), Flexible(child: label)]
: <Widget>[Flexible(child: label), SizedBox(width: gap), icon],
);
}
}
// BEGIN GENERATED TOKEN PROPERTIES - ElevatedButton
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
class _ElevatedButtonDefaultsM3 extends ButtonStyle {
_ElevatedButtonDefaultsM3(this.context)
: super(
animationDuration: kThemeChangeDuration,
enableFeedback: true,
alignment: Alignment.center,
);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
MaterialStateProperty<TextStyle?> get textStyle =>
MaterialStatePropertyAll<TextStyle?>(Theme.of(context).textTheme.labelLarge);
@override
MaterialStateProperty<Color?>? get backgroundColor =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return _colors.onSurface.withOpacity(0.12);
}
return _colors.surfaceContainerLow;
});
@override
MaterialStateProperty<Color?>? get foregroundColor =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return _colors.onSurface.withOpacity(0.38);
}
return _colors.primary;
});
@override
MaterialStateProperty<Color?>? get overlayColor =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return _colors.primary.withOpacity(0.1);
}
if (states.contains(MaterialState.hovered)) {
return _colors.primary.withOpacity(0.08);
}
if (states.contains(MaterialState.focused)) {
return _colors.primary.withOpacity(0.1);
}
return null;
});
@override
MaterialStateProperty<Color>? get shadowColor =>
MaterialStatePropertyAll<Color>(_colors.shadow);
@override
MaterialStateProperty<Color>? get surfaceTintColor =>
const MaterialStatePropertyAll<Color>(Colors.transparent);
@override
MaterialStateProperty<double>? get elevation =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return 0.0;
}
if (states.contains(MaterialState.pressed)) {
return 1.0;
}
if (states.contains(MaterialState.hovered)) {
return 3.0;
}
if (states.contains(MaterialState.focused)) {
return 1.0;
}
return 1.0;
});
@override
MaterialStateProperty<EdgeInsetsGeometry>? get padding =>
MaterialStatePropertyAll<EdgeInsetsGeometry>(_scaledPadding(context));
@override
MaterialStateProperty<Size>? get minimumSize =>
const MaterialStatePropertyAll<Size>(Size(64.0, 40.0));
// No default fixedSize
@override
MaterialStateProperty<Size>? get maximumSize =>
const MaterialStatePropertyAll<Size>(Size.infinite);
// No default side
@override
MaterialStateProperty<OutlinedBorder>? get shape =>
const MaterialStatePropertyAll<OutlinedBorder>(StadiumBorder());
@override
MaterialStateProperty<MouseCursor?>? get mouseCursor =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return SystemMouseCursors.basic;
}
return SystemMouseCursors.click;
});
@override
VisualDensity? get visualDensity => Theme.of(context).visualDensity;
@override
MaterialTapTargetSize? get tapTargetSize => Theme.of(context).materialTapTargetSize;
@override
InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory;
}
// END GENERATED TOKEN PROPERTIES - ElevatedButton
| flutter/packages/flutter/lib/src/material/elevated_button.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/elevated_button.dart",
"repo_id": "flutter",
"token_count": 8794
} | 234 |
// Copyright 2014 The Flutter Authors. 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 'colors.dart';
import 'theme.dart';
/// A header used in a Material Design [GridTile].
///
/// Typically used to add a one or two line header or footer on a [GridTile].
///
/// For a one-line header, include a [title] widget. To add a second line, also
/// include a [subtitle] widget. Use [leading] or [trailing] to add an icon.
///
/// See also:
///
/// * [GridTile]
/// * <https://material.io/design/components/image-lists.html#anatomy>
class GridTileBar extends StatelessWidget {
/// Creates a grid tile bar.
///
/// Typically used to with [GridTile].
const GridTileBar({
super.key,
this.backgroundColor,
this.leading,
this.title,
this.subtitle,
this.trailing,
});
/// The color to paint behind the child widgets.
///
/// Defaults to transparent.
final Color? backgroundColor;
/// A widget to display before the title.
///
/// Typically an [Icon] or an [IconButton] widget.
final Widget? leading;
/// The primary content of the list item.
///
/// Typically a [Text] widget.
final Widget? title;
/// Additional content displayed below the title.
///
/// Typically a [Text] widget.
final Widget? subtitle;
/// A widget to display after the title.
///
/// Typically an [Icon] or an [IconButton] widget.
final Widget? trailing;
@override
Widget build(BuildContext context) {
BoxDecoration? decoration;
if (backgroundColor != null) {
decoration = BoxDecoration(color: backgroundColor);
}
final EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(
start: leading != null ? 8.0 : 16.0,
end: trailing != null ? 8.0 : 16.0,
);
final ThemeData darkTheme = ThemeData.dark();
return Container(
padding: padding,
decoration: decoration,
height: (title != null && subtitle != null) ? 68.0 : 48.0,
child: Theme(
data: darkTheme,
child: IconTheme.merge(
data: const IconThemeData(color: Colors.white),
child: Row(
children: <Widget>[
if (leading != null)
Padding(padding: const EdgeInsetsDirectional.only(end: 8.0), child: leading),
if (title != null && subtitle != null)
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
DefaultTextStyle(
style: darkTheme.textTheme.titleMedium!,
softWrap: false,
overflow: TextOverflow.ellipsis,
child: title!,
),
DefaultTextStyle(
style: darkTheme.textTheme.bodySmall!,
softWrap: false,
overflow: TextOverflow.ellipsis,
child: subtitle!,
),
],
),
)
else if (title != null || subtitle != null)
Expanded(
child: DefaultTextStyle(
style: darkTheme.textTheme.titleMedium!,
softWrap: false,
overflow: TextOverflow.ellipsis,
child: title ?? subtitle!,
),
),
if (trailing != null)
Padding(padding: const EdgeInsetsDirectional.only(start: 8.0), child: trailing),
],
),
),
),
);
}
}
| flutter/packages/flutter/lib/src/material/grid_tile_bar.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/grid_tile_bar.dart",
"repo_id": "flutter",
"token_count": 1713
} | 235 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
/// A [Magnifier] positioned by rules dictated by the native Android magnifier.
///
/// The positioning rules are based on [magnifierInfo], as follows:
///
/// - The loupe tracks the gesture's _x_ coordinate, clamping to the beginning
/// and end of the currently editing line.
///
/// - The focal point never contains anything out of the bounds of the text
/// field or other widget being magnified (the [MagnifierInfo.fieldBounds]).
///
/// - The focal point always remains aligned with the _y_ coordinate of the touch.
///
/// - The loupe always remains on the screen.
///
/// - When the line targeted by the touch's _y_ coordinate changes, the position
/// is animated over [jumpBetweenLinesAnimationDuration].
///
/// This behavior was based on the Android 12 source code, where possible, and
/// on eyeballing a Pixel 6 running Android 12 otherwise.
class TextMagnifier extends StatefulWidget {
/// Creates a [TextMagnifier].
///
/// The [magnifierInfo] must be provided, and must be updated with new values
/// as the user's touch changes.
const TextMagnifier({
super.key,
required this.magnifierInfo,
});
/// A [TextMagnifierConfiguration] that returns a [CupertinoTextMagnifier] on
/// iOS, [TextMagnifier] on Android, and null on all other platforms, and
/// shows the editing handles only on iOS.
static TextMagnifierConfiguration adaptiveMagnifierConfiguration = TextMagnifierConfiguration(
shouldDisplayHandlesInMagnifier: defaultTargetPlatform == TargetPlatform.iOS,
magnifierBuilder: (
BuildContext context,
MagnifierController controller,
ValueNotifier<MagnifierInfo> magnifierInfo,
) {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
return CupertinoTextMagnifier(
controller: controller,
magnifierInfo: magnifierInfo,
);
case TargetPlatform.android:
return TextMagnifier(
magnifierInfo: magnifierInfo,
);
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
return null;
}
}
);
/// The duration that the position is animated if [TextMagnifier] just switched
/// between lines.
static const Duration jumpBetweenLinesAnimationDuration = Duration(milliseconds: 70);
/// The current status of the user's touch.
///
/// As the value of the [magnifierInfo] changes, the position of the loupe is
/// adjusted automatically, according to the rules described in the
/// [TextMagnifier] class description.
final ValueNotifier<MagnifierInfo> magnifierInfo;
@override
State<TextMagnifier> createState() => _TextMagnifierState();
}
class _TextMagnifierState extends State<TextMagnifier> {
// Should _only_ be null on construction. This is because of the animation logic.
//
// Animations are added when `last_build_y != current_build_y`. This condition
// is true on the initial render, which would mean that the initial
// build would be animated - this is undesired. Thus, this is null for the
// first frame and the condition becomes `magnifierPosition != null && last_build_y != this_build_y`.
Offset? _magnifierPosition;
// A timer that unsets itself after an animation duration.
// If the timer exists, then the magnifier animates its position -
// if this timer does not exist, the magnifier tracks the gesture (with respect
// to the positioning rules) directly.
Timer? _positionShouldBeAnimatedTimer;
bool get _positionShouldBeAnimated => _positionShouldBeAnimatedTimer != null;
Offset _extraFocalPointOffset = Offset.zero;
@override
void initState() {
super.initState();
widget.magnifierInfo
.addListener(_determineMagnifierPositionAndFocalPoint);
}
@override
void dispose() {
widget.magnifierInfo
.removeListener(_determineMagnifierPositionAndFocalPoint);
_positionShouldBeAnimatedTimer?.cancel();
super.dispose();
}
@override
void didChangeDependencies() {
_determineMagnifierPositionAndFocalPoint();
super.didChangeDependencies();
}
@override
void didUpdateWidget(TextMagnifier oldWidget) {
if (oldWidget.magnifierInfo != widget.magnifierInfo) {
oldWidget.magnifierInfo.removeListener(_determineMagnifierPositionAndFocalPoint);
widget.magnifierInfo.addListener(_determineMagnifierPositionAndFocalPoint);
}
super.didUpdateWidget(oldWidget);
}
void _determineMagnifierPositionAndFocalPoint() {
final MagnifierInfo selectionInfo =
widget.magnifierInfo.value;
final Rect screenRect = Offset.zero & MediaQuery.sizeOf(context);
// Since by default we draw at the top left corner, this offset
// shifts the magnifier so we draw at the center, and then also includes
// the "above touch point" shift.
final Offset basicMagnifierOffset = Offset(
Magnifier.kDefaultMagnifierSize.width / 2,
Magnifier.kDefaultMagnifierSize.height +
Magnifier.kStandardVerticalFocalPointShift);
// Since the magnifier should not go past the edges of the line,
// but must track the gesture otherwise, constrain the X of the magnifier
// to always stay between line start and end.
final double magnifierX = clampDouble(
selectionInfo.globalGesturePosition.dx,
selectionInfo.currentLineBoundaries.left,
selectionInfo.currentLineBoundaries.right);
// Place the magnifier at the previously calculated X, and the Y should be
// exactly at the center of the handle.
final Rect unadjustedMagnifierRect =
Offset(magnifierX, selectionInfo.caretRect.center.dy) - basicMagnifierOffset &
Magnifier.kDefaultMagnifierSize;
// Shift the magnifier so that, if we are ever out of the screen, we become in bounds.
// This probably won't have much of an effect on the X, since it is already bound
// to the currentLineBoundaries, but will shift vertically if the magnifier is out of bounds.
final Rect screenBoundsAdjustedMagnifierRect =
MagnifierController.shiftWithinBounds(
bounds: screenRect, rect: unadjustedMagnifierRect);
// Done with the magnifier position!
final Offset finalMagnifierPosition = screenBoundsAdjustedMagnifierRect.topLeft;
// The insets, from either edge, that the focal point should not point
// past lest the magnifier displays something out of bounds.
final double horizontalMaxFocalPointEdgeInsets =
(Magnifier.kDefaultMagnifierSize.width / 2) / Magnifier._magnification;
// Adjust the focal point horizontally such that none of the magnifier
// ever points to anything out of bounds.
final double newGlobalFocalPointX;
// If the text field is so narrow that we must show out of bounds,
// then settle for pointing to the center all the time.
if (selectionInfo.fieldBounds.width <
horizontalMaxFocalPointEdgeInsets * 2) {
newGlobalFocalPointX = selectionInfo.fieldBounds.center.dx;
} else {
// Otherwise, we can clamp the focal point to always point in bounds.
newGlobalFocalPointX = clampDouble(
screenBoundsAdjustedMagnifierRect.center.dx,
selectionInfo.fieldBounds.left + horizontalMaxFocalPointEdgeInsets,
selectionInfo.fieldBounds.right - horizontalMaxFocalPointEdgeInsets);
}
// Since the previous value is now a global offset (i.e. `newGlobalFocalPoint`
// is now a global offset), we must subtract the magnifier's global offset
// to obtain the relative shift in the focal point.
final double newRelativeFocalPointX =
newGlobalFocalPointX - screenBoundsAdjustedMagnifierRect.center.dx;
// The Y component means that if we are pressed up against the top of the screen,
// then we should adjust the focal point such that it now points to how far we moved
// the magnifier. screenBoundsAdjustedMagnifierRect.top == unadjustedMagnifierRect.top for most cases,
// but when pressed up against the top of the screen, we adjust the focal point by
// the amount that we shifted from our "natural" position.
final Offset focalPointAdjustmentForScreenBoundsAdjustment = Offset(
newRelativeFocalPointX,
unadjustedMagnifierRect.top - screenBoundsAdjustedMagnifierRect.top,
);
Timer? positionShouldBeAnimated = _positionShouldBeAnimatedTimer;
if (_magnifierPosition != null && finalMagnifierPosition.dy != _magnifierPosition!.dy) {
if (_positionShouldBeAnimatedTimer != null &&
_positionShouldBeAnimatedTimer!.isActive) {
_positionShouldBeAnimatedTimer!.cancel();
}
// Create a timer that deletes itself when the timer is complete.
// This is `mounted` safe, since the timer is canceled in `dispose`.
positionShouldBeAnimated = Timer(
TextMagnifier.jumpBetweenLinesAnimationDuration,
() => setState(() {
_positionShouldBeAnimatedTimer = null;
}));
}
setState(() {
_magnifierPosition = finalMagnifierPosition;
_positionShouldBeAnimatedTimer = positionShouldBeAnimated;
_extraFocalPointOffset = focalPointAdjustmentForScreenBoundsAdjustment;
});
}
@override
Widget build(BuildContext context) {
assert(_magnifierPosition != null,
'Magnifier position should only be null before the first build.');
return AnimatedPositioned(
top: _magnifierPosition!.dy,
left: _magnifierPosition!.dx,
// Material magnifier typically does not animate, unless we jump between lines,
// in which case we animate between lines.
duration: _positionShouldBeAnimated
? TextMagnifier.jumpBetweenLinesAnimationDuration
: Duration.zero,
child: Magnifier(
additionalFocalPointOffset: _extraFocalPointOffset,
),
);
}
}
/// A Material-styled magnifying glass.
///
/// {@macro flutter.widgets.magnifier.intro}
///
/// This widget focuses on mimicking the _style_ of the magnifier on material.
/// For a widget that is focused on mimicking the _behavior_ of a material
/// magnifier, see [TextMagnifier], which uses [Magnifier].
///
/// The styles implemented in this widget were based on the Android 12 source
/// code, where possible, and on eyeballing a Pixel 6 running Android 12
/// otherwise.
class Magnifier extends StatelessWidget {
/// Creates a [RawMagnifier] in the Material style.
const Magnifier({
super.key,
this.additionalFocalPointOffset = Offset.zero,
this.borderRadius = const BorderRadius.all(Radius.circular(_borderRadius)),
this.filmColor = const Color.fromARGB(8, 158, 158, 158),
this.shadows = const <BoxShadow>[
BoxShadow(
blurRadius: 1.5,
offset: Offset(0.0, 2.0),
spreadRadius: 0.75,
color: Color.fromARGB(25, 0, 0, 0),
)
],
this.clipBehavior = Clip.hardEdge,
this.size = Magnifier.kDefaultMagnifierSize,
});
/// The default size of this [Magnifier].
///
/// The size of the magnifier may be modified through the constructor;
/// [kDefaultMagnifierSize] is extracted from the default parameter of
/// [Magnifier]'s constructor so that positioners may depend on it.
static const Size kDefaultMagnifierSize = Size(77.37, 37.9);
/// The vertical distance that the magnifier should be above the focal point.
///
/// The [kStandardVerticalFocalPointShift] value is a constant so that
/// positioning of this [Magnifier] can be done with a guaranteed size, as
/// opposed to an estimate.
static const double kStandardVerticalFocalPointShift = 22.0;
static const double _borderRadius = 40;
static const double _magnification = 1.25;
/// Any additional offset the focal point requires to "point"
/// to the correct place.
///
/// This value is added to [kStandardVerticalFocalPointShift] to obtain the
/// actual offset.
///
/// This is useful for instances where the magnifier is not pointing to
/// something directly below it.
final Offset additionalFocalPointOffset;
/// The border radius for this magnifier.
///
/// The magnifier's shape is a [RoundedRectangleBorder] with this radius.
final BorderRadius borderRadius;
/// The color to tint the image in this [Magnifier].
///
/// On native Android, there is a almost transparent gray tint to the
/// magnifier, in order to better distinguish the contents of the lens from
/// the background.
final Color filmColor;
/// A list of shadows cast by the [Magnifier].
///
/// If the shadows use a [BlurStyle] that paints inside the shape, or if they
/// are offset, then a [clipBehavior] that enables clipping (such as the
/// default [Clip.hardEdge]) is recommended, otherwise the shadow will occlude
/// the magnifier (the shadow is drawn above the magnifier so as to not be
/// included in the magnified image).
///
/// By default, the shadows are offset vertically by two logical pixels, so
/// clipping is recommended.
///
/// A shadow that uses [BlurStyle.outer] and is not offset does not need
/// clipping; in that case, consider setting [clipBehavior] to [Clip.none].
final List<BoxShadow> shadows;
/// Whether and how to clip the [shadows] that render inside the loupe.
///
/// Defaults to [Clip.hardEdge].
///
/// A value of [Clip.none] can be used if the shadow will not paint where the
/// magnified image appears, or if doing so is intentional (e.g. to blur the
/// edges of the magnified image).
///
/// See the discussion at [shadows].
final Clip clipBehavior;
/// The [Size] of this [Magnifier].
///
/// The [shadows] are drawn outside of the [size].
final Size size;
@override
Widget build(BuildContext context) {
return RawMagnifier(
decoration: MagnifierDecoration(
shape: RoundedRectangleBorder(borderRadius: borderRadius),
shadows: shadows,
),
clipBehavior: clipBehavior,
magnificationScale: _magnification,
focalPointOffset: additionalFocalPointOffset +
Offset(0, kStandardVerticalFocalPointShift + kDefaultMagnifierSize.height / 2),
size: size,
child: ColoredBox(
// This couldn't be part of the decoration (even if the
// MagnifierDecoration supported specifying a color) because the
// decoration's shadows are offset and therefore we set a clipBehavior
// that clips the inner part of the decoration to avoid occluding the
// magnified image with the shadow.
color: filmColor,
),
);
}
}
| flutter/packages/flutter/lib/src/material/magnifier.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/magnifier.dart",
"repo_id": "flutter",
"token_count": 4670
} | 236 |
// Copyright 2014 The Flutter Authors. 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 lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'material_state.dart';
import 'navigation_drawer.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// Defines default property values for descendant [NavigationDrawer]
/// widgets.
///
/// Descendant widgets obtain the current [NavigationDrawerThemeData] object
/// using `NavigationDrawerTheme.of(context)`. Instances of
/// [NavigationDrawerThemeData] can be customized with
/// [NavigationDrawerThemeData.copyWith].
///
/// Typically a [NavigationDrawerThemeData] is specified as part of the
/// overall [Theme] with [ThemeData.navigationDrawerTheme]. Alternatively, a
/// [NavigationDrawerTheme] inherited widget can be used to theme [NavigationDrawer]s
/// in a subtree of widgets.
///
/// All [NavigationDrawerThemeData] properties are `null` by default.
/// When null, the [NavigationDrawer] will provide its own defaults based on the
/// overall [Theme]'s textTheme and colorScheme. See the individual
/// [NavigationDrawer] properties for details.
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
@immutable
class NavigationDrawerThemeData with Diagnosticable {
/// Creates a theme that can be used for [ThemeData.navigationDrawerTheme] and
/// [NavigationDrawerTheme].
const NavigationDrawerThemeData({
this.tileHeight,
this.backgroundColor,
this.elevation,
this.shadowColor,
this.surfaceTintColor,
this.indicatorColor,
this.indicatorShape,
this.indicatorSize,
this.labelTextStyle,
this.iconTheme,
});
/// Overrides the default height of [NavigationDrawerDestination].
final double? tileHeight;
/// Overrides the default value of [NavigationDrawer.backgroundColor].
final Color? backgroundColor;
/// Overrides the default value of [NavigationDrawer.elevation].
final double? elevation;
/// Overrides the default value of [NavigationDrawer.shadowColor].
final Color? shadowColor;
/// Overrides the default value of [NavigationDrawer.surfaceTintColor].
final Color? surfaceTintColor;
/// Overrides the default value of [NavigationDrawer]'s selection indicator.
final Color? indicatorColor;
/// Overrides the default shape of the [NavigationDrawer]'s selection indicator.
final ShapeBorder? indicatorShape;
/// Overrides the default size of the [NavigationDrawer]'s selection indicator.
final Size? indicatorSize;
/// The style to merge with the default text style for
/// [NavigationDestination] labels.
///
/// You can use this to specify a different style when the label is selected.
final MaterialStateProperty<TextStyle?>? labelTextStyle;
/// The theme to merge with the default icon theme for
/// [NavigationDestination] icons.
///
/// You can use this to specify a different icon theme when the icon is
/// selected.
final MaterialStateProperty<IconThemeData?>? iconTheme;
/// Creates a copy of this object with the given fields replaced with the
/// new values.
NavigationDrawerThemeData copyWith({
double? tileHeight,
Color? backgroundColor,
double? elevation,
Color? shadowColor,
Color? surfaceTintColor,
Color? indicatorColor,
ShapeBorder? indicatorShape,
Size? indicatorSize,
MaterialStateProperty<TextStyle?>? labelTextStyle,
MaterialStateProperty<IconThemeData?>? iconTheme,
}) {
return NavigationDrawerThemeData(
tileHeight: tileHeight ?? this.tileHeight,
backgroundColor: backgroundColor ?? this.backgroundColor,
elevation: elevation ?? this.elevation,
shadowColor: shadowColor ?? this.shadowColor,
surfaceTintColor: surfaceTintColor ?? this.surfaceTintColor,
indicatorColor: indicatorColor ?? this.indicatorColor,
indicatorShape: indicatorShape ?? this.indicatorShape,
indicatorSize: indicatorSize ?? this.indicatorSize,
labelTextStyle: labelTextStyle ?? this.labelTextStyle,
iconTheme: iconTheme ?? this.iconTheme,
);
}
/// Linearly interpolate between two navigation rail themes.
///
/// If both arguments are null then null is returned.
///
/// {@macro dart.ui.shadow.lerp}
static NavigationDrawerThemeData? lerp(NavigationDrawerThemeData? a, NavigationDrawerThemeData? b, double t) {
if (identical(a, b)) {
return a;
}
return NavigationDrawerThemeData(
tileHeight: lerpDouble(a?.tileHeight, b?.tileHeight, t),
backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t),
elevation: lerpDouble(a?.elevation, b?.elevation, t),
shadowColor: Color.lerp(a?.shadowColor, b?.shadowColor, t),
surfaceTintColor: Color.lerp(a?.surfaceTintColor, b?.surfaceTintColor, t),
indicatorColor: Color.lerp(a?.indicatorColor, b?.indicatorColor, t),
indicatorShape: ShapeBorder.lerp(a?.indicatorShape, b?.indicatorShape, t),
indicatorSize: Size.lerp(a?.indicatorSize, a?.indicatorSize, t),
labelTextStyle: MaterialStateProperty.lerp<TextStyle?>(
a?.labelTextStyle, b?.labelTextStyle, t, TextStyle.lerp),
iconTheme: MaterialStateProperty.lerp<IconThemeData?>(
a?.iconTheme, b?.iconTheme, t, IconThemeData.lerp),
);
}
@override
int get hashCode => Object.hash(
tileHeight,
backgroundColor,
elevation,
shadowColor,
surfaceTintColor,
indicatorColor,
indicatorShape,
indicatorSize,
labelTextStyle,
iconTheme,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is NavigationDrawerThemeData &&
other.tileHeight == tileHeight &&
other.backgroundColor == backgroundColor &&
other.elevation == elevation &&
other.shadowColor == shadowColor &&
other.surfaceTintColor == surfaceTintColor &&
other.indicatorColor == indicatorColor &&
other.indicatorShape == indicatorShape &&
other.indicatorSize == indicatorSize &&
other.labelTextStyle == labelTextStyle &&
other.iconTheme == iconTheme;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties
.add(DoubleProperty('tileHeight', tileHeight, defaultValue: null));
properties.add(
ColorProperty('backgroundColor', backgroundColor, defaultValue: null));
properties.add(DoubleProperty('elevation', elevation, defaultValue: null));
properties.add(ColorProperty('shadowColor', shadowColor, defaultValue: null));
properties.add(ColorProperty('surfaceTintColor', surfaceTintColor,
defaultValue: null));
properties.add(
ColorProperty('indicatorColor', indicatorColor, defaultValue: null));
properties.add(DiagnosticsProperty<ShapeBorder>(
'indicatorShape', indicatorShape,
defaultValue: null));
properties.add(DiagnosticsProperty<Size>('indicatorSize', indicatorSize,
defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<TextStyle?>>(
'labelTextStyle', labelTextStyle,
defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<IconThemeData?>>(
'iconTheme', iconTheme,
defaultValue: null));
}
}
/// An inherited widget that defines visual properties for [NavigationDrawer]s and
/// [NavigationDestination]s in this widget's subtree.
///
/// Values specified here are used for [NavigationDrawer] properties that are not
/// given an explicit non-null value.
///
/// See also:
///
/// * [ThemeData.navigationDrawerTheme], which describes the
/// [NavigationDrawerThemeData] in the overall theme for the application.
class NavigationDrawerTheme extends InheritedTheme {
/// Creates a navigation rail theme that controls the
/// [NavigationDrawerThemeData] properties for a [NavigationDrawer].
const NavigationDrawerTheme({
super.key,
required this.data,
required super.child,
});
/// Specifies the background color, label text style, icon theme, and label
/// type values for descendant [NavigationDrawer] widgets.
final NavigationDrawerThemeData data;
/// The closest instance of this class that encloses the given context.
///
/// If there is no enclosing [NavigationDrawerTheme] widget, then
/// [ThemeData.navigationDrawerTheme] is used.
static NavigationDrawerThemeData of(BuildContext context) {
final NavigationDrawerTheme? navigationDrawerTheme =
context.dependOnInheritedWidgetOfExactType<NavigationDrawerTheme>();
return navigationDrawerTheme?.data ??
Theme.of(context).navigationDrawerTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return NavigationDrawerTheme(data: data, child: child);
}
@override
bool updateShouldNotify(NavigationDrawerTheme oldWidget) =>
data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/navigation_drawer_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/navigation_drawer_theme.dart",
"repo_id": "flutter",
"token_count": 2974
} | 237 |
// Copyright 2014 The Flutter Authors. 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 lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'material_state.dart';
import 'theme.dart';
import 'theme_data.dart';
// Examples can assume:
// late BuildContext context;
/// Defines default property values for descendant [Radio] widgets.
///
/// Descendant widgets obtain the current [RadioThemeData] object using
/// `RadioTheme.of(context)`. Instances of [RadioThemeData] can be customized
/// with [RadioThemeData.copyWith].
///
/// Typically a [RadioThemeData] is specified as part of the overall [Theme]
/// with [ThemeData.radioTheme].
///
/// All [RadioThemeData] properties are `null` by default. When null, the
/// [Radio] will use the values from [ThemeData] if they exist, otherwise it
/// will provide its own defaults based on the overall [Theme]'s colorScheme.
/// See the individual [Radio] properties for details.
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
/// * [RadioTheme], which is used by descendants to obtain the
/// [RadioThemeData].
@immutable
class RadioThemeData with Diagnosticable {
/// Creates a theme that can be used for [ThemeData.radioTheme].
const RadioThemeData({
this.mouseCursor,
this.fillColor,
this.overlayColor,
this.splashRadius,
this.materialTapTargetSize,
this.visualDensity,
});
/// {@macro flutter.material.radio.mouseCursor}
///
/// If specified, overrides the default value of [Radio.mouseCursor]. The
/// default value is [MaterialStateMouseCursor.clickable].
final MaterialStateProperty<MouseCursor?>? mouseCursor;
/// {@macro flutter.material.radio.fillColor}
///
/// If specified, overrides the default value of [Radio.fillColor].
final MaterialStateProperty<Color?>? fillColor;
/// {@macro flutter.material.radio.overlayColor}
///
/// If specified, overrides the default value of [Radio.overlayColor].
final MaterialStateProperty<Color?>? overlayColor;
/// {@macro flutter.material.radio.splashRadius}
///
/// If specified, overrides the default value of [Radio.splashRadius]. The
/// default value is [kRadialReactionRadius].
final double? splashRadius;
/// {@macro flutter.material.radio.materialTapTargetSize}
///
/// If specified, overrides the default value of
/// [Radio.materialTapTargetSize]. The default value is the value of
/// [ThemeData.materialTapTargetSize].
final MaterialTapTargetSize? materialTapTargetSize;
/// {@macro flutter.material.radio.visualDensity}
///
/// If specified, overrides the default value of [Radio.visualDensity]. The
/// default value is the value of [ThemeData.visualDensity].
final VisualDensity? visualDensity;
/// Creates a copy of this object but with the given fields replaced with the
/// new values.
RadioThemeData copyWith({
MaterialStateProperty<MouseCursor?>? mouseCursor,
MaterialStateProperty<Color?>? fillColor,
MaterialStateProperty<Color?>? overlayColor,
double? splashRadius,
MaterialTapTargetSize? materialTapTargetSize,
VisualDensity? visualDensity,
}) {
return RadioThemeData(
mouseCursor: mouseCursor ?? this.mouseCursor,
fillColor: fillColor ?? this.fillColor,
overlayColor: overlayColor ?? this.overlayColor,
splashRadius: splashRadius ?? this.splashRadius,
materialTapTargetSize: materialTapTargetSize ?? this.materialTapTargetSize,
visualDensity: visualDensity ?? this.visualDensity,
);
}
/// Linearly interpolate between two [RadioThemeData]s.
///
/// {@macro dart.ui.shadow.lerp}
static RadioThemeData lerp(RadioThemeData? a, RadioThemeData? b, double t) {
if (identical(a, b) && a != null) {
return a;
}
return RadioThemeData(
mouseCursor: t < 0.5 ? a?.mouseCursor : b?.mouseCursor,
fillColor: MaterialStateProperty.lerp<Color?>(a?.fillColor, b?.fillColor, t, Color.lerp),
materialTapTargetSize: t < 0.5 ? a?.materialTapTargetSize : b?.materialTapTargetSize,
overlayColor: MaterialStateProperty.lerp<Color?>(a?.overlayColor, b?.overlayColor, t, Color.lerp),
splashRadius: lerpDouble(a?.splashRadius, b?.splashRadius, t),
visualDensity: t < 0.5 ? a?.visualDensity : b?.visualDensity,
);
}
@override
int get hashCode => Object.hash(
mouseCursor,
fillColor,
overlayColor,
splashRadius,
materialTapTargetSize,
visualDensity,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is RadioThemeData
&& other.mouseCursor == mouseCursor
&& other.fillColor == fillColor
&& other.overlayColor == overlayColor
&& other.splashRadius == splashRadius
&& other.materialTapTargetSize == materialTapTargetSize
&& other.visualDensity == visualDensity;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<MaterialStateProperty<MouseCursor?>>('mouseCursor', mouseCursor, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('fillColor', fillColor, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('overlayColor', overlayColor, defaultValue: null));
properties.add(DoubleProperty('splashRadius', splashRadius, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialTapTargetSize>('materialTapTargetSize', materialTapTargetSize, defaultValue: null));
properties.add(DiagnosticsProperty<VisualDensity>('visualDensity', visualDensity, defaultValue: null));
}
}
/// Applies a radio theme to descendant [Radio] widgets.
///
/// Descendant widgets obtain the current theme's [RadioTheme] object using
/// [RadioTheme.of]. When a widget uses [RadioTheme.of], it is automatically
/// rebuilt if the theme later changes.
///
/// A radio theme can be specified as part of the overall Material theme using
/// [ThemeData.radioTheme].
///
/// See also:
///
/// * [RadioThemeData], which describes the actual configuration of a radio
/// theme.
class RadioTheme extends InheritedWidget {
/// Constructs a radio theme that configures all descendant [Radio] widgets.
const RadioTheme({
super.key,
required this.data,
required super.child,
});
/// The properties used for all descendant [Radio] widgets.
final RadioThemeData data;
/// Returns the configuration [data] from the closest [RadioTheme] ancestor.
/// If there is no ancestor, it returns [ThemeData.radioTheme].
///
/// Typical usage is as follows:
///
/// ```dart
/// RadioThemeData theme = RadioTheme.of(context);
/// ```
static RadioThemeData of(BuildContext context) {
final RadioTheme? radioTheme = context.dependOnInheritedWidgetOfExactType<RadioTheme>();
return radioTheme?.data ?? Theme.of(context).radioTheme;
}
@override
bool updateShouldNotify(RadioTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/radio_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/radio_theme.dart",
"repo_id": "flutter",
"token_count": 2294
} | 238 |
// Copyright 2014 The Flutter Authors. 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';
// Based on https://material.io/design/environment/elevation.html
// Currently, only the elevation values that are bound to one or more widgets are
// defined here.
/// Map of elevation offsets used by Material Design to [BoxShadow] definitions.
///
/// The following elevations have defined shadows: 1, 2, 3, 4, 6, 8, 9, 12, 16, 24.
///
/// Each entry has three shadows which must be combined to obtain the defined
/// effect for that elevation.
///
/// This is useful when simulating a shadow with a [BoxDecoration] or other
/// class that uses a list of [BoxShadow] objects.
///
/// Shadows defined by [kElevationToShadow] use [BlurStyle.normal]. To convert a
/// shadow from [kElevationToShadow] to use a different [BlurStyle] (e.g. to use
/// it in a [MagnifierDecoration]), consider an expression such as the
/// following:
///
/// ```dart
/// kElevationToShadow[12]!.map((BoxShadow shadow) => shadow.copyWith(blurStyle: BlurStyle.outer)).toList(),
/// ```
///
/// See also:
///
/// * [Material], which takes an arbitrary double for its elevation and generates
/// a shadow dynamically.
/// * <https://material.io/design/environment/elevation.html>
const Map<int, List<BoxShadow>> kElevationToShadow = _elevationToShadow; // to hide the literal from the docs
const Color _kKeyUmbraOpacity = Color(0x33000000); // alpha = 0.2
const Color _kKeyPenumbraOpacity = Color(0x24000000); // alpha = 0.14
const Color _kAmbientShadowOpacity = Color(0x1F000000); // alpha = 0.12
const Map<int, List<BoxShadow>> _elevationToShadow = <int, List<BoxShadow>>{
// The empty list depicts no elevation.
0: <BoxShadow>[],
1: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 2.0), blurRadius: 1.0, spreadRadius: -1.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 1.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 3.0, color: _kAmbientShadowOpacity),
],
2: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 1.0, spreadRadius: -2.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 2.0), blurRadius: 2.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 5.0, color: _kAmbientShadowOpacity),
],
3: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 3.0, spreadRadius: -2.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 4.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 8.0, color: _kAmbientShadowOpacity),
],
4: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 2.0), blurRadius: 4.0, spreadRadius: -1.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 4.0), blurRadius: 5.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 10.0, color: _kAmbientShadowOpacity),
],
6: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 5.0, spreadRadius: -1.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 6.0), blurRadius: 10.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 1.0), blurRadius: 18.0, color: _kAmbientShadowOpacity),
],
8: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 5.0), blurRadius: 5.0, spreadRadius: -3.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 8.0), blurRadius: 10.0, spreadRadius: 1.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 14.0, spreadRadius: 2.0, color: _kAmbientShadowOpacity),
],
9: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 5.0), blurRadius: 6.0, spreadRadius: -3.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 9.0), blurRadius: 12.0, spreadRadius: 1.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 3.0), blurRadius: 16.0, spreadRadius: 2.0, color: _kAmbientShadowOpacity),
],
12: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 7.0), blurRadius: 8.0, spreadRadius: -4.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 12.0), blurRadius: 17.0, spreadRadius: 2.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 5.0), blurRadius: 22.0, spreadRadius: 4.0, color: _kAmbientShadowOpacity),
],
16: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 8.0), blurRadius: 10.0, spreadRadius: -5.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 16.0), blurRadius: 24.0, spreadRadius: 2.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 6.0), blurRadius: 30.0, spreadRadius: 5.0, color: _kAmbientShadowOpacity),
],
24: <BoxShadow>[
BoxShadow(offset: Offset(0.0, 11.0), blurRadius: 15.0, spreadRadius: -7.0, color: _kKeyUmbraOpacity),
BoxShadow(offset: Offset(0.0, 24.0), blurRadius: 38.0, spreadRadius: 3.0, color: _kKeyPenumbraOpacity),
BoxShadow(offset: Offset(0.0, 9.0), blurRadius: 46.0, spreadRadius: 8.0, color: _kAmbientShadowOpacity),
],
};
| flutter/packages/flutter/lib/src/material/shadows.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/shadows.dart",
"repo_id": "flutter",
"token_count": 1984
} | 239 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// A [ButtonStyle] that overrides the default appearance of
/// [TextButton]s when it's used with [TextButtonTheme] or with the
/// overall [Theme]'s [ThemeData.textButtonTheme].
///
/// The [style]'s properties override [TextButton]'s default style,
/// i.e. the [ButtonStyle] returned by [TextButton.defaultStyleOf]. Only
/// the style's non-null property values or resolved non-null
/// [MaterialStateProperty] values are used.
///
/// See also:
///
/// * [TextButtonTheme], the theme which is configured with this class.
/// * [TextButton.defaultStyleOf], which returns the default [ButtonStyle]
/// for text buttons.
/// * [TextButton.styleFrom], which converts simple values into a
/// [ButtonStyle] that's consistent with [TextButton]'s defaults.
/// * [MaterialStateProperty.resolve], "resolve" a material state property
/// to a simple value based on a set of [MaterialState]s.
/// * [ThemeData.textButtonTheme], which can be used to override the default
/// [ButtonStyle] for [TextButton]s below the overall [Theme].
@immutable
class TextButtonThemeData with Diagnosticable {
/// Creates a [TextButtonThemeData].
///
/// The [style] may be null.
const TextButtonThemeData({ this.style });
/// Overrides for [TextButton]'s default style.
///
/// Non-null properties or non-null resolved [MaterialStateProperty]
/// values override the [ButtonStyle] returned by
/// [TextButton.defaultStyleOf].
///
/// If [style] is null, then this theme doesn't override anything.
final ButtonStyle? style;
/// Linearly interpolate between two text button themes.
static TextButtonThemeData? lerp(TextButtonThemeData? a, TextButtonThemeData? b, double t) {
if (identical(a, b)) {
return a;
}
return TextButtonThemeData(
style: ButtonStyle.lerp(a?.style, b?.style, t),
);
}
@override
int get hashCode => style.hashCode;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is TextButtonThemeData && other.style == style;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ButtonStyle>('style', style, defaultValue: null));
}
}
/// Overrides the default [ButtonStyle] of its [TextButton] descendants.
///
/// See also:
///
/// * [TextButtonThemeData], which is used to configure this theme.
/// * [TextButton.defaultStyleOf], which returns the default [ButtonStyle]
/// for text buttons.
/// * [TextButton.styleFrom], which converts simple values into a
/// [ButtonStyle] that's consistent with [TextButton]'s defaults.
/// * [ThemeData.textButtonTheme], which can be used to override the default
/// [ButtonStyle] for [TextButton]s below the overall [Theme].
class TextButtonTheme extends InheritedTheme {
/// Create a [TextButtonTheme].
const TextButtonTheme({
super.key,
required this.data,
required super.child,
});
/// The configuration of this theme.
final TextButtonThemeData data;
/// The closest instance of this class that encloses the given context.
///
/// If there is no enclosing [TextButtonTheme] widget, then
/// [ThemeData.textButtonTheme] is used.
///
/// Typical usage is as follows:
///
/// ```dart
/// TextButtonThemeData theme = TextButtonTheme.of(context);
/// ```
static TextButtonThemeData of(BuildContext context) {
final TextButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType<TextButtonTheme>();
return buttonTheme?.data ?? Theme.of(context).textButtonTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return TextButtonTheme(data: data, child: child);
}
@override
bool updateShouldNotify(TextButtonTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/text_button_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/text_button_theme.dart",
"repo_id": "flutter",
"token_count": 1283
} | 240 |
// Copyright 2014 The Flutter Authors. 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 lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// Defines the visual properties of [Tooltip] widgets, a tooltip theme.
///
/// Each property of [TooltipThemeData] corresponds to a property of [Tooltip],
/// and describes the value to use when the [Tooltip] property is
/// not given an explicit non-null value.
///
/// Use this class to configure a [TooltipTheme] widget, or to set the
/// [ThemeData.tooltipTheme] for a [Theme] widget or [MaterialApp.theme].
///
/// To obtain the current ambient tooltip theme, use [TooltipTheme.of].
///
/// See also:
///
/// * [TooltipTheme], a widget which overrides the tooltip theme for a subtree.
/// * [ThemeData.tooltipTheme], which specifies a tooltip theme as part of
/// an overall theme.
/// * [MaterialApp.theme], which specifies a theme for the whole application.
@immutable
class TooltipThemeData with Diagnosticable {
/// Creates the set of properties used to configure [Tooltip]s.
const TooltipThemeData({
this.height,
this.padding,
this.margin,
this.verticalOffset,
this.preferBelow,
this.excludeFromSemantics,
this.decoration,
this.textStyle,
this.textAlign,
this.waitDuration,
this.showDuration,
this.exitDuration,
this.triggerMode,
this.enableFeedback,
});
/// The height of [Tooltip.child].
final double? height;
/// If provided, the amount of space by which to inset [Tooltip.child].
final EdgeInsetsGeometry? padding;
/// If provided, the amount of empty space to surround the [Tooltip].
final EdgeInsetsGeometry? margin;
/// The vertical gap between the widget and the displayed tooltip.
///
/// When [preferBelow] is set to true and tooltips have sufficient space to
/// display themselves, this property defines how much vertical space
/// tooltips will position themselves under their corresponding widgets.
/// Otherwise, tooltips will position themselves above their corresponding
/// widgets with the given offset.
final double? verticalOffset;
/// Whether the tooltip is displayed below its widget by default.
///
/// If there is insufficient space to display the tooltip in the preferred
/// direction, the tooltip will be displayed in the opposite direction.
///
/// Applying `false` for the entire app is recommended
/// to avoid having a finger or cursor hide a tooltip.
final bool? preferBelow;
/// Whether the [Tooltip.message] should be excluded from the semantics
/// tree.
///
/// By default, [Tooltip]s will add a [Semantics] label that is set to
/// [Tooltip.message]. Set this property to true if the app is going to
/// provide its own custom semantics label.
final bool? excludeFromSemantics;
/// The [Tooltip]'s shape and background color.
final Decoration? decoration;
/// The style to use for the message of [Tooltip]s.
final TextStyle? textStyle;
/// The [TextAlign] to use for the message of [Tooltip]s.
final TextAlign? textAlign;
/// The length of time that a pointer must hover over a tooltip's widget
/// before the tooltip will be shown.
final Duration? waitDuration;
/// The length of time that the tooltip will be shown once it has appeared.
final Duration? showDuration;
/// The length of time that a pointer must have stopped hovering over a
/// tooltip's widget before the tooltip will be hidden.
final Duration? exitDuration;
/// The [TooltipTriggerMode] that will show the tooltip.
final TooltipTriggerMode? triggerMode;
/// Whether the tooltip should provide acoustic and/or haptic feedback.
///
/// For example, on Android a tap will produce a clicking sound and a
/// long-press will produce a short vibration, when feedback is enabled.
///
/// This value is used if [Tooltip.enableFeedback] is null.
/// If this value is null, the default is true.
///
/// See also:
///
/// * [Feedback], for providing platform-specific feedback to certain actions.
final bool? enableFeedback;
/// Creates a copy of this object but with the given fields replaced with the
/// new values.
TooltipThemeData copyWith({
double? height,
EdgeInsetsGeometry? padding,
EdgeInsetsGeometry? margin,
double? verticalOffset,
bool? preferBelow,
bool? excludeFromSemantics,
Decoration? decoration,
TextStyle? textStyle,
TextAlign? textAlign,
Duration? waitDuration,
Duration? showDuration,
Duration? exitDuration,
TooltipTriggerMode? triggerMode,
bool? enableFeedback,
}) {
return TooltipThemeData(
height: height ?? this.height,
padding: padding ?? this.padding,
margin: margin ?? this.margin,
verticalOffset: verticalOffset ?? this.verticalOffset,
preferBelow: preferBelow ?? this.preferBelow,
excludeFromSemantics: excludeFromSemantics ?? this.excludeFromSemantics,
decoration: decoration ?? this.decoration,
textStyle: textStyle ?? this.textStyle,
textAlign: textAlign ?? this.textAlign,
waitDuration: waitDuration ?? this.waitDuration,
showDuration: showDuration ?? this.showDuration,
triggerMode: triggerMode ?? this.triggerMode,
enableFeedback: enableFeedback ?? this.enableFeedback,
);
}
/// Linearly interpolate between two tooltip themes.
///
/// If both arguments are null, then null is returned.
///
/// {@macro dart.ui.shadow.lerp}
static TooltipThemeData? lerp(TooltipThemeData? a, TooltipThemeData? b, double t) {
if (identical(a, b)) {
return a;
}
return TooltipThemeData(
height: lerpDouble(a?.height, b?.height, t),
padding: EdgeInsetsGeometry.lerp(a?.padding, b?.padding, t),
margin: EdgeInsetsGeometry.lerp(a?.margin, b?.margin, t),
verticalOffset: lerpDouble(a?.verticalOffset, b?.verticalOffset, t),
preferBelow: t < 0.5 ? a?.preferBelow: b?.preferBelow,
excludeFromSemantics: t < 0.5 ? a?.excludeFromSemantics : b?.excludeFromSemantics,
decoration: Decoration.lerp(a?.decoration, b?.decoration, t),
textStyle: TextStyle.lerp(a?.textStyle, b?.textStyle, t),
textAlign: t < 0.5 ? a?.textAlign: b?.textAlign,
);
}
@override
int get hashCode => Object.hash(
height,
padding,
margin,
verticalOffset,
preferBelow,
excludeFromSemantics,
decoration,
textStyle,
textAlign,
waitDuration,
showDuration,
exitDuration,
triggerMode,
enableFeedback,
);
@override
bool operator==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is TooltipThemeData
&& other.height == height
&& other.padding == padding
&& other.margin == margin
&& other.verticalOffset == verticalOffset
&& other.preferBelow == preferBelow
&& other.excludeFromSemantics == excludeFromSemantics
&& other.decoration == decoration
&& other.textStyle == textStyle
&& other.textAlign == textAlign
&& other.waitDuration == waitDuration
&& other.showDuration == showDuration
&& other.exitDuration == exitDuration
&& other.triggerMode == triggerMode
&& other.enableFeedback == enableFeedback;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty('height', height, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('margin', margin, defaultValue: null));
properties.add(DoubleProperty('vertical offset', verticalOffset, defaultValue: null));
properties.add(FlagProperty('position', value: preferBelow, ifTrue: 'below', ifFalse: 'above', showName: true));
properties.add(FlagProperty('semantics', value: excludeFromSemantics, ifTrue: 'excluded', showName: true));
properties.add(DiagnosticsProperty<Decoration>('decoration', decoration, defaultValue: null));
properties.add(DiagnosticsProperty<TextStyle>('textStyle', textStyle, defaultValue: null));
properties.add(DiagnosticsProperty<TextAlign>('textAlign', textAlign, defaultValue: null));
properties.add(DiagnosticsProperty<Duration>('wait duration', waitDuration, defaultValue: null));
properties.add(DiagnosticsProperty<Duration>('show duration', showDuration, defaultValue: null));
properties.add(DiagnosticsProperty<Duration>('exit duration', exitDuration, defaultValue: null));
properties.add(DiagnosticsProperty<TooltipTriggerMode>('triggerMode', triggerMode, defaultValue: null));
properties.add(FlagProperty('enableFeedback', value: enableFeedback, ifTrue: 'true', showName: true));
}
}
/// Applies a tooltip theme to descendant [Tooltip] widgets.
///
/// A tooltip theme describes the values to use for [Tooltip] properties
/// that are not given an explicit non-null value.
///
/// Descendant widgets obtain the ambient tooltip theme, a [TooltipThemeData],
/// using [TooltipTheme.of].
///
/// {@tool snippet}
///
/// Here is an example of a tooltip theme that applies a blue foreground
/// with non-rounded corners.
///
/// ```dart
/// TooltipTheme(
/// data: TooltipThemeData(
/// decoration: BoxDecoration(
/// color: Colors.blue.withOpacity(0.9),
/// borderRadius: BorderRadius.zero,
/// ),
/// ),
/// child: Tooltip(
/// message: 'Example tooltip',
/// child: IconButton(
/// iconSize: 36.0,
/// icon: const Icon(Icons.touch_app),
/// onPressed: () {},
/// ),
/// ),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [TooltipThemeData], which describes the actual configuration of a
/// tooltip theme.
/// * [TooltipVisibility], which can be used to visually disable descendant [Tooltip]s.
class TooltipTheme extends InheritedTheme {
/// Creates a tooltip theme that controls the configurations for
/// [Tooltip].
const TooltipTheme({
super.key,
required this.data,
required super.child,
});
/// The properties for descendant [Tooltip] widgets.
final TooltipThemeData data;
/// Returns the ambient tooltip theme.
///
/// The result comes from the closest [TooltipTheme] ancestor if any,
/// and otherwise from [Theme.of] and [ThemeData.tooltipTheme].
///
/// When a widget uses this method, it is automatically rebuilt if the
/// tooltip theme later changes, so that the changes can be applied.
///
/// Typical usage is as follows:
///
/// ```dart
/// TooltipThemeData theme = TooltipTheme.of(context);
/// ```
static TooltipThemeData of(BuildContext context) {
final TooltipTheme? tooltipTheme = context.dependOnInheritedWidgetOfExactType<TooltipTheme>();
return tooltipTheme?.data ?? Theme.of(context).tooltipTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return TooltipTheme(data: data, child: child);
}
@override
bool updateShouldNotify(TooltipTheme oldWidget) => data != oldWidget.data;
}
/// The method of interaction that will trigger a tooltip.
/// Used in [Tooltip.triggerMode] and [TooltipThemeData.triggerMode].
///
/// On desktop, a tooltip will be shown as soon as a pointer hovers over
/// the widget, regardless of the value of [Tooltip.triggerMode].
///
/// See also:
///
/// * [Tooltip.waitDuration], which defines the length of time that
/// a pointer must hover over a tooltip's widget before the tooltip
/// will be shown.
enum TooltipTriggerMode {
/// Tooltip will only be shown by calling `ensureTooltipVisible`.
manual,
/// Tooltip will be shown after a long press.
///
/// See also:
///
/// * [GestureDetector.onLongPress], the event that is used for trigger.
/// * [Feedback.forLongPress], the feedback method called when feedback is enabled.
longPress,
/// Tooltip will be shown after a single tap.
///
/// See also:
///
/// * [GestureDetector.onTap], the event that is used for trigger.
/// * [Feedback.forTap], the feedback method called when feedback is enabled.
tap,
}
| flutter/packages/flutter/lib/src/material/tooltip_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/tooltip_theme.dart",
"repo_id": "flutter",
"token_count": 3887
} | 241 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show lerpDouble;
import 'package:flutter/foundation.dart';
import 'basic_types.dart';
import 'borders.dart';
/// A border that fits a circle within the available space.
///
/// Typically used with [ShapeDecoration] to draw a circle.
///
/// The [dimensions] assume that the border is being used in a square space.
/// When applied to a rectangular space, the border paints in the center of the
/// rectangle.
///
/// The [eccentricity] parameter describes how much a circle will deform to
/// fit the rectangle it is a border for. A value of zero implies no
/// deformation (a circle touching at least two sides of the rectangle), a
/// value of one implies full deformation (an oval touching all sides of the
/// rectangle).
///
/// See also:
///
/// * [OvalBorder], which draws a Circle touching all the edges of the box.
/// * [BorderSide], which is used to describe each side of the box.
/// * [Border], which, when used with [BoxDecoration], can also describe a circle.
class CircleBorder extends OutlinedBorder {
/// Create a circle border.
const CircleBorder({ super.side, this.eccentricity = 0.0 })
: assert(eccentricity >= 0.0, 'The eccentricity argument $eccentricity is not greater than or equal to zero.'),
assert(eccentricity <= 1.0, 'The eccentricity argument $eccentricity is not less than or equal to one.');
/// Defines the ratio (0.0-1.0) from which the border will deform
/// to fit a rectangle.
/// When 0.0, it draws a circle touching at least two sides of the rectangle.
/// When 1.0, it draws an oval touching all sides of the rectangle.
final double eccentricity;
@override
ShapeBorder scale(double t) => CircleBorder(side: side.scale(t), eccentricity: eccentricity);
@override
ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
if (a is CircleBorder) {
return CircleBorder(
side: BorderSide.lerp(a.side, side, t),
eccentricity: clampDouble(ui.lerpDouble(a.eccentricity, eccentricity, t)!, 0.0, 1.0),
);
}
return super.lerpFrom(a, t);
}
@override
ShapeBorder? lerpTo(ShapeBorder? b, double t) {
if (b is CircleBorder) {
return CircleBorder(
side: BorderSide.lerp(side, b.side, t),
eccentricity: clampDouble(ui.lerpDouble(eccentricity, b.eccentricity, t)!, 0.0, 1.0),
);
}
return super.lerpTo(b, t);
}
@override
Path getInnerPath(Rect rect, { TextDirection? textDirection }) {
return Path()..addOval(_adjustRect(rect).deflate(side.strokeInset));
}
@override
Path getOuterPath(Rect rect, { TextDirection? textDirection }) {
return Path()..addOval(_adjustRect(rect));
}
@override
void paintInterior(Canvas canvas, Rect rect, Paint paint, { TextDirection? textDirection }) {
if (eccentricity == 0.0) {
canvas.drawCircle(rect.center, rect.shortestSide / 2.0, paint);
} else {
canvas.drawOval(_adjustRect(rect), paint);
}
}
@override
bool get preferPaintInterior => true;
@override
CircleBorder copyWith({ BorderSide? side, double? eccentricity }) {
return CircleBorder(side: side ?? this.side, eccentricity: eccentricity ?? this.eccentricity);
}
@override
void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) {
switch (side.style) {
case BorderStyle.none:
break;
case BorderStyle.solid:
if (eccentricity == 0.0) {
canvas.drawCircle(rect.center, (rect.shortestSide + side.strokeOffset) / 2, side.toPaint());
} else {
final Rect borderRect = _adjustRect(rect);
canvas.drawOval(borderRect.inflate(side.strokeOffset / 2), side.toPaint());
}
}
}
Rect _adjustRect(Rect rect) {
if (eccentricity == 0.0 || rect.width == rect.height) {
return Rect.fromCircle(center: rect.center, radius: rect.shortestSide / 2.0);
}
if (rect.width < rect.height) {
final double delta = (1.0 - eccentricity) * (rect.height - rect.width) / 2.0;
return Rect.fromLTRB(
rect.left,
rect.top + delta,
rect.right,
rect.bottom - delta,
);
} else {
final double delta = (1.0 - eccentricity) * (rect.width - rect.height) / 2.0;
return Rect.fromLTRB(
rect.left + delta,
rect.top,
rect.right - delta,
rect.bottom,
);
}
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is CircleBorder
&& other.side == side
&& other.eccentricity == eccentricity;
}
@override
int get hashCode => Object.hash(side, eccentricity);
@override
String toString() {
if (eccentricity != 0.0) {
return '${objectRuntimeType(this, 'CircleBorder')}($side, eccentricity: $eccentricity)';
}
return '${objectRuntimeType(this, 'CircleBorder')}($side)';
}
}
| flutter/packages/flutter/lib/src/painting/circle_border.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/circle_border.dart",
"repo_id": "flutter",
"token_count": 1840
} | 242 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui' as ui show Codec, FrameInfo, Image;
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
const String _flutterPaintingLibrary = 'package:flutter/painting.dart';
/// A [dart:ui.Image] object with its corresponding scale.
///
/// ImageInfo objects are used by [ImageStream] objects to represent the
/// actual data of the image once it has been obtained.
///
/// The disposing contract for [ImageInfo] (as well as for [ui.Image])
/// is different from traditional one, where
/// an object should dispose a member if the object created the member.
/// Instead, the disposal contract is as follows:
///
/// * [ImageInfo] disposes [image], even if it is received as a constructor argument.
/// * [ImageInfo] is expected to be disposed not by the object, that created it,
/// but by the object that owns reference to it.
/// * It is expected that only one object owns reference to [ImageInfo] object.
///
/// Safety tips:
///
/// * To share the [ImageInfo] or [ui.Image] between objects, use the [clone] method,
/// which will not clone the entire underlying image, but only reference to it and information about it.
/// * After passing a [ui.Image] or [ImageInfo] reference to another object,
/// release the reference.
@immutable
class ImageInfo {
/// Creates an [ImageInfo] object for the given [image] and [scale].
///
/// The [debugLabel] may be used to identify the source of this image.
///
/// See details for disposing contract in the class description.
ImageInfo({ required this.image, this.scale = 1.0, this.debugLabel }) {
if (kFlutterMemoryAllocationsEnabled) {
MemoryAllocations.instance.dispatchObjectCreated(
library: _flutterPaintingLibrary,
className: '$ImageInfo',
object: this,
);
}
}
/// Creates an [ImageInfo] with a cloned [image].
///
/// This method must be used in cases where a client holding an [ImageInfo]
/// needs to share the image info object with another client and will still
/// need to access the underlying image data at some later point, e.g. to
/// share it again with another client.
///
/// See details for disposing contract in the class description.
///
/// See also:
///
/// * [Image.clone], which describes how and why to clone images.
ImageInfo clone() {
return ImageInfo(
image: image.clone(),
scale: scale,
debugLabel: debugLabel,
);
}
/// Whether this [ImageInfo] is a [clone] of the `other`.
///
/// This method is a convenience wrapper for [Image.isCloneOf], and is useful
/// for clients that are trying to determine whether new layout or painting
/// logic is required when receiving a new image reference.
///
/// {@tool snippet}
///
/// The following sample shows how to appropriately check whether the
/// [ImageInfo] reference refers to new image data or not (in this case in a
/// setter).
///
/// ```dart
/// ImageInfo? get imageInfo => _imageInfo;
/// ImageInfo? _imageInfo;
/// set imageInfo (ImageInfo? value) {
/// // If the image reference is exactly the same, do nothing.
/// if (value == _imageInfo) {
/// return;
/// }
/// // If it is a clone of the current reference, we must dispose of it and
/// // can do so immediately. Since the underlying image has not changed,
/// // We don't have any additional work to do here.
/// if (value != null && _imageInfo != null && value.isCloneOf(_imageInfo!)) {
/// value.dispose();
/// return;
/// }
/// // It is a new image. Dispose of the old one and take a reference
/// // to the new one.
/// _imageInfo?.dispose();
/// _imageInfo = value;
/// // Perform work to determine size, paint the image, etc.
/// // ...
/// }
/// ```
/// {@end-tool}
bool isCloneOf(ImageInfo other) {
return other.image.isCloneOf(image)
&& scale == scale
&& other.debugLabel == debugLabel;
}
/// The raw image pixels.
///
/// This is the object to pass to the [Canvas.drawImage],
/// [Canvas.drawImageRect], or [Canvas.drawImageNine] methods when painting
/// the image.
final ui.Image image;
/// The size of raw image pixels in bytes.
int get sizeBytes => image.height * image.width * 4;
/// The linear scale factor for drawing this image at its intended size.
///
/// The scale factor applies to the width and the height.
///
/// {@template flutter.painting.imageInfo.scale}
/// For example, if this is 2.0, it means that there are four image pixels for
/// every one logical pixel, and the image's actual width and height (as given
/// by the [dart:ui.Image.width] and [dart:ui.Image.height] properties) are
/// double the height and width that should be used when painting the image
/// (e.g. in the arguments given to [Canvas.drawImage]).
/// {@endtemplate}
final double scale;
/// A string used for debugging purposes to identify the source of this image.
final String? debugLabel;
/// Disposes of this object.
///
/// Once this method has been called, the object should not be used anymore,
/// and no clones of it or the image it contains can be made.
void dispose() {
assert((image.debugGetOpenHandleStackTraces()?.length ?? 1) > 0);
if (kFlutterMemoryAllocationsEnabled) {
MemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
image.dispose();
}
@override
String toString() => '${debugLabel != null ? '$debugLabel ' : ''}$image @ ${debugFormatDouble(scale)}x';
@override
int get hashCode => Object.hash(image, scale, debugLabel);
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is ImageInfo
&& other.image == image
&& other.scale == scale
&& other.debugLabel == debugLabel;
}
}
/// Interface for receiving notifications about the loading of an image.
///
/// This class overrides [operator ==] and [hashCode] to compare the individual
/// callbacks in the listener, meaning that if you add an instance of this class
/// as a listener (e.g. via [ImageStream.addListener]), you can instantiate a
/// _different_ instance of this class when you remove the listener, and the
/// listener will be properly removed as long as all associated callbacks are
/// equal.
///
/// Used by [ImageStream] and [ImageStreamCompleter].
@immutable
class ImageStreamListener {
/// Creates a new [ImageStreamListener].
const ImageStreamListener(
this.onImage, {
this.onChunk,
this.onError,
});
/// Callback for getting notified that an image is available.
///
/// This callback may fire multiple times (e.g. if the [ImageStreamCompleter]
/// that drives the notifications fires multiple times). An example of such a
/// case would be an image with multiple frames within it (such as an animated
/// GIF).
///
/// For more information on how to interpret the parameters to the callback,
/// see the documentation on [ImageListener].
///
/// See also:
///
/// * [onError], which will be called instead of [onImage] if an error occurs
/// during loading.
final ImageListener onImage;
/// Callback for getting notified when a chunk of bytes has been received
/// during the loading of the image.
///
/// This callback may fire many times (e.g. when used with a [NetworkImage],
/// where the image bytes are loaded incrementally over the wire) or not at
/// all (e.g. when used with a [MemoryImage], where the image bytes are
/// already available in memory).
///
/// This callback may also continue to fire after the [onImage] callback has
/// fired (e.g. for multi-frame images that continue to load after the first
/// frame is available).
final ImageChunkListener? onChunk;
/// Callback for getting notified when an error occurs while loading an image.
///
/// If an error occurs during loading, [onError] will be called instead of
/// [onImage].
///
/// If [onError] is called and does not throw, then the error is considered to
/// be handled. An error handler can explicitly rethrow the exception reported
/// to it to safely indicate that it did not handle the exception.
///
/// If an image stream has no listeners that handled the error when the error
/// was first encountered, then the error is reported using
/// [FlutterError.reportError], with the [FlutterErrorDetails.silent] flag set
/// to true.
final ImageErrorListener? onError;
@override
int get hashCode => Object.hash(onImage, onChunk, onError);
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is ImageStreamListener
&& other.onImage == onImage
&& other.onChunk == onChunk
&& other.onError == onError;
}
}
/// Signature for callbacks reporting that an image is available.
///
/// Used in [ImageStreamListener].
///
/// The `image` argument contains information about the image to be rendered.
/// The implementer of [ImageStreamListener.onImage] is expected to call dispose
/// on the [ui.Image] it receives.
///
/// The `synchronousCall` argument is true if the listener is being invoked
/// during the call to `addListener`. This can be useful if, for example,
/// [ImageStream.addListener] is invoked during a frame, so that a new rendering
/// frame is requested if the call was asynchronous (after the current frame)
/// and no rendering frame is requested if the call was synchronous (within the
/// same stack frame as the call to [ImageStream.addListener]).
typedef ImageListener = void Function(ImageInfo image, bool synchronousCall);
/// Signature for listening to [ImageChunkEvent] events.
///
/// Used in [ImageStreamListener].
typedef ImageChunkListener = void Function(ImageChunkEvent event);
/// Signature for reporting errors when resolving images.
///
/// Used in [ImageStreamListener], as well as by [ImageCache.putIfAbsent] and
/// [precacheImage], to report errors.
typedef ImageErrorListener = void Function(Object exception, StackTrace? stackTrace);
/// An immutable notification of image bytes that have been incrementally loaded.
///
/// Chunk events represent progress notifications while an image is being
/// loaded (e.g. from disk or over the network).
///
/// See also:
///
/// * [ImageChunkListener], the means by which callers get notified of
/// these events.
@immutable
class ImageChunkEvent with Diagnosticable {
/// Creates a new chunk event.
const ImageChunkEvent({
required this.cumulativeBytesLoaded,
required this.expectedTotalBytes,
}) : assert(cumulativeBytesLoaded >= 0),
assert(expectedTotalBytes == null || expectedTotalBytes >= 0);
/// The number of bytes that have been received across the wire thus far.
final int cumulativeBytesLoaded;
/// The expected number of bytes that need to be received to finish loading
/// the image.
///
/// This value is not necessarily equal to the expected _size_ of the image
/// in bytes, as the bytes required to load the image may be compressed.
///
/// This value will be null if the number is not known in advance.
///
/// When this value is null, the chunk event may still be useful as an
/// indication that data is loading (and how much), but it cannot represent a
/// loading completion percentage.
final int? expectedTotalBytes;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(IntProperty('cumulativeBytesLoaded', cumulativeBytesLoaded));
properties.add(IntProperty('expectedTotalBytes', expectedTotalBytes));
}
}
/// A handle to an image resource.
///
/// ImageStream represents a handle to a [dart:ui.Image] object and its scale
/// (together represented by an [ImageInfo] object). The underlying image object
/// might change over time, either because the image is animating or because the
/// underlying image resource was mutated.
///
/// ImageStream objects can also represent an image that hasn't finished
/// loading.
///
/// ImageStream objects are backed by [ImageStreamCompleter] objects.
///
/// The [ImageCache] will consider an image to be live until the listener count
/// drops to zero after adding at least one listener. The
/// [ImageStreamCompleter.addOnLastListenerRemovedCallback] method is used for
/// tracking this information.
///
/// See also:
///
/// * [ImageProvider], which has an example that includes the use of an
/// [ImageStream] in a [Widget].
class ImageStream with Diagnosticable {
/// Create an initially unbound image stream.
///
/// Once an [ImageStreamCompleter] is available, call [setCompleter].
ImageStream();
/// The completer that has been assigned to this image stream.
///
/// Generally there is no need to deal with the completer directly.
ImageStreamCompleter? get completer => _completer;
ImageStreamCompleter? _completer;
List<ImageStreamListener>? _listeners;
/// Assigns a particular [ImageStreamCompleter] to this [ImageStream].
///
/// This is usually done automatically by the [ImageProvider] that created the
/// [ImageStream].
///
/// This method can only be called once per stream. To have an [ImageStream]
/// represent multiple images over time, assign it a completer that
/// completes several images in succession.
void setCompleter(ImageStreamCompleter value) {
assert(_completer == null);
_completer = value;
if (_listeners != null) {
final List<ImageStreamListener> initialListeners = _listeners!;
_listeners = null;
_completer!._addingInitialListeners = true;
initialListeners.forEach(_completer!.addListener);
_completer!._addingInitialListeners = false;
}
}
/// Adds a listener callback that is called whenever a new concrete [ImageInfo]
/// object is available. If a concrete image is already available, this object
/// will call the listener synchronously.
///
/// If the assigned [completer] completes multiple images over its lifetime,
/// this listener will fire multiple times.
///
/// {@template flutter.painting.imageStream.addListener}
/// The listener will be passed a flag indicating whether a synchronous call
/// occurred. If the listener is added within a render object paint function,
/// then use this flag to avoid calling [RenderObject.markNeedsPaint] during
/// a paint.
///
/// If a duplicate `listener` is registered N times, then it will be called N
/// times when the image stream completes (whether because a new image is
/// available or because an error occurs). Likewise, to remove all instances
/// of the listener, [removeListener] would need to called N times as well.
///
/// When a `listener` receives an [ImageInfo] object, the `listener` is
/// responsible for disposing of the [ImageInfo.image].
/// {@endtemplate}
void addListener(ImageStreamListener listener) {
if (_completer != null) {
return _completer!.addListener(listener);
}
_listeners ??= <ImageStreamListener>[];
_listeners!.add(listener);
}
/// Stops listening for events from this stream's [ImageStreamCompleter].
///
/// If [listener] has been added multiple times, this removes the _first_
/// instance of the listener.
void removeListener(ImageStreamListener listener) {
if (_completer != null) {
return _completer!.removeListener(listener);
}
assert(_listeners != null);
for (int i = 0; i < _listeners!.length; i += 1) {
if (_listeners![i] == listener) {
_listeners!.removeAt(i);
break;
}
}
}
/// Returns an object which can be used with `==` to determine if this
/// [ImageStream] shares the same listeners list as another [ImageStream].
///
/// This can be used to avoid un-registering and re-registering listeners
/// after calling [ImageProvider.resolve] on a new, but possibly equivalent,
/// [ImageProvider].
///
/// The key may change once in the lifetime of the object. When it changes, it
/// will go from being different than other [ImageStream]'s keys to
/// potentially being the same as others'. No notification is sent when this
/// happens.
Object get key => _completer ?? this;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(ObjectFlagProperty<ImageStreamCompleter>(
'completer',
_completer,
ifPresent: _completer?.toStringShort(),
ifNull: 'unresolved',
));
properties.add(ObjectFlagProperty<List<ImageStreamListener>>(
'listeners',
_listeners,
ifPresent: '${_listeners?.length} listener${_listeners?.length == 1 ? "" : "s" }',
ifNull: 'no listeners',
level: _completer != null ? DiagnosticLevel.hidden : DiagnosticLevel.info,
));
_completer?.debugFillProperties(properties);
}
}
/// An opaque handle that keeps an [ImageStreamCompleter] alive even if it has
/// lost its last listener.
///
/// To create a handle, use [ImageStreamCompleter.keepAlive].
///
/// Such handles are useful when an image cache needs to keep a completer alive
/// but does not actually have a listener subscribed, or when a widget that
/// displays an image needs to temporarily unsubscribe from the completer but
/// may re-subscribe in the future, for example when the [TickerMode] changes.
class ImageStreamCompleterHandle {
ImageStreamCompleterHandle._(ImageStreamCompleter this._completer) {
_completer!._keepAliveHandles += 1;
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectCreated(
library: _flutterPaintingLibrary,
className: '$ImageStreamCompleterHandle',
object: this,
);
}
}
ImageStreamCompleter? _completer;
/// Call this method to signal the [ImageStreamCompleter] that it can now be
/// disposed when its last listener drops.
///
/// This method must only be called once per object.
void dispose() {
assert(_completer != null);
assert(_completer!._keepAliveHandles > 0);
assert(!_completer!._disposed);
_completer!._keepAliveHandles -= 1;
_completer!._maybeDispose();
_completer = null;
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
}
}
/// Base class for those that manage the loading of [dart:ui.Image] objects for
/// [ImageStream]s.
///
/// [ImageStreamListener] objects are rarely constructed directly. Generally, an
/// [ImageProvider] subclass will return an [ImageStream] and automatically
/// configure it with the right [ImageStreamCompleter] when possible.
abstract class ImageStreamCompleter with Diagnosticable {
final List<ImageStreamListener> _listeners = <ImageStreamListener>[];
final List<ImageErrorListener> _ephemeralErrorListeners = <ImageErrorListener>[];
ImageInfo? _currentImage;
FlutterErrorDetails? _currentError;
/// A string identifying the source of the underlying image.
String? debugLabel;
/// Whether any listeners are currently registered.
///
/// Clients should not depend on this value for their behavior, because having
/// one listener's logic change when another listener happens to start or stop
/// listening will lead to extremely hard-to-track bugs. Subclasses might use
/// this information to determine whether to do any work when there are no
/// listeners, however; for example, [MultiFrameImageStreamCompleter] uses it
/// to determine when to iterate through frames of an animated image.
///
/// Typically this is used by overriding [addListener], checking if
/// [hasListeners] is false before calling `super.addListener()`, and if so,
/// starting whatever work is needed to determine when to notify listeners;
/// and similarly, by overriding [removeListener], checking if [hasListeners]
/// is false after calling `super.removeListener()`, and if so, stopping that
/// same work.
///
/// The ephemeral error listeners (added through [addEphemeralErrorListener])
/// will not be taken into consideration in this property.
@protected
@visibleForTesting
bool get hasListeners => _listeners.isNotEmpty;
/// We must avoid disposing a completer if it has never had a listener, even
/// if all [keepAlive] handles get disposed.
bool _hadAtLeastOneListener = false;
/// Whether the future listeners added to this completer are initial listeners.
///
/// This can be set to true when an [ImageStream] adds its initial listeners to
/// this completer. This ultimately controls the synchronousCall parameter for
/// the listener callbacks. When adding cached listeners to a completer,
/// [_addingInitialListeners] can be set to false to indicate to the listeners
/// that they are being called asynchronously.
bool _addingInitialListeners = false;
/// Adds a listener callback that is called whenever a new concrete [ImageInfo]
/// object is available or an error is reported. If a concrete image is
/// already available, or if an error has been already reported, this object
/// will notify the listener synchronously.
///
/// If the [ImageStreamCompleter] completes multiple images over its lifetime,
/// this listener's [ImageStreamListener.onImage] will fire multiple times.
///
/// {@macro flutter.painting.imageStream.addListener}
///
/// See also:
///
/// * [addEphemeralErrorListener], which adds an error listener that is
/// automatically removed after first image load or error.
void addListener(ImageStreamListener listener) {
_checkDisposed();
_hadAtLeastOneListener = true;
_listeners.add(listener);
if (_currentImage != null) {
try {
listener.onImage(_currentImage!.clone(), !_addingInitialListeners);
} catch (exception, stack) {
reportError(
context: ErrorDescription('by a synchronously-called image listener'),
exception: exception,
stack: stack,
);
}
}
if (_currentError != null && listener.onError != null) {
try {
listener.onError!(_currentError!.exception, _currentError!.stack);
} catch (newException, newStack) {
if (newException != _currentError!.exception) {
FlutterError.reportError(
FlutterErrorDetails(
exception: newException,
library: 'image resource service',
context: ErrorDescription('by a synchronously-called image error listener'),
stack: newStack,
),
);
}
}
}
}
/// Adds an error listener callback that is called when the first error is reported.
///
/// The callback will be removed automatically after the first successful
/// image load or the first error - that is why it is called "ephemeral".
///
/// If a concrete image is already available, the listener will be discarded
/// synchronously. If an error has been already reported, the listener
/// will be notified synchronously.
///
/// The presence of a listener will affect neither the lifecycle of this object
/// nor what [hasListeners] reports.
///
/// It is different from [addListener] in a few points: Firstly, this one only
/// listens to errors, while [addListener] listens to all kinds of events.
/// Secondly, this listener will be automatically removed according to the
/// rules mentioned above, while [addListener] will need manual removal.
/// Thirdly, this listener will not affect how this object is disposed, while
/// any non-removed listener added via [addListener] will forbid this object
/// from disposal.
///
/// When you want to know full information and full control, use [addListener].
/// When you only want to get notified for an error ephemerally, use this function.
///
/// See also:
///
/// * [addListener], which adds a full-featured listener and needs manual
/// removal.
void addEphemeralErrorListener(ImageErrorListener listener) {
_checkDisposed();
if (_currentError != null) {
// immediately fire the listener, and no need to add to _ephemeralErrorListeners
try {
listener(_currentError!.exception, _currentError!.stack);
} catch (newException, newStack) {
if (newException != _currentError!.exception) {
FlutterError.reportError(
FlutterErrorDetails(
exception: newException,
library: 'image resource service',
context: ErrorDescription('by a synchronously-called image error listener'),
stack: newStack,
),
);
}
}
} else if (_currentImage == null) {
// add to _ephemeralErrorListeners to wait for the error,
// only if no image has been loaded
_ephemeralErrorListeners.add(listener);
}
}
int _keepAliveHandles = 0;
/// Creates an [ImageStreamCompleterHandle] that will prevent this stream from
/// being disposed at least until the handle is disposed.
///
/// Such handles are useful when an image cache needs to keep a completer
/// alive but does not itself have a listener subscribed, or when a widget
/// that displays an image needs to temporarily unsubscribe from the completer
/// but may re-subscribe in the future, for example when the [TickerMode]
/// changes.
ImageStreamCompleterHandle keepAlive() {
_checkDisposed();
return ImageStreamCompleterHandle._(this);
}
/// Stops the specified [listener] from receiving image stream events.
///
/// If [listener] has been added multiple times, this removes the _first_
/// instance of the listener.
///
/// Once all listeners have been removed and all [keepAlive] handles have been
/// disposed, this image stream is no longer usable.
void removeListener(ImageStreamListener listener) {
_checkDisposed();
for (int i = 0; i < _listeners.length; i += 1) {
if (_listeners[i] == listener) {
_listeners.removeAt(i);
break;
}
}
if (_listeners.isEmpty) {
final List<VoidCallback> callbacks = _onLastListenerRemovedCallbacks.toList();
for (final VoidCallback callback in callbacks) {
callback();
}
_onLastListenerRemovedCallbacks.clear();
_maybeDispose();
}
}
bool _disposed = false;
@mustCallSuper
void _maybeDispose() {
if (!_hadAtLeastOneListener || _disposed || _listeners.isNotEmpty || _keepAliveHandles != 0) {
return;
}
_ephemeralErrorListeners.clear();
_currentImage?.dispose();
_currentImage = null;
_disposed = true;
}
void _checkDisposed() {
if (_disposed) {
throw StateError(
'Stream has been disposed.\n'
'An ImageStream is considered disposed once at least one listener has '
'been added and subsequently all listeners have been removed and no '
'handles are outstanding from the keepAlive method.\n'
'To resolve this error, maintain at least one listener on the stream, '
'or create an ImageStreamCompleterHandle from the keepAlive '
'method, or create a new stream for the image.',
);
}
}
final List<VoidCallback> _onLastListenerRemovedCallbacks = <VoidCallback>[];
/// Adds a callback to call when [removeListener] results in an empty
/// list of listeners and there are no [keepAlive] handles outstanding.
///
/// This callback will never fire if [removeListener] is never called.
void addOnLastListenerRemovedCallback(VoidCallback callback) {
_checkDisposed();
_onLastListenerRemovedCallbacks.add(callback);
}
/// Removes a callback previously supplied to
/// [addOnLastListenerRemovedCallback].
void removeOnLastListenerRemovedCallback(VoidCallback callback) {
_checkDisposed();
_onLastListenerRemovedCallbacks.remove(callback);
}
/// Calls all the registered listeners to notify them of a new image.
@protected
@pragma('vm:notify-debugger-on-exception')
void setImage(ImageInfo image) {
_checkDisposed();
_currentImage?.dispose();
_currentImage = image;
_ephemeralErrorListeners.clear();
if (_listeners.isEmpty) {
return;
}
// Make a copy to allow for concurrent modification.
final List<ImageStreamListener> localListeners =
List<ImageStreamListener>.of(_listeners);
for (final ImageStreamListener listener in localListeners) {
try {
listener.onImage(image.clone(), false);
} catch (exception, stack) {
reportError(
context: ErrorDescription('by an image listener'),
exception: exception,
stack: stack,
);
}
}
}
/// Calls all the registered error listeners to notify them of an error that
/// occurred while resolving the image.
///
/// If no error listeners (listeners with an [ImageStreamListener.onError]
/// specified) are attached, or if the handlers all rethrow the exception
/// verbatim (with `throw exception`), a [FlutterError] will be reported using
/// [FlutterError.reportError].
///
/// The `context` should be a string describing where the error was caught, in
/// a form that will make sense in English when following the word "thrown",
/// as in "thrown while obtaining the image from the network" (for the context
/// "while obtaining the image from the network").
///
/// The `exception` is the error being reported; the `stack` is the
/// [StackTrace] associated with the exception.
///
/// The `informationCollector` is a callback (of type [InformationCollector])
/// that is called when the exception is used by [FlutterError.reportError].
/// It is used to obtain further details to include in the logs, which may be
/// expensive to collect, and thus should only be collected if the error is to
/// be logged in the first place.
///
/// The `silent` argument causes the exception to not be reported to the logs
/// in release builds, if passed to [FlutterError.reportError]. (It is still
/// sent to error handlers.) It should be set to true if the error is one that
/// is expected to be encountered in release builds, for example network
/// errors. That way, logs on end-user devices will not have spurious
/// messages, but errors during development will still be reported.
///
/// See [FlutterErrorDetails] for further details on these values.
@pragma('vm:notify-debugger-on-exception')
void reportError({
DiagnosticsNode? context,
required Object exception,
StackTrace? stack,
InformationCollector? informationCollector,
bool silent = false,
}) {
_currentError = FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'image resource service',
context: context,
informationCollector: informationCollector,
silent: silent,
);
// Make a copy to allow for concurrent modification.
final List<ImageErrorListener> localErrorListeners = <ImageErrorListener>[
..._listeners
.map<ImageErrorListener?>((ImageStreamListener listener) => listener.onError)
.whereType<ImageErrorListener>(),
..._ephemeralErrorListeners,
];
_ephemeralErrorListeners.clear();
bool handled = false;
for (final ImageErrorListener errorListener in localErrorListeners) {
try {
errorListener(exception, stack);
handled = true;
} catch (newException, newStack) {
if (newException != exception) {
FlutterError.reportError(
FlutterErrorDetails(
context: ErrorDescription('when reporting an error to an image listener'),
library: 'image resource service',
exception: newException,
stack: newStack,
),
);
}
}
}
if (!handled) {
FlutterError.reportError(_currentError!);
}
}
/// Calls all the registered [ImageChunkListener]s (listeners with an
/// [ImageStreamListener.onChunk] specified) to notify them of a new
/// [ImageChunkEvent].
@protected
void reportImageChunkEvent(ImageChunkEvent event) {
_checkDisposed();
if (hasListeners) {
// Make a copy to allow for concurrent modification.
final List<ImageChunkListener> localListeners = _listeners
.map<ImageChunkListener?>((ImageStreamListener listener) => listener.onChunk)
.whereType<ImageChunkListener>()
.toList();
for (final ImageChunkListener listener in localListeners) {
listener(event);
}
}
}
/// Accumulates a list of strings describing the object's state. Subclasses
/// should override this to have their information included in [toString].
@override
void debugFillProperties(DiagnosticPropertiesBuilder description) {
super.debugFillProperties(description);
description.add(DiagnosticsProperty<ImageInfo>('current', _currentImage, ifNull: 'unresolved', showName: false));
description.add(ObjectFlagProperty<List<ImageStreamListener>>(
'listeners',
_listeners,
ifPresent: '${_listeners.length} listener${_listeners.length == 1 ? "" : "s" }',
));
description.add(ObjectFlagProperty<List<ImageErrorListener>>(
'ephemeralErrorListeners',
_ephemeralErrorListeners,
ifPresent: '${_ephemeralErrorListeners.length} ephemeralErrorListener${_ephemeralErrorListeners.length == 1 ? "" : "s" }',
));
description.add(FlagProperty('disposed', value: _disposed, ifTrue: '<disposed>'));
}
}
/// Manages the loading of [dart:ui.Image] objects for static [ImageStream]s (those
/// with only one frame).
class OneFrameImageStreamCompleter extends ImageStreamCompleter {
/// Creates a manager for one-frame [ImageStream]s.
///
/// The image resource awaits the given [Future]. When the future resolves,
/// it notifies the [ImageListener]s that have been registered with
/// [addListener].
///
/// The [InformationCollector], if provided, is invoked if the given [Future]
/// resolves with an error, and can be used to supplement the reported error
/// message (for example, giving the image's URL).
///
/// Errors are reported using [FlutterError.reportError] with the `silent`
/// argument on [FlutterErrorDetails] set to true, meaning that by default the
/// message is only dumped to the console in debug mode (see [
/// FlutterErrorDetails]).
OneFrameImageStreamCompleter(Future<ImageInfo> image, { InformationCollector? informationCollector }) {
image.then<void>(setImage, onError: (Object error, StackTrace stack) {
reportError(
context: ErrorDescription('resolving a single-frame image stream'),
exception: error,
stack: stack,
informationCollector: informationCollector,
silent: true,
);
});
}
}
/// Manages the decoding and scheduling of image frames.
///
/// New frames will only be emitted while there are registered listeners to the
/// stream (registered with [addListener]).
///
/// This class deals with 2 types of frames:
///
/// * image frames - image frames of an animated image.
/// * app frames - frames that the flutter engine is drawing to the screen to
/// show the app GUI.
///
/// For single frame images the stream will only complete once.
///
/// For animated images, this class eagerly decodes the next image frame,
/// and notifies the listeners that a new frame is ready on the first app frame
/// that is scheduled after the image frame duration has passed.
///
/// Scheduling new timers only from scheduled app frames, makes sure we pause
/// the animation when the app is not visible (as new app frames will not be
/// scheduled).
///
/// See the following timeline example:
///
/// | Time | Event | Comment |
/// |------|--------------------------------------------|---------------------------|
/// | t1 | App frame scheduled (image frame A posted) | |
/// | t2 | App frame scheduled | |
/// | t3 | App frame scheduled | |
/// | t4 | Image frame B decoded | |
/// | t5 | App frame scheduled | t5 - t1 < frameB_duration |
/// | t6 | App frame scheduled (image frame B posted) | t6 - t1 > frameB_duration |
///
class MultiFrameImageStreamCompleter extends ImageStreamCompleter {
/// Creates a image stream completer.
///
/// Immediately starts decoding the first image frame when the codec is ready.
///
/// The `codec` parameter is a future for an initialized [ui.Codec] that will
/// be used to decode the image.
///
/// The `scale` parameter is the linear scale factor for drawing this frames
/// of this image at their intended size.
///
/// The `tag` parameter is passed on to created [ImageInfo] objects to
/// help identify the source of the image.
///
/// The `chunkEvents` parameter is an optional stream of notifications about
/// the loading progress of the image. If this stream is provided, the events
/// produced by the stream will be delivered to registered [ImageChunkListener]s
/// (see [addListener]).
MultiFrameImageStreamCompleter({
required Future<ui.Codec> codec,
required double scale,
String? debugLabel,
Stream<ImageChunkEvent>? chunkEvents,
InformationCollector? informationCollector,
}) : _informationCollector = informationCollector,
_scale = scale {
this.debugLabel = debugLabel;
codec.then<void>(_handleCodecReady, onError: (Object error, StackTrace stack) {
reportError(
context: ErrorDescription('resolving an image codec'),
exception: error,
stack: stack,
informationCollector: informationCollector,
silent: true,
);
});
if (chunkEvents != null) {
_chunkSubscription = chunkEvents.listen(reportImageChunkEvent,
onError: (Object error, StackTrace stack) {
reportError(
context: ErrorDescription('loading an image'),
exception: error,
stack: stack,
informationCollector: informationCollector,
silent: true,
);
},
);
}
}
StreamSubscription<ImageChunkEvent>? _chunkSubscription;
ui.Codec? _codec;
final double _scale;
final InformationCollector? _informationCollector;
ui.FrameInfo? _nextFrame;
// When the current was first shown.
late Duration _shownTimestamp;
// The requested duration for the current frame;
Duration? _frameDuration;
// How many frames have been emitted so far.
int _framesEmitted = 0;
Timer? _timer;
// Used to guard against registering multiple _handleAppFrame callbacks for the same frame.
bool _frameCallbackScheduled = false;
void _handleCodecReady(ui.Codec codec) {
_codec = codec;
assert(_codec != null);
if (hasListeners) {
_decodeNextFrameAndSchedule();
}
}
void _handleAppFrame(Duration timestamp) {
_frameCallbackScheduled = false;
if (!hasListeners) {
return;
}
assert(_nextFrame != null);
if (_isFirstFrame() || _hasFrameDurationPassed(timestamp)) {
_emitFrame(ImageInfo(
image: _nextFrame!.image.clone(),
scale: _scale,
debugLabel: debugLabel,
));
_shownTimestamp = timestamp;
_frameDuration = _nextFrame!.duration;
_nextFrame!.image.dispose();
_nextFrame = null;
final int completedCycles = _framesEmitted ~/ _codec!.frameCount;
if (_codec!.repetitionCount == -1 || completedCycles <= _codec!.repetitionCount) {
_decodeNextFrameAndSchedule();
}
return;
}
final Duration delay = _frameDuration! - (timestamp - _shownTimestamp);
_timer = Timer(delay * timeDilation, () {
_scheduleAppFrame();
});
}
bool _isFirstFrame() {
return _frameDuration == null;
}
bool _hasFrameDurationPassed(Duration timestamp) {
return timestamp - _shownTimestamp >= _frameDuration!;
}
Future<void> _decodeNextFrameAndSchedule() async {
// This will be null if we gave it away. If not, it's still ours and it
// must be disposed of.
_nextFrame?.image.dispose();
_nextFrame = null;
try {
_nextFrame = await _codec!.getNextFrame();
} catch (exception, stack) {
reportError(
context: ErrorDescription('resolving an image frame'),
exception: exception,
stack: stack,
informationCollector: _informationCollector,
silent: true,
);
return;
}
if (_codec!.frameCount == 1) {
// ImageStreamCompleter listeners removed while waiting for next frame to
// be decoded.
// There's no reason to emit the frame without active listeners.
if (!hasListeners) {
return;
}
// This is not an animated image, just return it and don't schedule more
// frames.
_emitFrame(ImageInfo(
image: _nextFrame!.image.clone(),
scale: _scale,
debugLabel: debugLabel,
));
_nextFrame!.image.dispose();
_nextFrame = null;
return;
}
_scheduleAppFrame();
}
void _scheduleAppFrame() {
if (_frameCallbackScheduled) {
return;
}
_frameCallbackScheduled = true;
SchedulerBinding.instance.scheduleFrameCallback(_handleAppFrame);
}
void _emitFrame(ImageInfo imageInfo) {
setImage(imageInfo);
_framesEmitted += 1;
}
@override
void addListener(ImageStreamListener listener) {
if (!hasListeners && _codec != null && (_currentImage == null || _codec!.frameCount > 1)) {
_decodeNextFrameAndSchedule();
}
super.addListener(listener);
}
@override
void removeListener(ImageStreamListener listener) {
super.removeListener(listener);
if (!hasListeners) {
_timer?.cancel();
_timer = null;
}
}
@override
void _maybeDispose() {
super._maybeDispose();
if (_disposed) {
_chunkSubscription?.onData(null);
_chunkSubscription?.cancel();
_chunkSubscription = null;
}
}
}
| flutter/packages/flutter/lib/src/painting/image_stream.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/image_stream.dart",
"repo_id": "flutter",
"token_count": 13416
} | 243 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show Locale, LocaleStringAttribute, ParagraphBuilder, SpellOutStringAttribute, StringAttribute;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'basic_types.dart';
import 'inline_span.dart';
import 'text_painter.dart';
import 'text_scaler.dart';
// Examples can assume:
// late TextSpan myTextSpan;
/// An immutable span of text.
///
/// A [TextSpan] object can be styled using its [style] property. The style will
/// be applied to the [text] and the [children].
///
/// A [TextSpan] object can just have plain text, or it can have children
/// [TextSpan] objects with their own styles that (possibly only partially)
/// override the [style] of this object. If a [TextSpan] has both [text] and
/// [children], then the [text] is treated as if it was an un-styled [TextSpan]
/// at the start of the [children] list. Leaving the [TextSpan.text] field null
/// results in the [TextSpan] acting as an empty node in the [InlineSpan] tree
/// with a list of children.
///
/// To paint a [TextSpan] on a [Canvas], use a [TextPainter]. To display a text
/// span in a widget, use a [RichText]. For text with a single style, consider
/// using the [Text] widget.
///
/// {@tool snippet}
///
/// The text "Hello world!", in black:
///
/// ```dart
/// const TextSpan(
/// text: 'Hello world!',
/// style: TextStyle(color: Colors.black),
/// )
/// ```
/// {@end-tool}
///
/// _There is some more detailed sample code in the documentation for the
/// [recognizer] property._
///
/// The [TextSpan.text] will be used as the semantics label unless overridden
/// by the [TextSpan.semanticsLabel] property. Any [PlaceholderSpan]s in the
/// [TextSpan.children] list will separate the text before and after it into two
/// semantics nodes.
///
/// See also:
///
/// * [WidgetSpan], a leaf node that represents an embedded inline widget in an
/// [InlineSpan] tree. Specify a widget within the [children] list by
/// wrapping the widget with a [WidgetSpan]. The widget will be laid out
/// inline within the paragraph.
/// * [Text], a widget for showing uniformly-styled text.
/// * [RichText], a widget for finer control of text rendering.
/// * [TextPainter], a class for painting [TextSpan] objects on a [Canvas].
@immutable
class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotation {
/// Creates a [TextSpan] with the given values.
///
/// For the object to be useful, at least one of [text] or
/// [children] should be set.
const TextSpan({
this.text,
this.children,
super.style,
this.recognizer,
MouseCursor? mouseCursor,
this.onEnter,
this.onExit,
this.semanticsLabel,
this.locale,
this.spellOut,
}) : mouseCursor = mouseCursor ??
(recognizer == null ? MouseCursor.defer : SystemMouseCursors.click),
assert(!(text == null && semanticsLabel != null));
/// The text contained in this span.
///
/// If both [text] and [children] are non-null, the text will precede the
/// children.
///
/// This getter does not include the contents of its children.
final String? text;
/// Additional spans to include as children.
///
/// If both [text] and [children] are non-null, the text will precede the
/// children.
///
/// Modifying the list after the [TextSpan] has been created is not supported
/// and may have unexpected results.
///
/// The list must not contain any nulls.
final List<InlineSpan>? children;
/// A gesture recognizer that will receive events that hit this span.
///
/// [InlineSpan] itself does not implement hit testing or event dispatch. The
/// object that manages the [InlineSpan] painting is also responsible for
/// dispatching events. In the rendering library, that is the
/// [RenderParagraph] object, which corresponds to the [RichText] widget in
/// the widgets layer; these objects do not bubble events in [InlineSpan]s,
/// so a [recognizer] is only effective for events that directly hit the
/// [text] of that [InlineSpan], not any of its [children].
///
/// [InlineSpan] also does not manage the lifetime of the gesture recognizer.
/// The code that owns the [GestureRecognizer] object must call
/// [GestureRecognizer.dispose] when the [InlineSpan] object is no longer
/// used.
///
/// {@tool snippet}
///
/// This example shows how to manage the lifetime of a gesture recognizer
/// provided to an [InlineSpan] object. It defines a `BuzzingText` widget
/// which uses the [HapticFeedback] class to vibrate the device when the user
/// long-presses the "find the" span, which is underlined in wavy green. The
/// hit-testing is handled by the [RichText] widget. It also changes the
/// hovering mouse cursor to `precise`.
///
/// ```dart
/// class BuzzingText extends StatefulWidget {
/// const BuzzingText({super.key});
///
/// @override
/// State<BuzzingText> createState() => _BuzzingTextState();
/// }
///
/// class _BuzzingTextState extends State<BuzzingText> {
/// late LongPressGestureRecognizer _longPressRecognizer;
///
/// @override
/// void initState() {
/// super.initState();
/// _longPressRecognizer = LongPressGestureRecognizer()
/// ..onLongPress = _handlePress;
/// }
///
/// @override
/// void dispose() {
/// _longPressRecognizer.dispose();
/// super.dispose();
/// }
///
/// void _handlePress() {
/// HapticFeedback.vibrate();
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// return Text.rich(
/// TextSpan(
/// text: 'Can you ',
/// style: const TextStyle(color: Colors.black),
/// children: <InlineSpan>[
/// TextSpan(
/// text: 'find the',
/// style: const TextStyle(
/// color: Colors.green,
/// decoration: TextDecoration.underline,
/// decorationStyle: TextDecorationStyle.wavy,
/// ),
/// recognizer: _longPressRecognizer,
/// mouseCursor: SystemMouseCursors.precise,
/// ),
/// const TextSpan(
/// text: ' secret?',
/// ),
/// ],
/// ),
/// );
/// }
/// }
/// ```
/// {@end-tool}
final GestureRecognizer? recognizer;
/// Mouse cursor when the mouse hovers over this span.
///
/// The default value is [SystemMouseCursors.click] if [recognizer] is not
/// null, or [MouseCursor.defer] otherwise.
///
/// [TextSpan] itself does not implement hit testing or cursor changing.
/// The object that manages the [TextSpan] painting is responsible
/// to return the [TextSpan] in its hit test, as well as providing the
/// correct mouse cursor when the [TextSpan]'s mouse cursor is
/// [MouseCursor.defer].
final MouseCursor mouseCursor;
@override
final PointerEnterEventListener? onEnter;
@override
final PointerExitEventListener? onExit;
/// Returns the value of [mouseCursor].
///
/// This field, required by [MouseTrackerAnnotation], is hidden publicly to
/// avoid the confusion as a text cursor.
@protected
@override
MouseCursor get cursor => mouseCursor;
/// An alternative semantics label for this [TextSpan].
///
/// If present, the semantics of this span will contain this value instead
/// of the actual text.
///
/// This is useful for replacing abbreviations or shorthands with the full
/// text value:
///
/// ```dart
/// const TextSpan(text: r'$$', semanticsLabel: 'Double dollars')
/// ```
final String? semanticsLabel;
/// The language of the text in this span and its span children.
///
/// Setting the locale of this text span affects the way that assistive
/// technologies, such as VoiceOver or TalkBack, pronounce the text.
///
/// If this span contains other text span children, they also inherit the
/// locale from this span unless explicitly set to different locales.
final ui.Locale? locale;
/// Whether the assistive technologies should spell out this text character
/// by character.
///
/// If the text is 'hello world', setting this to true causes the assistive
/// technologies, such as VoiceOver or TalkBack, to pronounce
/// 'h-e-l-l-o-space-w-o-r-l-d' instead of complete words. This is useful for
/// texts, such as passwords or verification codes.
///
/// If this span contains other text span children, they also inherit the
/// property from this span unless explicitly set.
///
/// If the property is not set, this text span inherits the spell out setting
/// from its parent. If this text span does not have a parent or the parent
/// does not have a spell out setting, this text span does not spell out the
/// text by default.
final bool? spellOut;
@override
bool get validForMouseTracker => true;
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
if (event is PointerDownEvent) {
recognizer?.addPointer(event);
}
}
/// Apply the [style], [text], and [children] of this object to the
/// given [ParagraphBuilder], from which a [Paragraph] can be obtained.
/// [Paragraph] objects can be drawn on [Canvas] objects.
///
/// Rather than using this directly, it's simpler to use the
/// [TextPainter] class to paint [TextSpan] objects onto [Canvas]
/// objects.
@override
void build(
ui.ParagraphBuilder builder, {
TextScaler textScaler = TextScaler.noScaling,
List<PlaceholderDimensions>? dimensions,
}) {
assert(debugAssertIsValid());
final bool hasStyle = style != null;
if (hasStyle) {
builder.pushStyle(style!.getTextStyle(textScaler: textScaler));
}
if (text != null) {
try {
builder.addText(text!);
} on ArgumentError catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'painting library',
context: ErrorDescription('while building a TextSpan'),
silent: true,
));
// Use a Unicode replacement character as a substitute for invalid text.
builder.addText('\uFFFD');
}
}
final List<InlineSpan>? children = this.children;
if (children != null) {
for (final InlineSpan child in children) {
child.build(
builder,
textScaler: textScaler,
dimensions: dimensions,
);
}
}
if (hasStyle) {
builder.pop();
}
}
/// Walks this [TextSpan] and its descendants in pre-order and calls [visitor]
/// for each span that has text.
///
/// When `visitor` returns true, the walk will continue. When `visitor`
/// returns false, then the walk will end.
@override
bool visitChildren(InlineSpanVisitor visitor) {
if (text != null && !visitor(this)) {
return false;
}
final List<InlineSpan>? children = this.children;
if (children != null) {
for (final InlineSpan child in children) {
if (!child.visitChildren(visitor)) {
return false;
}
}
}
return true;
}
@override
bool visitDirectChildren(InlineSpanVisitor visitor) {
final List<InlineSpan>? children = this.children;
if (children != null) {
for (final InlineSpan child in children) {
if (!visitor(child)) {
return false;
}
}
}
return true;
}
/// Returns the text span that contains the given position in the text.
@override
InlineSpan? getSpanForPositionVisitor(TextPosition position, Accumulator offset) {
final String? text = this.text;
if (text == null || text.isEmpty) {
return null;
}
final TextAffinity affinity = position.affinity;
final int targetOffset = position.offset;
final int endOffset = offset.value + text.length;
if (offset.value == targetOffset && affinity == TextAffinity.downstream ||
offset.value < targetOffset && targetOffset < endOffset ||
endOffset == targetOffset && affinity == TextAffinity.upstream) {
return this;
}
offset.increment(text.length);
return null;
}
@override
void computeToPlainText(
StringBuffer buffer, {
bool includeSemanticsLabels = true,
bool includePlaceholders = true,
}) {
assert(debugAssertIsValid());
if (semanticsLabel != null && includeSemanticsLabels) {
buffer.write(semanticsLabel);
} else if (text != null) {
buffer.write(text);
}
if (children != null) {
for (final InlineSpan child in children!) {
child.computeToPlainText(buffer,
includeSemanticsLabels: includeSemanticsLabels,
includePlaceholders: includePlaceholders,
);
}
}
}
@override
void computeSemanticsInformation(
List<InlineSpanSemanticsInformation> collector, {
ui.Locale? inheritedLocale,
bool inheritedSpellOut = false,
}) {
assert(debugAssertIsValid());
final ui.Locale? effectiveLocale = locale ?? inheritedLocale;
final bool effectiveSpellOut = spellOut ?? inheritedSpellOut;
if (text != null) {
final int textLength = semanticsLabel?.length ?? text!.length;
collector.add(InlineSpanSemanticsInformation(
text!,
stringAttributes: <ui.StringAttribute>[
if (effectiveSpellOut && textLength > 0)
ui.SpellOutStringAttribute(range: TextRange(start: 0, end: textLength)),
if (effectiveLocale != null && textLength > 0)
ui.LocaleStringAttribute(locale: effectiveLocale, range: TextRange(start: 0, end: textLength)),
],
semanticsLabel: semanticsLabel,
recognizer: recognizer,
));
}
final List<InlineSpan>? children = this.children;
if (children != null) {
for (final InlineSpan child in children) {
if (child is TextSpan) {
child.computeSemanticsInformation(
collector,
inheritedLocale: effectiveLocale,
inheritedSpellOut: effectiveSpellOut,
);
} else {
child.computeSemanticsInformation(collector);
}
}
}
}
@override
int? codeUnitAtVisitor(int index, Accumulator offset) {
final String? text = this.text;
if (text == null) {
return null;
}
final int localOffset = index - offset.value;
assert(localOffset >= 0);
offset.increment(text.length);
return localOffset < text.length ? text.codeUnitAt(localOffset) : null;
}
/// In debug mode, throws an exception if the object is not in a valid
/// configuration. Otherwise, returns true.
///
/// This is intended to be used as follows:
///
/// ```dart
/// assert(myTextSpan.debugAssertIsValid());
/// ```
@override
bool debugAssertIsValid() {
assert(() {
if (children != null) {
for (final InlineSpan child in children!) {
assert(child.debugAssertIsValid());
}
}
return true;
}());
return super.debugAssertIsValid();
}
@override
RenderComparison compareTo(InlineSpan other) {
if (identical(this, other)) {
return RenderComparison.identical;
}
if (other.runtimeType != runtimeType) {
return RenderComparison.layout;
}
final TextSpan textSpan = other as TextSpan;
if (textSpan.text != text ||
children?.length != textSpan.children?.length ||
(style == null) != (textSpan.style == null)) {
return RenderComparison.layout;
}
RenderComparison result = recognizer == textSpan.recognizer ?
RenderComparison.identical :
RenderComparison.metadata;
if (style != null) {
final RenderComparison candidate = style!.compareTo(textSpan.style!);
if (candidate.index > result.index) {
result = candidate;
}
if (result == RenderComparison.layout) {
return result;
}
}
if (children != null) {
for (int index = 0; index < children!.length; index += 1) {
final RenderComparison candidate = children![index].compareTo(textSpan.children![index]);
if (candidate.index > result.index) {
result = candidate;
}
if (result == RenderComparison.layout) {
return result;
}
}
}
return result;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
if (super != other) {
return false;
}
return other is TextSpan
&& other.text == text
&& other.recognizer == recognizer
&& other.semanticsLabel == semanticsLabel
&& onEnter == other.onEnter
&& onExit == other.onExit
&& mouseCursor == other.mouseCursor
&& listEquals<InlineSpan>(other.children, children);
}
@override
int get hashCode => Object.hash(
super.hashCode,
text,
recognizer,
semanticsLabel,
onEnter,
onExit,
mouseCursor,
children == null ? null : Object.hashAll(children!),
);
@override
String toStringShort() => objectRuntimeType(this, 'TextSpan');
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(
StringProperty(
'text',
text,
showName: false,
defaultValue: null,
),
);
if (style == null && text == null && children == null) {
properties.add(DiagnosticsNode.message('(empty)'));
}
properties.add(DiagnosticsProperty<GestureRecognizer>(
'recognizer', recognizer,
description: recognizer?.runtimeType.toString(),
defaultValue: null,
));
properties.add(FlagsSummary<Function?>(
'callbacks',
<String, Function?> {
'enter': onEnter,
'exit': onExit,
},
));
properties.add(DiagnosticsProperty<MouseCursor>('mouseCursor', cursor, defaultValue: MouseCursor.defer));
if (semanticsLabel != null) {
properties.add(StringProperty('semanticsLabel', semanticsLabel));
}
}
@override
List<DiagnosticsNode> debugDescribeChildren() {
return children?.map<DiagnosticsNode>((InlineSpan child) {
return child.toDiagnosticsNode();
}).toList() ?? const <DiagnosticsNode>[];
}
}
| flutter/packages/flutter/lib/src/painting/text_span.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/text_span.dart",
"repo_id": "flutter",
"token_count": 6600
} | 244 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'object.dart';
import 'proxy_box.dart';
import 'proxy_sliver.dart';
import 'sliver.dart';
/// Paints a [Decoration] either before or after its child paints.
///
/// If the child has infinite scroll extent, then the [Decoration] paints itself up to the
/// bottom cache extent.
class RenderDecoratedSliver extends RenderProxySliver {
/// Creates a decorated sliver.
///
/// The [decoration], [position], and [configuration] arguments must not be
/// null. By default the decoration paints behind the child.
///
/// The [ImageConfiguration] will be passed to the decoration (with the size
/// filled in) to let it resolve images.
RenderDecoratedSliver({
required Decoration decoration,
DecorationPosition position = DecorationPosition.background,
ImageConfiguration configuration = ImageConfiguration.empty,
}) : _decoration = decoration,
_position = position,
_configuration = configuration;
/// What decoration to paint.
///
/// Commonly a [BoxDecoration].
Decoration get decoration => _decoration;
Decoration _decoration;
set decoration(Decoration value) {
if (value == decoration) {
return;
}
_decoration = value;
_painter?.dispose();
_painter = decoration.createBoxPainter(markNeedsPaint);
markNeedsPaint();
}
/// Whether to paint the box decoration behind or in front of the child.
DecorationPosition get position => _position;
DecorationPosition _position;
set position(DecorationPosition value) {
if (value == position) {
return;
}
_position = value;
markNeedsPaint();
}
/// The settings to pass to the decoration when painting, so that it can
/// resolve images appropriately. See [ImageProvider.resolve] and
/// [BoxPainter.paint].
///
/// The [ImageConfiguration.textDirection] field is also used by
/// direction-sensitive [Decoration]s for painting and hit-testing.
ImageConfiguration get configuration => _configuration;
ImageConfiguration _configuration;
set configuration(ImageConfiguration value) {
if (value == configuration) {
return;
}
_configuration = value;
markNeedsPaint();
}
BoxPainter? _painter;
@override
void attach(covariant PipelineOwner owner) {
_painter = decoration.createBoxPainter(markNeedsPaint);
super.attach(owner);
}
@override
void detach() {
_painter?.dispose();
_painter = null;
super.detach();
}
@override
void dispose() {
_painter?.dispose();
_painter = null;
super.dispose();
}
@override
void paint(PaintingContext context, Offset offset) {
if (child == null || !child!.geometry!.visible) {
return;
}
// In the case where the child sliver has infinite scroll extent, the decoration
// should only extend down to the bottom cache extent.
final double cappedMainAxisExtent = child!.geometry!.scrollExtent.isInfinite
? constraints.scrollOffset + child!.geometry!.cacheExtent + constraints.cacheOrigin
: child!.geometry!.scrollExtent;
final (Size childSize, Offset scrollOffset) = switch (constraints.axis) {
Axis.horizontal => (Size(cappedMainAxisExtent, constraints.crossAxisExtent), Offset(-constraints.scrollOffset, 0.0)),
Axis.vertical => (Size(constraints.crossAxisExtent, cappedMainAxisExtent), Offset(0.0, -constraints.scrollOffset)),
};
offset += (child!.parentData! as SliverPhysicalParentData).paintOffset;
void paintDecoration() => _painter!.paint(context.canvas, offset + scrollOffset, configuration.copyWith(size: childSize));
switch (position) {
case DecorationPosition.background:
paintDecoration();
context.paintChild(child!, offset);
case DecorationPosition.foreground:
context.paintChild(child!, offset);
paintDecoration();
}
}
}
| flutter/packages/flutter/lib/src/rendering/decorated_sliver.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/decorated_sliver.dart",
"repo_id": "flutter",
"token_count": 1278
} | 245 |
// Copyright 2014 The Flutter Authors. 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 'dart:ui' as ui show Color;
import 'package:flutter/animation.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/semantics.dart';
import 'layer.dart';
import 'object.dart';
import 'proxy_box.dart';
import 'sliver.dart';
/// A base class for sliver render objects that resemble their children.
///
/// A proxy sliver has a single child and mimics all the properties of
/// that child by calling through to the child for each function in the render
/// sliver protocol. For example, a proxy sliver determines its geometry by
/// asking its sliver child to layout with the same constraints and then
/// matching the geometry.
///
/// A proxy sliver isn't useful on its own because you might as well just
/// replace the proxy sliver with its child. However, RenderProxySliver is a
/// useful base class for render objects that wish to mimic most, but not all,
/// of the properties of their sliver child.
///
/// See also:
///
/// * [RenderProxyBox], a base class for render boxes that resemble their
/// children.
abstract class RenderProxySliver extends RenderSliver with RenderObjectWithChildMixin<RenderSliver> {
/// Creates a proxy render sliver.
///
/// Proxy render slivers aren't created directly because they proxy
/// the render sliver protocol to their sliver [child]. Instead, use one of
/// the subclasses.
RenderProxySliver([RenderSliver? child]) {
this.child = child;
}
@override
void setupParentData(RenderObject child) {
if (child.parentData is! SliverPhysicalParentData) {
child.parentData = SliverPhysicalParentData();
}
}
@override
void performLayout() {
assert(child != null);
child!.layout(constraints, parentUsesSize: true);
geometry = child!.geometry;
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null) {
context.paintChild(child!, offset);
}
}
@override
bool hitTestChildren(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) {
return child != null
&& child!.geometry!.hitTestExtent > 0
&& child!.hitTest(
result,
mainAxisPosition: mainAxisPosition,
crossAxisPosition: crossAxisPosition,
);
}
@override
double childMainAxisPosition(RenderSliver child) {
assert(child == this.child);
return 0.0;
}
@override
void applyPaintTransform(RenderObject child, Matrix4 transform) {
final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData;
childParentData.applyPaintTransform(transform);
}
}
/// Makes its sliver child partially transparent.
///
/// This class paints its sliver child into an intermediate buffer and then
/// blends the sliver child back into the scene, partially transparent.
///
/// For values of opacity other than 0.0 and 1.0, this class is relatively
/// expensive, because it requires painting the sliver child into an intermediate
/// buffer. For the value 0.0, the sliver child is not painted at all.
/// For the value 1.0, the sliver child is painted immediately without an
/// intermediate buffer.
class RenderSliverOpacity extends RenderProxySliver {
/// Creates a partially transparent render object.
///
/// The [opacity] argument must be between 0.0 and 1.0, inclusive.
RenderSliverOpacity({
double opacity = 1.0,
bool alwaysIncludeSemantics = false,
RenderSliver? sliver,
}) : assert(opacity >= 0.0 && opacity <= 1.0),
_opacity = opacity,
_alwaysIncludeSemantics = alwaysIncludeSemantics,
_alpha = ui.Color.getAlphaFromOpacity(opacity) {
child = sliver;
}
@override
bool get alwaysNeedsCompositing => child != null && (_alpha > 0);
int _alpha;
/// The fraction to scale the child's alpha value.
///
/// An opacity of one is fully opaque. An opacity of zero is fully transparent
/// (i.e. invisible).
///
/// Values one and zero are painted with a fast path. Other values require
/// painting the child into an intermediate buffer, which is expensive.
double get opacity => _opacity;
double _opacity;
set opacity(double value) {
assert(value >= 0.0 && value <= 1.0);
if (_opacity == value) {
return;
}
final bool didNeedCompositing = alwaysNeedsCompositing;
final bool wasVisible = _alpha != 0;
_opacity = value;
_alpha = ui.Color.getAlphaFromOpacity(_opacity);
if (didNeedCompositing != alwaysNeedsCompositing) {
markNeedsCompositingBitsUpdate();
}
markNeedsPaint();
if (wasVisible != (_alpha != 0) && !alwaysIncludeSemantics) {
markNeedsSemanticsUpdate();
}
}
/// Whether child semantics are included regardless of the opacity.
///
/// If false, semantics are excluded when [opacity] is 0.0.
///
/// Defaults to false.
bool get alwaysIncludeSemantics => _alwaysIncludeSemantics;
bool _alwaysIncludeSemantics;
set alwaysIncludeSemantics(bool value) {
if (value == _alwaysIncludeSemantics) {
return;
}
_alwaysIncludeSemantics = value;
markNeedsSemanticsUpdate();
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null && child!.geometry!.visible) {
if (_alpha == 0) {
// No need to keep the layer. We'll create a new one if necessary.
layer = null;
return;
}
assert(needsCompositing);
layer = context.pushOpacity(
offset,
_alpha,
super.paint,
oldLayer: layer as OpacityLayer?,
);
assert(() {
layer!.debugCreator = debugCreator;
return true;
}());
}
}
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
if (child != null && (_alpha != 0 || alwaysIncludeSemantics)) {
visitor(child!);
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty('opacity', opacity));
properties.add(FlagProperty('alwaysIncludeSemantics', value: alwaysIncludeSemantics, ifTrue: 'alwaysIncludeSemantics'));
}
}
/// A render object that is invisible during hit testing.
///
/// When [ignoring] is true, this render object (and its subtree) is invisible
/// to hit testing. It still consumes space during layout and paints its sliver
/// child as usual. It just cannot be the target of located events, because its
/// render object returns false from [hitTest].
///
/// ## Semantics
///
/// Using this class may also affect how the semantics subtree underneath is
/// collected.
///
/// {@macro flutter.widgets.IgnorePointer.semantics}
///
/// {@macro flutter.widgets.IgnorePointer.ignoringSemantics}
class RenderSliverIgnorePointer extends RenderProxySliver {
/// Creates a render object that is invisible to hit testing.
RenderSliverIgnorePointer({
RenderSliver? sliver,
bool ignoring = true,
@Deprecated(
'Create a custom sliver ignore pointer widget instead. '
'This feature was deprecated after v3.8.0-12.0.pre.'
)
bool? ignoringSemantics,
}) : _ignoring = ignoring,
_ignoringSemantics = ignoringSemantics {
child = sliver;
}
/// Whether this render object is ignored during hit testing.
///
/// Regardless of whether this render object is ignored during hit testing, it
/// will still consume space during layout and be visible during painting.
///
/// {@macro flutter.widgets.IgnorePointer.semantics}
bool get ignoring => _ignoring;
bool _ignoring;
set ignoring(bool value) {
if (value == _ignoring) {
return;
}
_ignoring = value;
if (ignoringSemantics == null) {
markNeedsSemanticsUpdate();
}
}
/// Whether the semantics of this render object is ignored when compiling the
/// semantics tree.
///
/// {@macro flutter.widgets.IgnorePointer.ignoringSemantics}
@Deprecated(
'Create a custom sliver ignore pointer widget instead. '
'This feature was deprecated after v3.8.0-12.0.pre.'
)
bool? get ignoringSemantics => _ignoringSemantics;
bool? _ignoringSemantics;
set ignoringSemantics(bool? value) {
if (value == _ignoringSemantics) {
return;
}
_ignoringSemantics = value;
markNeedsSemanticsUpdate();
}
@override
bool hitTest(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) {
return !ignoring
&& super.hitTest(
result,
mainAxisPosition: mainAxisPosition,
crossAxisPosition: crossAxisPosition,
);
}
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
if (_ignoringSemantics ?? false) {
return;
}
super.visitChildrenForSemantics(visitor);
}
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
// Do not block user interactions if _ignoringSemantics is false; otherwise,
// delegate to absorbing
config.isBlockingUserActions = ignoring && (_ignoringSemantics ?? true);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<bool>('ignoring', ignoring));
properties.add(
DiagnosticsProperty<bool>(
'ignoringSemantics',
ignoringSemantics,
description: ignoringSemantics == null ? null : 'implicitly $ignoringSemantics',
),
);
}
}
/// Lays the sliver child out as if it was in the tree, but without painting
/// anything, without making the sliver child available for hit testing, and
/// without taking any room in the parent.
class RenderSliverOffstage extends RenderProxySliver {
/// Creates an offstage render object.
RenderSliverOffstage({
bool offstage = true,
RenderSliver? sliver,
}) : _offstage = offstage {
child = sliver;
}
/// Whether the sliver child is hidden from the rest of the tree.
///
/// If true, the sliver child is laid out as if it was in the tree, but
/// without painting anything, without making the sliver child available for
/// hit testing, and without taking any room in the parent.
///
/// If false, the sliver child is included in the tree as normal.
bool get offstage => _offstage;
bool _offstage;
set offstage(bool value) {
if (value == _offstage) {
return;
}
_offstage = value;
markNeedsLayoutForSizedByParentChange();
}
@override
void performLayout() {
assert(child != null);
child!.layout(constraints, parentUsesSize: true);
if (!offstage) {
geometry = child!.geometry;
} else {
geometry = SliverGeometry.zero;
}
}
@override
bool hitTest(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) {
return !offstage && super.hitTest(
result,
mainAxisPosition: mainAxisPosition,
crossAxisPosition: crossAxisPosition,
);
}
@override
bool hitTestChildren(SliverHitTestResult result, {required double mainAxisPosition, required double crossAxisPosition}) {
return !offstage
&& child != null
&& child!.geometry!.hitTestExtent > 0
&& child!.hitTest(
result,
mainAxisPosition: mainAxisPosition,
crossAxisPosition: crossAxisPosition,
);
}
@override
void paint(PaintingContext context, Offset offset) {
if (offstage) {
return;
}
context.paintChild(child!, offset);
}
@override
void visitChildrenForSemantics(RenderObjectVisitor visitor) {
if (offstage) {
return;
}
super.visitChildrenForSemantics(visitor);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<bool>('offstage', offstage));
}
@override
List<DiagnosticsNode> debugDescribeChildren() {
if (child == null) {
return <DiagnosticsNode>[];
}
return <DiagnosticsNode>[
child!.toDiagnosticsNode(
name: 'child',
style: offstage ? DiagnosticsTreeStyle.offstage : DiagnosticsTreeStyle.sparse,
),
];
}
}
/// Makes its sliver child partially transparent, driven from an [Animation].
///
/// This is a variant of [RenderSliverOpacity] that uses an [Animation<double>]
/// rather than a [double] to control the opacity.
class RenderSliverAnimatedOpacity extends RenderProxySliver with RenderAnimatedOpacityMixin<RenderSliver> {
/// Creates a partially transparent render object.
RenderSliverAnimatedOpacity({
required Animation<double> opacity,
bool alwaysIncludeSemantics = false,
RenderSliver? sliver,
}) {
this.opacity = opacity;
this.alwaysIncludeSemantics = alwaysIncludeSemantics;
child = sliver;
}
}
/// Applies a cross-axis constraint to its sliver child.
///
/// This render object takes a [maxExtent] parameter and uses the smaller of
/// [maxExtent] and the parent's [SliverConstraints.crossAxisExtent] as the
/// cross axis extent of the [SliverConstraints] passed to the sliver child.
class RenderSliverConstrainedCrossAxis extends RenderProxySliver {
/// Creates a render object that constrains the cross axis extent of its sliver child.
///
/// The [maxExtent] parameter must be nonnegative.
RenderSliverConstrainedCrossAxis({
required double maxExtent
}) : _maxExtent = maxExtent,
assert(maxExtent >= 0.0);
/// The cross axis extent to apply to the sliver child.
///
/// This value must be nonnegative.
double get maxExtent => _maxExtent;
double _maxExtent;
set maxExtent(double value) {
if (_maxExtent == value) {
return;
}
_maxExtent = value;
markNeedsLayout();
}
@override
void performLayout() {
assert(child != null);
assert(maxExtent >= 0.0);
child!.layout(
constraints.copyWith(crossAxisExtent: min(_maxExtent, constraints.crossAxisExtent)),
parentUsesSize: true,
);
final SliverGeometry childLayoutGeometry = child!.geometry!;
geometry = childLayoutGeometry.copyWith(crossAxisExtent: min(_maxExtent, constraints.crossAxisExtent));
}
}
| flutter/packages/flutter/lib/src/rendering/proxy_sliver.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/proxy_sliver.dart",
"repo_id": "flutter",
"token_count": 4706
} | 246 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart' hide Border;
/// Border specification for [Table] widgets.
///
/// This is like [Border], with the addition of two sides: the inner horizontal
/// borders between rows and the inner vertical borders between columns.
///
/// The sides are represented by [BorderSide] objects.
@immutable
class TableBorder {
/// Creates a border for a table.
///
/// All the sides of the border default to [BorderSide.none].
const TableBorder({
this.top = BorderSide.none,
this.right = BorderSide.none,
this.bottom = BorderSide.none,
this.left = BorderSide.none,
this.horizontalInside = BorderSide.none,
this.verticalInside = BorderSide.none,
this.borderRadius = BorderRadius.zero,
});
/// A uniform border with all sides the same color and width.
///
/// The sides default to black solid borders, one logical pixel wide.
factory TableBorder.all({
Color color = const Color(0xFF000000),
double width = 1.0,
BorderStyle style = BorderStyle.solid,
BorderRadius borderRadius = BorderRadius.zero,
}) {
final BorderSide side = BorderSide(color: color, width: width, style: style);
return TableBorder(top: side, right: side, bottom: side, left: side, horizontalInside: side, verticalInside: side, borderRadius: borderRadius);
}
/// Creates a border for a table where all the interior sides use the same
/// styling and all the exterior sides use the same styling.
const TableBorder.symmetric({
BorderSide inside = BorderSide.none,
BorderSide outside = BorderSide.none,
this.borderRadius = BorderRadius.zero,
}) : top = outside,
right = outside,
bottom = outside,
left = outside,
horizontalInside = inside,
verticalInside = inside;
/// The top side of this border.
final BorderSide top;
/// The right side of this border.
final BorderSide right;
/// The bottom side of this border.
final BorderSide bottom;
/// The left side of this border.
final BorderSide left;
/// The horizontal interior sides of this border.
final BorderSide horizontalInside;
/// The vertical interior sides of this border.
final BorderSide verticalInside;
/// The [BorderRadius] to use when painting the corners of this border.
///
/// It is also applied to [DataTable]'s [Material].
final BorderRadius borderRadius;
/// The widths of the sides of this border represented as an [EdgeInsets].
///
/// This can be used, for example, with a [Padding] widget to inset a box by
/// the size of these borders.
EdgeInsets get dimensions {
return EdgeInsets.fromLTRB(left.width, top.width, right.width, bottom.width);
}
/// Whether all the sides of the border (outside and inside) are identical.
/// Uniform borders are typically more efficient to paint.
bool get isUniform {
final Color topColor = top.color;
if (right.color != topColor ||
bottom.color != topColor ||
left.color != topColor ||
horizontalInside.color != topColor ||
verticalInside.color != topColor) {
return false;
}
final double topWidth = top.width;
if (right.width != topWidth ||
bottom.width != topWidth ||
left.width != topWidth ||
horizontalInside.width != topWidth ||
verticalInside.width != topWidth) {
return false;
}
final BorderStyle topStyle = top.style;
if (right.style != topStyle ||
bottom.style != topStyle ||
left.style != topStyle ||
horizontalInside.style != topStyle ||
verticalInside.style != topStyle) {
return false;
}
return true;
}
/// Creates a copy of this border but with the widths scaled by the factor `t`.
///
/// The `t` argument represents the multiplicand, or the position on the
/// timeline for an interpolation from nothing to `this`, with 0.0 meaning
/// that the object returned should be the nil variant of this object, 1.0
/// meaning that no change should be applied, returning `this` (or something
/// equivalent to `this`), and other values meaning that the object should be
/// multiplied by `t`. Negative values are treated like zero.
///
/// Values for `t` are usually obtained from an [Animation<double>], such as
/// an [AnimationController].
///
/// See also:
///
/// * [BorderSide.scale], which is used to implement this method.
TableBorder scale(double t) {
return TableBorder(
top: top.scale(t),
right: right.scale(t),
bottom: bottom.scale(t),
left: left.scale(t),
horizontalInside: horizontalInside.scale(t),
verticalInside: verticalInside.scale(t),
);
}
/// Linearly interpolate between two table borders.
///
/// If a border is null, it is treated as having only [BorderSide.none]
/// borders.
///
/// {@macro dart.ui.shadow.lerp}
static TableBorder? lerp(TableBorder? a, TableBorder? b, double t) {
if (identical(a, b)) {
return a;
}
if (a == null) {
return b!.scale(t);
}
if (b == null) {
return a.scale(1.0 - t);
}
return TableBorder(
top: BorderSide.lerp(a.top, b.top, t),
right: BorderSide.lerp(a.right, b.right, t),
bottom: BorderSide.lerp(a.bottom, b.bottom, t),
left: BorderSide.lerp(a.left, b.left, t),
horizontalInside: BorderSide.lerp(a.horizontalInside, b.horizontalInside, t),
verticalInside: BorderSide.lerp(a.verticalInside, b.verticalInside, t),
);
}
/// Paints the border around the given [Rect] on the given [Canvas], with the
/// given rows and columns.
///
/// Uniform borders are more efficient to paint than more complex borders.
///
/// The `rows` argument specifies the vertical positions between the rows,
/// relative to the given rectangle. For example, if the table contained two
/// rows of height 100.0 each, then `rows` would contain a single value,
/// 100.0, which is the vertical position between the two rows (relative to
/// the top edge of `rect`).
///
/// The `columns` argument specifies the horizontal positions between the
/// columns, relative to the given rectangle. For example, if the table
/// contained two columns of height 100.0 each, then `columns` would contain a
/// single value, 100.0, which is the vertical position between the two
/// columns (relative to the left edge of `rect`).
///
/// The [verticalInside] border is only drawn if there are at least two
/// columns. The [horizontalInside] border is only drawn if there are at least
/// two rows. The horizontal borders are drawn after the vertical borders.
///
/// The outer borders (in the order [top], [right], [bottom], [left], with
/// [left] above the others) are painted after the inner borders.
///
/// The paint order is particularly notable in the case of
/// partially-transparent borders.
void paint(
Canvas canvas,
Rect rect, {
required Iterable<double> rows,
required Iterable<double> columns,
}) {
// properties can't be null
// arguments can't be null
assert(rows.isEmpty || (rows.first >= 0.0 && rows.last <= rect.height));
assert(columns.isEmpty || (columns.first >= 0.0 && columns.last <= rect.width));
if (columns.isNotEmpty || rows.isNotEmpty) {
final Paint paint = Paint();
final Path path = Path();
if (columns.isNotEmpty) {
switch (verticalInside.style) {
case BorderStyle.solid:
paint
..color = verticalInside.color
..strokeWidth = verticalInside.width
..style = PaintingStyle.stroke;
path.reset();
for (final double x in columns) {
path.moveTo(rect.left + x, rect.top);
path.lineTo(rect.left + x, rect.bottom);
}
canvas.drawPath(path, paint);
case BorderStyle.none:
break;
}
}
if (rows.isNotEmpty) {
switch (horizontalInside.style) {
case BorderStyle.solid:
paint
..color = horizontalInside.color
..strokeWidth = horizontalInside.width
..style = PaintingStyle.stroke;
path.reset();
for (final double y in rows) {
path.moveTo(rect.left, rect.top + y);
path.lineTo(rect.right, rect.top + y);
}
canvas.drawPath(path, paint);
case BorderStyle.none:
break;
}
}
}
if (!isUniform || borderRadius == BorderRadius.zero) {
paintBorder(canvas, rect, top: top, right: right, bottom: bottom, left: left);
} else {
final RRect outer = borderRadius.toRRect(rect);
final RRect inner = outer.deflate(top.width);
final Paint paint = Paint()..color = top.color;
canvas.drawDRRect(outer, inner, paint);
}
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is TableBorder
&& other.top == top
&& other.right == right
&& other.bottom == bottom
&& other.left == left
&& other.horizontalInside == horizontalInside
&& other.verticalInside == verticalInside
&& other.borderRadius == borderRadius;
}
@override
int get hashCode => Object.hash(top, right, bottom, left, horizontalInside, verticalInside, borderRadius);
@override
String toString() => 'TableBorder($top, $right, $bottom, $left, $horizontalInside, $verticalInside, $borderRadius)';
}
| flutter/packages/flutter/lib/src/rendering/table_border.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/table_border.dart",
"repo_id": "flutter",
"token_count": 3406
} | 247 |
// Copyright 2014 The Flutter Authors. 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 TextDirection;
import 'package:flutter/services.dart' show SystemChannels;
import 'semantics_event.dart' show AnnounceSemanticsEvent, Assertiveness, TooltipSemanticsEvent;
export 'dart:ui' show TextDirection;
/// Allows access to the platform's accessibility services.
///
/// Events sent by this service are handled by the platform-specific
/// accessibility bridge in Flutter's engine.
///
/// When possible, prefer using mechanisms like [Semantics] to implicitly
/// trigger announcements over using this event.
abstract final class SemanticsService {
/// Sends a semantic announcement.
///
/// This should be used for announcement that are not seamlessly announced by
/// the system as a result of a UI state change.
///
/// For example a camera application can use this method to make accessibility
/// announcements regarding objects in the viewfinder.
///
/// The assertiveness level of the announcement is determined by [assertiveness].
/// Currently, this is only supported by the web engine and has no effect on
/// other platforms. The default mode is [Assertiveness.polite].
static Future<void> announce(String message, TextDirection textDirection, {Assertiveness assertiveness = Assertiveness.polite}) async {
final AnnounceSemanticsEvent event = AnnounceSemanticsEvent(message, textDirection, assertiveness: assertiveness);
await SystemChannels.accessibility.send(event.toMap());
}
/// Sends a semantic announcement of a tooltip.
///
/// Currently only honored on Android. The contents of [message] will be
/// read by TalkBack.
static Future<void> tooltip(String message) async {
final TooltipSemanticsEvent event = TooltipSemanticsEvent(message);
await SystemChannels.accessibility.send(event.toMap());
}
}
| flutter/packages/flutter/lib/src/semantics/semantics_service.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/semantics/semantics_service.dart",
"repo_id": "flutter",
"token_count": 498
} | 248 |
// Copyright 2014 The Flutter Authors. 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';
/// A class representing rich content (such as a PNG image) inserted via the
/// system input method.
///
/// The following data is represented in this class:
/// - MIME Type
/// - Bytes
/// - URI
@immutable
class KeyboardInsertedContent {
/// Creates an object to represent content that is inserted from the virtual
/// keyboard.
///
/// The mime type and URI will always be provided, but the bytedata may be null.
const KeyboardInsertedContent({required this.mimeType, required this.uri, this.data});
/// Converts JSON received from the Flutter Engine into the Dart class.
KeyboardInsertedContent.fromJson(Map<String, dynamic> metadata):
mimeType = metadata['mimeType'] as String,
uri = metadata['uri'] as String,
data = metadata['data'] != null
? Uint8List.fromList(List<int>.from(metadata['data'] as Iterable<dynamic>))
: null;
/// The mime type of the inserted content.
final String mimeType;
/// The URI (location) of the inserted content, usually a "content://" URI.
final String uri;
/// The bytedata of the inserted content.
final Uint8List? data;
/// Convenience getter to check if bytedata is available for the inserted content.
bool get hasData => data?.isNotEmpty ?? false;
@override
String toString() => '${objectRuntimeType(this, 'KeyboardInsertedContent')}($mimeType, $uri, $data)';
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is KeyboardInsertedContent
&& other.mimeType == mimeType
&& other.uri == uri
&& other.data == data;
}
@override
int get hashCode => Object.hash(mimeType, uri, data);
}
| flutter/packages/flutter/lib/src/services/keyboard_inserted_content.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/keyboard_inserted_content.dart",
"repo_id": "flutter",
"token_count": 607
} | 249 |
// Copyright 2014 The Flutter Authors. 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 'keyboard_maps.g.dart';
import 'raw_keyboard.dart';
export 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder;
export 'keyboard_key.g.dart' show LogicalKeyboardKey, PhysicalKeyboardKey;
/// Platform-specific key event data for Linux.
///
/// This class is deprecated and will be removed. Platform specific key event
/// data will no longer be available. See [KeyEvent] for what is available.
///
/// Different window toolkit implementations can map to different key codes. This class
/// will use the correct mapping depending on the [keyHelper] provided.
///
/// See also:
///
/// * [RawKeyboard], which uses this interface to expose key data.
@Deprecated(
'Platform specific key event data is no longer available. See KeyEvent for what is available. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
class RawKeyEventDataLinux extends RawKeyEventData {
/// Creates a key event data structure specific for Linux.
@Deprecated(
'Platform specific key event data is no longer available. See KeyEvent for what is available. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
const RawKeyEventDataLinux({
required this.keyHelper,
this.unicodeScalarValues = 0,
this.scanCode = 0,
this.keyCode = 0,
this.modifiers = 0,
required this.isDown,
this.specifiedLogicalKey,
}) : assert((unicodeScalarValues & ~LogicalKeyboardKey.valueMask) == 0);
/// A helper class that abstracts the fetching of the toolkit-specific mappings.
///
/// There is no real concept of a "native" window toolkit on Linux, and each implementation
/// (GLFW, GTK, QT, etc) may have a different key code mapping.
final KeyHelper keyHelper;
/// An int with up to two Unicode scalar values generated by a single keystroke. An assertion
/// will fire if more than two values are encoded in a single keystroke.
///
/// This is typically the character that [keyCode] would produce without any modifier keys.
/// For dead keys, it is typically the diacritic it would add to a character. Defaults to 0,
/// asserted to be not null.
final int unicodeScalarValues;
/// The hardware scan code id corresponding to this key event.
///
/// These values are not reliable and vary from device to device, so this
/// information is mainly useful for debugging.
final int scanCode;
/// The hardware key code corresponding to this key event.
///
/// This is the physical key that was pressed, not the Unicode character.
/// This value may be different depending on the window toolkit used. See [KeyHelper].
final int keyCode;
/// A mask of the current modifiers using the values in Modifier Flags.
/// This value may be different depending on the window toolkit used. See [KeyHelper].
final int modifiers;
/// Whether or not this key event is a key down (true) or key up (false).
final bool isDown;
/// A logical key specified by the embedding that should be used instead of
/// deriving from raw data.
///
/// The GTK embedding detects the keyboard layout and maps some keys to
/// logical keys in a way that can not be derived from per-key information.
///
/// This is not part of the native GTK key event.
final int? specifiedLogicalKey;
@override
String get keyLabel => unicodeScalarValues == 0 ? '' : String.fromCharCode(unicodeScalarValues);
@override
PhysicalKeyboardKey get physicalKey => kLinuxToPhysicalKey[scanCode] ?? PhysicalKeyboardKey(LogicalKeyboardKey.webPlane + scanCode);
@override
LogicalKeyboardKey get logicalKey {
if (specifiedLogicalKey != null) {
final int key = specifiedLogicalKey!;
return LogicalKeyboardKey.findKeyByKeyId(key) ?? LogicalKeyboardKey(key);
}
// Look to see if the keyCode is a printable number pad key, so that a
// difference between regular keys (e.g. "=") and the number pad version
// (e.g. the "=" on the number pad) can be determined.
final LogicalKeyboardKey? numPadKey = keyHelper.numpadKey(keyCode);
if (numPadKey != null) {
return numPadKey;
}
// If it has a non-control-character label, then either return the existing
// constant, or construct a new Unicode-based key from it. Don't mark it as
// autogenerated, since the label uniquely identifies an ID from the Unicode
// plane.
if (keyLabel.isNotEmpty &&
!LogicalKeyboardKey.isControlCharacter(keyLabel)) {
final int keyId = LogicalKeyboardKey.unicodePlane | (unicodeScalarValues & LogicalKeyboardKey.valueMask);
return LogicalKeyboardKey.findKeyByKeyId(keyId) ?? LogicalKeyboardKey(keyId);
}
// Look to see if the keyCode is one we know about and have a mapping for.
final LogicalKeyboardKey? newKey = keyHelper.logicalKey(keyCode);
if (newKey != null) {
return newKey;
}
// This is a non-printable key that we don't know about, so we mint a new
// code.
return LogicalKeyboardKey(keyCode | keyHelper.platformPlane);
}
@override
bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}) {
return keyHelper.isModifierPressed(key, modifiers, side: side, keyCode: keyCode, isDown: isDown);
}
@override
KeyboardSide getModifierSide(ModifierKey key) {
return keyHelper.getModifierSide(key);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<String>('toolkit', keyHelper.debugToolkit));
properties.add(DiagnosticsProperty<int>('unicodeScalarValues', unicodeScalarValues));
properties.add(DiagnosticsProperty<int>('scanCode', scanCode));
properties.add(DiagnosticsProperty<int>('keyCode', keyCode));
properties.add(DiagnosticsProperty<int>('modifiers', modifiers));
properties.add(DiagnosticsProperty<bool>('isDown', isDown));
properties.add(DiagnosticsProperty<int?>('specifiedLogicalKey', specifiedLogicalKey, defaultValue: null));
}
@override
bool operator==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is RawKeyEventDataLinux
&& other.keyHelper.runtimeType == keyHelper.runtimeType
&& other.unicodeScalarValues == unicodeScalarValues
&& other.scanCode == scanCode
&& other.keyCode == keyCode
&& other.modifiers == modifiers
&& other.isDown == isDown;
}
@override
int get hashCode => Object.hash(
keyHelper.runtimeType,
unicodeScalarValues,
scanCode,
keyCode,
modifiers,
isDown,
);
}
/// Abstract class for window-specific key mappings.
///
/// Given that there might be multiple window toolkit implementations (GLFW,
/// GTK, QT, etc), this creates a common interface for each of the
/// different toolkits.
///
/// This class is deprecated and will be removed. Platform specific key event
/// data will no longer be available. See [KeyEvent] for what is available.
@Deprecated(
'No longer supported. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
abstract class KeyHelper {
/// Create a KeyHelper implementation depending on the given toolkit.
@Deprecated(
'No longer supported. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
factory KeyHelper(String toolkit) {
if (toolkit == 'glfw') {
return GLFWKeyHelper();
} else if (toolkit == 'gtk') {
return GtkKeyHelper();
} else {
throw FlutterError('Window toolkit not recognized: $toolkit');
}
}
/// Returns the name for the toolkit.
///
/// This is used in debug mode to generate readable string.
String get debugToolkit;
/// Returns a [KeyboardSide] enum value that describes which side or sides of
/// the given keyboard modifier key were pressed at the time of this event.
@Deprecated(
'No longer supported. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
KeyboardSide getModifierSide(ModifierKey key);
/// Returns true if the given [ModifierKey] was pressed at the time of this
/// event.
@Deprecated(
'No longer supported. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown});
/// The numpad key from the specific key code mapping.
LogicalKeyboardKey? numpadKey(int keyCode);
/// The logical key from the specific key code mapping.
LogicalKeyboardKey? logicalKey(int keyCode);
/// The platform plane mask value of this platform.
int get platformPlane;
}
/// Helper class that uses GLFW-specific key mappings.
///
/// This class is deprecated and will be removed. Platform specific key event
/// data will no longer be available. See [KeyEvent] for what is available.
@Deprecated(
'No longer supported. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
class GLFWKeyHelper implements KeyHelper {
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether the CAPS LOCK modifier key is on.
///
/// {@template flutter.services.GLFWKeyHelper.modifierCapsLock}
/// Use this value if you need to decode the [RawKeyEventDataLinux.modifiers]
/// field yourself, but it's much easier to use [isModifierPressed] if you
/// just want to know if a modifier is pressed. This is especially true on
/// GLFW, since its modifiers don't include the effects of the current key
/// event.
/// {@endtemplate}
static const int modifierCapsLock = 0x0010;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether one of the SHIFT modifier keys is pressed.
///
/// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock}
static const int modifierShift = 0x0001;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether one of the CTRL modifier keys is pressed.
///
/// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock}
static const int modifierControl = 0x0002;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether one of the ALT modifier keys is pressed.
///
/// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock}
static const int modifierAlt = 0x0004;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether one of the Meta(SUPER) modifier keys is pressed.
///
/// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock}
static const int modifierMeta = 0x0008;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether any key in the numeric keypad is pressed.
///
/// {@macro flutter.services.GLFWKeyHelper.modifierCapsLock}
static const int modifierNumericPad = 0x0020;
@override
String get debugToolkit => 'GLFW';
int _mergeModifiers({required int modifiers, required int keyCode, required bool isDown}) {
// GLFW Key codes for modifier keys.
const int shiftLeftKeyCode = 340;
const int shiftRightKeyCode = 344;
const int controlLeftKeyCode = 341;
const int controlRightKeyCode = 345;
const int altLeftKeyCode = 342;
const int altRightKeyCode = 346;
const int metaLeftKeyCode = 343;
const int metaRightKeyCode = 347;
const int capsLockKeyCode = 280;
const int numLockKeyCode = 282;
// On GLFW, the "modifiers" bitfield is the state as it is BEFORE this event
// happened, not AFTER, like every other platform. Consequently, if this is
// a key down, then we need to add the correct modifier bits, and if it's a
// key up, we need to remove them.
final int modifierChange = switch (keyCode) {
shiftLeftKeyCode || shiftRightKeyCode => modifierShift,
controlLeftKeyCode || controlRightKeyCode => modifierControl,
altLeftKeyCode || altRightKeyCode => modifierAlt,
metaLeftKeyCode || metaRightKeyCode => modifierMeta,
capsLockKeyCode => modifierCapsLock,
numLockKeyCode => modifierNumericPad,
_ => 0,
};
return isDown ? modifiers | modifierChange : modifiers & ~modifierChange;
}
@override
bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) {
modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown);
return switch (key) {
ModifierKey.controlModifier => modifiers & modifierControl != 0,
ModifierKey.shiftModifier => modifiers & modifierShift != 0,
ModifierKey.altModifier => modifiers & modifierAlt != 0,
ModifierKey.metaModifier => modifiers & modifierMeta != 0,
ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0,
ModifierKey.numLockModifier => modifiers & modifierNumericPad != 0,
// These are not used in GLFW keyboards.
ModifierKey.functionModifier => false,
ModifierKey.symbolModifier => false,
ModifierKey.scrollLockModifier => false,
};
}
@override
KeyboardSide getModifierSide(ModifierKey key) {
// Neither GLFW nor X11 provide a distinction between left and right
// modifiers, so defaults to KeyboardSide.all.
// https://code.woboq.org/qt5/include/X11/X.h.html#_M/ShiftMask
return KeyboardSide.all;
}
@override
LogicalKeyboardKey? numpadKey(int keyCode) {
return kGlfwNumpadMap[keyCode];
}
@override
LogicalKeyboardKey? logicalKey(int keyCode) {
return kGlfwToLogicalKey[keyCode];
}
@override
int get platformPlane => LogicalKeyboardKey.glfwPlane;
}
/// Helper class that uses GTK-specific key mappings.
///
/// This class is deprecated and will be removed. Platform specific key event
/// data will no longer be available. See [KeyEvent] for what is available.
@Deprecated(
'No longer supported. '
'This feature was deprecated after v3.18.0-2.0.pre.',
)
class GtkKeyHelper implements KeyHelper {
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether one of the SHIFT modifier keys is pressed.
///
/// {@template flutter.services.GtkKeyHelper.modifierShift}
/// Use this value if you need to decode the [RawKeyEventDataLinux.modifiers] field yourself, but
/// it's much easier to use [isModifierPressed] if you just want to know if a
/// modifier is pressed. This is especially true on GTK, since its modifiers
/// don't include the effects of the current key event.
/// {@endtemplate}
static const int modifierShift = 1 << 0;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether the CAPS LOCK modifier key is on.
///
/// {@macro flutter.services.GtkKeyHelper.modifierShift}
static const int modifierCapsLock = 1 << 1;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether one of the CTRL modifier keys is pressed.
///
/// {@macro flutter.services.GtkKeyHelper.modifierShift}
static const int modifierControl = 1 << 2;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether the first modifier key is pressed (usually mapped to alt).
///
/// {@macro flutter.services.GtkKeyHelper.modifierShift}
static const int modifierMod1 = 1 << 3;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether the second modifier key is pressed (assumed to be mapped to
/// num lock).
///
/// {@macro flutter.services.GtkKeyHelper.modifierShift}
static const int modifierMod2 = 1 << 4;
/// This mask is used to check the [RawKeyEventDataLinux.modifiers] field to
/// test whether one of the Meta(SUPER) modifier keys is pressed.
///
/// {@macro flutter.services.GtkKeyHelper.modifierShift}
static const int modifierMeta = 1 << 26;
@override
String get debugToolkit => 'GTK';
int _mergeModifiers({required int modifiers, required int keyCode, required bool isDown}) {
// GTK Key codes for modifier keys.
const int shiftLeftKeyCode = 0xffe1;
const int shiftRightKeyCode = 0xffe2;
const int controlLeftKeyCode = 0xffe3;
const int controlRightKeyCode = 0xffe4;
const int capsLockKeyCode = 0xffe5;
const int shiftLockKeyCode = 0xffe6;
const int altLeftKeyCode = 0xffe9;
const int altRightKeyCode = 0xffea;
const int metaLeftKeyCode = 0xffeb;
const int metaRightKeyCode = 0xffec;
const int numLockKeyCode = 0xff7f;
// On GTK, the "modifiers" bitfield is the state as it is BEFORE this event
// happened, not AFTER, like every other platform. Consequently, if this is
// a key down, then we need to add the correct modifier bits, and if it's a
// key up, we need to remove them.
final int modifierChange = switch (keyCode) {
shiftLeftKeyCode || shiftRightKeyCode => modifierShift,
controlLeftKeyCode || controlRightKeyCode => modifierControl,
altLeftKeyCode || altRightKeyCode => modifierMod1,
metaLeftKeyCode || metaRightKeyCode => modifierMeta,
capsLockKeyCode || shiftLockKeyCode => modifierCapsLock,
numLockKeyCode => modifierMod2,
_ => 0,
};
return isDown ? modifiers | modifierChange : modifiers & ~modifierChange;
}
@override
bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) {
modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown);
return switch (key) {
ModifierKey.controlModifier => modifiers & modifierControl != 0,
ModifierKey.shiftModifier => modifiers & modifierShift != 0,
ModifierKey.altModifier => modifiers & modifierMod1 != 0,
ModifierKey.metaModifier => modifiers & modifierMeta != 0,
ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0,
ModifierKey.numLockModifier => modifiers & modifierMod2 != 0,
// These are not used in GTK keyboards.
ModifierKey.functionModifier => false,
ModifierKey.symbolModifier => false,
ModifierKey.scrollLockModifier => false,
};
}
@override
KeyboardSide getModifierSide(ModifierKey key) {
// Neither GTK nor X11 provide a distinction between left and right
// modifiers, so defaults to KeyboardSide.all.
// https://code.woboq.org/qt5/include/X11/X.h.html#_M/ShiftMask
return KeyboardSide.all;
}
@override
LogicalKeyboardKey? numpadKey(int keyCode) {
return kGtkNumpadMap[keyCode];
}
@override
LogicalKeyboardKey? logicalKey(int keyCode) {
return kGtkToLogicalKey[keyCode];
}
@override
int get platformPlane => LogicalKeyboardKey.gtkPlane;
}
| flutter/packages/flutter/lib/src/services/raw_keyboard_linux.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/raw_keyboard_linux.dart",
"repo_id": "flutter",
"token_count": 6022
} | 250 |
// Copyright 2014 The Flutter Authors. 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 TextRange;
import 'text_editing.dart';
export 'dart:ui' show TextPosition, TextRange;
export 'text_editing.dart' show TextSelection;
/// A read-only interface for accessing visual information about the
/// implementing text.
abstract class TextLayoutMetrics {
// TODO(gspencergoog): replace when we expose this ICU information.
/// Check if the given code unit is a white space or separator
/// character.
///
/// Includes newline characters from ASCII and separators from the
/// [unicode separator category](https://www.compart.com/en/unicode/category/Zs)
static bool isWhitespace(int codeUnit) {
switch (codeUnit) {
case 0x9: // horizontal tab
case 0xA: // line feed
case 0xB: // vertical tab
case 0xC: // form feed
case 0xD: // carriage return
case 0x1C: // file separator
case 0x1D: // group separator
case 0x1E: // record separator
case 0x1F: // unit separator
case 0x20: // space
case 0xA0: // no-break space
case 0x1680: // ogham space mark
case 0x2000: // en quad
case 0x2001: // em quad
case 0x2002: // en space
case 0x2003: // em space
case 0x2004: // three-per-em space
case 0x2005: // four-er-em space
case 0x2006: // six-per-em space
case 0x2007: // figure space
case 0x2008: // punctuation space
case 0x2009: // thin space
case 0x200A: // hair space
case 0x202F: // narrow no-break space
case 0x205F: // medium mathematical space
case 0x3000: // ideographic space
break;
default:
return false;
}
return true;
}
/// Check if the given code unit is a line terminator character.
///
/// Includes newline characters from ASCII
/// (https://www.unicode.org/standard/reports/tr13/tr13-5.html).
static bool isLineTerminator(int codeUnit) {
switch (codeUnit) {
case 0x0A: // line feed
case 0x0B: // vertical feed
case 0x0C: // form feed
case 0x0D: // carriage return
case 0x85: // new line
case 0x2028: // line separator
case 0x2029: // paragraph separator
return true;
default:
return false;
}
}
/// {@template flutter.services.TextLayoutMetrics.getLineAtOffset}
/// Return a [TextSelection] containing the line of the given [TextPosition].
/// {@endtemplate}
TextSelection getLineAtOffset(TextPosition position);
/// {@macro flutter.painting.TextPainter.getWordBoundary}
TextRange getWordBoundary(TextPosition position);
/// {@template flutter.services.TextLayoutMetrics.getTextPositionAbove}
/// Returns the TextPosition above the given offset into the text.
///
/// If the offset is already on the first line, the given offset will be
/// returned.
/// {@endtemplate}
TextPosition getTextPositionAbove(TextPosition position);
/// {@template flutter.services.TextLayoutMetrics.getTextPositionBelow}
/// Returns the TextPosition below the given offset into the text.
///
/// If the offset is already on the last line, the given offset will be
/// returned.
/// {@endtemplate}
TextPosition getTextPositionBelow(TextPosition position);
}
| flutter/packages/flutter/lib/src/services/text_layout_metrics.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/text_layout_metrics.dart",
"repo_id": "flutter",
"token_count": 1171
} | 251 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async' show StreamSubscription;
import 'package:flutter/foundation.dart';
import 'framework.dart';
/// Base class for widgets that build themselves based on interaction with
/// a specified [Stream].
///
/// A [StreamBuilderBase] is stateful and maintains a summary of the interaction
/// so far. The type of the summary and how it is updated with each interaction
/// is defined by sub-classes.
///
/// Examples of summaries include:
///
/// * the running average of a stream of integers;
/// * the current direction and speed based on a stream of geolocation data;
/// * a graph displaying data points from a stream.
///
/// In general, the summary is the result of a fold computation over the data
/// items and errors received from the stream along with pseudo-events
/// representing termination or change of stream. The initial summary is
/// specified by sub-classes by overriding [initial]. The summary updates on
/// receipt of stream data and errors are specified by overriding [afterData] and
/// [afterError], respectively. If needed, the summary may be updated on stream
/// termination by overriding [afterDone]. Finally, the summary may be updated
/// on change of stream by overriding [afterDisconnected] and [afterConnected].
///
/// `T` is the type of stream events.
///
/// `S` is the type of interaction summary.
///
/// See also:
///
/// * [StreamBuilder], which is specialized for the case where only the most
/// recent interaction is needed for widget building.
abstract class StreamBuilderBase<T, S> extends StatefulWidget {
/// Creates a [StreamBuilderBase] connected to the specified [stream].
const StreamBuilderBase({ super.key, required this.stream });
/// The asynchronous computation to which this builder is currently connected,
/// possibly null. When changed, the current summary is updated using
/// [afterDisconnected], if the previous stream was not null, followed by
/// [afterConnected], if the new stream is not null.
final Stream<T>? stream;
/// Returns the initial summary of stream interaction, typically representing
/// the fact that no interaction has happened at all.
///
/// Sub-classes must override this method to provide the initial value for
/// the fold computation.
S initial();
/// Returns an updated version of the [current] summary reflecting that we
/// are now connected to a stream.
///
/// The default implementation returns [current] as is.
S afterConnected(S current) => current;
/// Returns an updated version of the [current] summary following a data event.
///
/// Sub-classes must override this method to specify how the current summary
/// is combined with the new data item in the fold computation.
S afterData(S current, T data);
/// Returns an updated version of the [current] summary following an error
/// with a stack trace.
///
/// The default implementation returns [current] as is.
S afterError(S current, Object error, StackTrace stackTrace) => current;
/// Returns an updated version of the [current] summary following stream
/// termination.
///
/// The default implementation returns [current] as is.
S afterDone(S current) => current;
/// Returns an updated version of the [current] summary reflecting that we
/// are no longer connected to a stream.
///
/// The default implementation returns [current] as is.
S afterDisconnected(S current) => current;
/// Returns a Widget based on the [currentSummary].
Widget build(BuildContext context, S currentSummary);
@override
State<StreamBuilderBase<T, S>> createState() => _StreamBuilderBaseState<T, S>();
}
/// State for [StreamBuilderBase].
class _StreamBuilderBaseState<T, S> extends State<StreamBuilderBase<T, S>> {
StreamSubscription<T>? _subscription;
late S _summary;
@override
void initState() {
super.initState();
_summary = widget.initial();
_subscribe();
}
@override
void didUpdateWidget(StreamBuilderBase<T, S> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.stream != widget.stream) {
if (_subscription != null) {
_unsubscribe();
_summary = widget.afterDisconnected(_summary);
}
_subscribe();
}
}
@override
Widget build(BuildContext context) => widget.build(context, _summary);
@override
void dispose() {
_unsubscribe();
super.dispose();
}
void _subscribe() {
if (widget.stream != null) {
_subscription = widget.stream!.listen((T data) {
setState(() {
_summary = widget.afterData(_summary, data);
});
}, onError: (Object error, StackTrace stackTrace) {
setState(() {
_summary = widget.afterError(_summary, error, stackTrace);
});
}, onDone: () {
setState(() {
_summary = widget.afterDone(_summary);
});
});
_summary = widget.afterConnected(_summary);
}
}
void _unsubscribe() {
if (_subscription != null) {
_subscription!.cancel();
_subscription = null;
}
}
}
/// The state of connection to an asynchronous computation.
///
/// The usual flow of state is as follows:
///
/// 1. [none], maybe with some initial data.
/// 2. [waiting], indicating that the asynchronous operation has begun,
/// typically with the data being null.
/// 3. [active], with data being non-null, and possible changing over time.
/// 4. [done], with data being non-null.
///
/// See also:
///
/// * [AsyncSnapshot], which augments a connection state with information
/// received from the asynchronous computation.
enum ConnectionState {
/// Not currently connected to any asynchronous computation.
///
/// For example, a [FutureBuilder] whose [FutureBuilder.future] is null.
none,
/// Connected to an asynchronous computation and awaiting interaction.
waiting,
/// Connected to an active asynchronous computation.
///
/// For example, a [Stream] that has returned at least one value, but is not
/// yet done.
active,
/// Connected to a terminated asynchronous computation.
done,
}
/// Immutable representation of the most recent interaction with an asynchronous
/// computation.
///
/// See also:
///
/// * [StreamBuilder], which builds itself based on a snapshot from interacting
/// with a [Stream].
/// * [FutureBuilder], which builds itself based on a snapshot from interacting
/// with a [Future].
@immutable
class AsyncSnapshot<T> {
/// Creates an [AsyncSnapshot] with the specified [connectionState],
/// and optionally either [data] or [error] with an optional [stackTrace]
/// (but not both data and error).
const AsyncSnapshot._(this.connectionState, this.data, this.error, this.stackTrace)
: assert(data == null || error == null),
assert(stackTrace == null || error != null);
/// Creates an [AsyncSnapshot] in [ConnectionState.none] with null data and error.
const AsyncSnapshot.nothing() : this._(ConnectionState.none, null, null, null);
/// Creates an [AsyncSnapshot] in [ConnectionState.waiting] with null data and error.
const AsyncSnapshot.waiting() : this._(ConnectionState.waiting, null, null, null);
/// Creates an [AsyncSnapshot] in the specified [state] and with the specified [data].
const AsyncSnapshot.withData(ConnectionState state, T data): this._(state, data, null, null);
/// Creates an [AsyncSnapshot] in the specified [state] with the specified [error]
/// and a [stackTrace].
///
/// If no [stackTrace] is explicitly specified, [StackTrace.empty] will be used instead.
const AsyncSnapshot.withError(
ConnectionState state,
Object error, [
StackTrace stackTrace = StackTrace.empty,
]) : this._(state, null, error, stackTrace);
/// Current state of connection to the asynchronous computation.
final ConnectionState connectionState;
/// The latest data received by the asynchronous computation.
///
/// If this is non-null, [hasData] will be true.
///
/// If [error] is not null, this will be null. See [hasError].
///
/// If the asynchronous computation has never returned a value, this may be
/// set to an initial data value specified by the relevant widget. See
/// [FutureBuilder.initialData] and [StreamBuilder.initialData].
final T? data;
/// Returns latest data received, failing if there is no data.
///
/// Throws [error], if [hasError]. Throws [StateError], if neither [hasData]
/// nor [hasError].
T get requireData {
if (hasData) {
return data!;
}
if (hasError) {
Error.throwWithStackTrace(error!, stackTrace!);
}
throw StateError('Snapshot has neither data nor error');
}
/// The latest error object received by the asynchronous computation.
///
/// If this is non-null, [hasError] will be true.
///
/// If [data] is not null, this will be null.
final Object? error;
/// The latest stack trace object received by the asynchronous computation.
///
/// This will not be null iff [error] is not null. Consequently, [stackTrace]
/// will be non-null when [hasError] is true.
///
/// However, even when not null, [stackTrace] might be empty. The stack trace
/// is empty when there is an error but no stack trace has been provided.
final StackTrace? stackTrace;
/// Returns a snapshot like this one, but in the specified [state].
///
/// The [data], [error], and [stackTrace] fields persist unmodified, even if
/// the new state is [ConnectionState.none].
AsyncSnapshot<T> inState(ConnectionState state) => AsyncSnapshot<T>._(state, data, error, stackTrace);
/// Returns whether this snapshot contains a non-null [data] value.
///
/// This can be false even when the asynchronous computation has completed
/// successfully, if the computation did not return a non-null value. For
/// example, a [Future<void>] will complete with the null value even if it
/// completes successfully.
bool get hasData => data != null;
/// Returns whether this snapshot contains a non-null [error] value.
///
/// This is always true if the asynchronous computation's last result was
/// failure.
bool get hasError => error != null;
@override
String toString() => '${objectRuntimeType(this, 'AsyncSnapshot')}($connectionState, $data, $error, $stackTrace)';
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is AsyncSnapshot<T>
&& other.connectionState == connectionState
&& other.data == data
&& other.error == error
&& other.stackTrace == stackTrace;
}
@override
int get hashCode => Object.hash(connectionState, data, error);
}
/// Signature for strategies that build widgets based on asynchronous
/// interaction.
///
/// See also:
///
/// * [StreamBuilder], which delegates to an [AsyncWidgetBuilder] to build
/// itself based on a snapshot from interacting with a [Stream].
/// * [FutureBuilder], which delegates to an [AsyncWidgetBuilder] to build
/// itself based on a snapshot from interacting with a [Future].
typedef AsyncWidgetBuilder<T> = Widget Function(BuildContext context, AsyncSnapshot<T> snapshot);
/// Widget that builds itself based on the latest snapshot of interaction with
/// a [Stream].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=MkKEWHfy99Y}
///
/// ## Managing the stream
///
/// The [stream] must have been obtained earlier, e.g. during [State.initState],
/// [State.didUpdateWidget], or [State.didChangeDependencies]. It must not be
/// created during the [State.build] or [StatelessWidget.build] method call when
/// constructing the [StreamBuilder]. If the [stream] is created at the same
/// time as the [StreamBuilder], then every time the [StreamBuilder]'s parent is
/// rebuilt, the asynchronous task will be restarted.
///
/// A general guideline is to assume that every `build` method could get called
/// every frame, and to treat omitted calls as an optimization.
///
/// ## Timing
///
/// Widget rebuilding is scheduled by each interaction, using [State.setState],
/// but is otherwise decoupled from the timing of the stream. The [builder]
/// is called at the discretion of the Flutter pipeline, and will thus receive a
/// timing-dependent sub-sequence of the snapshots that represent the
/// interaction with the stream.
///
/// As an example, when interacting with a stream producing the integers
/// 0 through 9, the [builder] may be called with any ordered sub-sequence
/// of the following snapshots that includes the last one (the one with
/// ConnectionState.done):
///
/// * `AsyncSnapshot<int>.withData(ConnectionState.waiting, null)`
/// * `AsyncSnapshot<int>.withData(ConnectionState.active, 0)`
/// * `AsyncSnapshot<int>.withData(ConnectionState.active, 1)`
/// * ...
/// * `AsyncSnapshot<int>.withData(ConnectionState.active, 9)`
/// * `AsyncSnapshot<int>.withData(ConnectionState.done, 9)`
///
/// The actual sequence of invocations of the [builder] depends on the relative
/// timing of events produced by the stream and the build rate of the Flutter
/// pipeline.
///
/// Changing the [StreamBuilder] configuration to another stream during event
/// generation introduces snapshot pairs of the form:
///
/// * `AsyncSnapshot<int>.withData(ConnectionState.none, 5)`
/// * `AsyncSnapshot<int>.withData(ConnectionState.waiting, 5)`
///
/// The latter will be produced only when the new stream is non-null, and the
/// former only when the old stream is non-null.
///
/// The stream may produce errors, resulting in snapshots of the form:
///
/// * `AsyncSnapshot<int>.withError(ConnectionState.active, 'some error', someStackTrace)`
///
/// The data and error fields of snapshots produced are only changed when the
/// state is `ConnectionState.active`.
///
/// The initial snapshot data can be controlled by specifying [initialData].
/// This should be used to ensure that the first frame has the expected value,
/// as the builder will always be called before the stream listener has a chance
/// to be processed.
///
/// {@tool dartpad}
/// This sample shows a [StreamBuilder] that listens to a Stream that emits bids
/// for an auction. Every time the StreamBuilder receives a bid from the Stream,
/// it will display the price of the bid below an icon. If the Stream emits an
/// error, the error is displayed below an error icon. When the Stream finishes
/// emitting bids, the final price is displayed.
///
/// ** See code in examples/api/lib/widgets/async/stream_builder.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ValueListenableBuilder], which wraps a [ValueListenable] instead of a
/// [Stream].
/// * [StreamBuilderBase], which supports widget building based on a computation
/// that spans all interactions made with the stream.
class StreamBuilder<T> extends StreamBuilderBase<T, AsyncSnapshot<T>> {
/// Creates a new [StreamBuilder] that builds itself based on the latest
/// snapshot of interaction with the specified [stream] and whose build
/// strategy is given by [builder].
///
/// The [initialData] is used to create the initial snapshot.
const StreamBuilder({
super.key,
this.initialData,
required super.stream,
required this.builder,
});
/// The build strategy currently used by this builder.
///
/// This builder must only return a widget and should not have any side
/// effects as it may be called multiple times.
final AsyncWidgetBuilder<T> builder;
/// The data that will be used to create the initial snapshot.
///
/// Providing this value (presumably obtained synchronously somehow when the
/// [Stream] was created) ensures that the first frame will show useful data.
/// Otherwise, the first frame will be built with the value null, regardless
/// of whether a value is available on the stream: since streams are
/// asynchronous, no events from the stream can be obtained before the initial
/// build.
final T? initialData;
@override
AsyncSnapshot<T> initial() => initialData == null
? AsyncSnapshot<T>.nothing()
: AsyncSnapshot<T>.withData(ConnectionState.none, initialData as T);
@override
AsyncSnapshot<T> afterConnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.waiting);
@override
AsyncSnapshot<T> afterData(AsyncSnapshot<T> current, T data) {
return AsyncSnapshot<T>.withData(ConnectionState.active, data);
}
@override
AsyncSnapshot<T> afterError(AsyncSnapshot<T> current, Object error, StackTrace stackTrace) {
return AsyncSnapshot<T>.withError(ConnectionState.active, error, stackTrace);
}
@override
AsyncSnapshot<T> afterDone(AsyncSnapshot<T> current) => current.inState(ConnectionState.done);
@override
AsyncSnapshot<T> afterDisconnected(AsyncSnapshot<T> current) => current.inState(ConnectionState.none);
@override
Widget build(BuildContext context, AsyncSnapshot<T> currentSummary) => builder(context, currentSummary);
}
/// A widget that builds itself based on the latest snapshot of interaction with
/// a [Future].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=zEdw_1B7JHY}
///
/// ## Managing the future
///
/// The [future] must have been obtained earlier, e.g. during [State.initState],
/// [State.didUpdateWidget], or [State.didChangeDependencies]. It must not be
/// created during the [State.build] or [StatelessWidget.build] method call when
/// constructing the [FutureBuilder]. If the [future] is created at the same
/// time as the [FutureBuilder], then every time the [FutureBuilder]'s parent is
/// rebuilt, the asynchronous task will be restarted.
///
/// A general guideline is to assume that every `build` method could get called
/// every frame, and to treat omitted calls as an optimization.
///
/// ## Timing
///
/// Widget rebuilding is scheduled by the completion of the future, using
/// [State.setState], but is otherwise decoupled from the timing of the future.
/// The [builder] callback is called at the discretion of the Flutter pipeline, and
/// will thus receive a timing-dependent sub-sequence of the snapshots that
/// represent the interaction with the future.
///
/// A side-effect of this is that providing a new but already-completed future
/// to a [FutureBuilder] will result in a single frame in the
/// [ConnectionState.waiting] state. This is because there is no way to
/// synchronously determine that a [Future] has already completed.
///
/// ## Builder contract
///
/// For a future that completes successfully with data, assuming [initialData]
/// is null, the [builder] will be called with either both or only the latter of
/// the following snapshots:
///
/// * `AsyncSnapshot<String>.withData(ConnectionState.waiting, null)`
/// * `AsyncSnapshot<String>.withData(ConnectionState.done, 'some data')`
///
/// If that same future instead completed with an error, the [builder] would be
/// called with either both or only the latter of:
///
/// * `AsyncSnapshot<String>.withData(ConnectionState.waiting, null)`
/// * `AsyncSnapshot<String>.withError(ConnectionState.done, 'some error', someStackTrace)`
///
/// The initial snapshot data can be controlled by specifying [initialData]. You
/// would use this facility to ensure that if the [builder] is invoked before
/// the future completes, the snapshot carries data of your choice rather than
/// the default null value.
///
/// The data and error fields of the snapshot change only as the connection
/// state field transitions from `waiting` to `done`, and they will be retained
/// when changing the [FutureBuilder] configuration to another future. If the
/// old future has already completed successfully with data as above, changing
/// configuration to a new future results in snapshot pairs of the form:
///
/// * `AsyncSnapshot<String>.withData(ConnectionState.none, 'data of first future')`
/// * `AsyncSnapshot<String>.withData(ConnectionState.waiting, 'data of second future')`
///
/// In general, the latter will be produced only when the new future is
/// non-null, and the former only when the old future is non-null.
///
/// A [FutureBuilder] behaves identically to a [StreamBuilder] configured with
/// `future?.asStream()`, except that snapshots with `ConnectionState.active`
/// may appear for the latter, depending on how the stream is implemented.
///
/// {@tool dartpad}
/// This sample shows a [FutureBuilder] that displays a loading spinner while it
/// loads data. It displays a success icon and text if the [Future] completes
/// with a result, or an error icon and text if the [Future] completes with an
/// error. Assume the `_calculation` field is set by pressing a button elsewhere
/// in the UI.
///
/// ** See code in examples/api/lib/widgets/async/future_builder.0.dart **
/// {@end-tool}
class FutureBuilder<T> extends StatefulWidget {
/// Creates a widget that builds itself based on the latest snapshot of
/// interaction with a [Future].
const FutureBuilder({
super.key,
required this.future,
this.initialData,
required this.builder,
});
/// The asynchronous computation to which this builder is currently connected,
/// possibly null.
///
/// If no future has yet completed, including in the case where [future] is
/// null, the data provided to the [builder] will be set to [initialData].
final Future<T>? future;
/// The build strategy currently used by this builder.
///
/// The builder is provided with an [AsyncSnapshot] object whose
/// [AsyncSnapshot.connectionState] property will be one of the following
/// values:
///
/// * [ConnectionState.none]: [future] is null. The [AsyncSnapshot.data] will
/// be set to [initialData], unless a future has previously completed, in
/// which case the previous result persists.
///
/// * [ConnectionState.waiting]: [future] is not null, but has not yet
/// completed. The [AsyncSnapshot.data] will be set to [initialData],
/// unless a future has previously completed, in which case the previous
/// result persists.
///
/// * [ConnectionState.done]: [future] is not null, and has completed. If the
/// future completed successfully, the [AsyncSnapshot.data] will be set to
/// the value to which the future completed. If it completed with an error,
/// [AsyncSnapshot.hasError] will be true and [AsyncSnapshot.error] will be
/// set to the error object.
///
/// This builder must only return a widget and should not have any side
/// effects as it may be called multiple times.
final AsyncWidgetBuilder<T> builder;
/// The data that will be used to create the snapshots provided until a
/// non-null [future] has completed.
///
/// If the future completes with an error, the data in the [AsyncSnapshot]
/// provided to the [builder] will become null, regardless of [initialData].
/// (The error itself will be available in [AsyncSnapshot.error], and
/// [AsyncSnapshot.hasError] will be true.)
final T? initialData;
/// Whether the latest error received by the asynchronous computation should
/// be rethrown or swallowed. This property is useful for debugging purposes.
///
/// When set to true, will rethrow the latest error only in debug mode.
///
/// Defaults to `false`, resulting in swallowing of errors.
static bool debugRethrowError = false;
@override
State<FutureBuilder<T>> createState() => _FutureBuilderState<T>();
}
/// State for [FutureBuilder].
class _FutureBuilderState<T> extends State<FutureBuilder<T>> {
/// An object that identifies the currently active callbacks. Used to avoid
/// calling setState from stale callbacks, e.g. after disposal of this state,
/// or after widget reconfiguration to a new Future.
Object? _activeCallbackIdentity;
late AsyncSnapshot<T> _snapshot;
@override
void initState() {
super.initState();
_snapshot = widget.initialData == null
? AsyncSnapshot<T>.nothing()
: AsyncSnapshot<T>.withData(ConnectionState.none, widget.initialData as T);
_subscribe();
}
@override
void didUpdateWidget(FutureBuilder<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.future == widget.future) {
return;
}
if (_activeCallbackIdentity != null) {
_unsubscribe();
_snapshot = _snapshot.inState(ConnectionState.none);
}
_subscribe();
}
@override
Widget build(BuildContext context) => widget.builder(context, _snapshot);
@override
void dispose() {
_unsubscribe();
super.dispose();
}
void _subscribe() {
if (widget.future == null) {
// There is no future to subscribe to, do nothing.
return;
}
final Object callbackIdentity = Object();
_activeCallbackIdentity = callbackIdentity;
widget.future!.then<void>((T data) {
if (_activeCallbackIdentity == callbackIdentity) {
setState(() {
_snapshot = AsyncSnapshot<T>.withData(ConnectionState.done, data);
});
}
}, onError: (Object error, StackTrace stackTrace) {
if (_activeCallbackIdentity == callbackIdentity) {
setState(() {
_snapshot = AsyncSnapshot<T>.withError(ConnectionState.done, error, stackTrace);
});
}
assert(() {
if (FutureBuilder.debugRethrowError) {
Future<Object>.error(error, stackTrace);
}
return true;
}());
});
// An implementation like `SynchronousFuture` may have already called the
// .then closure. Do not overwrite it in that case.
if (_snapshot.connectionState != ConnectionState.done) {
_snapshot = _snapshot.inState(ConnectionState.waiting);
}
}
void _unsubscribe() {
_activeCallbackIdentity = null;
}
}
| flutter/packages/flutter/lib/src/widgets/async.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/async.dart",
"repo_id": "flutter",
"token_count": 7352
} | 252 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/services.dart';
import 'actions.dart';
import 'focus_traversal.dart';
import 'framework.dart';
import 'scrollable_helpers.dart';
import 'shortcuts.dart';
import 'text_editing_intents.dart';
/// A widget with the shortcuts used for the default text editing behavior.
///
/// This default behavior can be overridden by placing a [Shortcuts] widget
/// lower in the widget tree than this. See the [Action] class for an example
/// of remapping an [Intent] to a custom [Action].
///
/// The [Shortcuts] widget usually takes precedence over system keybindings.
/// Proceed with caution if the shortcut you wish to override is also used by
/// the system. For example, overriding [LogicalKeyboardKey.backspace] could
/// cause CJK input methods to discard more text than they should when the
/// backspace key is pressed during text composition on iOS.
///
/// {@macro flutter.widgets.editableText.shortcutsAndTextInput}
///
/// {@tool snippet}
///
/// This example shows how to use an additional [Shortcuts] widget to override
/// some default text editing keyboard shortcuts to have new behavior. Instead
/// of moving the cursor, alt + up/down will change the focused widget.
///
/// ```dart
/// @override
/// Widget build(BuildContext context) {
/// // If using WidgetsApp or its descendants MaterialApp or CupertinoApp,
/// // then DefaultTextEditingShortcuts is already being inserted into the
/// // widget tree.
/// return const DefaultTextEditingShortcuts(
/// child: Center(
/// child: Shortcuts(
/// shortcuts: <ShortcutActivator, Intent>{
/// SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): NextFocusIntent(),
/// SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): PreviousFocusIntent(),
/// },
/// child: Column(
/// children: <Widget>[
/// TextField(
/// decoration: InputDecoration(
/// hintText: 'alt + down moves to the next field.',
/// ),
/// ),
/// TextField(
/// decoration: InputDecoration(
/// hintText: 'And alt + up moves to the previous.',
/// ),
/// ),
/// ],
/// ),
/// ),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// {@tool snippet}
///
/// This example shows how to use an additional [Shortcuts] widget to override
/// default text editing shortcuts to have completely custom behavior defined by
/// a custom Intent and Action. Here, the up/down arrow keys increment/decrement
/// a counter instead of moving the cursor.
///
/// ```dart
/// class IncrementCounterIntent extends Intent {}
/// class DecrementCounterIntent extends Intent {}
///
/// class MyWidget extends StatefulWidget {
/// const MyWidget({ super.key });
///
/// @override
/// MyWidgetState createState() => MyWidgetState();
/// }
///
/// class MyWidgetState extends State<MyWidget> {
///
/// int _counter = 0;
///
/// @override
/// Widget build(BuildContext context) {
/// // If using WidgetsApp or its descendants MaterialApp or CupertinoApp,
/// // then DefaultTextEditingShortcuts is already being inserted into the
/// // widget tree.
/// return DefaultTextEditingShortcuts(
/// child: Center(
/// child: Column(
/// mainAxisAlignment: MainAxisAlignment.center,
/// children: <Widget>[
/// const Text(
/// 'You have pushed the button this many times:',
/// ),
/// Text(
/// '$_counter',
/// style: Theme.of(context).textTheme.headlineMedium,
/// ),
/// Shortcuts(
/// shortcuts: <ShortcutActivator, Intent>{
/// const SingleActivator(LogicalKeyboardKey.arrowUp): IncrementCounterIntent(),
/// const SingleActivator(LogicalKeyboardKey.arrowDown): DecrementCounterIntent(),
/// },
/// child: Actions(
/// actions: <Type, Action<Intent>>{
/// IncrementCounterIntent: CallbackAction<IncrementCounterIntent>(
/// onInvoke: (IncrementCounterIntent intent) {
/// setState(() {
/// _counter++;
/// });
/// return null;
/// },
/// ),
/// DecrementCounterIntent: CallbackAction<DecrementCounterIntent>(
/// onInvoke: (DecrementCounterIntent intent) {
/// setState(() {
/// _counter--;
/// });
/// return null;
/// },
/// ),
/// },
/// child: const TextField(
/// maxLines: 2,
/// decoration: InputDecoration(
/// hintText: 'Up/down increment/decrement here.',
/// ),
/// ),
/// ),
/// ),
/// const TextField(
/// maxLines: 2,
/// decoration: InputDecoration(
/// hintText: 'Up/down behave normally here.',
/// ),
/// ),
/// ],
/// ),
/// ),
/// );
/// }
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [WidgetsApp], which creates a DefaultTextEditingShortcuts.
class DefaultTextEditingShortcuts extends StatelessWidget {
/// Creates a [DefaultTextEditingShortcuts] widget that provides the default text editing
/// shortcuts on the current platform.
const DefaultTextEditingShortcuts({
super.key,
required this.child,
});
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
// These shortcuts are shared between all platforms except Apple platforms,
// because they use different modifier keys as the line/word modifier.
static final Map<ShortcutActivator, Intent> _commonShortcuts = <ShortcutActivator, Intent>{
// Delete Shortcuts.
for (final bool pressShift in const <bool>[true, false])
...<SingleActivator, Intent>{
SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DeleteCharacterIntent(forward: false),
SingleActivator(LogicalKeyboardKey.backspace, control: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: false),
SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): const DeleteToLineBreakIntent(forward: false),
SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DeleteCharacterIntent(forward: true),
SingleActivator(LogicalKeyboardKey.delete, control: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: true),
SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): const DeleteToLineBreakIntent(forward: true),
},
// Arrow: Move selection.
const SingleActivator(LogicalKeyboardKey.arrowLeft): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowRight): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowUp): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowDown): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true),
// Shift + Arrow: Extend selection.
const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowRight, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, control: true): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, control: true): const ExtendSelectionToNextParagraphBoundaryIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, control: true): const ExtendSelectionToNextParagraphBoundaryIntent(forward: true, collapseSelection: false),
// Page Up / Down: Move selection by page.
const SingleActivator(LogicalKeyboardKey.pageUp): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.pageDown): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true),
// Shift + Page Up / Down: Extend selection by page.
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.keyX, control: true): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard),
const SingleActivator(LogicalKeyboardKey.keyC, control: true): CopySelectionTextIntent.copy,
const SingleActivator(LogicalKeyboardKey.keyV, control: true): const PasteTextIntent(SelectionChangedCause.keyboard),
const SingleActivator(LogicalKeyboardKey.keyA, control: true): const SelectAllTextIntent(SelectionChangedCause.keyboard),
const SingleActivator(LogicalKeyboardKey.keyZ, control: true): const UndoTextIntent(SelectionChangedCause.keyboard),
const SingleActivator(LogicalKeyboardKey.keyZ, shift: true, control: true): const RedoTextIntent(SelectionChangedCause.keyboard),
// These keys should go to the IME when a field is focused, not to other
// Shortcuts.
const SingleActivator(LogicalKeyboardKey.space): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.enter): const DoNothingAndStopPropagationTextIntent(),
};
// The following key combinations have no effect on text editing on this
// platform:
// * End
// * Home
// * Meta + X
// * Meta + C
// * Meta + V
// * Meta + A
// * Meta + shift? + Z
// * Meta + shift? + arrow down
// * Meta + shift? + arrow left
// * Meta + shift? + arrow right
// * Meta + shift? + arrow up
// * Shift + end
// * Shift + home
// * Meta + shift? + delete
// * Meta + shift? + backspace
static final Map<ShortcutActivator, Intent> _androidShortcuts = _commonShortcuts;
static final Map<ShortcutActivator, Intent> _fuchsiaShortcuts = _androidShortcuts;
static final Map<ShortcutActivator, Intent> _linuxNumpadShortcuts = <ShortcutActivator, Intent>{
// When numLock is on, numpad keys shortcuts require shift to be pressed too.
const SingleActivator(LogicalKeyboardKey.numpad6, shift: true, numLock: LockState.locked): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad4, shift: true, numLock: LockState.locked): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad8, shift: true, numLock: LockState.locked): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad2, shift: true, numLock: LockState.locked): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad6, shift: true, control: true, numLock: LockState.locked): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad4, shift: true, control: true, numLock: LockState.locked): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad8, shift: true, control: true, numLock: LockState.locked): const ExtendSelectionToNextParagraphBoundaryIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad2, shift: true, control: true, numLock: LockState.locked): const ExtendSelectionToNextParagraphBoundaryIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad9, shift: true, numLock: LockState.locked): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad3, shift: true, numLock: LockState.locked): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad7, shift: true, numLock: LockState.locked): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpad1, shift: true, numLock: LockState.locked): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.numpadDecimal, shift: true, numLock: LockState.locked): const DeleteCharacterIntent(forward: true),
const SingleActivator(LogicalKeyboardKey.numpadDecimal, shift: true, control: true, numLock: LockState.locked): const DeleteToNextWordBoundaryIntent(forward: true),
// When numLock is off, numpad keys shortcuts require shift not to be pressed.
const SingleActivator(LogicalKeyboardKey.numpad6, numLock: LockState.unlocked): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad4, numLock: LockState.unlocked): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad8, numLock: LockState.unlocked): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad2, numLock: LockState.unlocked): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad6, control: true, numLock: LockState.unlocked): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad4, control: true, numLock: LockState.unlocked): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad8, control: true, numLock: LockState.unlocked): const ExtendSelectionToNextParagraphBoundaryIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad2, control: true, numLock: LockState.unlocked): const ExtendSelectionToNextParagraphBoundaryIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad9, numLock: LockState.unlocked): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad3, numLock: LockState.unlocked): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad7, numLock: LockState.unlocked): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpad1, numLock: LockState.unlocked): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.numpadDecimal, numLock: LockState.unlocked): const DeleteCharacterIntent(forward: true),
const SingleActivator(LogicalKeyboardKey.numpadDecimal, control: true, numLock: LockState.unlocked): const DeleteToNextWordBoundaryIntent(forward: true),
};
static final Map<ShortcutActivator, Intent> _linuxShortcuts = <ShortcutActivator, Intent>{
..._commonShortcuts,
..._linuxNumpadShortcuts,
const SingleActivator(LogicalKeyboardKey.home): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.end): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false),
// The following key combinations have no effect on text editing on this
// platform:
// * Control + shift? + end
// * Control + shift? + home
// * Meta + X
// * Meta + C
// * Meta + V
// * Meta + A
// * Meta + shift? + Z
// * Meta + shift? + arrow down
// * Meta + shift? + arrow left
// * Meta + shift? + arrow right
// * Meta + shift? + arrow up
// * Meta + shift? + delete
// * Meta + shift? + backspace
};
// macOS document shortcuts: https://support.apple.com/en-us/HT201236.
// The macOS shortcuts uses different word/line modifiers than most other
// platforms.
static final Map<ShortcutActivator, Intent> _macShortcuts = <ShortcutActivator, Intent>{
for (final bool pressShift in const <bool>[true, false])
...<SingleActivator, Intent>{
SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DeleteCharacterIntent(forward: false),
SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: false),
SingleActivator(LogicalKeyboardKey.backspace, meta: true, shift: pressShift): const DeleteToLineBreakIntent(forward: false),
SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DeleteCharacterIntent(forward: true),
SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): const DeleteToNextWordBoundaryIntent(forward: true),
SingleActivator(LogicalKeyboardKey.delete, meta: true, shift: pressShift): const DeleteToLineBreakIntent(forward: true),
},
const SingleActivator(LogicalKeyboardKey.arrowLeft): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowRight): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowUp): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowDown): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true),
// Shift + Arrow: Extend selection.
const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): const ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): const ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): const ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: false),
const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): const ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: true),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): const ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: false),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): const ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: true),
const SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, meta: true): const ExpandSelectionToLineBreakIntent(forward: false),
const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, meta: true): const ExpandSelectionToLineBreakIntent(forward: true),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, meta: true): const ExpandSelectionToDocumentBoundaryIntent(forward: false),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, meta: true): const ExpandSelectionToDocumentBoundaryIntent(forward: true),
const SingleActivator(LogicalKeyboardKey.keyT, control: true): const TransposeCharactersIntent(),
const SingleActivator(LogicalKeyboardKey.home): const ScrollToDocumentBoundaryIntent(forward: false),
const SingleActivator(LogicalKeyboardKey.end): const ScrollToDocumentBoundaryIntent(forward: true),
const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExpandSelectionToDocumentBoundaryIntent(forward: false),
const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExpandSelectionToDocumentBoundaryIntent(forward: true),
const SingleActivator(LogicalKeyboardKey.pageUp): const ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
const SingleActivator(LogicalKeyboardKey.pageDown): const ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.keyX, meta: true): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard),
const SingleActivator(LogicalKeyboardKey.keyC, meta: true): CopySelectionTextIntent.copy,
const SingleActivator(LogicalKeyboardKey.keyV, meta: true): const PasteTextIntent(SelectionChangedCause.keyboard),
const SingleActivator(LogicalKeyboardKey.keyA, meta: true): const SelectAllTextIntent(SelectionChangedCause.keyboard),
const SingleActivator(LogicalKeyboardKey.keyZ, meta: true): const UndoTextIntent(SelectionChangedCause.keyboard),
const SingleActivator(LogicalKeyboardKey.keyZ, shift: true, meta: true): const RedoTextIntent(SelectionChangedCause.keyboard),
const SingleActivator(LogicalKeyboardKey.keyE, control: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.keyA, control: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.keyF, control: true): const ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.keyB, control: true): const ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.keyN, control: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.keyP, control: true): const ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true),
// These keys should go to the IME when a field is focused, not to other
// Shortcuts.
const SingleActivator(LogicalKeyboardKey.space): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.enter): const DoNothingAndStopPropagationTextIntent(),
// The following key combinations have no effect on text editing on this
// platform:
// * End
// * Home
// * Control + shift? + end
// * Control + shift? + home
// * Control + shift? + Z
};
// There is no complete documentation of iOS shortcuts: use macOS ones.
static final Map<ShortcutActivator, Intent> _iOSShortcuts = _macShortcuts;
// The following key combinations have no effect on text editing on this
// platform:
// * Meta + X
// * Meta + C
// * Meta + V
// * Meta + A
// * Meta + shift? + arrow down
// * Meta + shift? + arrow left
// * Meta + shift? + arrow right
// * Meta + shift? + arrow up
// * Meta + delete
// * Meta + backspace
static final Map<ShortcutActivator, Intent> _windowsShortcuts = <ShortcutActivator, Intent>{
..._commonShortcuts,
const SingleActivator(LogicalKeyboardKey.pageUp): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.pageDown): const ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.home): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true, continuesAtWrap: true),
const SingleActivator(LogicalKeyboardKey.end): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true, continuesAtWrap: true),
const SingleActivator(LogicalKeyboardKey.home, shift: true): const ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: false, continuesAtWrap: true),
const SingleActivator(LogicalKeyboardKey.end, shift: true): const ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: false, continuesAtWrap: true),
const SingleActivator(LogicalKeyboardKey.home, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.end, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true),
const SingleActivator(LogicalKeyboardKey.home, shift: true, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: false),
const SingleActivator(LogicalKeyboardKey.end, shift: true, control: true): const ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: false),
};
// Web handles its text selection natively and doesn't use any of these
// shortcuts in Flutter.
static final Map<ShortcutActivator, Intent> _webDisablingTextShortcuts = <ShortcutActivator, Intent>{
for (final bool pressShift in const <bool>[true, false])
...<SingleActivator, Intent>{
SingleActivator(LogicalKeyboardKey.backspace, shift: pressShift): const DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.delete, shift: pressShift): const DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.backspace, control: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.delete, control: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.backspace, meta: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.delete, meta: true, shift: pressShift): const DoNothingAndStopPropagationTextIntent(),
},
..._commonDisablingTextShortcuts,
const SingleActivator(LogicalKeyboardKey.keyX, control: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.keyX, meta: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.keyC, control: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.keyC, meta: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.keyV, control: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.keyV, meta: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.keyA, control: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.keyA, meta: true): const DoNothingAndStopPropagationTextIntent(),
};
static const Map<ShortcutActivator, Intent> _commonDisablingTextShortcuts = <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.arrowDown, alt: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowRight, alt: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowUp, alt: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown, meta: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowLeft, meta: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowRight, meta: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowUp, meta: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowLeft): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowRight): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowUp): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowLeft, control: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowRight, control: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, control: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, control: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.space): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.enter): DoNothingAndStopPropagationTextIntent(),
};
static final Map<ShortcutActivator, Intent> _macDisablingTextShortcuts = <ShortcutActivator, Intent>{
..._commonDisablingTextShortcuts,
..._iOSDisablingTextShortcuts,
const SingleActivator(LogicalKeyboardKey.escape): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.tab): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.tab, shift: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.arrowDown, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.arrowUp, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, alt: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.arrowLeft, shift: true, meta: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.arrowRight, shift: true, meta: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.pageUp): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.pageDown): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.end): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.home): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.pageUp, shift: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.pageDown, shift: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.end, shift: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.home, shift: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.end, control: true): const DoNothingAndStopPropagationTextIntent(),
const SingleActivator(LogicalKeyboardKey.home, control: true): const DoNothingAndStopPropagationTextIntent(),
};
// Hand backspace/delete events that do not depend on text layout (delete
// character and delete to the next word) back to the IME to allow it to
// update composing text properly.
static const Map<ShortcutActivator, Intent> _iOSDisablingTextShortcuts = <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.backspace): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.backspace, shift: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.delete): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.delete, shift: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.backspace, alt: true, shift: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.backspace, alt: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.delete, alt: true, shift: true): DoNothingAndStopPropagationTextIntent(),
SingleActivator(LogicalKeyboardKey.delete, alt: true): DoNothingAndStopPropagationTextIntent(),
};
static Map<ShortcutActivator, Intent> get _shortcuts {
return switch (defaultTargetPlatform) {
TargetPlatform.android => _androidShortcuts,
TargetPlatform.fuchsia => _fuchsiaShortcuts,
TargetPlatform.iOS => _iOSShortcuts,
TargetPlatform.linux => _linuxShortcuts,
TargetPlatform.macOS => _macShortcuts,
TargetPlatform.windows => _windowsShortcuts,
};
}
Map<ShortcutActivator, Intent>? _getDisablingShortcut() {
if (kIsWeb) {
switch (defaultTargetPlatform) {
case TargetPlatform.linux:
return <ShortcutActivator, Intent>{
..._webDisablingTextShortcuts,
for (final ShortcutActivator activator in _linuxNumpadShortcuts.keys)
activator as SingleActivator: const DoNothingAndStopPropagationTextIntent(),
};
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.windows:
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return _webDisablingTextShortcuts;
}
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return null;
case TargetPlatform.iOS:
return _iOSDisablingTextShortcuts;
case TargetPlatform.macOS:
return _macDisablingTextShortcuts;
}
}
@override
Widget build(BuildContext context) {
Widget result = child;
final Map<ShortcutActivator, Intent>? disablingShortcut = _getDisablingShortcut();
if (disablingShortcut != null) {
// These shortcuts make sure of the following:
//
// 1. Shortcuts fired when an EditableText is focused are ignored and
// forwarded to the platform by the EditableText's Actions, because it
// maps DoNothingAndStopPropagationTextIntent to DoNothingAction.
// 2. Shortcuts fired when no EditableText is focused will still trigger
// _shortcuts assuming DoNothingAndStopPropagationTextIntent is
// unhandled elsewhere.
result = Shortcuts(
debugLabel: '<Web Disabling Text Editing Shortcuts>',
shortcuts: disablingShortcut,
child: result
);
}
return Shortcuts(
debugLabel: '<Default Text Editing Shortcuts>',
shortcuts: _shortcuts,
child: result
);
}
}
/// Maps the selector from NSStandardKeyBindingResponding to the Intent if the
/// selector is recognized.
Intent? intentForMacOSSelector(String selectorName) {
const Map<String, Intent> selectorToIntent = <String, Intent>{
'deleteBackward:': DeleteCharacterIntent(forward: false),
'deleteWordBackward:': DeleteToNextWordBoundaryIntent(forward: false),
'deleteToBeginningOfLine:': DeleteToLineBreakIntent(forward: false),
'deleteForward:': DeleteCharacterIntent(forward: true),
'deleteWordForward:': DeleteToNextWordBoundaryIntent(forward: true),
'deleteToEndOfLine:': DeleteToLineBreakIntent(forward: true),
'moveLeft:': ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true),
'moveRight:': ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true),
'moveForward:': ExtendSelectionByCharacterIntent(forward: true, collapseSelection: true),
'moveBackward:': ExtendSelectionByCharacterIntent(forward: false, collapseSelection: true),
'moveUp:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: true),
'moveDown:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: true),
'moveLeftAndModifySelection:': ExtendSelectionByCharacterIntent(forward: false, collapseSelection: false),
'moveRightAndModifySelection:': ExtendSelectionByCharacterIntent(forward: true, collapseSelection: false),
'moveUpAndModifySelection:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: false, collapseSelection: false),
'moveDownAndModifySelection:': ExtendSelectionVerticallyToAdjacentLineIntent(forward: true, collapseSelection: false),
'moveWordLeft:': ExtendSelectionToNextWordBoundaryIntent(forward: false, collapseSelection: true),
'moveWordRight:': ExtendSelectionToNextWordBoundaryIntent(forward: true, collapseSelection: true),
'moveToBeginningOfParagraph:': ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true),
'moveToEndOfParagraph:': ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true),
'moveWordLeftAndModifySelection:': ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: false),
'moveWordRightAndModifySelection:': ExtendSelectionToNextWordBoundaryOrCaretLocationIntent(forward: true),
'moveParagraphBackwardAndModifySelection:': ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: false),
'moveParagraphForwardAndModifySelection:': ExtendSelectionToNextParagraphBoundaryOrCaretLocationIntent(forward: true),
'moveToLeftEndOfLine:': ExtendSelectionToLineBreakIntent(forward: false, collapseSelection: true),
'moveToRightEndOfLine:': ExtendSelectionToLineBreakIntent(forward: true, collapseSelection: true),
'moveToBeginningOfDocument:': ExtendSelectionToDocumentBoundaryIntent(forward: false, collapseSelection: true),
'moveToEndOfDocument:': ExtendSelectionToDocumentBoundaryIntent(forward: true, collapseSelection: true),
'moveToLeftEndOfLineAndModifySelection:': ExpandSelectionToLineBreakIntent(forward: false),
'moveToRightEndOfLineAndModifySelection:': ExpandSelectionToLineBreakIntent(forward: true),
'moveToBeginningOfDocumentAndModifySelection:': ExpandSelectionToDocumentBoundaryIntent(forward: false),
'moveToEndOfDocumentAndModifySelection:': ExpandSelectionToDocumentBoundaryIntent(forward: true),
'transpose:': TransposeCharactersIntent(),
'scrollToBeginningOfDocument:': ScrollToDocumentBoundaryIntent(forward: false),
'scrollToEndOfDocument:': ScrollToDocumentBoundaryIntent(forward: true),
'scrollPageUp:': ScrollIntent(direction: AxisDirection.up, type: ScrollIncrementType.page),
'scrollPageDown:': ScrollIntent(direction: AxisDirection.down, type: ScrollIncrementType.page),
'pageUpAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent(forward: false, collapseSelection: false),
'pageDownAndModifySelection:': ExtendSelectionVerticallyToAdjacentPageIntent(forward: true, collapseSelection: false),
// Escape key when there's no IME selection popup.
'cancelOperation:': DismissIntent(),
// Tab when there's no IME selection.
'insertTab:': NextFocusIntent(),
'insertBacktab:': PreviousFocusIntent(),
};
return selectorToIntent[selectorName];
}
| flutter/packages/flutter/lib/src/widgets/default_text_editing_shortcuts.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/default_text_editing_shortcuts.dart",
"repo_id": "flutter",
"token_count": 14225
} | 253 |
// Copyright 2014 The Flutter Authors. 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/rendering.dart';
import 'basic.dart';
import 'framework.dart';
import 'media_query.dart';
import 'scroll_configuration.dart';
export 'package:flutter/gestures.dart' show
DragDownDetails,
DragEndDetails,
DragStartDetails,
DragUpdateDetails,
ForcePressDetails,
GestureDragCancelCallback,
GestureDragDownCallback,
GestureDragEndCallback,
GestureDragStartCallback,
GestureDragUpdateCallback,
GestureForcePressEndCallback,
GestureForcePressPeakCallback,
GestureForcePressStartCallback,
GestureForcePressUpdateCallback,
GestureLongPressCallback,
GestureLongPressEndCallback,
GestureLongPressMoveUpdateCallback,
GestureLongPressStartCallback,
GestureLongPressUpCallback,
GestureScaleEndCallback,
GestureScaleStartCallback,
GestureScaleUpdateCallback,
GestureTapCallback,
GestureTapCancelCallback,
GestureTapDownCallback,
GestureTapUpCallback,
LongPressEndDetails,
LongPressMoveUpdateDetails,
LongPressStartDetails,
ScaleEndDetails,
ScaleStartDetails,
ScaleUpdateDetails,
TapDownDetails,
TapUpDetails,
Velocity;
export 'package:flutter/rendering.dart' show RenderSemanticsGestureHandler;
// Examples can assume:
// late bool _lights;
// void setState(VoidCallback fn) { }
// late String _last;
// late Color _color;
/// Factory for creating gesture recognizers.
///
/// `T` is the type of gesture recognizer this class manages.
///
/// Used by [RawGestureDetector.gestures].
@optionalTypeArgs
abstract class GestureRecognizerFactory<T extends GestureRecognizer> {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const GestureRecognizerFactory();
/// Must return an instance of T.
T constructor();
/// Must configure the given instance (which will have been created by
/// `constructor`).
///
/// This normally means setting the callbacks.
void initializer(T instance);
bool _debugAssertTypeMatches(Type type) {
assert(type == T, 'GestureRecognizerFactory of type $T was used where type $type was specified.');
return true;
}
}
/// Signature for closures that implement [GestureRecognizerFactory.constructor].
typedef GestureRecognizerFactoryConstructor<T extends GestureRecognizer> = T Function();
/// Signature for closures that implement [GestureRecognizerFactory.initializer].
typedef GestureRecognizerFactoryInitializer<T extends GestureRecognizer> = void Function(T instance);
/// Factory for creating gesture recognizers that delegates to callbacks.
///
/// Used by [RawGestureDetector.gestures].
class GestureRecognizerFactoryWithHandlers<T extends GestureRecognizer> extends GestureRecognizerFactory<T> {
/// Creates a gesture recognizer factory with the given callbacks.
const GestureRecognizerFactoryWithHandlers(this._constructor, this._initializer);
final GestureRecognizerFactoryConstructor<T> _constructor;
final GestureRecognizerFactoryInitializer<T> _initializer;
@override
T constructor() => _constructor();
@override
void initializer(T instance) => _initializer(instance);
}
/// A widget that detects gestures.
///
/// Attempts to recognize gestures that correspond to its non-null callbacks.
///
/// If this widget has a child, it defers to that child for its sizing behavior.
/// If it does not have a child, it grows to fit the parent instead.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=WhVXkCFPmK4}
///
/// By default a GestureDetector with an invisible child ignores touches;
/// this behavior can be controlled with [behavior].
///
/// GestureDetector also listens for accessibility events and maps
/// them to the callbacks. To ignore accessibility events, set
/// [excludeFromSemantics] to true.
///
/// See <http://flutter.dev/gestures/> for additional information.
///
/// Material design applications typically react to touches with ink splash
/// effects. The [InkWell] class implements this effect and can be used in place
/// of a [GestureDetector] for handling taps.
///
/// {@tool dartpad}
/// This example contains a black light bulb wrapped in a [GestureDetector]. It
/// turns the light bulb yellow when the "TURN LIGHT ON" button is tapped by
/// setting the `_lights` field, and off again when "TURN LIGHT OFF" is tapped.
///
/// ** See code in examples/api/lib/widgets/gesture_detector/gesture_detector.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example uses a [Container] that wraps a [GestureDetector] widget which
/// detects a tap.
///
/// Since the [GestureDetector] does not have a child, it takes on the size of its
/// parent, making the entire area of the surrounding [Container] clickable. When
/// tapped, the [Container] turns yellow by setting the `_color` field. When
/// tapped again, it goes back to white.
///
/// ** See code in examples/api/lib/widgets/gesture_detector/gesture_detector.1.dart **
/// {@end-tool}
///
/// ### Troubleshooting
///
/// Why isn't my parent [GestureDetector.onTap] method called?
///
/// Given a parent [GestureDetector] with an onTap callback, and a child
/// GestureDetector that also defines an onTap callback, when the inner
/// GestureDetector is tapped, both GestureDetectors send a [GestureRecognizer]
/// into the gesture arena. This is because the pointer coordinates are within the
/// bounds of both GestureDetectors. The child GestureDetector wins in this
/// scenario because it was the first to enter the arena, resolving as first come,
/// first served. The child onTap is called, and the parent's is not as the gesture has
/// been consumed.
/// For more information on gesture disambiguation see:
/// [Gesture disambiguation](https://docs.flutter.dev/development/ui/advanced/gestures#gesture-disambiguation).
///
/// Setting [GestureDetector.behavior] to [HitTestBehavior.opaque]
/// or [HitTestBehavior.translucent] has no impact on parent-child relationships:
/// both GestureDetectors send a GestureRecognizer into the gesture arena, only one wins.
///
/// Some callbacks (e.g. onTapDown) can fire before a recognizer wins the arena,
/// and others (e.g. onTapCancel) fire even when it loses the arena. Therefore,
/// the parent detector in the example above may call some of its callbacks even
/// though it loses in the arena.
///
/// {@tool dartpad}
/// This example uses a [GestureDetector] that wraps a green [Container] and a second
/// GestureDetector that wraps a yellow Container. The second GestureDetector is
/// a child of the green Container.
/// Both GestureDetectors define an onTap callback. When the callback is called it
/// adds a red border to the corresponding Container.
///
/// When the green Container is tapped, it's parent GestureDetector enters
/// the gesture arena. It wins because there is no competing GestureDetector and
/// the green Container shows a red border.
/// When the yellow Container is tapped, it's parent GestureDetector enters
/// the gesture arena. The GestureDetector that wraps the green Container also
/// enters the gesture arena (the pointer events coordinates are inside both
/// GestureDetectors bounds). The GestureDetector that wraps the yellow Container
/// wins because it was the first detector to enter the arena.
///
/// This example sets [debugPrintGestureArenaDiagnostics] to true.
/// This flag prints useful information about gesture arenas.
///
/// Changing the [GestureDetector.behavior] property to [HitTestBehavior.translucent]
/// or [HitTestBehavior.opaque] has no impact: both GestureDetectors send a [GestureRecognizer]
/// into the gesture arena, only one wins.
///
/// ** See code in examples/api/lib/widgets/gesture_detector/gesture_detector.2.dart **
/// {@end-tool}
///
/// ## Debugging
///
/// To see how large the hit test box of a [GestureDetector] is for debugging
/// purposes, set [debugPaintPointersEnabled] to true.
///
/// See also:
///
/// * [Listener], a widget for listening to lower-level raw pointer events.
/// * [MouseRegion], a widget that tracks the movement of mice, even when no
/// button is pressed.
/// * [RawGestureDetector], a widget that is used to detect custom gestures.
class GestureDetector extends StatelessWidget {
/// Creates a widget that detects gestures.
///
/// Pan and scale callbacks cannot be used simultaneously because scale is a
/// superset of pan. Use the scale callbacks instead.
///
/// Horizontal and vertical drag callbacks cannot be used simultaneously
/// because a combination of a horizontal and vertical drag is a pan.
/// Use the pan callbacks instead.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=WhVXkCFPmK4}
///
/// By default, gesture detectors contribute semantic information to the tree
/// that is used by assistive technology.
GestureDetector({
super.key,
this.child,
this.onTapDown,
this.onTapUp,
this.onTap,
this.onTapCancel,
this.onSecondaryTap,
this.onSecondaryTapDown,
this.onSecondaryTapUp,
this.onSecondaryTapCancel,
this.onTertiaryTapDown,
this.onTertiaryTapUp,
this.onTertiaryTapCancel,
this.onDoubleTapDown,
this.onDoubleTap,
this.onDoubleTapCancel,
this.onLongPressDown,
this.onLongPressCancel,
this.onLongPress,
this.onLongPressStart,
this.onLongPressMoveUpdate,
this.onLongPressUp,
this.onLongPressEnd,
this.onSecondaryLongPressDown,
this.onSecondaryLongPressCancel,
this.onSecondaryLongPress,
this.onSecondaryLongPressStart,
this.onSecondaryLongPressMoveUpdate,
this.onSecondaryLongPressUp,
this.onSecondaryLongPressEnd,
this.onTertiaryLongPressDown,
this.onTertiaryLongPressCancel,
this.onTertiaryLongPress,
this.onTertiaryLongPressStart,
this.onTertiaryLongPressMoveUpdate,
this.onTertiaryLongPressUp,
this.onTertiaryLongPressEnd,
this.onVerticalDragDown,
this.onVerticalDragStart,
this.onVerticalDragUpdate,
this.onVerticalDragEnd,
this.onVerticalDragCancel,
this.onHorizontalDragDown,
this.onHorizontalDragStart,
this.onHorizontalDragUpdate,
this.onHorizontalDragEnd,
this.onHorizontalDragCancel,
this.onForcePressStart,
this.onForcePressPeak,
this.onForcePressUpdate,
this.onForcePressEnd,
this.onPanDown,
this.onPanStart,
this.onPanUpdate,
this.onPanEnd,
this.onPanCancel,
this.onScaleStart,
this.onScaleUpdate,
this.onScaleEnd,
this.behavior,
this.excludeFromSemantics = false,
this.dragStartBehavior = DragStartBehavior.start,
this.trackpadScrollCausesScale = false,
this.trackpadScrollToScaleFactor = kDefaultTrackpadScrollToScaleFactor,
this.supportedDevices,
}) : assert(() {
final bool haveVerticalDrag = onVerticalDragStart != null || onVerticalDragUpdate != null || onVerticalDragEnd != null;
final bool haveHorizontalDrag = onHorizontalDragStart != null || onHorizontalDragUpdate != null || onHorizontalDragEnd != null;
final bool havePan = onPanStart != null || onPanUpdate != null || onPanEnd != null;
final bool haveScale = onScaleStart != null || onScaleUpdate != null || onScaleEnd != null;
if (havePan || haveScale) {
if (havePan && haveScale) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Incorrect GestureDetector arguments.'),
ErrorDescription(
'Having both a pan gesture recognizer and a scale gesture recognizer is redundant; scale is a superset of pan.',
),
ErrorHint('Just use the scale gesture recognizer.'),
]);
}
final String recognizer = havePan ? 'pan' : 'scale';
if (haveVerticalDrag && haveHorizontalDrag) {
throw FlutterError(
'Incorrect GestureDetector arguments.\n'
'Simultaneously having a vertical drag gesture recognizer, a horizontal drag gesture recognizer, and a $recognizer gesture recognizer '
'will result in the $recognizer gesture recognizer being ignored, since the other two will catch all drags.',
);
}
}
return true;
}());
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// A pointer that might cause a tap with a primary button has contacted the
/// screen at a particular location.
///
/// This is called after a short timeout, even if the winning gesture has not
/// yet been selected. If the tap gesture wins, [onTapUp] will be called,
/// otherwise [onTapCancel] will be called.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapDownCallback? onTapDown;
/// A pointer that will trigger a tap with a primary button has stopped
/// contacting the screen at a particular location.
///
/// This triggers immediately before [onTap] in the case of the tap gesture
/// winning. If the tap gesture did not win, [onTapCancel] is called instead.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapUpCallback? onTapUp;
/// A tap with a primary button has occurred.
///
/// This triggers when the tap gesture wins. If the tap gesture did not win,
/// [onTapCancel] is called instead.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [onTapUp], which is called at the same time but includes details
/// regarding the pointer position.
final GestureTapCallback? onTap;
/// The pointer that previously triggered [onTapDown] will not end up causing
/// a tap.
///
/// This is called after [onTapDown], and instead of [onTapUp] and [onTap], if
/// the tap gesture did not win.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapCancelCallback? onTapCancel;
/// A tap with a secondary button has occurred.
///
/// This triggers when the tap gesture wins. If the tap gesture did not win,
/// [onSecondaryTapCancel] is called instead.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [onSecondaryTapUp], which is called at the same time but includes details
/// regarding the pointer position.
final GestureTapCallback? onSecondaryTap;
/// A pointer that might cause a tap with a secondary button has contacted the
/// screen at a particular location.
///
/// This is called after a short timeout, even if the winning gesture has not
/// yet been selected. If the tap gesture wins, [onSecondaryTapUp] will be
/// called, otherwise [onSecondaryTapCancel] will be called.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
final GestureTapDownCallback? onSecondaryTapDown;
/// A pointer that will trigger a tap with a secondary button has stopped
/// contacting the screen at a particular location.
///
/// This triggers in the case of the tap gesture winning. If the tap gesture
/// did not win, [onSecondaryTapCancel] is called instead.
///
/// See also:
///
/// * [onSecondaryTap], a handler triggered right after this one that doesn't
/// pass any details about the tap.
/// * [kSecondaryButton], the button this callback responds to.
final GestureTapUpCallback? onSecondaryTapUp;
/// The pointer that previously triggered [onSecondaryTapDown] will not end up
/// causing a tap.
///
/// This is called after [onSecondaryTapDown], and instead of
/// [onSecondaryTapUp], if the tap gesture did not win.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
final GestureTapCancelCallback? onSecondaryTapCancel;
/// A pointer that might cause a tap with a tertiary button has contacted the
/// screen at a particular location.
///
/// This is called after a short timeout, even if the winning gesture has not
/// yet been selected. If the tap gesture wins, [onTertiaryTapUp] will be
/// called, otherwise [onTertiaryTapCancel] will be called.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
final GestureTapDownCallback? onTertiaryTapDown;
/// A pointer that will trigger a tap with a tertiary button has stopped
/// contacting the screen at a particular location.
///
/// This triggers in the case of the tap gesture winning. If the tap gesture
/// did not win, [onTertiaryTapCancel] is called instead.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
final GestureTapUpCallback? onTertiaryTapUp;
/// The pointer that previously triggered [onTertiaryTapDown] will not end up
/// causing a tap.
///
/// This is called after [onTertiaryTapDown], and instead of
/// [onTertiaryTapUp], if the tap gesture did not win.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
final GestureTapCancelCallback? onTertiaryTapCancel;
/// A pointer that might cause a double tap has contacted the screen at a
/// particular location.
///
/// Triggered immediately after the down event of the second tap.
///
/// If the user completes the double tap and the gesture wins, [onDoubleTap]
/// will be called after this callback. Otherwise, [onDoubleTapCancel] will
/// be called after this callback.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapDownCallback? onDoubleTapDown;
/// The user has tapped the screen with a primary button at the same location
/// twice in quick succession.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapCallback? onDoubleTap;
/// The pointer that previously triggered [onDoubleTapDown] will not end up
/// causing a double tap.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureTapCancelCallback? onDoubleTapCancel;
/// The pointer has contacted the screen with a primary button, which might
/// be the start of a long-press.
///
/// This triggers after the pointer down event.
///
/// If the user completes the long-press, and this gesture wins,
/// [onLongPressStart] will be called after this callback. Otherwise,
/// [onLongPressCancel] will be called after this callback.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [onSecondaryLongPressDown], a similar callback but for a secondary button.
/// * [onTertiaryLongPressDown], a similar callback but for a tertiary button.
/// * [LongPressGestureRecognizer.onLongPressDown], which exposes this
/// callback at the gesture layer.
final GestureLongPressDownCallback? onLongPressDown;
/// A pointer that previously triggered [onLongPressDown] will not end up
/// causing a long-press.
///
/// This triggers once the gesture loses if [onLongPressDown] has previously
/// been triggered.
///
/// If the user completed the long-press, and the gesture won, then
/// [onLongPressStart] and [onLongPress] are called instead.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressCancel], which exposes this
/// callback at the gesture layer.
final GestureLongPressCancelCallback? onLongPressCancel;
/// Called when a long press gesture with a primary button has been recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately after) [onLongPressStart].
/// The only difference between the two is that this callback does not
/// contain details of the position at which the pointer initially contacted
/// the screen.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPress], which exposes this
/// callback at the gesture layer.
final GestureLongPressCallback? onLongPress;
/// Called when a long press gesture with a primary button has been recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately before) [onLongPress].
/// The only difference between the two is that this callback contains
/// details of the position at which the pointer initially contacted the
/// screen, whereas [onLongPress] does not.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressStart], which exposes this
/// callback at the gesture layer.
final GestureLongPressStartCallback? onLongPressStart;
/// A pointer has been drag-moved after a long-press with a primary button.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressMoveUpdate], which exposes this
/// callback at the gesture layer.
final GestureLongPressMoveUpdateCallback? onLongPressMoveUpdate;
/// A pointer that has triggered a long-press with a primary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately after) [onLongPressEnd].
/// The only difference between the two is that this callback does not
/// contain details of the state of the pointer when it stopped contacting
/// the screen.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressUp], which exposes this
/// callback at the gesture layer.
final GestureLongPressUpCallback? onLongPressUp;
/// A pointer that has triggered a long-press with a primary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately before) [onLongPressUp].
/// The only difference between the two is that this callback contains
/// details of the state of the pointer when it stopped contacting the
/// screen, whereas [onLongPressUp] does not.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onLongPressEnd], which exposes this
/// callback at the gesture layer.
final GestureLongPressEndCallback? onLongPressEnd;
/// The pointer has contacted the screen with a secondary button, which might
/// be the start of a long-press.
///
/// This triggers after the pointer down event.
///
/// If the user completes the long-press, and this gesture wins,
/// [onSecondaryLongPressStart] will be called after this callback. Otherwise,
/// [onSecondaryLongPressCancel] will be called after this callback.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [onLongPressDown], a similar callback but for a secondary button.
/// * [onTertiaryLongPressDown], a similar callback but for a tertiary button.
/// * [LongPressGestureRecognizer.onSecondaryLongPressDown], which exposes
/// this callback at the gesture layer.
final GestureLongPressDownCallback? onSecondaryLongPressDown;
/// A pointer that previously triggered [onSecondaryLongPressDown] will not
/// end up causing a long-press.
///
/// This triggers once the gesture loses if [onSecondaryLongPressDown] has
/// previously been triggered.
///
/// If the user completed the long-press, and the gesture won, then
/// [onSecondaryLongPressStart] and [onSecondaryLongPress] are called instead.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressCancel], which exposes
/// this callback at the gesture layer.
final GestureLongPressCancelCallback? onSecondaryLongPressCancel;
/// Called when a long press gesture with a secondary button has been
/// recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately after)
/// [onSecondaryLongPressStart]. The only difference between the two is that
/// this callback does not contain details of the position at which the
/// pointer initially contacted the screen.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPress], which exposes
/// this callback at the gesture layer.
final GestureLongPressCallback? onSecondaryLongPress;
/// Called when a long press gesture with a secondary button has been
/// recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately before)
/// [onSecondaryLongPress]. The only difference between the two is that this
/// callback contains details of the position at which the pointer initially
/// contacted the screen, whereas [onSecondaryLongPress] does not.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressStart], which exposes
/// this callback at the gesture layer.
final GestureLongPressStartCallback? onSecondaryLongPressStart;
/// A pointer has been drag-moved after a long press with a secondary button.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressMoveUpdate], which exposes
/// this callback at the gesture layer.
final GestureLongPressMoveUpdateCallback? onSecondaryLongPressMoveUpdate;
/// A pointer that has triggered a long-press with a secondary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately after)
/// [onSecondaryLongPressEnd]. The only difference between the two is that
/// this callback does not contain details of the state of the pointer when
/// it stopped contacting the screen.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressUp], which exposes
/// this callback at the gesture layer.
final GestureLongPressUpCallback? onSecondaryLongPressUp;
/// A pointer that has triggered a long-press with a secondary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately before)
/// [onSecondaryLongPressUp]. The only difference between the two is that
/// this callback contains details of the state of the pointer when it
/// stopped contacting the screen, whereas [onSecondaryLongPressUp] does not.
///
/// See also:
///
/// * [kSecondaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onSecondaryLongPressEnd], which exposes
/// this callback at the gesture layer.
final GestureLongPressEndCallback? onSecondaryLongPressEnd;
/// The pointer has contacted the screen with a tertiary button, which might
/// be the start of a long-press.
///
/// This triggers after the pointer down event.
///
/// If the user completes the long-press, and this gesture wins,
/// [onTertiaryLongPressStart] will be called after this callback. Otherwise,
/// [onTertiaryLongPressCancel] will be called after this callback.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [onLongPressDown], a similar callback but for a primary button.
/// * [onSecondaryLongPressDown], a similar callback but for a secondary button.
/// * [LongPressGestureRecognizer.onTertiaryLongPressDown], which exposes
/// this callback at the gesture layer.
final GestureLongPressDownCallback? onTertiaryLongPressDown;
/// A pointer that previously triggered [onTertiaryLongPressDown] will not
/// end up causing a long-press.
///
/// This triggers once the gesture loses if [onTertiaryLongPressDown] has
/// previously been triggered.
///
/// If the user completed the long-press, and the gesture won, then
/// [onTertiaryLongPressStart] and [onTertiaryLongPress] are called instead.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressCancel], which exposes
/// this callback at the gesture layer.
final GestureLongPressCancelCallback? onTertiaryLongPressCancel;
/// Called when a long press gesture with a tertiary button has been
/// recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately after)
/// [onTertiaryLongPressStart]. The only difference between the two is that
/// this callback does not contain details of the position at which the
/// pointer initially contacted the screen.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPress], which exposes
/// this callback at the gesture layer.
final GestureLongPressCallback? onTertiaryLongPress;
/// Called when a long press gesture with a tertiary button has been
/// recognized.
///
/// Triggered when a pointer has remained in contact with the screen at the
/// same location for a long period of time.
///
/// This is equivalent to (and is called immediately before)
/// [onTertiaryLongPress]. The only difference between the two is that this
/// callback contains details of the position at which the pointer initially
/// contacted the screen, whereas [onTertiaryLongPress] does not.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressStart], which exposes
/// this callback at the gesture layer.
final GestureLongPressStartCallback? onTertiaryLongPressStart;
/// A pointer has been drag-moved after a long press with a tertiary button.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressMoveUpdate], which exposes
/// this callback at the gesture layer.
final GestureLongPressMoveUpdateCallback? onTertiaryLongPressMoveUpdate;
/// A pointer that has triggered a long-press with a tertiary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately after)
/// [onTertiaryLongPressEnd]. The only difference between the two is that
/// this callback does not contain details of the state of the pointer when
/// it stopped contacting the screen.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressUp], which exposes
/// this callback at the gesture layer.
final GestureLongPressUpCallback? onTertiaryLongPressUp;
/// A pointer that has triggered a long-press with a tertiary button has
/// stopped contacting the screen.
///
/// This is equivalent to (and is called immediately before)
/// [onTertiaryLongPressUp]. The only difference between the two is that
/// this callback contains details of the state of the pointer when it
/// stopped contacting the screen, whereas [onTertiaryLongPressUp] does not.
///
/// See also:
///
/// * [kTertiaryButton], the button this callback responds to.
/// * [LongPressGestureRecognizer.onTertiaryLongPressEnd], which exposes
/// this callback at the gesture layer.
final GestureLongPressEndCallback? onTertiaryLongPressEnd;
/// A pointer has contacted the screen with a primary button and might begin
/// to move vertically.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragDownCallback? onVerticalDragDown;
/// A pointer has contacted the screen with a primary button and has begun to
/// move vertically.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragStartCallback? onVerticalDragStart;
/// A pointer that is in contact with the screen with a primary button and
/// moving vertically has moved in the vertical direction.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragUpdateCallback? onVerticalDragUpdate;
/// A pointer that was previously in contact with the screen with a primary
/// button and moving vertically is no longer in contact with the screen and
/// was moving at a specific velocity when it stopped contacting the screen.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragEndCallback? onVerticalDragEnd;
/// The pointer that previously triggered [onVerticalDragDown] did not
/// complete.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragCancelCallback? onVerticalDragCancel;
/// A pointer has contacted the screen with a primary button and might begin
/// to move horizontally.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragDownCallback? onHorizontalDragDown;
/// A pointer has contacted the screen with a primary button and has begun to
/// move horizontally.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragStartCallback? onHorizontalDragStart;
/// A pointer that is in contact with the screen with a primary button and
/// moving horizontally has moved in the horizontal direction.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragUpdateCallback? onHorizontalDragUpdate;
/// A pointer that was previously in contact with the screen with a primary
/// button and moving horizontally is no longer in contact with the screen and
/// was moving at a specific velocity when it stopped contacting the screen.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragEndCallback? onHorizontalDragEnd;
/// The pointer that previously triggered [onHorizontalDragDown] did not
/// complete.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragCancelCallback? onHorizontalDragCancel;
/// A pointer has contacted the screen with a primary button and might begin
/// to move.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragDownCallback? onPanDown;
/// A pointer has contacted the screen with a primary button and has begun to
/// move.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragStartCallback? onPanStart;
/// A pointer that is in contact with the screen with a primary button and
/// moving has moved again.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragUpdateCallback? onPanUpdate;
/// A pointer that was previously in contact with the screen with a primary
/// button and moving is no longer in contact with the screen and was moving
/// at a specific velocity when it stopped contacting the screen.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragEndCallback? onPanEnd;
/// The pointer that previously triggered [onPanDown] did not complete.
///
/// See also:
///
/// * [kPrimaryButton], the button this callback responds to.
final GestureDragCancelCallback? onPanCancel;
/// The pointers in contact with the screen have established a focal point and
/// initial scale of 1.0.
final GestureScaleStartCallback? onScaleStart;
/// The pointers in contact with the screen have indicated a new focal point
/// and/or scale.
final GestureScaleUpdateCallback? onScaleUpdate;
/// The pointers are no longer in contact with the screen.
final GestureScaleEndCallback? onScaleEnd;
/// The pointer is in contact with the screen and has pressed with sufficient
/// force to initiate a force press. The amount of force is at least
/// [ForcePressGestureRecognizer.startPressure].
///
/// This callback will only be fired on devices with pressure
/// detecting screens.
final GestureForcePressStartCallback? onForcePressStart;
/// The pointer is in contact with the screen and has pressed with the maximum
/// force. The amount of force is at least
/// [ForcePressGestureRecognizer.peakPressure].
///
/// This callback will only be fired on devices with pressure
/// detecting screens.
final GestureForcePressPeakCallback? onForcePressPeak;
/// A pointer is in contact with the screen, has previously passed the
/// [ForcePressGestureRecognizer.startPressure] and is either moving on the
/// plane of the screen, pressing the screen with varying forces or both
/// simultaneously.
///
/// This callback will only be fired on devices with pressure
/// detecting screens.
final GestureForcePressUpdateCallback? onForcePressUpdate;
/// The pointer tracked by [onForcePressStart] is no longer in contact with the screen.
///
/// This callback will only be fired on devices with pressure
/// detecting screens.
final GestureForcePressEndCallback? onForcePressEnd;
/// How this gesture detector should behave during hit testing when deciding
/// how the hit test propagates to children and whether to consider targets
/// behind this one.
///
/// This defaults to [HitTestBehavior.deferToChild] if [child] is not null and
/// [HitTestBehavior.translucent] if child is null.
///
/// See [HitTestBehavior] for the allowed values and their meanings.
final HitTestBehavior? behavior;
/// Whether to exclude these gestures from the semantics tree. For
/// example, the long-press gesture for showing a tooltip is
/// excluded because the tooltip itself is included in the semantics
/// tree directly and so having a gesture to show it would result in
/// duplication of information.
final bool excludeFromSemantics;
/// Determines the way that drag start behavior is handled.
///
/// If set to [DragStartBehavior.start], gesture drag behavior will
/// begin at the position where the drag gesture won the arena. If set to
/// [DragStartBehavior.down] it will begin at the position where a down event
/// is first detected.
///
/// In general, setting this to [DragStartBehavior.start] will make drag
/// animation smoother and setting it to [DragStartBehavior.down] will make
/// drag behavior feel slightly more reactive.
///
/// By default, the drag start behavior is [DragStartBehavior.start].
///
/// Only the [DragGestureRecognizer.onStart] callbacks for the
/// [VerticalDragGestureRecognizer], [HorizontalDragGestureRecognizer] and
/// [PanGestureRecognizer] are affected by this setting.
///
/// See also:
///
/// * [DragGestureRecognizer.dragStartBehavior], which gives an example for the different behaviors.
final DragStartBehavior dragStartBehavior;
/// The kind of devices that are allowed to be recognized.
///
/// If set to null, events from all device types will be recognized. Defaults to null.
final Set<PointerDeviceKind>? supportedDevices;
/// {@macro flutter.gestures.scale.trackpadScrollCausesScale}
final bool trackpadScrollCausesScale;
/// {@macro flutter.gestures.scale.trackpadScrollToScaleFactor}
final Offset trackpadScrollToScaleFactor;
@override
Widget build(BuildContext context) {
final Map<Type, GestureRecognizerFactory> gestures = <Type, GestureRecognizerFactory>{};
final DeviceGestureSettings? gestureSettings = MediaQuery.maybeGestureSettingsOf(context);
final ScrollBehavior configuration = ScrollConfiguration.of(context);
if (onTapDown != null ||
onTapUp != null ||
onTap != null ||
onTapCancel != null ||
onSecondaryTap != null ||
onSecondaryTapDown != null ||
onSecondaryTapUp != null ||
onSecondaryTapCancel != null||
onTertiaryTapDown != null ||
onTertiaryTapUp != null ||
onTertiaryTapCancel != null
) {
gestures[TapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
() => TapGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(TapGestureRecognizer instance) {
instance
..onTapDown = onTapDown
..onTapUp = onTapUp
..onTap = onTap
..onTapCancel = onTapCancel
..onSecondaryTap = onSecondaryTap
..onSecondaryTapDown = onSecondaryTapDown
..onSecondaryTapUp = onSecondaryTapUp
..onSecondaryTapCancel = onSecondaryTapCancel
..onTertiaryTapDown = onTertiaryTapDown
..onTertiaryTapUp = onTertiaryTapUp
..onTertiaryTapCancel = onTertiaryTapCancel
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onDoubleTap != null ||
onDoubleTapDown != null ||
onDoubleTapCancel != null) {
gestures[DoubleTapGestureRecognizer] = GestureRecognizerFactoryWithHandlers<DoubleTapGestureRecognizer>(
() => DoubleTapGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(DoubleTapGestureRecognizer instance) {
instance
..onDoubleTapDown = onDoubleTapDown
..onDoubleTap = onDoubleTap
..onDoubleTapCancel = onDoubleTapCancel
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onLongPressDown != null ||
onLongPressCancel != null ||
onLongPress != null ||
onLongPressStart != null ||
onLongPressMoveUpdate != null ||
onLongPressUp != null ||
onLongPressEnd != null ||
onSecondaryLongPressDown != null ||
onSecondaryLongPressCancel != null ||
onSecondaryLongPress != null ||
onSecondaryLongPressStart != null ||
onSecondaryLongPressMoveUpdate != null ||
onSecondaryLongPressUp != null ||
onSecondaryLongPressEnd != null ||
onTertiaryLongPressDown != null ||
onTertiaryLongPressCancel != null ||
onTertiaryLongPress != null ||
onTertiaryLongPressStart != null ||
onTertiaryLongPressMoveUpdate != null ||
onTertiaryLongPressUp != null ||
onTertiaryLongPressEnd != null) {
gestures[LongPressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
() => LongPressGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(LongPressGestureRecognizer instance) {
instance
..onLongPressDown = onLongPressDown
..onLongPressCancel = onLongPressCancel
..onLongPress = onLongPress
..onLongPressStart = onLongPressStart
..onLongPressMoveUpdate = onLongPressMoveUpdate
..onLongPressUp = onLongPressUp
..onLongPressEnd = onLongPressEnd
..onSecondaryLongPressDown = onSecondaryLongPressDown
..onSecondaryLongPressCancel = onSecondaryLongPressCancel
..onSecondaryLongPress = onSecondaryLongPress
..onSecondaryLongPressStart = onSecondaryLongPressStart
..onSecondaryLongPressMoveUpdate = onSecondaryLongPressMoveUpdate
..onSecondaryLongPressUp = onSecondaryLongPressUp
..onSecondaryLongPressEnd = onSecondaryLongPressEnd
..onTertiaryLongPressDown = onTertiaryLongPressDown
..onTertiaryLongPressCancel = onTertiaryLongPressCancel
..onTertiaryLongPress = onTertiaryLongPress
..onTertiaryLongPressStart = onTertiaryLongPressStart
..onTertiaryLongPressMoveUpdate = onTertiaryLongPressMoveUpdate
..onTertiaryLongPressUp = onTertiaryLongPressUp
..onTertiaryLongPressEnd = onTertiaryLongPressEnd
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onVerticalDragDown != null ||
onVerticalDragStart != null ||
onVerticalDragUpdate != null ||
onVerticalDragEnd != null ||
onVerticalDragCancel != null) {
gestures[VerticalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<VerticalDragGestureRecognizer>(
() => VerticalDragGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(VerticalDragGestureRecognizer instance) {
instance
..onDown = onVerticalDragDown
..onStart = onVerticalDragStart
..onUpdate = onVerticalDragUpdate
..onEnd = onVerticalDragEnd
..onCancel = onVerticalDragCancel
..dragStartBehavior = dragStartBehavior
..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context)
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onHorizontalDragDown != null ||
onHorizontalDragStart != null ||
onHorizontalDragUpdate != null ||
onHorizontalDragEnd != null ||
onHorizontalDragCancel != null) {
gestures[HorizontalDragGestureRecognizer] = GestureRecognizerFactoryWithHandlers<HorizontalDragGestureRecognizer>(
() => HorizontalDragGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(HorizontalDragGestureRecognizer instance) {
instance
..onDown = onHorizontalDragDown
..onStart = onHorizontalDragStart
..onUpdate = onHorizontalDragUpdate
..onEnd = onHorizontalDragEnd
..onCancel = onHorizontalDragCancel
..dragStartBehavior = dragStartBehavior
..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context)
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onPanDown != null ||
onPanStart != null ||
onPanUpdate != null ||
onPanEnd != null ||
onPanCancel != null) {
gestures[PanGestureRecognizer] = GestureRecognizerFactoryWithHandlers<PanGestureRecognizer>(
() => PanGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(PanGestureRecognizer instance) {
instance
..onDown = onPanDown
..onStart = onPanStart
..onUpdate = onPanUpdate
..onEnd = onPanEnd
..onCancel = onPanCancel
..dragStartBehavior = dragStartBehavior
..multitouchDragStrategy = configuration.getMultitouchDragStrategy(context)
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
if (onScaleStart != null || onScaleUpdate != null || onScaleEnd != null) {
gestures[ScaleGestureRecognizer] = GestureRecognizerFactoryWithHandlers<ScaleGestureRecognizer>(
() => ScaleGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(ScaleGestureRecognizer instance) {
instance
..onStart = onScaleStart
..onUpdate = onScaleUpdate
..onEnd = onScaleEnd
..dragStartBehavior = dragStartBehavior
..gestureSettings = gestureSettings
..trackpadScrollCausesScale = trackpadScrollCausesScale
..trackpadScrollToScaleFactor = trackpadScrollToScaleFactor
..supportedDevices = supportedDevices;
},
);
}
if (onForcePressStart != null ||
onForcePressPeak != null ||
onForcePressUpdate != null ||
onForcePressEnd != null) {
gestures[ForcePressGestureRecognizer] = GestureRecognizerFactoryWithHandlers<ForcePressGestureRecognizer>(
() => ForcePressGestureRecognizer(debugOwner: this, supportedDevices: supportedDevices),
(ForcePressGestureRecognizer instance) {
instance
..onStart = onForcePressStart
..onPeak = onForcePressPeak
..onUpdate = onForcePressUpdate
..onEnd = onForcePressEnd
..gestureSettings = gestureSettings
..supportedDevices = supportedDevices;
},
);
}
return RawGestureDetector(
gestures: gestures,
behavior: behavior,
excludeFromSemantics: excludeFromSemantics,
child: child,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<DragStartBehavior>('startBehavior', dragStartBehavior));
}
}
/// A widget that detects gestures described by the given gesture
/// factories.
///
/// For common gestures, use a [GestureDetector].
/// [RawGestureDetector] is useful primarily when developing your
/// own gesture recognizers.
///
/// Configuring the gesture recognizers requires a carefully constructed map, as
/// described in [gestures] and as shown in the example below.
///
/// {@tool snippet}
///
/// This example shows how to hook up a [TapGestureRecognizer]. It assumes that
/// the code is being used inside a [State] object with a `_last` field that is
/// then displayed as the child of the gesture detector.
///
/// ```dart
/// RawGestureDetector(
/// gestures: <Type, GestureRecognizerFactory>{
/// TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
/// () => TapGestureRecognizer(),
/// (TapGestureRecognizer instance) {
/// instance
/// ..onTapDown = (TapDownDetails details) { setState(() { _last = 'down'; }); }
/// ..onTapUp = (TapUpDetails details) { setState(() { _last = 'up'; }); }
/// ..onTap = () { setState(() { _last = 'tap'; }); }
/// ..onTapCancel = () { setState(() { _last = 'cancel'; }); };
/// },
/// ),
/// },
/// child: Container(width: 300.0, height: 300.0, color: Colors.yellow, child: Text(_last)),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [GestureDetector], a less flexible but much simpler widget that does the same thing.
/// * [Listener], a widget that reports raw pointer events.
/// * [GestureRecognizer], the class that you extend to create a custom gesture recognizer.
class RawGestureDetector extends StatefulWidget {
/// Creates a widget that detects gestures.
///
/// Gesture detectors can contribute semantic information to the tree that is
/// used by assistive technology. The behavior can be configured by
/// [semantics], or disabled with [excludeFromSemantics].
const RawGestureDetector({
super.key,
this.child,
this.gestures = const <Type, GestureRecognizerFactory>{},
this.behavior,
this.excludeFromSemantics = false,
this.semantics,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// The gestures that this widget will attempt to recognize.
///
/// This should be a map from [GestureRecognizer] subclasses to
/// [GestureRecognizerFactory] subclasses specialized with the same type.
///
/// This value can be late-bound at layout time using
/// [RawGestureDetectorState.replaceGestureRecognizers].
final Map<Type, GestureRecognizerFactory> gestures;
/// How this gesture detector should behave during hit testing.
///
/// This defaults to [HitTestBehavior.deferToChild] if [child] is not null and
/// [HitTestBehavior.translucent] if child is null.
final HitTestBehavior? behavior;
/// Whether to exclude these gestures from the semantics tree. For
/// example, the long-press gesture for showing a tooltip is
/// excluded because the tooltip itself is included in the semantics
/// tree directly and so having a gesture to show it would result in
/// duplication of information.
final bool excludeFromSemantics;
/// Describes the semantics notations that should be added to the underlying
/// render object [RenderSemanticsGestureHandler].
///
/// It has no effect if [excludeFromSemantics] is true.
///
/// When [semantics] is null, [RawGestureDetector] will fall back to a
/// default delegate which checks if the detector owns certain gesture
/// recognizers and calls their callbacks if they exist:
///
/// * During a semantic tap, it calls [TapGestureRecognizer]'s
/// `onTapDown`, `onTapUp`, and `onTap`.
/// * During a semantic long press, it calls [LongPressGestureRecognizer]'s
/// `onLongPressDown`, `onLongPressStart`, `onLongPress`, `onLongPressEnd`
/// and `onLongPressUp`.
/// * During a semantic horizontal drag, it calls [HorizontalDragGestureRecognizer]'s
/// `onDown`, `onStart`, `onUpdate` and `onEnd`, then
/// [PanGestureRecognizer]'s `onDown`, `onStart`, `onUpdate` and `onEnd`.
/// * During a semantic vertical drag, it calls [VerticalDragGestureRecognizer]'s
/// `onDown`, `onStart`, `onUpdate` and `onEnd`, then
/// [PanGestureRecognizer]'s `onDown`, `onStart`, `onUpdate` and `onEnd`.
///
/// {@tool snippet}
/// This custom gesture detector listens to force presses, while also allows
/// the same callback to be triggered by semantic long presses.
///
/// ```dart
/// class ForcePressGestureDetectorWithSemantics extends StatelessWidget {
/// const ForcePressGestureDetectorWithSemantics({
/// super.key,
/// required this.child,
/// required this.onForcePress,
/// });
///
/// final Widget child;
/// final VoidCallback onForcePress;
///
/// @override
/// Widget build(BuildContext context) {
/// return RawGestureDetector(
/// gestures: <Type, GestureRecognizerFactory>{
/// ForcePressGestureRecognizer: GestureRecognizerFactoryWithHandlers<ForcePressGestureRecognizer>(
/// () => ForcePressGestureRecognizer(debugOwner: this),
/// (ForcePressGestureRecognizer instance) {
/// instance.onStart = (_) => onForcePress();
/// }
/// ),
/// },
/// behavior: HitTestBehavior.opaque,
/// semantics: _LongPressSemanticsDelegate(onForcePress),
/// child: child,
/// );
/// }
/// }
///
/// class _LongPressSemanticsDelegate extends SemanticsGestureDelegate {
/// _LongPressSemanticsDelegate(this.onLongPress);
///
/// VoidCallback onLongPress;
///
/// @override
/// void assignSemantics(RenderSemanticsGestureHandler renderObject) {
/// renderObject.onLongPress = onLongPress;
/// }
/// }
/// ```
/// {@end-tool}
final SemanticsGestureDelegate? semantics;
@override
RawGestureDetectorState createState() => RawGestureDetectorState();
}
/// State for a [RawGestureDetector].
class RawGestureDetectorState extends State<RawGestureDetector> {
Map<Type, GestureRecognizer>? _recognizers = const <Type, GestureRecognizer>{};
SemanticsGestureDelegate? _semantics;
@override
void initState() {
super.initState();
_semantics = widget.semantics ?? _DefaultSemanticsGestureDelegate(this);
_syncAll(widget.gestures);
}
@override
void didUpdateWidget(RawGestureDetector oldWidget) {
super.didUpdateWidget(oldWidget);
if (!(oldWidget.semantics == null && widget.semantics == null)) {
_semantics = widget.semantics ?? _DefaultSemanticsGestureDelegate(this);
}
_syncAll(widget.gestures);
}
/// This method can be called after the build phase, during the
/// layout of the nearest descendant [RenderObjectWidget] of the
/// gesture detector, to update the list of active gesture
/// recognizers.
///
/// The typical use case is [Scrollable]s, which put their viewport
/// in their gesture detector, and then need to know the dimensions
/// of the viewport and the viewport's child to determine whether
/// the gesture detector should be enabled.
///
/// The argument should follow the same conventions as
/// [RawGestureDetector.gestures]. It acts like a temporary replacement for
/// that value until the next build.
void replaceGestureRecognizers(Map<Type, GestureRecognizerFactory> gestures) {
assert(() {
if (!context.findRenderObject()!.owner!.debugDoingLayout) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Unexpected call to replaceGestureRecognizers() method of RawGestureDetectorState.'),
ErrorDescription('The replaceGestureRecognizers() method can only be called during the layout phase.'),
ErrorHint(
'To set the gesture recognizers at other times, trigger a new build using setState() '
'and provide the new gesture recognizers as constructor arguments to the corresponding '
'RawGestureDetector or GestureDetector object.',
),
]);
}
return true;
}());
_syncAll(gestures);
if (!widget.excludeFromSemantics) {
final RenderSemanticsGestureHandler semanticsGestureHandler = context.findRenderObject()! as RenderSemanticsGestureHandler;
_updateSemanticsForRenderObject(semanticsGestureHandler);
}
}
/// This method can be called to filter the list of available semantic actions,
/// after the render object was created.
///
/// The actual filtering is happening in the next frame and a frame will be
/// scheduled if non is pending.
///
/// This is used by [Scrollable] to configure system accessibility tools so
/// that they know in which direction a particular list can be scrolled.
///
/// If this is never called, then the actions are not filtered. If the list of
/// actions to filter changes, it must be called again.
void replaceSemanticsActions(Set<SemanticsAction> actions) {
if (widget.excludeFromSemantics) {
return;
}
final RenderSemanticsGestureHandler? semanticsGestureHandler = context.findRenderObject() as RenderSemanticsGestureHandler?;
assert(() {
if (semanticsGestureHandler == null) {
throw FlutterError(
'Unexpected call to replaceSemanticsActions() method of RawGestureDetectorState.\n'
'The replaceSemanticsActions() method can only be called after the RenderSemanticsGestureHandler has been created.',
);
}
return true;
}());
semanticsGestureHandler!.validActions = actions; // will call _markNeedsSemanticsUpdate(), if required.
}
@override
void dispose() {
for (final GestureRecognizer recognizer in _recognizers!.values) {
recognizer.dispose();
}
_recognizers = null;
super.dispose();
}
void _syncAll(Map<Type, GestureRecognizerFactory> gestures) {
assert(_recognizers != null);
final Map<Type, GestureRecognizer> oldRecognizers = _recognizers!;
_recognizers = <Type, GestureRecognizer>{};
for (final Type type in gestures.keys) {
assert(gestures[type] != null);
assert(gestures[type]!._debugAssertTypeMatches(type));
assert(!_recognizers!.containsKey(type));
_recognizers![type] = oldRecognizers[type] ?? gestures[type]!.constructor();
assert(_recognizers![type].runtimeType == type, 'GestureRecognizerFactory of type $type created a GestureRecognizer of type ${_recognizers![type].runtimeType}. The GestureRecognizerFactory must be specialized with the type of the class that it returns from its constructor method.');
gestures[type]!.initializer(_recognizers![type]!);
}
for (final Type type in oldRecognizers.keys) {
if (!_recognizers!.containsKey(type)) {
oldRecognizers[type]!.dispose();
}
}
}
void _handlePointerDown(PointerDownEvent event) {
assert(_recognizers != null);
for (final GestureRecognizer recognizer in _recognizers!.values) {
recognizer.addPointer(event);
}
}
void _handlePointerPanZoomStart(PointerPanZoomStartEvent event) {
assert(_recognizers != null);
for (final GestureRecognizer recognizer in _recognizers!.values) {
recognizer.addPointerPanZoom(event);
}
}
HitTestBehavior get _defaultBehavior {
return widget.child == null ? HitTestBehavior.translucent : HitTestBehavior.deferToChild;
}
void _updateSemanticsForRenderObject(RenderSemanticsGestureHandler renderObject) {
assert(!widget.excludeFromSemantics);
assert(_semantics != null);
_semantics!.assignSemantics(renderObject);
}
@override
Widget build(BuildContext context) {
Widget result = Listener(
onPointerDown: _handlePointerDown,
onPointerPanZoomStart: _handlePointerPanZoomStart,
behavior: widget.behavior ?? _defaultBehavior,
child: widget.child,
);
if (!widget.excludeFromSemantics) {
result = _GestureSemantics(
behavior: widget.behavior ?? _defaultBehavior,
assignSemantics: _updateSemanticsForRenderObject,
child: result,
);
}
return result;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
if (_recognizers == null) {
properties.add(DiagnosticsNode.message('DISPOSED'));
} else {
final List<String> gestures = _recognizers!.values.map<String>((GestureRecognizer recognizer) => recognizer.debugDescription).toList();
properties.add(IterableProperty<String>('gestures', gestures, ifEmpty: '<none>'));
properties.add(IterableProperty<GestureRecognizer>('recognizers', _recognizers!.values, level: DiagnosticLevel.fine));
properties.add(DiagnosticsProperty<bool>('excludeFromSemantics', widget.excludeFromSemantics, defaultValue: false));
if (!widget.excludeFromSemantics) {
properties.add(DiagnosticsProperty<SemanticsGestureDelegate>('semantics', widget.semantics, defaultValue: null));
}
}
properties.add(EnumProperty<HitTestBehavior>('behavior', widget.behavior, defaultValue: null));
}
}
typedef _AssignSemantics = void Function(RenderSemanticsGestureHandler);
class _GestureSemantics extends SingleChildRenderObjectWidget {
const _GestureSemantics({
super.child,
required this.behavior,
required this.assignSemantics,
});
final HitTestBehavior behavior;
final _AssignSemantics assignSemantics;
@override
RenderSemanticsGestureHandler createRenderObject(BuildContext context) {
final RenderSemanticsGestureHandler renderObject = RenderSemanticsGestureHandler()
..behavior = behavior;
assignSemantics(renderObject);
return renderObject;
}
@override
void updateRenderObject(BuildContext context, RenderSemanticsGestureHandler renderObject) {
renderObject.behavior = behavior;
assignSemantics(renderObject);
}
}
/// A base class that describes what semantics notations a [RawGestureDetector]
/// should add to the render object [RenderSemanticsGestureHandler].
///
/// It is used to allow custom [GestureDetector]s to add semantics notations.
abstract class SemanticsGestureDelegate {
/// Create a delegate of gesture semantics.
const SemanticsGestureDelegate();
/// Assigns semantics notations to the [RenderSemanticsGestureHandler] render
/// object of the gesture detector.
///
/// This method is called when the widget is created, updated, or during
/// [RawGestureDetectorState.replaceGestureRecognizers].
void assignSemantics(RenderSemanticsGestureHandler renderObject);
@override
String toString() => '${objectRuntimeType(this, 'SemanticsGestureDelegate')}()';
}
// The default semantics delegate of [RawGestureDetector]. Its behavior is
// described in [RawGestureDetector.semantics].
//
// For readers who come here to learn how to write custom semantics delegates:
// this is not a proper sample code. It has access to the detector state as well
// as its private properties, which are inaccessible normally. It is designed
// this way in order to work independently in a [RawGestureRecognizer] to
// preserve existing behavior.
//
// Instead, a normal delegate will store callbacks as properties, and use them
// in `assignSemantics`.
class _DefaultSemanticsGestureDelegate extends SemanticsGestureDelegate {
_DefaultSemanticsGestureDelegate(this.detectorState);
final RawGestureDetectorState detectorState;
@override
void assignSemantics(RenderSemanticsGestureHandler renderObject) {
assert(!detectorState.widget.excludeFromSemantics);
final Map<Type, GestureRecognizer> recognizers = detectorState._recognizers!;
renderObject
..onTap = _getTapHandler(recognizers)
..onLongPress = _getLongPressHandler(recognizers)
..onHorizontalDragUpdate = _getHorizontalDragUpdateHandler(recognizers)
..onVerticalDragUpdate = _getVerticalDragUpdateHandler(recognizers);
}
GestureTapCallback? _getTapHandler(Map<Type, GestureRecognizer> recognizers) {
final TapGestureRecognizer? tap = recognizers[TapGestureRecognizer] as TapGestureRecognizer?;
if (tap == null) {
return null;
}
return () {
tap.onTapDown?.call(TapDownDetails());
tap.onTapUp?.call(TapUpDetails(kind: PointerDeviceKind.unknown));
tap.onTap?.call();
};
}
GestureLongPressCallback? _getLongPressHandler(Map<Type, GestureRecognizer> recognizers) {
final LongPressGestureRecognizer? longPress = recognizers[LongPressGestureRecognizer] as LongPressGestureRecognizer?;
if (longPress == null) {
return null;
}
return () {
longPress.onLongPressDown?.call(const LongPressDownDetails());
longPress.onLongPressStart?.call(const LongPressStartDetails());
longPress.onLongPress?.call();
longPress.onLongPressEnd?.call(const LongPressEndDetails());
longPress.onLongPressUp?.call();
};
}
GestureDragUpdateCallback? _getHorizontalDragUpdateHandler(Map<Type, GestureRecognizer> recognizers) {
final HorizontalDragGestureRecognizer? horizontal = recognizers[HorizontalDragGestureRecognizer] as HorizontalDragGestureRecognizer?;
final PanGestureRecognizer? pan = recognizers[PanGestureRecognizer] as PanGestureRecognizer?;
final GestureDragUpdateCallback? horizontalHandler = horizontal == null ?
null :
(DragUpdateDetails details) {
horizontal.onDown?.call(DragDownDetails());
horizontal.onStart?.call(DragStartDetails());
horizontal.onUpdate?.call(details);
horizontal.onEnd?.call(DragEndDetails(primaryVelocity: 0.0));
};
final GestureDragUpdateCallback? panHandler = pan == null ?
null :
(DragUpdateDetails details) {
pan.onDown?.call(DragDownDetails());
pan.onStart?.call(DragStartDetails());
pan.onUpdate?.call(details);
pan.onEnd?.call(DragEndDetails());
};
if (horizontalHandler == null && panHandler == null) {
return null;
}
return (DragUpdateDetails details) {
if (horizontalHandler != null) {
horizontalHandler(details);
}
if (panHandler != null) {
panHandler(details);
}
};
}
GestureDragUpdateCallback? _getVerticalDragUpdateHandler(Map<Type, GestureRecognizer> recognizers) {
final VerticalDragGestureRecognizer? vertical = recognizers[VerticalDragGestureRecognizer] as VerticalDragGestureRecognizer?;
final PanGestureRecognizer? pan = recognizers[PanGestureRecognizer] as PanGestureRecognizer?;
final GestureDragUpdateCallback? verticalHandler = vertical == null ?
null :
(DragUpdateDetails details) {
vertical.onDown?.call(DragDownDetails());
vertical.onStart?.call(DragStartDetails());
vertical.onUpdate?.call(details);
vertical.onEnd?.call(DragEndDetails(primaryVelocity: 0.0));
};
final GestureDragUpdateCallback? panHandler = pan == null ?
null :
(DragUpdateDetails details) {
pan.onDown?.call(DragDownDetails());
pan.onStart?.call(DragStartDetails());
pan.onUpdate?.call(details);
pan.onEnd?.call(DragEndDetails());
};
if (verticalHandler == null && panHandler == null) {
return null;
}
return (DragUpdateDetails details) {
if (verticalHandler != null) {
verticalHandler(details);
}
if (panHandler != null) {
panHandler(details);
}
};
}
}
| flutter/packages/flutter/lib/src/widgets/gesture_detector.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/gesture_detector.dart",
"repo_id": "flutter",
"token_count": 21917
} | 254 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'debug.dart';
import 'framework.dart';
/// The signature of the [LayoutBuilder] builder function.
typedef LayoutWidgetBuilder = Widget Function(BuildContext context, BoxConstraints constraints);
/// An abstract superclass for widgets that defer their building until layout.
///
/// Similar to the [Builder] widget except that the framework calls the [builder]
/// function at layout time and provides the constraints that this widget should
/// adhere to. This is useful when the parent constrains the child's size and layout,
/// and doesn't depend on the child's intrinsic size.
///
/// {@template flutter.widgets.ConstrainedLayoutBuilder}
/// The [builder] function is called in the following situations:
///
/// * The first time the widget is laid out.
/// * When the parent widget passes different layout constraints.
/// * When the parent widget updates this widget.
/// * When the dependencies that the [builder] function subscribes to change.
///
/// The [builder] function is _not_ called during layout if the parent passes
/// the same constraints repeatedly.
/// {@endtemplate}
///
/// Subclasses must return a [RenderObject] that mixes in
/// [RenderConstrainedLayoutBuilder].
abstract class ConstrainedLayoutBuilder<ConstraintType extends Constraints> extends RenderObjectWidget {
/// Creates a widget that defers its building until layout.
const ConstrainedLayoutBuilder({
super.key,
required this.builder,
});
@override
RenderObjectElement createElement() => _LayoutBuilderElement<ConstraintType>(this);
/// Called at layout time to construct the widget tree.
///
/// The builder must not return null.
final Widget Function(BuildContext context, ConstraintType constraints) builder;
/// Whether [builder] needs to be called again even if the layout constraints
/// are the same.
///
/// When this widget's configuration is updated, the [builder] callback most
/// likely needs to be called to build this widget's child. However,
/// subclasses may provide ways in which the widget can be updated without
/// needing to rebuild the child. Such subclasses can use this method to tell
/// the framework when the child widget should be rebuilt.
///
/// When this method is called by the framework, the newly configured widget
/// is asked if it requires a rebuild, and it is passed the old widget as a
/// parameter.
///
/// See also:
///
/// * [State.setState] and [State.didUpdateWidget], which talk about widget
/// configuration changes and how they're triggered.
/// * [Element.update], the method that actually updates the widget's
/// configuration.
@protected
bool updateShouldRebuild(covariant ConstrainedLayoutBuilder<ConstraintType> oldWidget) => true;
// updateRenderObject is redundant with the logic in the LayoutBuilderElement below.
}
class _LayoutBuilderElement<ConstraintType extends Constraints> extends RenderObjectElement {
_LayoutBuilderElement(ConstrainedLayoutBuilder<ConstraintType> super.widget);
@override
RenderConstrainedLayoutBuilder<ConstraintType, RenderObject> get renderObject => super.renderObject as RenderConstrainedLayoutBuilder<ConstraintType, RenderObject>;
Element? _child;
@override
BuildScope get buildScope => _buildScope;
late final BuildScope _buildScope = BuildScope(scheduleRebuild: _scheduleRebuild);
// To schedule a rebuild, markNeedsLayout needs to be called on this Element's
// render object (as the rebuilding is done in its performLayout call). However,
// the render tree should typically be kept clean during the postFrameCallbacks
// and the idle phase, so the layout data can be safely read.
bool _deferredCallbackScheduled = false;
void _scheduleRebuild() {
if (_deferredCallbackScheduled) {
return;
}
final bool deferMarkNeedsLayout = switch (SchedulerBinding.instance.schedulerPhase) {
SchedulerPhase.idle || SchedulerPhase.postFrameCallbacks => true,
SchedulerPhase.transientCallbacks || SchedulerPhase.midFrameMicrotasks || SchedulerPhase.persistentCallbacks => false,
};
if (!deferMarkNeedsLayout) {
renderObject.markNeedsLayout();
return;
}
_deferredCallbackScheduled = true;
SchedulerBinding.instance.scheduleFrameCallback(_frameCallback);
}
void _frameCallback(Duration timestamp) {
_deferredCallbackScheduled = false;
// This method is only called when the render tree is stable, if the Element
// is deactivated it will never be reincorporated back to the tree.
if (mounted) {
renderObject.markNeedsLayout();
}
}
@override
void visitChildren(ElementVisitor visitor) {
if (_child != null) {
visitor(_child!);
}
}
@override
void forgetChild(Element child) {
assert(child == _child);
_child = null;
super.forgetChild(child);
}
@override
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot); // Creates the renderObject.
renderObject.updateCallback(_rebuildWithConstraints);
}
@override
void update(ConstrainedLayoutBuilder<ConstraintType> newWidget) {
assert(widget != newWidget);
final ConstrainedLayoutBuilder<ConstraintType> oldWidget = widget as ConstrainedLayoutBuilder<ConstraintType>;
super.update(newWidget);
assert(widget == newWidget);
renderObject.updateCallback(_rebuildWithConstraints);
if (newWidget.updateShouldRebuild(oldWidget)) {
_needsBuild = true;
renderObject.markNeedsLayout();
}
}
@override
void markNeedsBuild() {
super.markNeedsBuild();
renderObject.markNeedsLayout();
_needsBuild = true;
}
@override
void performRebuild() {
// This gets called if markNeedsBuild() is called on us.
// That might happen if, e.g., our builder uses Inherited widgets.
// Force the callback to be called, even if the layout constraints are the
// same. This is because that callback may depend on the updated widget
// configuration, or an inherited widget.
renderObject.markNeedsLayout();
_needsBuild = true;
super.performRebuild(); // Calls widget.updateRenderObject (a no-op in this case).
}
@override
void unmount() {
renderObject.updateCallback(null);
super.unmount();
}
// The constraints that were passed to this class last time it was laid out.
// These constraints are compared to the new constraints to determine whether
// [ConstrainedLayoutBuilder.builder] needs to be called.
ConstraintType? _previousConstraints;
bool _needsBuild = true;
void _rebuildWithConstraints(ConstraintType constraints) {
@pragma('vm:notify-debugger-on-exception')
void updateChildCallback() {
Widget built;
try {
built = (widget as ConstrainedLayoutBuilder<ConstraintType>).builder(this, constraints);
debugWidgetBuilderValue(widget, built);
} catch (e, stack) {
built = ErrorWidget.builder(
_reportException(
ErrorDescription('building $widget'),
e,
stack,
informationCollector: () => <DiagnosticsNode>[
if (kDebugMode)
DiagnosticsDebugCreator(DebugCreator(this)),
],
),
);
}
try {
_child = updateChild(_child, built, null);
assert(_child != null);
} catch (e, stack) {
built = ErrorWidget.builder(
_reportException(
ErrorDescription('building $widget'),
e,
stack,
informationCollector: () => <DiagnosticsNode>[
if (kDebugMode)
DiagnosticsDebugCreator(DebugCreator(this)),
],
),
);
_child = updateChild(null, built, slot);
} finally {
_needsBuild = false;
_previousConstraints = constraints;
}
}
final VoidCallback? callback = _needsBuild || (constraints != _previousConstraints)
? updateChildCallback
: null;
owner!.buildScope(this, callback);
}
@override
void insertRenderObjectChild(RenderObject child, Object? slot) {
final RenderObjectWithChildMixin<RenderObject> renderObject = this.renderObject;
assert(slot == null);
assert(renderObject.debugValidateChild(child));
renderObject.child = child;
assert(renderObject == this.renderObject);
}
@override
void moveRenderObjectChild(RenderObject child, Object? oldSlot, Object? newSlot) {
assert(false);
}
@override
void removeRenderObjectChild(RenderObject child, Object? slot) {
final RenderConstrainedLayoutBuilder<ConstraintType, RenderObject> renderObject = this.renderObject;
assert(renderObject.child == child);
renderObject.child = null;
assert(renderObject == this.renderObject);
}
}
/// Generic mixin for [RenderObject]s created by [ConstrainedLayoutBuilder].
///
/// Provides a callback that should be called at layout time, typically in
/// [RenderObject.performLayout].
mixin RenderConstrainedLayoutBuilder<ConstraintType extends Constraints, ChildType extends RenderObject> on RenderObjectWithChildMixin<ChildType> {
LayoutCallback<ConstraintType>? _callback;
/// Change the layout callback.
void updateCallback(LayoutCallback<ConstraintType>? value) {
if (value == _callback) {
return;
}
_callback = value;
markNeedsLayout();
}
/// Invoke the callback supplied via [updateCallback].
///
/// Typically this results in [ConstrainedLayoutBuilder.builder] being called
/// during layout.
void rebuildIfNecessary() {
assert(_callback != null);
invokeLayoutCallback(_callback!);
}
}
/// Builds a widget tree that can depend on the parent widget's size.
///
/// Similar to the [Builder] widget except that the framework calls the [builder]
/// function at layout time and provides the parent widget's constraints. This
/// is useful when the parent constrains the child's size and doesn't depend on
/// the child's intrinsic size. The [LayoutBuilder]'s final size will match its
/// child's size.
///
/// {@macro flutter.widgets.ConstrainedLayoutBuilder}
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=IYDVcriKjsw}
///
/// If the child should be smaller than the parent, consider wrapping the child
/// in an [Align] widget. If the child might want to be bigger, consider
/// wrapping it in a [SingleChildScrollView] or [OverflowBox].
///
/// {@tool dartpad}
/// This example uses a [LayoutBuilder] to build a different widget depending on the available width. Resize the
/// DartPad window to see [LayoutBuilder] in action!
///
/// ** See code in examples/api/lib/widgets/layout_builder/layout_builder.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [SliverLayoutBuilder], the sliver counterpart of this widget.
/// * [Builder], which calls a `builder` function at build time.
/// * [StatefulBuilder], which passes its `builder` function a `setState` callback.
/// * [CustomSingleChildLayout], which positions its child during layout.
/// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
class LayoutBuilder extends ConstrainedLayoutBuilder<BoxConstraints> {
/// Creates a widget that defers its building until layout.
const LayoutBuilder({
super.key,
required super.builder,
});
@override
RenderObject createRenderObject(BuildContext context) => _RenderLayoutBuilder();
}
class _RenderLayoutBuilder extends RenderBox with RenderObjectWithChildMixin<RenderBox>, RenderConstrainedLayoutBuilder<BoxConstraints, RenderBox> {
@override
double computeMinIntrinsicWidth(double height) {
assert(_debugThrowIfNotCheckingIntrinsics());
return 0.0;
}
@override
double computeMaxIntrinsicWidth(double height) {
assert(_debugThrowIfNotCheckingIntrinsics());
return 0.0;
}
@override
double computeMinIntrinsicHeight(double width) {
assert(_debugThrowIfNotCheckingIntrinsics());
return 0.0;
}
@override
double computeMaxIntrinsicHeight(double width) {
assert(_debugThrowIfNotCheckingIntrinsics());
return 0.0;
}
@override
Size computeDryLayout(BoxConstraints constraints) {
assert(debugCannotComputeDryLayout(reason:
'Calculating the dry layout would require running the layout callback '
'speculatively, which might mutate the live render object tree.',
));
return Size.zero;
}
@override
double? computeDryBaseline(BoxConstraints constraints, TextBaseline baseline) {
assert(debugCannotComputeDryLayout(reason:
'Calculating the dry baseline would require running the layout callback '
'speculatively, which might mutate the live render object tree.',
));
return null;
}
@override
void performLayout() {
final BoxConstraints constraints = this.constraints;
rebuildIfNecessary();
if (child != null) {
child!.layout(constraints, parentUsesSize: true);
size = constraints.constrain(child!.size);
} else {
size = constraints.biggest;
}
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
return child?.getDistanceToActualBaseline(baseline)
?? super.computeDistanceToActualBaseline(baseline);
}
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return child?.hitTest(result, position: position) ?? false;
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null) {
context.paintChild(child!, offset);
}
}
bool _debugThrowIfNotCheckingIntrinsics() {
assert(() {
if (!RenderObject.debugCheckingIntrinsics) {
throw FlutterError(
'LayoutBuilder does not support returning intrinsic dimensions.\n'
'Calculating the intrinsic dimensions would require running the layout '
'callback speculatively, which might mutate the live render object tree.',
);
}
return true;
}());
return true;
}
}
FlutterErrorDetails _reportException(
DiagnosticsNode context,
Object exception,
StackTrace stack, {
InformationCollector? informationCollector,
}) {
final FlutterErrorDetails details = FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: context,
informationCollector: informationCollector,
);
FlutterError.reportError(details);
return details;
}
| flutter/packages/flutter/lib/src/widgets/layout_builder.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/layout_builder.dart",
"repo_id": "flutter",
"token_count": 4610
} | 255 |
// Copyright 2014 The Flutter Authors. 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 'framework.dart';
// Examples can assume:
// late BuildContext context;
/// A [Key] that can be used to persist the widget state in storage after the
/// destruction and will be restored when recreated.
///
/// Each key with its value plus the ancestor chain of other [PageStorageKey]s
/// need to be unique within the widget's closest ancestor [PageStorage]. To
/// make it possible for a saved value to be found when a widget is recreated,
/// the key's value must not be objects whose identity will change each time the
/// widget is created.
///
/// See also:
///
/// * [PageStorage], which manages the data storage for widgets using
/// [PageStorageKey]s.
class PageStorageKey<T> extends ValueKey<T> {
/// Creates a [ValueKey] that defines where [PageStorage] values will be saved.
const PageStorageKey(super.value);
}
@immutable
class _StorageEntryIdentifier {
const _StorageEntryIdentifier(this.keys);
final List<PageStorageKey<dynamic>> keys;
bool get isNotEmpty => keys.isNotEmpty;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is _StorageEntryIdentifier
&& listEquals<PageStorageKey<dynamic>>(other.keys, keys);
}
@override
int get hashCode => Object.hashAll(keys);
@override
String toString() {
return 'StorageEntryIdentifier(${keys.join(":")})';
}
}
/// A storage bucket associated with a page in an app.
///
/// Useful for storing per-page state that persists across navigations from one
/// page to another.
class PageStorageBucket {
static bool _maybeAddKey(BuildContext context, List<PageStorageKey<dynamic>> keys) {
final Widget widget = context.widget;
final Key? key = widget.key;
if (key is PageStorageKey) {
keys.add(key);
}
return widget is! PageStorage;
}
List<PageStorageKey<dynamic>> _allKeys(BuildContext context) {
final List<PageStorageKey<dynamic>> keys = <PageStorageKey<dynamic>>[];
if (_maybeAddKey(context, keys)) {
context.visitAncestorElements((Element element) {
return _maybeAddKey(element, keys);
});
}
return keys;
}
_StorageEntryIdentifier _computeIdentifier(BuildContext context) {
return _StorageEntryIdentifier(_allKeys(context));
}
Map<Object, dynamic>? _storage;
/// Write the given data into this page storage bucket using the
/// specified identifier or an identifier computed from the given context.
/// The computed identifier is based on the [PageStorageKey]s
/// found in the path from context to the [PageStorage] widget that
/// owns this page storage bucket.
///
/// If an explicit identifier is not provided and no [PageStorageKey]s
/// are found, then the `data` is not saved.
void writeState(BuildContext context, dynamic data, { Object? identifier }) {
_storage ??= <Object, dynamic>{};
if (identifier != null) {
_storage![identifier] = data;
} else {
final _StorageEntryIdentifier contextIdentifier = _computeIdentifier(context);
if (contextIdentifier.isNotEmpty) {
_storage![contextIdentifier] = data;
}
}
}
/// Read given data from into this page storage bucket using the specified
/// identifier or an identifier computed from the given context.
/// The computed identifier is based on the [PageStorageKey]s
/// found in the path from context to the [PageStorage] widget that
/// owns this page storage bucket.
///
/// If an explicit identifier is not provided and no [PageStorageKey]s
/// are found, then null is returned.
dynamic readState(BuildContext context, { Object? identifier }) {
if (_storage == null) {
return null;
}
if (identifier != null) {
return _storage![identifier];
}
final _StorageEntryIdentifier contextIdentifier = _computeIdentifier(context);
return contextIdentifier.isNotEmpty ? _storage![contextIdentifier] : null;
}
}
/// Establish a subtree in which widgets can opt into persisting states after
/// being destroyed.
///
/// [PageStorage] is used to save and restore values that can outlive the widget.
/// For example, when multiple pages are grouped in tabs, when a page is
/// switched out, its widget is destroyed and its state is lost. By adding a
/// [PageStorage] at the root and adding a [PageStorageKey] to each page, some of the
/// page's state (e.g. the scroll position of a [Scrollable] widget) will be stored
/// automatically in its closest ancestor [PageStorage], and restored when it's
/// switched back.
///
/// Usually you don't need to explicitly use a [PageStorage], since it's already
/// included in routes.
///
/// [PageStorageKey] is used by [Scrollable] if [ScrollController.keepScrollOffset]
/// is enabled to save their [ScrollPosition]s. When more than one scrollable
/// ([ListView], [SingleChildScrollView], [TextField], etc.) appears within the
/// widget's closest ancestor [PageStorage] (such as within the same route), to
/// save all of their positions independently, one must give each of them unique
/// [PageStorageKey]s, or set the `keepScrollOffset` property of some such
/// widgets to false to prevent saving.
///
/// {@tool dartpad}
/// This sample shows how to explicitly use a [PageStorage] to
/// store the states of its children pages. Each page includes a scrollable
/// list, whose position is preserved when switching between the tabs thanks to
/// the help of [PageStorageKey].
///
/// ** See code in examples/api/lib/widgets/page_storage/page_storage.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [ModalRoute], which includes this class.
class PageStorage extends StatelessWidget {
/// Creates a widget that provides a storage bucket for its descendants.
const PageStorage({
super.key,
required this.bucket,
required this.child,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// The page storage bucket to use for this subtree.
final PageStorageBucket bucket;
/// The [PageStorageBucket] from the closest instance of a [PageStorage]
/// widget that encloses the given context.
///
/// Returns null if none exists.
///
/// Typical usage is as follows:
///
/// ```dart
/// PageStorageBucket? bucket = PageStorage.of(context);
/// ```
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [PageStorage.of], which is similar to this method, but
/// asserts if no [PageStorage] ancestor is found.
static PageStorageBucket? maybeOf(BuildContext context) {
final PageStorage? widget = context.findAncestorWidgetOfExactType<PageStorage>();
return widget?.bucket;
}
/// The [PageStorageBucket] from the closest instance of a [PageStorage]
/// widget that encloses the given context.
///
/// If no ancestor is found, this method will assert in debug mode, and throw
/// an exception in release mode.
///
/// Typical usage is as follows:
///
/// ```dart
/// PageStorageBucket bucket = PageStorage.of(context);
/// ```
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [PageStorage.maybeOf], which is similar to this method, but
/// returns null if no [PageStorage] ancestor is found.
static PageStorageBucket of(BuildContext context) {
final PageStorageBucket? bucket = maybeOf(context);
assert(() {
if (bucket == null) {
throw FlutterError(
'PageStorage.of() was called with a context that does not contain a '
'PageStorage widget.\n'
'No PageStorage widget ancestor could be found starting from the '
'context that was passed to PageStorage.of(). This can happen '
'because you are using a widget that looks for a PageStorage '
'ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return bucket!;
}
@override
Widget build(BuildContext context) => child;
}
| flutter/packages/flutter/lib/src/widgets/page_storage.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/page_storage.dart",
"repo_id": "flutter",
"token_count": 2494
} | 256 |
// Copyright 2014 The Flutter Authors. 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 'package:collection/collection.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'basic.dart';
import 'binding.dart';
import 'framework.dart';
import 'navigator.dart';
import 'restoration.dart';
import 'restoration_properties.dart';
/// A piece of routing information.
///
/// The route information consists of a location string of the application and
/// a state object that configures the application in that location.
///
/// This information flows two ways, from the [RouteInformationProvider] to the
/// [Router] or from the [Router] to [RouteInformationProvider].
///
/// In the former case, the [RouteInformationProvider] notifies the [Router]
/// widget when a new [RouteInformation] is available. The [Router] widget takes
/// these information and navigates accordingly.
///
/// The latter case happens in web application where the [Router] reports route
/// changes back to the web engine.
///
/// The current [RouteInformation] of an application is also used for state
/// restoration purposes. Before an application is killed, the [Router] converts
/// its current configurations into a [RouteInformation] object utilizing the
/// [RouteInformationProvider]. The [RouteInformation] object is then serialized
/// out and persisted. During state restoration, the object is deserialized and
/// passed back to the [RouteInformationProvider], which turns it into a
/// configuration for the [Router] again to restore its state from.
class RouteInformation {
/// Creates a route information object.
///
/// Either `location` or `uri` must not be null.
const RouteInformation({
@Deprecated(
'Pass Uri.parse(location) to uri parameter instead. '
'This feature was deprecated after v3.8.0-3.0.pre.'
)
String? location,
Uri? uri,
this.state,
}) : _location = location,
_uri = uri,
assert((location != null) != (uri != null));
/// The location of the application.
///
/// The string is usually in the format of multiple string identifiers with
/// slashes in between. ex: `/`, `/path`, `/path/to/the/app`.
@Deprecated(
'Use uri instead. '
'This feature was deprecated after v3.8.0-3.0.pre.'
)
String get location {
return _location ?? Uri.decodeComponent(
Uri(
path: uri.path.isEmpty ? '/' : uri.path,
queryParameters: uri.queryParametersAll.isEmpty ? null : uri.queryParametersAll,
fragment: uri.fragment.isEmpty ? null : uri.fragment,
).toString(),
);
}
final String? _location;
/// The uri location of the application.
///
/// The host and scheme will not be empty if this object is created from a
/// deep link request. They represents the website that redirect the deep
/// link.
///
/// In web platform, the host and scheme are always empty.
Uri get uri {
if (_uri != null){
return _uri;
}
return Uri.parse(_location!);
}
final Uri? _uri;
/// The state of the application in the [uri].
///
/// The app can have different states even in the same location. For example,
/// the text inside a [TextField] or the scroll position in a [ScrollView].
/// These widget states can be stored in the [state].
///
/// On the web, this information is stored in the browser history when the
/// [Router] reports this route information back to the web engine
/// through the [PlatformRouteInformationProvider]. The information
/// is then passed back, along with the [uri], when the user
/// clicks the back or forward buttons.
///
/// This information is also serialized and persisted alongside the
/// [uri] for state restoration purposes. During state restoration,
/// the information is made available again to the [Router] so it can restore
/// its configuration to the previous state.
///
/// The state must be serializable.
final Object? state;
}
/// A convenient bundle to configure a [Router] widget.
///
/// To configure a [Router] widget, one needs to provide several delegates,
/// [RouteInformationProvider], [RouteInformationParser], [RouterDelegate],
/// and [BackButtonDispatcher]. This abstract class provides way to bundle these
/// delegates into a single object to configure a [Router].
///
/// The [backButtonDispatcher], [routeInformationProvider], and
/// [routeInformationProvider] are optional.
///
/// The [routeInformationProvider] and [routeInformationParser] must
/// both be provided or both not provided.
class RouterConfig<T> {
/// Creates a [RouterConfig].
///
/// The [backButtonDispatcher], [routeInformationProvider], and
/// [routeInformationParser] are optional.
///
/// The [routeInformationProvider] and [routeInformationParser] must both be
/// provided or both not provided.
const RouterConfig({
this.routeInformationProvider,
this.routeInformationParser,
required this.routerDelegate,
this.backButtonDispatcher,
}) : assert((routeInformationProvider == null) == (routeInformationParser == null));
/// The [RouteInformationProvider] that is used to configure the [Router].
final RouteInformationProvider? routeInformationProvider;
/// The [RouteInformationParser] that is used to configure the [Router].
final RouteInformationParser<T>? routeInformationParser;
/// The [RouterDelegate] that is used to configure the [Router].
final RouterDelegate<T> routerDelegate;
/// The [BackButtonDispatcher] that is used to configure the [Router].
final BackButtonDispatcher? backButtonDispatcher;
}
/// The dispatcher for opening and closing pages of an application.
///
/// This widget listens for routing information from the operating system (e.g.
/// an initial route provided on app startup, a new route obtained when an
/// intent is received, or a notification that the user hit the system back
/// button), parses route information into data of type `T`, and then converts
/// that data into [Page] objects that it passes to a [Navigator].
///
/// Each part of this process can be overridden and configured as desired.
///
/// The [routeInformationProvider] can be overridden to change how the name of
/// the route is obtained. The [RouteInformationProvider.value] is used as the
/// initial route when the [Router] is first created. Subsequent notifications
/// from the [RouteInformationProvider] to its listeners are treated as
/// notifications that the route information has changed.
///
/// The [backButtonDispatcher] can be overridden to change how back button
/// notifications are received. This must be a [BackButtonDispatcher], which is
/// an object where callbacks can be registered, and which can be chained so
/// that back button presses are delegated to subsidiary routers. The callbacks
/// are invoked to indicate that the user is trying to close the current route
/// (by pressing the system back button); the [Router] ensures that when this
/// callback is invoked, the message is passed to the [routerDelegate] and its
/// result is provided back to the [backButtonDispatcher]. Some platforms don't
/// have back buttons (e.g. iOS and desktop platforms); on those platforms this
/// notification is never sent. Typically, the [backButtonDispatcher] for the
/// root router is an instance of [RootBackButtonDispatcher], which uses a
/// [WidgetsBindingObserver] to listen to the `popRoute` notifications from
/// [SystemChannels.navigation]. Nested [Router]s typically use a
/// [ChildBackButtonDispatcher], which must be provided the
/// [BackButtonDispatcher] of its ancestor [Router] (available via [Router.of]).
///
/// The [routeInformationParser] can be overridden to change how names obtained
/// from the [routeInformationProvider] are interpreted. It must implement the
/// [RouteInformationParser] interface, specialized with the same type as the
/// [Router] itself. This type, `T`, represents the data type that the
/// [routeInformationParser] will generate.
///
/// The [routerDelegate] can be overridden to change how the output of the
/// [routeInformationParser] is interpreted. It must implement the
/// [RouterDelegate] interface, also specialized with `T`; it takes as input
/// the data (of type `T`) from the [routeInformationParser], and is responsible
/// for providing a navigating widget to insert into the widget tree. The
/// [RouterDelegate] interface is also [Listenable]; notifications are taken
/// to mean that the [Router] needs to rebuild.
///
/// ## Concerns regarding asynchrony
///
/// Some of the APIs (notably those involving [RouteInformationParser] and
/// [RouterDelegate]) are asynchronous.
///
/// When developing objects implementing these APIs, if the work can be done
/// entirely synchronously, then consider using [SynchronousFuture] for the
/// future returned from the relevant methods. This will allow the [Router] to
/// proceed in a completely synchronous way, which removes a number of
/// complications.
///
/// Using asynchronous computation is entirely reasonable, however, and the API
/// is designed to support it. For example, maybe a set of images need to be
/// loaded before a route can be shown; waiting for those images to be loaded
/// before [RouterDelegate.setNewRoutePath] returns is a reasonable approach to
/// handle this case.
///
/// If an asynchronous operation is ongoing when a new one is to be started, the
/// precise behavior will depend on the exact circumstances, as follows:
///
/// If the active operation is a [routeInformationParser] parsing a new route information:
/// that operation's result, if it ever completes, will be discarded.
///
/// If the active operation is a [routerDelegate] handling a pop request:
/// the previous pop is immediately completed with "false", claiming that the
/// previous pop was not handled (this may cause the application to close).
///
/// If the active operation is a [routerDelegate] handling an initial route
/// or a pushed route, the result depends on the new operation. If the new
/// operation is a pop request, then the original operation's result, if it ever
/// completes, will be discarded. If the new operation is a push request,
/// however, the [routeInformationParser] will be requested to start the parsing, and
/// only if that finishes before the original [routerDelegate] request
/// completes will that original request's result be discarded.
///
/// If the identity of the [Router] widget's delegates change while an
/// asynchronous operation is in progress, to keep matters simple, all active
/// asynchronous operations will have their results discarded. It is generally
/// considered unusual for these delegates to change during the lifetime of the
/// [Router].
///
/// If the [Router] itself is disposed while an asynchronous operation is in
/// progress, all active asynchronous operations will have their results
/// discarded also.
///
/// No explicit signals are provided to the [routeInformationParser] or
/// [routerDelegate] to indicate when any of the above happens, so it is
/// strongly recommended that [RouteInformationParser] and [RouterDelegate]
/// implementations not perform extensive computation.
///
/// ## Application architectural design
///
/// An application can have zero, one, or many [Router] widgets, depending on
/// its needs.
///
/// An application might have no [Router] widgets if it has only one "screen",
/// or if the facilities provided by [Navigator] are sufficient. This is common
/// for desktop applications, where subsidiary "screens" are represented using
/// different windows rather than changing the active interface.
///
/// A particularly elaborate application might have multiple [Router] widgets,
/// in a tree configuration, with the first handling the entire route parsing
/// and making the result available for routers in the subtree. The routers in
/// the subtree do not participate in route information parsing but merely take the
/// result from the first router to build their sub routes.
///
/// Most applications only need a single [Router].
///
/// ## URL updates for web applications
///
/// In the web platform, keeping the URL in the browser's location bar up to
/// date with the application state ensures that the browser constructs its
/// history entry correctly, allowing its back and forward buttons to function
/// as the user expects.
///
/// If an app state change leads to the [Router] rebuilding, the [Router] will
/// retrieve the new route information from the [routerDelegate]'s
/// [RouterDelegate.currentConfiguration] method and the
/// [routeInformationParser]'s [RouteInformationParser.restoreRouteInformation]
/// method.
///
/// If the location in the new route information is different from the
/// current location, this is considered to be a navigation event, the
/// [PlatformRouteInformationProvider.routerReportsNewRouteInformation] method
/// calls [SystemNavigator.routeInformationUpdated] with `replace = false` to
/// notify the engine, and through that the browser, to create a history entry
/// with the new url. Otherwise,
/// [PlatformRouteInformationProvider.routerReportsNewRouteInformation] calls
/// [SystemNavigator.routeInformationUpdated] with `replace = true` to update
/// the current history entry with the latest [RouteInformation].
///
/// One can force the [Router] to report new route information as navigation
/// event to the [routeInformationProvider] (and thus the browser) even if the
/// [RouteInformation.uri] has not changed by calling the [Router.navigate]
/// method with a callback that performs the state change. This causes [Router]
/// to call the [RouteInformationProvider.routerReportsNewRouteInformation] with
/// [RouteInformationReportingType.navigate], and thus causes
/// [PlatformRouteInformationProvider] to push a new history entry regardlessly.
/// This allows one to support the browser's back and forward buttons without
/// changing the URL. For example, the scroll position of a scroll view may be
/// saved in the [RouteInformation.state]. Using [Router.navigate] to update the
/// scroll position causes the browser to create a new history entry with the
/// [RouteInformation.state] that stores this new scroll position. When the user
/// clicks the back button, the app will go back to the previous scroll position
/// without changing the URL in the location bar.
///
/// One can also force the [Router] to ignore a navigation event by making
/// those changes during a callback passed to [Router.neglect]. The [Router]
/// calls the [RouteInformationProvider.routerReportsNewRouteInformation] with
/// [RouteInformationReportingType.neglect], and thus causes
/// [PlatformRouteInformationProvider] to replace the current history entry
/// regardlessly even if it detects location change.
///
/// To opt out of URL updates entirely, pass null for [routeInformationProvider]
/// and [routeInformationParser]. This is not recommended in general, but may be
/// appropriate in the following cases:
///
/// * The application does not target the web platform.
///
/// * There are multiple router widgets in the application. Only one [Router]
/// widget should update the URL (typically the top-most one created by the
/// [WidgetsApp.router], [MaterialApp.router], or [CupertinoApp.router]).
///
/// * The application does not need to implement in-app navigation using the
/// browser's back and forward buttons.
///
/// In other cases, it is strongly recommended to implement the
/// [RouterDelegate.currentConfiguration] and
/// [RouteInformationParser.restoreRouteInformation] APIs to provide an optimal
/// user experience when running on the web platform.
///
/// ## State Restoration
///
/// The [Router] will restore the current configuration of the [routerDelegate]
/// during state restoration if it is configured with a [restorationScopeId] and
/// state restoration is enabled for the subtree. For that, the value of
/// [RouterDelegate.currentConfiguration] is serialized and persisted before the
/// app is killed by the operating system. After the app is restarted, the value
/// is deserialized and passed back to the [RouterDelegate] via a call to
/// [RouterDelegate.setRestoredRoutePath] (which by default just calls
/// [RouterDelegate.setNewRoutePath]). It is the responsibility of the
/// [RouterDelegate] to use the configuration information provided to restore
/// its internal state.
///
/// To serialize [RouterDelegate.currentConfiguration] and to deserialize it
/// again, the [Router] calls [RouteInformationParser.restoreRouteInformation]
/// and [RouteInformationParser.parseRouteInformation], respectively. Therefore,
/// if a [restorationScopeId] is provided, a [routeInformationParser] must be
/// configured as well.
class Router<T> extends StatefulWidget {
/// Creates a router.
///
/// The [routeInformationProvider] and [routeInformationParser] can be null if this
/// router does not depend on route information. A common example is a sub router
/// that builds its content completely based on the app state.
///
/// The [routeInformationProvider] and [routeInformationParser] must
/// both be provided or not provided.
const Router({
super.key,
this.routeInformationProvider,
this.routeInformationParser,
required this.routerDelegate,
this.backButtonDispatcher,
this.restorationScopeId,
}) : assert(
routeInformationProvider == null || routeInformationParser != null,
'A routeInformationParser must be provided when a routeInformationProvider is specified.',
);
/// Creates a router with a [RouterConfig].
///
/// The [RouterConfig.routeInformationProvider] and
/// [RouterConfig.routeInformationParser] can be null if this router does not
/// depend on route information. A common example is a sub router that builds
/// its content completely based on the app state.
///
/// If the [RouterConfig.routeInformationProvider] is not null, then
/// [RouterConfig.routeInformationParser] must also not be
/// null.
factory Router.withConfig({
Key? key,
required RouterConfig<T> config,
String? restorationScopeId,
}) {
return Router<T>(
key: key,
routeInformationProvider: config.routeInformationProvider,
routeInformationParser: config.routeInformationParser,
routerDelegate: config.routerDelegate,
backButtonDispatcher: config.backButtonDispatcher,
restorationScopeId: restorationScopeId,
);
}
/// The route information provider for the router.
///
/// The value at the time of first build will be used as the initial route.
/// The [Router] listens to this provider and rebuilds with new names when
/// it notifies.
///
/// This can be null if this router does not rely on the route information
/// to build its content. In such case, the [routeInformationParser] must also
/// be null.
final RouteInformationProvider? routeInformationProvider;
/// The route information parser for the router.
///
/// When the [Router] gets a new route information from the [routeInformationProvider],
/// the [Router] uses this delegate to parse the route information and produce a
/// configuration. The configuration will be used by [routerDelegate] and
/// eventually rebuilds the [Router] widget.
///
/// Since this delegate is the primary consumer of the [routeInformationProvider],
/// it must not be null if [routeInformationProvider] is not null.
final RouteInformationParser<T>? routeInformationParser;
/// The router delegate for the router.
///
/// This delegate consumes the configuration from [routeInformationParser] and
/// builds a navigating widget for the [Router].
///
/// It is also the primary respondent for the [backButtonDispatcher]. The
/// [Router] relies on [RouterDelegate.popRoute] to handle the back
/// button.
///
/// If the [RouterDelegate.currentConfiguration] returns a non-null object,
/// this [Router] will opt for URL updates.
final RouterDelegate<T> routerDelegate;
/// The back button dispatcher for the router.
///
/// The two common alternatives are the [RootBackButtonDispatcher] for root
/// router, or the [ChildBackButtonDispatcher] for other routers.
final BackButtonDispatcher? backButtonDispatcher;
/// Restoration ID to save and restore the state of the [Router].
///
/// If non-null, the [Router] will persist the [RouterDelegate]'s current
/// configuration (i.e. [RouterDelegate.currentConfiguration]). During state
/// restoration, the [Router] informs the [RouterDelegate] of the previous
/// configuration by calling [RouterDelegate.setRestoredRoutePath] (which by
/// default just calls [RouterDelegate.setNewRoutePath]). It is the
/// responsibility of the [RouterDelegate] to restore its internal state based
/// on the provided configuration.
///
/// The router uses the [RouteInformationParser] to serialize and deserialize
/// [RouterDelegate.currentConfiguration]. Therefore, a
/// [routeInformationParser] must be provided when [restorationScopeId] is
/// non-null.
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
final String? restorationScopeId;
/// Retrieves the immediate [Router] ancestor from the given context.
///
/// This method provides access to the delegates in the [Router]. For example,
/// this can be used to access the [backButtonDispatcher] of the parent router
/// when creating a [ChildBackButtonDispatcher] for a nested [Router].
///
/// If no [Router] ancestor exists for the given context, this will assert in
/// debug mode, and throw an exception in release mode.
///
/// See also:
///
/// * [maybeOf], which is a similar function, but it will return null instead
/// of throwing an exception if no [Router] ancestor exists.
static Router<T> of<T extends Object?>(BuildContext context) {
final _RouterScope? scope = context.dependOnInheritedWidgetOfExactType<_RouterScope>();
assert(() {
if (scope == null) {
throw FlutterError(
'Router operation requested with a context that does not include a Router.\n'
'The context used to retrieve the Router must be that of a widget that '
'is a descendant of a Router widget.',
);
}
return true;
}());
return scope!.routerState.widget as Router<T>;
}
/// Retrieves the immediate [Router] ancestor from the given context.
///
/// This method provides access to the delegates in the [Router]. For example,
/// this can be used to access the [backButtonDispatcher] of the parent router
/// when creating a [ChildBackButtonDispatcher] for a nested [Router].
///
/// If no `Router` ancestor exists for the given context, this will return
/// null.
///
/// See also:
///
/// * [of], a similar method that returns a non-nullable value, and will
/// throw if no [Router] ancestor exists.
static Router<T>? maybeOf<T extends Object?>(BuildContext context) {
final _RouterScope? scope = context.dependOnInheritedWidgetOfExactType<_RouterScope>();
return scope?.routerState.widget as Router<T>?;
}
/// Forces the [Router] to run the [callback] and create a new history
/// entry in the browser.
///
/// The web application relies on the [Router] to report new route information
/// in order to create browser history entry. The [Router] will only report
/// them if it detects the [RouteInformation.uri] changes. Use this
/// method if you want the [Router] to report the route information even if
/// the location does not change. This can be useful when you want to
/// support the browser backward and forward button without changing the URL.
///
/// For example, you can store certain state such as the scroll position into
/// the [RouteInformation.state]. If you use this method to update the
/// scroll position multiple times with the same URL, the browser will create
/// a stack of new history entries with the same URL but different
/// [RouteInformation.state]s that store the new scroll positions. If the user
/// click the backward button in the browser, the browser will restore the
/// scroll positions saved in history entries without changing the URL.
///
/// See also:
///
/// * [Router]: see the "URL updates for web applications" section for more
/// information about route information reporting.
/// * [neglect]: which forces the [Router] to not create a new history entry
/// even if location does change.
static void navigate(BuildContext context, VoidCallback callback) {
final _RouterScope scope = context
.getElementForInheritedWidgetOfExactType<_RouterScope>()!
.widget as _RouterScope;
scope.routerState._setStateWithExplicitReportStatus(RouteInformationReportingType.navigate, callback);
}
/// Forces the [Router] to run the [callback] without creating a new history
/// entry in the browser.
///
/// The web application relies on the [Router] to report new route information
/// in order to create browser history entry. The [Router] will report them
/// automatically if it detects the [RouteInformation.uri] changes.
///
/// Creating a new route history entry makes users feel they have visited a
/// new page, and the browser back button brings them back to previous history
/// entry. Use this method if you don't want the [Router] to create a new
/// route information even if it detects changes as a result of running the
/// [callback].
///
/// Using this method will still update the URL and state in current history
/// entry.
///
/// See also:
///
/// * [Router]: see the "URL updates for web applications" section for more
/// information about route information reporting.
/// * [navigate]: which forces the [Router] to create a new history entry
/// even if location does not change.
static void neglect(BuildContext context, VoidCallback callback) {
final _RouterScope scope = context
.getElementForInheritedWidgetOfExactType<_RouterScope>()!
.widget as _RouterScope;
scope.routerState._setStateWithExplicitReportStatus(RouteInformationReportingType.neglect, callback);
}
@override
State<Router<T>> createState() => _RouterState<T>();
}
typedef _AsyncPassthrough<Q> = Future<Q> Function(Q);
typedef _RouteSetter<T> = Future<void> Function(T);
/// The [Router]'s intention when it reports a new [RouteInformation] to the
/// [RouteInformationProvider].
///
/// See also:
///
/// * [RouteInformationProvider.routerReportsNewRouteInformation]: which is
/// called by the router when it has a new route information to report.
enum RouteInformationReportingType {
/// Router does not have a specific intention.
///
/// The router generates a new route information every time it detects route
/// information may have change due to a rebuild. This is the default type if
/// neither [Router.neglect] nor [Router.navigate] was used during the
/// rebuild.
none,
/// The accompanying [RouteInformation] were generated during a
/// [Router.neglect] call.
neglect,
/// The accompanying [RouteInformation] were generated during a
/// [Router.navigate] call.
navigate,
}
class _RouterState<T> extends State<Router<T>> with RestorationMixin {
Object? _currentRouterTransaction;
RouteInformationReportingType? _currentIntentionToReport;
final _RestorableRouteInformation _routeInformation = _RestorableRouteInformation();
late bool _routeParsePending;
@override
String? get restorationId => widget.restorationScopeId;
@override
void initState() {
super.initState();
widget.routeInformationProvider?.addListener(_handleRouteInformationProviderNotification);
widget.backButtonDispatcher?.addCallback(_handleBackButtonDispatcherNotification);
widget.routerDelegate.addListener(_handleRouterDelegateNotification);
}
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_routeInformation, 'route');
if (_routeInformation.value != null) {
assert(widget.routeInformationParser != null);
_processRouteInformation(_routeInformation.value!, () => widget.routerDelegate.setRestoredRoutePath);
} else if (widget.routeInformationProvider != null) {
_processRouteInformation(widget.routeInformationProvider!.value, () => widget.routerDelegate.setInitialRoutePath);
}
}
bool _routeInformationReportingTaskScheduled = false;
void _scheduleRouteInformationReportingTask() {
if (_routeInformationReportingTaskScheduled || widget.routeInformationProvider == null) {
return;
}
assert(_currentIntentionToReport != null);
_routeInformationReportingTaskScheduled = true;
SchedulerBinding.instance.addPostFrameCallback(
_reportRouteInformation,
debugLabel: 'Router.reportRouteInfo',
);
}
void _reportRouteInformation(Duration timestamp) {
if (!mounted) {
return;
}
assert(_routeInformationReportingTaskScheduled);
_routeInformationReportingTaskScheduled = false;
if (_routeInformation.value != null) {
final RouteInformation currentRouteInformation = _routeInformation.value!;
assert(_currentIntentionToReport != null);
widget.routeInformationProvider!.routerReportsNewRouteInformation(currentRouteInformation, type: _currentIntentionToReport!);
}
_currentIntentionToReport = RouteInformationReportingType.none;
}
RouteInformation? _retrieveNewRouteInformation() {
final T? configuration = widget.routerDelegate.currentConfiguration;
if (configuration == null) {
return null;
}
return widget.routeInformationParser?.restoreRouteInformation(configuration);
}
void _setStateWithExplicitReportStatus(
RouteInformationReportingType status,
VoidCallback fn,
) {
assert(status.index >= RouteInformationReportingType.neglect.index);
assert(() {
if (_currentIntentionToReport != null &&
_currentIntentionToReport != RouteInformationReportingType.none &&
_currentIntentionToReport != status) {
FlutterError.reportError(
const FlutterErrorDetails(
exception:
'Both Router.navigate and Router.neglect have been called in this '
'build cycle, and the Router cannot decide whether to report the '
'route information. Please make sure only one of them is called '
'within the same build cycle.',
),
);
}
return true;
}());
_currentIntentionToReport = status;
_scheduleRouteInformationReportingTask();
fn();
}
void _maybeNeedToReportRouteInformation() {
_routeInformation.value = _retrieveNewRouteInformation();
_currentIntentionToReport ??= RouteInformationReportingType.none;
_scheduleRouteInformationReportingTask();
}
@override
void didChangeDependencies() {
_routeParsePending = true;
super.didChangeDependencies();
// The super.didChangeDependencies may have parsed the route information.
// This can happen if the didChangeDependencies is triggered by state
// restoration or first build.
final RouteInformation? currentRouteInformation = _routeInformation.value ?? widget.routeInformationProvider?.value;
if (currentRouteInformation != null && _routeParsePending) {
_processRouteInformation(currentRouteInformation, () => widget.routerDelegate.setNewRoutePath);
}
_routeParsePending = false;
_maybeNeedToReportRouteInformation();
}
@override
void didUpdateWidget(Router<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.routeInformationProvider != oldWidget.routeInformationProvider ||
widget.backButtonDispatcher != oldWidget.backButtonDispatcher ||
widget.routeInformationParser != oldWidget.routeInformationParser ||
widget.routerDelegate != oldWidget.routerDelegate) {
_currentRouterTransaction = Object();
}
if (widget.routeInformationProvider != oldWidget.routeInformationProvider) {
oldWidget.routeInformationProvider?.removeListener(_handleRouteInformationProviderNotification);
widget.routeInformationProvider?.addListener(_handleRouteInformationProviderNotification);
if (oldWidget.routeInformationProvider?.value != widget.routeInformationProvider?.value) {
_handleRouteInformationProviderNotification();
}
}
if (widget.backButtonDispatcher != oldWidget.backButtonDispatcher) {
oldWidget.backButtonDispatcher?.removeCallback(_handleBackButtonDispatcherNotification);
widget.backButtonDispatcher?.addCallback(_handleBackButtonDispatcherNotification);
}
if (widget.routerDelegate != oldWidget.routerDelegate) {
oldWidget.routerDelegate.removeListener(_handleRouterDelegateNotification);
widget.routerDelegate.addListener(_handleRouterDelegateNotification);
_maybeNeedToReportRouteInformation();
}
}
@override
void dispose() {
_routeInformation.dispose();
widget.routeInformationProvider?.removeListener(_handleRouteInformationProviderNotification);
widget.backButtonDispatcher?.removeCallback(_handleBackButtonDispatcherNotification);
widget.routerDelegate.removeListener(_handleRouterDelegateNotification);
_currentRouterTransaction = null;
super.dispose();
}
void _processRouteInformation(RouteInformation information, ValueGetter<_RouteSetter<T>> delegateRouteSetter) {
assert(_routeParsePending);
_routeParsePending = false;
_currentRouterTransaction = Object();
widget.routeInformationParser!
.parseRouteInformationWithDependencies(information, context)
.then<void>(_processParsedRouteInformation(_currentRouterTransaction, delegateRouteSetter));
}
_RouteSetter<T> _processParsedRouteInformation(Object? transaction, ValueGetter<_RouteSetter<T>> delegateRouteSetter) {
return (T data) async {
if (_currentRouterTransaction != transaction) {
return;
}
await delegateRouteSetter()(data);
if (_currentRouterTransaction == transaction) {
_rebuild();
}
};
}
void _handleRouteInformationProviderNotification() {
_routeParsePending = true;
_processRouteInformation(widget.routeInformationProvider!.value, () => widget.routerDelegate.setNewRoutePath);
}
Future<bool> _handleBackButtonDispatcherNotification() {
_currentRouterTransaction = Object();
return widget.routerDelegate
.popRoute()
.then<bool>(_handleRoutePopped(_currentRouterTransaction));
}
_AsyncPassthrough<bool> _handleRoutePopped(Object? transaction) {
return (bool data) {
if (transaction != _currentRouterTransaction) {
// A rebuilt was trigger from a different source. Returns true to
// prevent bubbling.
return SynchronousFuture<bool>(true);
}
_rebuild();
return SynchronousFuture<bool>(data);
};
}
Future<void> _rebuild([void value]) {
setState(() {/* routerDelegate is ready to rebuild */});
_maybeNeedToReportRouteInformation();
return SynchronousFuture<void>(value);
}
void _handleRouterDelegateNotification() {
setState(() {/* routerDelegate wants to rebuild */});
_maybeNeedToReportRouteInformation();
}
@override
Widget build(BuildContext context) {
return UnmanagedRestorationScope(
bucket: bucket,
child: _RouterScope(
routeInformationProvider: widget.routeInformationProvider,
backButtonDispatcher: widget.backButtonDispatcher,
routeInformationParser: widget.routeInformationParser,
routerDelegate: widget.routerDelegate,
routerState: this,
child: Builder(
// Use a Builder so that the build method below will have a
// BuildContext that contains the _RouterScope. This also prevents
// dependencies look ups in routerDelegate from rebuilding Router
// widget that may result in re-parsing the route information.
builder: widget.routerDelegate.build,
),
),
);
}
}
class _RouterScope extends InheritedWidget {
const _RouterScope({
required this.routeInformationProvider,
required this.backButtonDispatcher,
required this.routeInformationParser,
required this.routerDelegate,
required this.routerState,
required super.child,
}) : assert(routeInformationProvider == null || routeInformationParser != null);
final ValueListenable<RouteInformation?>? routeInformationProvider;
final BackButtonDispatcher? backButtonDispatcher;
final RouteInformationParser<Object?>? routeInformationParser;
final RouterDelegate<Object?> routerDelegate;
final _RouterState<Object?> routerState;
@override
bool updateShouldNotify(_RouterScope oldWidget) {
return routeInformationProvider != oldWidget.routeInformationProvider ||
backButtonDispatcher != oldWidget.backButtonDispatcher ||
routeInformationParser != oldWidget.routeInformationParser ||
routerDelegate != oldWidget.routerDelegate ||
routerState != oldWidget.routerState;
}
}
/// A class that can be extended or mixed in that invokes a single callback,
/// which then returns a value.
///
/// While multiple callbacks can be registered, when a notification is
/// dispatched there must be only a single callback. The return values of
/// multiple callbacks are not aggregated.
///
/// `T` is the return value expected from the callback.
///
/// See also:
///
/// * [Listenable] and its subclasses, which provide a similar mechanism for
/// one-way signaling.
class _CallbackHookProvider<T> {
final ObserverList<ValueGetter<T>> _callbacks = ObserverList<ValueGetter<T>>();
/// Whether a callback is currently registered.
@protected
bool get hasCallbacks => _callbacks.isNotEmpty;
/// Register the callback to be called when the object changes.
///
/// If other callbacks have already been registered, they must be removed
/// (with [removeCallback]) before the callback is next called.
void addCallback(ValueGetter<T> callback) => _callbacks.add(callback);
/// Remove a previously registered callback.
///
/// If the given callback is not registered, the call is ignored.
void removeCallback(ValueGetter<T> callback) => _callbacks.remove(callback);
/// Calls the (single) registered callback and returns its result.
///
/// If no callback is registered, or if the callback throws, returns
/// `defaultValue`.
///
/// Call this method whenever the callback is to be invoked. If there is more
/// than one callback registered, this method will throw a [StateError].
///
/// Exceptions thrown by callbacks will be caught and reported using
/// [FlutterError.reportError].
@protected
@pragma('vm:notify-debugger-on-exception')
T invokeCallback(T defaultValue) {
if (_callbacks.isEmpty) {
return defaultValue;
}
try {
return _callbacks.single();
} catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widget library',
context: ErrorDescription('while invoking the callback for $runtimeType'),
informationCollector: () => <DiagnosticsNode>[
DiagnosticsProperty<_CallbackHookProvider<T>>(
'The $runtimeType that invoked the callback was',
this,
style: DiagnosticsTreeStyle.errorProperty,
),
],
));
return defaultValue;
}
}
}
/// Report to a [Router] when the user taps the back button on platforms that
/// support back buttons (such as Android).
///
/// When [Router] widgets are nested, consider using a
/// [ChildBackButtonDispatcher], passing it the parent [BackButtonDispatcher],
/// so that the back button requests get dispatched to the appropriate [Router].
/// To make this work properly, it's important that whenever a [Router] thinks
/// it should get the back button messages (e.g. after the user taps inside it),
/// it calls [takePriority] on its [BackButtonDispatcher] (or
/// [ChildBackButtonDispatcher]) instance.
///
/// The class takes a single callback, which must return a [Future<bool>]. The
/// callback's semantics match [WidgetsBindingObserver.didPopRoute]'s, namely,
/// the callback should return a future that completes to true if it can handle
/// the pop request, and a future that completes to false otherwise.
abstract class BackButtonDispatcher extends _CallbackHookProvider<Future<bool>> {
late final LinkedHashSet<ChildBackButtonDispatcher> _children =
<ChildBackButtonDispatcher>{} as LinkedHashSet<ChildBackButtonDispatcher>;
@override
bool get hasCallbacks => super.hasCallbacks || (_children.isNotEmpty);
/// Handles a pop route request.
///
/// This method prioritizes the children list in reverse order and calls
/// [ChildBackButtonDispatcher.notifiedByParent] on them. If any of them
/// handles the request (by returning a future with true), it exits this
/// method by returning this future. Otherwise, it keeps moving on to the next
/// child until a child handles the request. If none of the children handles
/// the request, this back button dispatcher will then try to handle the request
/// by itself. This back button dispatcher handles the request by notifying the
/// router which in turn calls the [RouterDelegate.popRoute] and returns its
/// result.
///
/// To decide whether this back button dispatcher will handle the pop route
/// request, you can override the [RouterDelegate.popRoute] of the router
/// delegate you pass into the router with this back button dispatcher to
/// return a future of true or false.
@override
Future<bool> invokeCallback(Future<bool> defaultValue) {
if (_children.isNotEmpty) {
final List<ChildBackButtonDispatcher> children = _children.toList();
int childIndex = children.length - 1;
Future<bool> notifyNextChild(bool result) {
// If the previous child handles the callback, we return the result.
if (result) {
return SynchronousFuture<bool>(result);
}
// If the previous child did not handle the callback, we ask the next
// child to handle the it.
if (childIndex > 0) {
childIndex -= 1;
return children[childIndex]
.notifiedByParent(defaultValue)
.then<bool>(notifyNextChild);
}
// If none of the child handles the callback, the parent will then handle it.
return super.invokeCallback(defaultValue);
}
return children[childIndex]
.notifiedByParent(defaultValue)
.then<bool>(notifyNextChild);
}
return super.invokeCallback(defaultValue);
}
/// Creates a [ChildBackButtonDispatcher] that is a direct descendant of this
/// back button dispatcher.
///
/// To participate in handling the pop route request, call the [takePriority]
/// on the [ChildBackButtonDispatcher] created from this method.
///
/// When the pop route request is handled by this back button dispatcher, it
/// propagate the request to its direct descendants that have called the
/// [takePriority] method. If there are multiple candidates, the latest one
/// that called the [takePriority] wins the right to handle the request. If
/// the latest one does not handle the request (by returning a future of
/// false in [ChildBackButtonDispatcher.notifiedByParent]), the second latest
/// one will then have the right to handle the request. This dispatcher
/// continues finding the next candidate until there are no more candidates
/// and finally handles the request itself.
ChildBackButtonDispatcher createChildBackButtonDispatcher() {
return ChildBackButtonDispatcher(this);
}
/// Make this [BackButtonDispatcher] take priority among its peers.
///
/// This has no effect when a [BackButtonDispatcher] has no parents and no
/// children. If a [BackButtonDispatcher] does have parents or children,
/// however, it causes this object to be the one to dispatch the notification
/// when the parent would normally notify its callback.
///
/// The [BackButtonDispatcher] must have a listener registered before it can
/// be told to take priority.
void takePriority() => _children.clear();
/// Mark the given child as taking priority over this object and the other
/// children.
///
/// This causes [invokeCallback] to defer to the given child instead of
/// calling this object's callback.
///
/// Children are stored in a list, so that if the current child is removed
/// using [forget], a previous child will return to take its place. When
/// [takePriority] is called, the list is cleared.
///
/// Calling this again without first calling [forget] moves the child back to
/// the head of the list.
///
/// The [BackButtonDispatcher] must have a listener registered before it can
/// be told to defer to a child.
void deferTo(ChildBackButtonDispatcher child) {
assert(hasCallbacks);
_children.remove(child); // child may or may not be in the set already
_children.add(child);
}
/// Causes the given child to be removed from the list of children to which
/// this object might defer, as if [deferTo] had never been called for that
/// child.
///
/// This should only be called once per child, even if [deferTo] was called
/// multiple times for that child.
///
/// If no children are left in the list, this object will stop deferring to
/// its children. (This is not the same as calling [takePriority], since, if
/// this object itself is a [ChildBackButtonDispatcher], [takePriority] would
/// additionally attempt to claim priority from its parent, whereas removing
/// the last child does not.)
void forget(ChildBackButtonDispatcher child) => _children.remove(child);
}
/// The default implementation of back button dispatcher for the root router.
///
/// This dispatcher listens to platform pop route notifications. When the
/// platform wants to pop the current route, this dispatcher calls the
/// [BackButtonDispatcher.invokeCallback] method to handle the request.
class RootBackButtonDispatcher extends BackButtonDispatcher with WidgetsBindingObserver {
/// Create a root back button dispatcher.
RootBackButtonDispatcher();
@override
void addCallback(ValueGetter<Future<bool>> callback) {
if (!hasCallbacks) {
WidgetsBinding.instance.addObserver(this);
}
super.addCallback(callback);
}
@override
void removeCallback(ValueGetter<Future<bool>> callback) {
super.removeCallback(callback);
if (!hasCallbacks) {
WidgetsBinding.instance.removeObserver(this);
}
}
@override
Future<bool> didPopRoute() => invokeCallback(Future<bool>.value(false));
}
/// A variant of [BackButtonDispatcher] which listens to notifications from a
/// parent back button dispatcher, and can take priority from its parent for the
/// handling of such notifications.
///
/// Useful when [Router]s are being nested within each other.
///
/// Use [Router.of] to obtain a reference to the nearest ancestor [Router], from
/// which the [Router.backButtonDispatcher] can be found, and then used as the
/// [parent] of the [ChildBackButtonDispatcher].
class ChildBackButtonDispatcher extends BackButtonDispatcher {
/// Creates a back button dispatcher that acts as the child of another.
ChildBackButtonDispatcher(this.parent);
/// The back button dispatcher that this object will attempt to take priority
/// over when [takePriority] is called.
///
/// The parent must have a listener registered before this child object can
/// have its [takePriority] or [deferTo] methods used.
final BackButtonDispatcher parent;
/// The parent of this child back button dispatcher decide to let this
/// child to handle the invoke the callback request in
/// [BackButtonDispatcher.invokeCallback].
///
/// Return a boolean future with true if this child will handle the request;
/// otherwise, return a boolean future with false.
@protected
Future<bool> notifiedByParent(Future<bool> defaultValue) {
return invokeCallback(defaultValue);
}
@override
void takePriority() {
parent.deferTo(this);
super.takePriority();
}
@override
void deferTo(ChildBackButtonDispatcher child) {
assert(hasCallbacks);
parent.deferTo(this);
super.deferTo(child);
}
@override
void removeCallback(ValueGetter<Future<bool>> callback) {
super.removeCallback(callback);
if (!hasCallbacks) {
parent.forget(this);
}
}
}
/// A convenience widget that registers a callback for when the back button is pressed.
///
/// In order to use this widget, there must be an ancestor [Router] widget in the tree
/// that has a [RootBackButtonDispatcher]. e.g. The [Router] widget created by the
/// [MaterialApp.router] has a built-in [RootBackButtonDispatcher] by default.
///
/// It only applies to platforms that accept back button clicks, such as Android.
///
/// It can be useful for scenarios, in which you create a different state in your
/// screen but don't want to use a new page for that.
class BackButtonListener extends StatefulWidget {
/// Creates a BackButtonListener widget .
const BackButtonListener({
super.key,
required this.child,
required this.onBackButtonPressed,
});
/// The widget below this widget in the tree.
final Widget child;
/// The callback function that will be called when the back button is pressed.
///
/// It must return a boolean future with true if this child will handle the request;
/// otherwise, return a boolean future with false.
final ValueGetter<Future<bool>> onBackButtonPressed;
@override
State<BackButtonListener> createState() => _BackButtonListenerState();
}
class _BackButtonListenerState extends State<BackButtonListener> {
BackButtonDispatcher? dispatcher;
@override
void didChangeDependencies() {
dispatcher?.removeCallback(widget.onBackButtonPressed);
final BackButtonDispatcher? rootBackDispatcher = Router.of(context).backButtonDispatcher;
assert(rootBackDispatcher != null, 'The parent router must have a backButtonDispatcher to use this widget');
dispatcher = rootBackDispatcher!.createChildBackButtonDispatcher()
..addCallback(widget.onBackButtonPressed)
..takePriority();
super.didChangeDependencies();
}
@override
void didUpdateWidget(covariant BackButtonListener oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.onBackButtonPressed != widget.onBackButtonPressed) {
dispatcher?.removeCallback(oldWidget.onBackButtonPressed);
dispatcher?.addCallback(widget.onBackButtonPressed);
dispatcher?.takePriority();
}
}
@override
void dispose() {
dispatcher?.removeCallback(widget.onBackButtonPressed);
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
/// A delegate that is used by the [Router] widget to parse a route information
/// into a configuration of type T.
///
/// This delegate is used when the [Router] widget is first built with initial
/// route information from [Router.routeInformationProvider] and any subsequent
/// new route notifications from it. The [Router] widget calls the [parseRouteInformation]
/// with the route information from [Router.routeInformationProvider].
///
/// One of the [parseRouteInformation] or
/// [parseRouteInformationWithDependencies] must be implemented, otherwise a
/// runtime error will be thrown.
abstract class RouteInformationParser<T> {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const RouteInformationParser();
/// {@template flutter.widgets.RouteInformationParser.parseRouteInformation}
/// Converts the given route information into parsed data to pass to a
/// [RouterDelegate].
///
/// The method should return a future which completes when the parsing is
/// complete. The parsing may be asynchronous if, e.g., the parser needs to
/// communicate with the OEM thread to obtain additional data about the route.
///
/// Consider using a [SynchronousFuture] if the result can be computed
/// synchronously, so that the [Router] does not need to wait for the next
/// microtask to pass the data to the [RouterDelegate].
/// {@endtemplate}
///
/// One can implement [parseRouteInformationWithDependencies] instead if
/// the parsing depends on other dependencies from the [BuildContext].
Future<T> parseRouteInformation(RouteInformation routeInformation) {
throw UnimplementedError(
'One of the parseRouteInformation or '
'parseRouteInformationWithDependencies must be implemented'
);
}
/// {@macro flutter.widgets.RouteInformationParser.parseRouteInformation}
///
/// The input [BuildContext] can be used for looking up [InheritedWidget]s
/// If one uses [BuildContext.dependOnInheritedWidgetOfExactType], a
/// dependency will be created. The [Router] will re-parse the
/// [RouteInformation] from its [RouteInformationProvider] if the dependency
/// notifies its listeners.
///
/// One can also use [BuildContext.getElementForInheritedWidgetOfExactType] to
/// look up [InheritedWidget]s without creating dependencies.
Future<T> parseRouteInformationWithDependencies(RouteInformation routeInformation, BuildContext context) {
return parseRouteInformation(routeInformation);
}
/// Restore the route information from the given configuration.
///
/// This may return null, in which case the browser history will not be
/// updated and state restoration is disabled. See [Router]'s documentation
/// for details.
///
/// The [parseRouteInformation] method must produce an equivalent
/// configuration when passed this method's return value.
RouteInformation? restoreRouteInformation(T configuration) => null;
}
/// A delegate that is used by the [Router] widget to build and configure a
/// navigating widget.
///
/// This delegate is the core piece of the [Router] widget. It responds to
/// push route and pop route intents from the engine and notifies the [Router]
/// to rebuild. It also acts as a builder for the [Router] widget and builds a
/// navigating widget, typically a [Navigator], when the [Router] widget
/// builds.
///
/// When the engine pushes a new route, the route information is parsed by the
/// [RouteInformationParser] to produce a configuration of type T. The router
/// delegate receives the configuration through [setInitialRoutePath] or
/// [setNewRoutePath] to configure itself and builds the latest navigating
/// widget when asked ([build]).
///
/// When implementing subclasses, consider defining a [Listenable] app state object to be
/// used for building the navigating widget. The router delegate would update
/// the app state accordingly and notify its own listeners when the app state has
/// changed and when it receive route related engine intents (e.g.
/// [setNewRoutePath], [setInitialRoutePath], or [popRoute]).
///
/// All subclass must implement [setNewRoutePath], [popRoute], and [build].
///
/// ## State Restoration
///
/// If the [Router] owning this delegate is configured for state restoration, it
/// will persist and restore the configuration of this [RouterDelegate] using
/// the following mechanism: Before the app is killed by the operating system,
/// the value of [currentConfiguration] is serialized out and persisted. After
/// the app has restarted, the value is deserialized and passed back to the
/// [RouterDelegate] via a call to [setRestoredRoutePath] (which by default just
/// calls [setNewRoutePath]). It is the responsibility of the [RouterDelegate]
/// to use the configuration information provided to restore its internal state.
///
/// See also:
///
/// * [RouteInformationParser], which is responsible for parsing the route
/// information to a configuration before passing in to router delegate.
/// * [Router], which is the widget that wires all the delegates together to
/// provide a fully functional routing solution.
abstract class RouterDelegate<T> extends Listenable {
/// Called by the [Router] at startup with the structure that the
/// [RouteInformationParser] obtained from parsing the initial route.
///
/// This should configure the [RouterDelegate] so that when [build] is
/// invoked, it will create a widget tree that matches the initial route.
///
/// By default, this method forwards the [configuration] to [setNewRoutePath].
///
/// Consider using a [SynchronousFuture] if the result can be computed
/// synchronously, so that the [Router] does not need to wait for the next
/// microtask to schedule a build.
///
/// See also:
///
/// * [setRestoredRoutePath], which is called instead of this method during
/// state restoration.
Future<void> setInitialRoutePath(T configuration) {
return setNewRoutePath(configuration);
}
/// Called by the [Router] during state restoration.
///
/// When the [Router] is configured for state restoration, it will persist
/// the value of [currentConfiguration] during state serialization. During
/// state restoration, the [Router] calls this method (instead of
/// [setInitialRoutePath]) to pass the previous configuration back to the
/// delegate. It is the responsibility of the delegate to restore its internal
/// state based on the provided configuration.
///
/// By default, this method forwards the `configuration` to [setNewRoutePath].
Future<void> setRestoredRoutePath(T configuration) {
return setNewRoutePath(configuration);
}
/// Called by the [Router] when the [Router.routeInformationProvider] reports that a
/// new route has been pushed to the application by the operating system.
///
/// Consider using a [SynchronousFuture] if the result can be computed
/// synchronously, so that the [Router] does not need to wait for the next
/// microtask to schedule a build.
Future<void> setNewRoutePath(T configuration);
/// Called by the [Router] when the [Router.backButtonDispatcher] reports that
/// the operating system is requesting that the current route be popped.
///
/// The method should return a boolean [Future] to indicate whether this
/// delegate handles the request. Returning false will cause the entire app
/// to be popped.
///
/// Consider using a [SynchronousFuture] if the result can be computed
/// synchronously, so that the [Router] does not need to wait for the next
/// microtask to schedule a build.
Future<bool> popRoute();
/// Called by the [Router] when it detects a route information may have
/// changed as a result of rebuild.
///
/// If this getter returns non-null, the [Router] will start to report new
/// route information back to the engine. In web applications, the new
/// route information is used for populating browser history in order to
/// support the forward and the backward buttons.
///
/// When overriding this method, the configuration returned by this getter
/// must be able to construct the current app state and build the widget
/// with the same configuration in the [build] method if it is passed back
/// to the [setNewRoutePath]. Otherwise, the browser backward and forward
/// buttons will not work properly.
///
/// By default, this getter returns null, which prevents the [Router] from
/// reporting the route information. To opt in, a subclass can override this
/// getter to return the current configuration.
///
/// At most one [Router] can opt in to route information reporting. Typically,
/// only the top-most [Router] created by [WidgetsApp.router] should opt for
/// route information reporting.
///
/// ## State Restoration
///
/// This getter is also used by the [Router] to implement state restoration.
/// During state serialization, the [Router] will persist the current
/// configuration and during state restoration pass it back to the delegate
/// by calling [setRestoredRoutePath].
T? get currentConfiguration => null;
/// Called by the [Router] to obtain the widget tree that represents the
/// current state.
///
/// This is called whenever the [Future]s returned by [setInitialRoutePath],
/// [setNewRoutePath], or [setRestoredRoutePath] complete as well as when this
/// notifies its clients (see the [Listenable] interface, which this interface
/// includes). In addition, it may be called at other times. It is important,
/// therefore, that the methods above do not update the state that the [build]
/// method uses before they complete their respective futures.
///
/// Typically this method returns a suitably-configured [Navigator]. If you do
/// plan to create a navigator, consider using the
/// [PopNavigatorRouterDelegateMixin]. If state restoration is enabled for the
/// [Router] using this delegate, consider providing a non-null
/// [Navigator.restorationScopeId] to the [Navigator] returned by this method.
///
/// This method must not return null.
///
/// The `context` is the [Router]'s build context.
Widget build(BuildContext context);
}
/// A route information provider that provides route information for the
/// [Router] widget
///
/// This provider is responsible for handing the route information through [value]
/// getter and notifies listeners, typically the [Router] widget, when a new
/// route information is available.
///
/// When the router opts for route information reporting (by overriding the
/// [RouterDelegate.currentConfiguration] to return non-null), override the
/// [routerReportsNewRouteInformation] method to process the route information.
///
/// See also:
///
/// * [PlatformRouteInformationProvider], which wires up the itself with the
/// [WidgetsBindingObserver.didPushRoute] to propagate platform push route
/// intent to the [Router] widget, as well as reports new route information
/// from the [Router] back to the engine by overriding the
/// [routerReportsNewRouteInformation].
abstract class RouteInformationProvider extends ValueListenable<RouteInformation> {
/// A callback called when the [Router] widget reports new route information
///
/// The subclasses can override this method to update theirs values or trigger
/// other side effects. For example, the [PlatformRouteInformationProvider]
/// overrides this method to report the route information back to the engine.
///
/// The `routeInformation` is the new route information generated by the
/// Router rebuild, and it can be the same or different from the
/// [value].
///
/// The `type` denotes the [Router]'s intention when it reports this
/// `routeInformation`. It is useful when deciding how to update the internal
/// state of [RouteInformationProvider] subclass with the `routeInformation`.
/// For example, [PlatformRouteInformationProvider] uses this property to
/// decide whether to push or replace the browser history entry with the new
/// `routeInformation`.
///
/// For more information on how [Router] determines a navigation event, see
/// the "URL updates for web applications" section in the [Router]
/// documentation.
void routerReportsNewRouteInformation(RouteInformation routeInformation, {RouteInformationReportingType type = RouteInformationReportingType.none}) {}
}
/// The route information provider that propagates the platform route information changes.
///
/// This provider also reports the new route information from the [Router] widget
/// back to engine using message channel method, the
/// [SystemNavigator.routeInformationUpdated].
///
/// Each time [SystemNavigator.routeInformationUpdated] is called, the
/// [SystemNavigator.selectMultiEntryHistory] method is also called. This
/// overrides the initialization behavior of
/// [Navigator.reportsRouteUpdateToEngine].
class PlatformRouteInformationProvider extends RouteInformationProvider with WidgetsBindingObserver, ChangeNotifier {
/// Create a platform route information provider.
///
/// Use the [initialRouteInformation] to set the default route information for this
/// provider.
PlatformRouteInformationProvider({
required RouteInformation initialRouteInformation,
}) : _value = initialRouteInformation {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
static bool _equals(Uri a, Uri b) {
return a.path == b.path
&& a.fragment == b.fragment
&& const DeepCollectionEquality.unordered().equals(a.queryParametersAll, b.queryParametersAll);
}
@override
void routerReportsNewRouteInformation(RouteInformation routeInformation, {RouteInformationReportingType type = RouteInformationReportingType.none}) {
SystemNavigator.selectMultiEntryHistory();
SystemNavigator.routeInformationUpdated(
uri: routeInformation.uri,
state: routeInformation.state,
replace: switch (type) {
RouteInformationReportingType.neglect => true,
RouteInformationReportingType.navigate => false,
RouteInformationReportingType.none => _equals(_valueInEngine.uri, routeInformation.uri),
},
);
_value = routeInformation;
_valueInEngine = routeInformation;
}
@override
RouteInformation get value => _value;
RouteInformation _value;
RouteInformation _valueInEngine = RouteInformation(uri: Uri.parse(WidgetsBinding.instance.platformDispatcher.defaultRouteName));
void _platformReportsNewRouteInformation(RouteInformation routeInformation) {
if (_value == routeInformation) {
return;
}
_value = routeInformation;
_valueInEngine = routeInformation;
notifyListeners();
}
@override
void addListener(VoidCallback listener) {
if (!hasListeners) {
WidgetsBinding.instance.addObserver(this);
}
super.addListener(listener);
}
@override
void removeListener(VoidCallback listener) {
super.removeListener(listener);
if (!hasListeners) {
WidgetsBinding.instance.removeObserver(this);
}
}
@override
void dispose() {
// In practice, this will rarely be called. We assume that the listeners
// will be added and removed in a coherent fashion such that when the object
// is no longer being used, there's no listener, and so it will get garbage
// collected.
if (hasListeners) {
WidgetsBinding.instance.removeObserver(this);
}
super.dispose();
}
@override
Future<bool> didPushRouteInformation(RouteInformation routeInformation) async {
assert(hasListeners);
_platformReportsNewRouteInformation(routeInformation);
return true;
}
}
/// A mixin that wires [RouterDelegate.popRoute] to the [Navigator] it builds.
///
/// This mixin calls [Navigator.maybePop] when it receives an Android back
/// button intent through the [RouterDelegate.popRoute]. Using this mixin
/// guarantees that the back button still respects pageless routes in the
/// navigator.
///
/// Only use this mixin if you plan to build a navigator in the
/// [RouterDelegate.build].
mixin PopNavigatorRouterDelegateMixin<T> on RouterDelegate<T> {
/// The key used for retrieving the current navigator.
///
/// When using this mixin, be sure to use this key to create the navigator.
GlobalKey<NavigatorState>? get navigatorKey;
@override
Future<bool> popRoute() {
final NavigatorState? navigator = navigatorKey?.currentState;
return navigator?.maybePop() ?? SynchronousFuture<bool>(false);
}
}
class _RestorableRouteInformation extends RestorableValue<RouteInformation?> {
@override
RouteInformation? createDefaultValue() => null;
@override
void didUpdateValue(RouteInformation? oldValue) {
notifyListeners();
}
@override
RouteInformation? fromPrimitives(Object? data) {
if (data == null) {
return null;
}
assert(data is List<Object?> && data.length == 2);
final List<Object?> castedData = data as List<Object?>;
final String? uri = castedData.first as String?;
if (uri == null) {
return null;
}
return RouteInformation(uri: Uri.parse(uri), state: castedData.last);
}
@override
Object? toPrimitives() {
return value == null ? null : <Object?>[value!.uri.toString(), value!.state];
}
}
| flutter/packages/flutter/lib/src/widgets/router.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/router.dart",
"repo_id": "flutter",
"token_count": 18859
} | 257 |
// Copyright 2014 The Flutter Authors. 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/rendering.dart';
import 'basic.dart';
import 'debug.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'framework.dart';
import 'media_query.dart';
import 'notification_listener.dart';
import 'primary_scroll_controller.dart';
import 'scroll_configuration.dart';
import 'scroll_controller.dart';
import 'scroll_delegate.dart';
import 'scroll_notification.dart';
import 'scroll_physics.dart';
import 'scrollable.dart';
import 'scrollable_helpers.dart';
import 'sliver.dart';
import 'sliver_prototype_extent_list.dart';
import 'viewport.dart';
// Examples can assume:
// late int itemCount;
/// A representation of how a [ScrollView] should dismiss the on-screen
/// keyboard.
enum ScrollViewKeyboardDismissBehavior {
/// `manual` means there is no automatic dismissal of the on-screen keyboard.
/// It is up to the client to dismiss the keyboard.
manual,
/// `onDrag` means that the [ScrollView] will dismiss an on-screen keyboard
/// when a drag begins.
onDrag,
}
/// A widget that combines a [Scrollable] and a [Viewport] to create an
/// interactive scrolling pane of content in one dimension.
///
/// Scrollable widgets consist of three pieces:
///
/// 1. A [Scrollable] widget, which listens for various user gestures and
/// implements the interaction design for scrolling.
/// 2. A viewport widget, such as [Viewport] or [ShrinkWrappingViewport], which
/// implements the visual design for scrolling by displaying only a portion
/// of the widgets inside the scroll view.
/// 3. One or more slivers, which are widgets that can be composed to created
/// various scrolling effects, such as lists, grids, and expanding headers.
///
/// [ScrollView] helps orchestrate these pieces by creating the [Scrollable] and
/// the viewport and deferring to its subclass to create the slivers.
///
/// To learn more about slivers, see [CustomScrollView.slivers].
///
/// To control the initial scroll offset of the scroll view, provide a
/// [controller] with its [ScrollController.initialScrollOffset] property set.
///
/// {@template flutter.widgets.ScrollView.PageStorage}
/// ## Persisting the scroll position during a session
///
/// Scroll views attempt to persist their scroll position using [PageStorage].
/// This can be disabled by setting [ScrollController.keepScrollOffset] to false
/// on the [controller]. If it is enabled, using a [PageStorageKey] for the
/// [key] of this widget is recommended to help disambiguate different scroll
/// views from each other.
/// {@endtemplate}
///
/// See also:
///
/// * [ListView], which is a commonly used [ScrollView] that displays a
/// scrolling, linear list of child widgets.
/// * [PageView], which is a scrolling list of child widgets that are each the
/// size of the viewport.
/// * [GridView], which is a [ScrollView] that displays a scrolling, 2D array
/// of child widgets.
/// * [CustomScrollView], which is a [ScrollView] that creates custom scroll
/// effects using slivers.
/// * [ScrollNotification] and [NotificationListener], which can be used to watch
/// the scroll position without using a [ScrollController].
/// * [TwoDimensionalScrollView], which is a similar widget [ScrollView] that
/// scrolls in two dimensions.
abstract class ScrollView extends StatelessWidget {
/// Creates a widget that scrolls.
///
/// The [ScrollView.primary] argument defaults to true for vertical
/// scroll views if no [controller] has been provided. The [controller] argument
/// must be null if [primary] is explicitly set to true. If [primary] is true,
/// the nearest [PrimaryScrollController] surrounding the widget is attached
/// to this scroll view.
///
/// If the [shrinkWrap] argument is true, the [center] argument must be null.
///
/// The [anchor] argument must be in the range zero to one, inclusive.
const ScrollView({
super.key,
this.scrollDirection = Axis.vertical,
this.reverse = false,
this.controller,
this.primary,
ScrollPhysics? physics,
this.scrollBehavior,
this.shrinkWrap = false,
this.center,
this.anchor = 0.0,
this.cacheExtent,
this.semanticChildCount,
this.dragStartBehavior = DragStartBehavior.start,
this.keyboardDismissBehavior = ScrollViewKeyboardDismissBehavior.manual,
this.restorationId,
this.clipBehavior = Clip.hardEdge,
this.hitTestBehavior = HitTestBehavior.opaque,
}) : assert(
!(controller != null && (primary ?? false)),
'Primary ScrollViews obtain their ScrollController via inheritance '
'from a PrimaryScrollController widget. You cannot both set primary to '
'true and pass an explicit controller.',
),
assert(!shrinkWrap || center == null),
assert(anchor >= 0.0 && anchor <= 1.0),
assert(semanticChildCount == null || semanticChildCount >= 0),
physics = physics ?? ((primary ?? false) || (primary == null && controller == null && identical(scrollDirection, Axis.vertical)) ? const AlwaysScrollableScrollPhysics() : null);
/// {@template flutter.widgets.scroll_view.scrollDirection}
/// The [Axis] along which the scroll view's offset increases.
///
/// For the direction in which active scrolling may be occurring, see
/// [ScrollDirection].
///
/// Defaults to [Axis.vertical].
/// {@endtemplate}
final Axis scrollDirection;
/// {@template flutter.widgets.scroll_view.reverse}
/// Whether the scroll view scrolls in the reading direction.
///
/// For example, if the reading direction is left-to-right and
/// [scrollDirection] is [Axis.horizontal], then the scroll view scrolls from
/// left to right when [reverse] is false and from right to left when
/// [reverse] is true.
///
/// Similarly, if [scrollDirection] is [Axis.vertical], then the scroll view
/// scrolls from top to bottom when [reverse] is false and from bottom to top
/// when [reverse] is true.
///
/// Defaults to false.
/// {@endtemplate}
final bool reverse;
/// {@template flutter.widgets.scroll_view.controller}
/// An object that can be used to control the position to which this scroll
/// view is scrolled.
///
/// Must be null if [primary] is true.
///
/// A [ScrollController] serves several purposes. It can be used to control
/// the initial scroll position (see [ScrollController.initialScrollOffset]).
/// It can be used to control whether the scroll view should automatically
/// save and restore its scroll position in the [PageStorage] (see
/// [ScrollController.keepScrollOffset]). It can be used to read the current
/// scroll position (see [ScrollController.offset]), or change it (see
/// [ScrollController.animateTo]).
/// {@endtemplate}
final ScrollController? controller;
/// {@template flutter.widgets.scroll_view.primary}
/// Whether this is the primary scroll view associated with the parent
/// [PrimaryScrollController].
///
/// When this is true, the scroll view is scrollable even if it does not have
/// sufficient content to actually scroll. Otherwise, by default the user can
/// only scroll the view if it has sufficient content. See [physics].
///
/// Also when true, the scroll view is used for default [ScrollAction]s. If a
/// ScrollAction is not handled by an otherwise focused part of the application,
/// the ScrollAction will be evaluated using this scroll view, for example,
/// when executing [Shortcuts] key events like page up and down.
///
/// On iOS, this also identifies the scroll view that will scroll to top in
/// response to a tap in the status bar.
///
/// Cannot be true while a [ScrollController] is provided to `controller`,
/// only one ScrollController can be associated with a ScrollView.
///
/// Setting to false will explicitly prevent inheriting any
/// [PrimaryScrollController].
///
/// Defaults to null. When null, and a controller is not provided,
/// [PrimaryScrollController.shouldInherit] is used to decide automatic
/// inheritance.
///
/// By default, the [PrimaryScrollController] that is injected by each
/// [ModalRoute] is configured to automatically be inherited on
/// [TargetPlatformVariant.mobile] for ScrollViews in the [Axis.vertical]
/// scroll direction. Adding another to your app will override the
/// PrimaryScrollController above it.
///
/// The following video contains more information about scroll controllers,
/// the PrimaryScrollController widget, and their impact on your apps:
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=33_0ABjFJUU}
///
/// {@endtemplate}
final bool? primary;
/// {@template flutter.widgets.scroll_view.physics}
/// How the scroll view should respond to user input.
///
/// For example, determines how the scroll view continues to animate after the
/// user stops dragging the scroll view.
///
/// Defaults to matching platform conventions. Furthermore, if [primary] is
/// false, then the user cannot scroll if there is insufficient content to
/// scroll, while if [primary] is true, they can always attempt to scroll.
///
/// To force the scroll view to always be scrollable even if there is
/// insufficient content, as if [primary] was true but without necessarily
/// setting it to true, provide an [AlwaysScrollableScrollPhysics] physics
/// object, as in:
///
/// ```dart
/// physics: const AlwaysScrollableScrollPhysics(),
/// ```
///
/// To force the scroll view to use the default platform conventions and not
/// be scrollable if there is insufficient content, regardless of the value of
/// [primary], provide an explicit [ScrollPhysics] object, as in:
///
/// ```dart
/// physics: const ScrollPhysics(),
/// ```
///
/// The physics can be changed dynamically (by providing a new object in a
/// subsequent build), but new physics will only take effect if the _class_ of
/// the provided object changes. Merely constructing a new instance with a
/// different configuration is insufficient to cause the physics to be
/// reapplied. (This is because the final object used is generated
/// dynamically, which can be relatively expensive, and it would be
/// inefficient to speculatively create this object each frame to see if the
/// physics should be updated.)
/// {@endtemplate}
///
/// If an explicit [ScrollBehavior] is provided to [scrollBehavior], the
/// [ScrollPhysics] provided by that behavior will take precedence after
/// [physics].
final ScrollPhysics? physics;
/// {@macro flutter.widgets.shadow.scrollBehavior}
///
/// [ScrollBehavior]s also provide [ScrollPhysics]. If an explicit
/// [ScrollPhysics] is provided in [physics], it will take precedence,
/// followed by [scrollBehavior], and then the inherited ancestor
/// [ScrollBehavior].
final ScrollBehavior? scrollBehavior;
/// {@template flutter.widgets.scroll_view.shrinkWrap}
/// Whether the extent of the scroll view in the [scrollDirection] should be
/// determined by the contents being viewed.
///
/// If the scroll view does not shrink wrap, then the scroll view will expand
/// to the maximum allowed size in the [scrollDirection]. If the scroll view
/// has unbounded constraints in the [scrollDirection], then [shrinkWrap] must
/// be true.
///
/// Shrink wrapping the content of the scroll view is significantly more
/// expensive than expanding to the maximum allowed size because the content
/// can expand and contract during scrolling, which means the size of the
/// scroll view needs to be recomputed whenever the scroll position changes.
///
/// Defaults to false.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=LUqDNnv_dh0}
/// {@endtemplate}
final bool shrinkWrap;
/// The first child in the [GrowthDirection.forward] growth direction.
///
/// Children after [center] will be placed in the [AxisDirection] determined
/// by [scrollDirection] and [reverse] relative to the [center]. Children
/// before [center] will be placed in the opposite of the axis direction
/// relative to the [center]. This makes the [center] the inflection point of
/// the growth direction.
///
/// The [center] must be the key of one of the slivers built by [buildSlivers].
///
/// Of the built-in subclasses of [ScrollView], only [CustomScrollView]
/// supports [center]; for that class, the given key must be the key of one of
/// the slivers in the [CustomScrollView.slivers] list.
///
/// Most scroll views by default are ordered [GrowthDirection.forward].
/// Changing the default values of [ScrollView.anchor],
/// [ScrollView.center], or both, can configure a scroll view for
/// [GrowthDirection.reverse].
///
/// {@tool dartpad}
/// This sample shows a [CustomScrollView], with [Radio] buttons in the
/// [AppBar.bottom] that change the [AxisDirection] to illustrate different
/// configurations. The [CustomScrollView.anchor] and [CustomScrollView.center]
/// properties are also set to have the 0 scroll offset positioned in the middle
/// of the viewport, with [GrowthDirection.forward] and [GrowthDirection.reverse]
/// illustrated on either side. The sliver that shares the
/// [CustomScrollView.center] key is positioned at the [CustomScrollView.anchor].
///
/// ** See code in examples/api/lib/rendering/growth_direction/growth_direction.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [anchor], which controls where the [center] as aligned in the viewport.
final Key? center;
/// {@template flutter.widgets.scroll_view.anchor}
/// The relative position of the zero scroll offset.
///
/// For example, if [anchor] is 0.5 and the [AxisDirection] determined by
/// [scrollDirection] and [reverse] is [AxisDirection.down] or
/// [AxisDirection.up], then the zero scroll offset is vertically centered
/// within the viewport. If the [anchor] is 1.0, and the axis direction is
/// [AxisDirection.right], then the zero scroll offset is on the left edge of
/// the viewport.
///
/// Most scroll views by default are ordered [GrowthDirection.forward].
/// Changing the default values of [ScrollView.anchor],
/// [ScrollView.center], or both, can configure a scroll view for
/// [GrowthDirection.reverse].
///
/// {@tool dartpad}
/// This sample shows a [CustomScrollView], with [Radio] buttons in the
/// [AppBar.bottom] that change the [AxisDirection] to illustrate different
/// configurations. The [CustomScrollView.anchor] and [CustomScrollView.center]
/// properties are also set to have the 0 scroll offset positioned in the middle
/// of the viewport, with [GrowthDirection.forward] and [GrowthDirection.reverse]
/// illustrated on either side. The sliver that shares the
/// [CustomScrollView.center] key is positioned at the [CustomScrollView.anchor].
///
/// ** See code in examples/api/lib/rendering/growth_direction/growth_direction.0.dart **
/// {@end-tool}
/// {@endtemplate}
final double anchor;
/// {@macro flutter.rendering.RenderViewportBase.cacheExtent}
final double? cacheExtent;
/// The number of children that will contribute semantic information.
///
/// Some subtypes of [ScrollView] can infer this value automatically. For
/// example [ListView] will use the number of widgets in the child list,
/// while the [ListView.separated] constructor will use half that amount.
///
/// For [CustomScrollView] and other types which do not receive a builder
/// or list of widgets, the child count must be explicitly provided. If the
/// number is unknown or unbounded this should be left unset or set to null.
///
/// See also:
///
/// * [SemanticsConfiguration.scrollChildCount], the corresponding semantics property.
final int? semanticChildCount;
/// {@macro flutter.widgets.scrollable.dragStartBehavior}
final DragStartBehavior dragStartBehavior;
/// {@template flutter.widgets.scroll_view.keyboardDismissBehavior}
/// [ScrollViewKeyboardDismissBehavior] the defines how this [ScrollView] will
/// dismiss the keyboard automatically.
/// {@endtemplate}
final ScrollViewKeyboardDismissBehavior keyboardDismissBehavior;
/// {@macro flutter.widgets.scrollable.restorationId}
final String? restorationId;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// {@macro flutter.widgets.scrollable.hitTestBehavior}
///
/// Defaults to [HitTestBehavior.opaque].
final HitTestBehavior hitTestBehavior;
/// Returns the [AxisDirection] in which the scroll view scrolls.
///
/// Combines the [scrollDirection] with the [reverse] boolean to obtain the
/// concrete [AxisDirection].
///
/// If the [scrollDirection] is [Axis.horizontal], the ambient
/// [Directionality] is also considered when selecting the concrete
/// [AxisDirection]. For example, if the ambient [Directionality] is
/// [TextDirection.rtl], then the non-reversed [AxisDirection] is
/// [AxisDirection.left] and the reversed [AxisDirection] is
/// [AxisDirection.right].
@protected
AxisDirection getDirection(BuildContext context) {
return getAxisDirectionFromAxisReverseAndDirectionality(context, scrollDirection, reverse);
}
/// Build the list of widgets to place inside the viewport.
///
/// Subclasses should override this method to build the slivers for the inside
/// of the viewport.
///
/// To learn more about slivers, see [CustomScrollView.slivers].
@protected
List<Widget> buildSlivers(BuildContext context);
/// Build the viewport.
///
/// Subclasses may override this method to change how the viewport is built.
/// The default implementation uses a [ShrinkWrappingViewport] if [shrinkWrap]
/// is true, and a regular [Viewport] otherwise.
///
/// The `offset` argument is the value obtained from
/// [Scrollable.viewportBuilder].
///
/// The `axisDirection` argument is the value obtained from [getDirection],
/// which by default uses [scrollDirection] and [reverse].
///
/// The `slivers` argument is the value obtained from [buildSlivers].
@protected
Widget buildViewport(
BuildContext context,
ViewportOffset offset,
AxisDirection axisDirection,
List<Widget> slivers,
) {
assert(() {
switch (axisDirection) {
case AxisDirection.up:
case AxisDirection.down:
return debugCheckHasDirectionality(
context,
why: 'to determine the cross-axis direction of the scroll view',
hint: 'Vertical scroll views create Viewport widgets that try to determine their cross axis direction '
'from the ambient Directionality.',
);
case AxisDirection.left:
case AxisDirection.right:
return true;
}
}());
if (shrinkWrap) {
return ShrinkWrappingViewport(
axisDirection: axisDirection,
offset: offset,
slivers: slivers,
clipBehavior: clipBehavior,
);
}
return Viewport(
axisDirection: axisDirection,
offset: offset,
slivers: slivers,
cacheExtent: cacheExtent,
center: center,
anchor: anchor,
clipBehavior: clipBehavior,
);
}
@override
Widget build(BuildContext context) {
final List<Widget> slivers = buildSlivers(context);
final AxisDirection axisDirection = getDirection(context);
final bool effectivePrimary = primary
?? controller == null && PrimaryScrollController.shouldInherit(context, scrollDirection);
final ScrollController? scrollController = effectivePrimary
? PrimaryScrollController.maybeOf(context)
: controller;
final Scrollable scrollable = Scrollable(
dragStartBehavior: dragStartBehavior,
axisDirection: axisDirection,
controller: scrollController,
physics: physics,
scrollBehavior: scrollBehavior,
semanticChildCount: semanticChildCount,
restorationId: restorationId,
hitTestBehavior: hitTestBehavior,
viewportBuilder: (BuildContext context, ViewportOffset offset) {
return buildViewport(context, offset, axisDirection, slivers);
},
clipBehavior: clipBehavior,
);
final Widget scrollableResult = effectivePrimary && scrollController != null
// Further descendant ScrollViews will not inherit the same PrimaryScrollController
? PrimaryScrollController.none(child: scrollable)
: scrollable;
if (keyboardDismissBehavior == ScrollViewKeyboardDismissBehavior.onDrag) {
return NotificationListener<ScrollUpdateNotification>(
child: scrollableResult,
onNotification: (ScrollUpdateNotification notification) {
final FocusScopeNode currentScope = FocusScope.of(context);
if (notification.dragDetails != null && !currentScope.hasPrimaryFocus && currentScope.hasFocus) {
FocusManager.instance.primaryFocus?.unfocus();
}
return false;
},
);
} else {
return scrollableResult;
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<Axis>('scrollDirection', scrollDirection));
properties.add(FlagProperty('reverse', value: reverse, ifTrue: 'reversed', showName: true));
properties.add(DiagnosticsProperty<ScrollController>('controller', controller, showName: false, defaultValue: null));
properties.add(FlagProperty('primary', value: primary, ifTrue: 'using primary controller', showName: true));
properties.add(DiagnosticsProperty<ScrollPhysics>('physics', physics, showName: false, defaultValue: null));
properties.add(FlagProperty('shrinkWrap', value: shrinkWrap, ifTrue: 'shrink-wrapping', showName: true));
}
}
/// A [ScrollView] that creates custom scroll effects using [slivers].
///
/// A [CustomScrollView] lets you supply [slivers] directly to create various
/// scrolling effects, such as lists, grids, and expanding headers. For example,
/// to create a scroll view that contains an expanding app bar followed by a
/// list and a grid, use a list of three slivers: [SliverAppBar], [SliverList],
/// and [SliverGrid].
///
/// [Widget]s in these [slivers] must produce [RenderSliver] objects.
///
/// To control the initial scroll offset of the scroll view, provide a
/// [controller] with its [ScrollController.initialScrollOffset] property set.
///
/// {@animation 400 376 https://flutter.github.io/assets-for-api-docs/assets/widgets/custom_scroll_view.mp4}
///
/// {@tool snippet}
///
/// This sample code shows a scroll view that contains a flexible pinned app
/// bar, a grid, and an infinite list.
///
/// ```dart
/// CustomScrollView(
/// slivers: <Widget>[
/// const SliverAppBar(
/// pinned: true,
/// expandedHeight: 250.0,
/// flexibleSpace: FlexibleSpaceBar(
/// title: Text('Demo'),
/// ),
/// ),
/// SliverGrid(
/// gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
/// maxCrossAxisExtent: 200.0,
/// mainAxisSpacing: 10.0,
/// crossAxisSpacing: 10.0,
/// childAspectRatio: 4.0,
/// ),
/// delegate: SliverChildBuilderDelegate(
/// (BuildContext context, int index) {
/// return Container(
/// alignment: Alignment.center,
/// color: Colors.teal[100 * (index % 9)],
/// child: Text('Grid Item $index'),
/// );
/// },
/// childCount: 20,
/// ),
/// ),
/// SliverFixedExtentList(
/// itemExtent: 50.0,
/// delegate: SliverChildBuilderDelegate(
/// (BuildContext context, int index) {
/// return Container(
/// alignment: Alignment.center,
/// color: Colors.lightBlue[100 * (index % 9)],
/// child: Text('List Item $index'),
/// );
/// },
/// ),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
///
/// {@tool dartpad}
/// By default, if items are inserted at the "top" of a scrolling container like
/// [ListView] or [CustomScrollView], the top item and all of the items below it
/// are scrolled downwards. In some applications, it's preferable to have the
/// top of the list just grow upwards, without changing the scroll position.
/// This example demonstrates how to do that with a [CustomScrollView] with
/// two [SliverList] children, and the [CustomScrollView.center] set to the key
/// of the bottom SliverList. The top one SliverList will grow upwards, and the
/// bottom SliverList will grow downwards.
///
/// ** See code in examples/api/lib/widgets/scroll_view/custom_scroll_view.1.dart **
/// {@end-tool}
///
/// ## Accessibility
///
/// A [CustomScrollView] can allow Talkback/VoiceOver to make announcements
/// to the user when the scroll state changes. For example, on Android an
/// announcement might be read as "showing items 1 to 10 of 23". To produce
/// this announcement, the scroll view needs three pieces of information:
///
/// * The first visible child index.
/// * The total number of children.
/// * The total number of visible children.
///
/// The last value can be computed exactly by the framework, however the first
/// two must be provided. Most of the higher-level scrollable widgets provide
/// this information automatically. For example, [ListView] provides each child
/// widget with a semantic index automatically and sets the semantic child
/// count to the length of the list.
///
/// To determine visible indexes, the scroll view needs a way to associate the
/// generated semantics of each scrollable item with a semantic index. This can
/// be done by wrapping the child widgets in an [IndexedSemantics].
///
/// This semantic index is not necessarily the same as the index of the widget in
/// the scrollable, because some widgets may not contribute semantic
/// information. Consider a [ListView.separated]: every other widget is a
/// divider with no semantic information. In this case, only odd numbered
/// widgets have a semantic index (equal to the index ~/ 2). Furthermore, the
/// total number of children in this example would be half the number of
/// widgets. (The [ListView.separated] constructor handles this
/// automatically; this is only used here as an example.)
///
/// The total number of visible children can be provided by the constructor
/// parameter `semanticChildCount`. This should always be the same as the
/// number of widgets wrapped in [IndexedSemantics].
///
/// {@macro flutter.widgets.ScrollView.PageStorage}
///
/// See also:
///
/// * [SliverList], which is a sliver that displays linear list of children.
/// * [SliverFixedExtentList], which is a more efficient sliver that displays
/// linear list of children that have the same extent along the scroll axis.
/// * [SliverGrid], which is a sliver that displays a 2D array of children.
/// * [SliverPadding], which is a sliver that adds blank space around another
/// sliver.
/// * [SliverAppBar], which is a sliver that displays a header that can expand
/// and float as the scroll view scrolls.
/// * [ScrollNotification] and [NotificationListener], which can be used to watch
/// the scroll position without using a [ScrollController].
/// * [IndexedSemantics], which allows annotating child lists with an index
/// for scroll announcements.
class CustomScrollView extends ScrollView {
/// Creates a [ScrollView] that creates custom scroll effects using slivers.
///
/// See the [ScrollView] constructor for more details on these arguments.
const CustomScrollView({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.scrollBehavior,
super.shrinkWrap,
super.center,
super.anchor,
super.cacheExtent,
this.slivers = const <Widget>[],
super.semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
});
/// The slivers to place inside the viewport.
///
/// ## What is a sliver?
///
/// > _**sliver** (noun): a small, thin piece of something._
///
/// A _sliver_ is a widget backed by a [RenderSliver] subclass, i.e. one that
/// implements the constraint/geometry protocol that uses [SliverConstraints]
/// and [SliverGeometry].
///
/// This is as distinct from those widgets that are backed by [RenderBox]
/// subclasses, which use [BoxConstraints] and [Size] respectively, and are
/// known as box widgets. (Widgets like [Container], [Row], and [SizedBox] are
/// box widgets.)
///
/// While boxes are much more straightforward (implementing a simple
/// two-dimensional Cartesian layout system), slivers are much more powerful,
/// and are optimized for one-axis scrolling environments.
///
/// Slivers are hosted in viewports, also known as scroll views, most notably
/// [CustomScrollView].
///
/// ## Examples of slivers
///
/// The Flutter framework has many built-in sliver widgets, and custom widgets
/// can be created in the same manner. By convention, sliver widgets always
/// start with the prefix `Sliver` and are always used in properties called
/// `sliver` or `slivers` (as opposed to `child` and `children` which are used
/// for box widgets).
///
/// Examples of widgets unique to the sliver world include:
///
/// * [SliverList], a lazily-loading list of variably-sized box widgets.
/// * [SliverFixedExtentList], a lazily-loading list of box widgets that are
/// all forced to the same height.
/// * [SliverPrototypeExtentList], a lazily-loading list of box widgets that
/// are all forced to the same height as a given prototype widget.
/// * [SliverGrid], a lazily-loading grid of box widgets.
/// * [SliverAnimatedList] and [SliverAnimatedGrid], animated variants of
/// [SliverList] and [SliverGrid].
/// * [SliverFillRemaining], a widget that fills all remaining space in a
/// scroll view, and lays a box widget out inside that space.
/// * [SliverFillViewport], a widget that lays a list of boxes out, each
/// being sized to fit the whole viewport.
/// * [SliverPersistentHeader], a sliver that implements pinned and floating
/// headers, e.g. used to implement [SliverAppBar].
/// * [SliverToBoxAdapter], a sliver that wraps a box widget.
///
/// Examples of sliver variants of common box widgets include:
///
/// * [SliverOpacity], [SliverAnimatedOpacity], and [SliverFadeTransition],
/// sliver versions of [Opacity], [AnimatedOpacity], and [FadeTransition].
/// * [SliverIgnorePointer], a sliver version of [IgnorePointer].
/// * [SliverLayoutBuilder], a sliver version of [LayoutBuilder].
/// * [SliverOffstage], a sliver version of [Offstage].
/// * [SliverPadding], a sliver version of [Padding].
/// * [SliverReorderableList], a sliver version of [ReorderableList]
/// * [SliverSafeArea], a sliver version of [SafeArea].
/// * [SliverVisibility], a sliver version of [Visibility].
///
/// ## Benefits of slivers over boxes
///
/// The sliver protocol ([SliverConstraints] and [SliverGeometry]) enables
/// _scroll effects_, such as floating app bars, widgets that expand and
/// shrink during scroll, section headers that are pinned only while the
/// section's children are visible, etc.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=Mz3kHQxBjGg}
///
/// ## Mixing slivers and boxes
///
/// In general, slivers always wrap box widgets to actually render anything
/// (for example, there is no sliver equivalent of [Text] or [Container]);
/// the sliver part of the equation is mostly about how these boxes should
/// be laid out in a viewport (i.e. when scrolling).
///
/// Typically, the simplest way to combine boxes into a sliver environment is
/// to use a [SliverList] (maybe using a [ListView, which is a convenient
/// combination of a [CustomScrollView] and a [SliverList]). In rare cases,
/// e.g. if a single [Divider] widget is needed between two [SliverGrid]s,
/// a [SliverToBoxAdapter] can be used to wrap the box widgets.
///
/// ## Performance considerations
///
/// Because the purpose of scroll views is to, well, scroll, it is common
/// for scroll views to contain more contents than are rendered on the screen
/// at any particular time.
///
/// To improve the performance of scroll views, the content can be rendered in
/// _lazy_ widgets, notably [SliverList] and [SliverGrid] (and their variants,
/// such as [SliverFixedExtentList] and [SliverAnimatedGrid]). These widgets
/// ensure that only the portion of their child lists that are actually
/// visible get built, laid out, and painted.
///
/// The [ListView] and [GridView] widgets provide a convenient way to combine
/// a [CustomScrollView] and a [SliverList] or [SliverGrid] (respectively).
final List<Widget> slivers;
@override
List<Widget> buildSlivers(BuildContext context) => slivers;
}
/// A [ScrollView] that uses a single child layout model.
///
/// {@template flutter.widgets.BoxScroll.scrollBehaviour}
/// [ScrollView]s are often decorated with [Scrollbar]s and overscroll indicators,
/// which are managed by the inherited [ScrollBehavior]. Placing a
/// [ScrollConfiguration] above a ScrollView can modify these behaviors for that
/// ScrollView, or can be managed app-wide by providing a ScrollBehavior to
/// [MaterialApp.scrollBehavior] or [CupertinoApp.scrollBehavior].
/// {@endtemplate}
///
/// See also:
///
/// * [ListView], which is a [BoxScrollView] that uses a linear layout model.
/// * [GridView], which is a [BoxScrollView] that uses a 2D layout model.
/// * [CustomScrollView], which can combine multiple child layout models into a
/// single scroll view.
abstract class BoxScrollView extends ScrollView {
/// Creates a [ScrollView] uses a single child layout model.
///
/// If the [primary] argument is true, the [controller] must be null.
const BoxScrollView({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
this.padding,
super.cacheExtent,
super.semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
});
/// The amount of space by which to inset the children.
final EdgeInsetsGeometry? padding;
@override
List<Widget> buildSlivers(BuildContext context) {
Widget sliver = buildChildLayout(context);
EdgeInsetsGeometry? effectivePadding = padding;
if (padding == null) {
final MediaQueryData? mediaQuery = MediaQuery.maybeOf(context);
if (mediaQuery != null) {
// Automatically pad sliver with padding from MediaQuery.
final EdgeInsets mediaQueryHorizontalPadding =
mediaQuery.padding.copyWith(top: 0.0, bottom: 0.0);
final EdgeInsets mediaQueryVerticalPadding =
mediaQuery.padding.copyWith(left: 0.0, right: 0.0);
// Consume the main axis padding with SliverPadding.
effectivePadding = scrollDirection == Axis.vertical
? mediaQueryVerticalPadding
: mediaQueryHorizontalPadding;
// Leave behind the cross axis padding.
sliver = MediaQuery(
data: mediaQuery.copyWith(
padding: scrollDirection == Axis.vertical
? mediaQueryHorizontalPadding
: mediaQueryVerticalPadding,
),
child: sliver,
);
}
}
if (effectivePadding != null) {
sliver = SliverPadding(padding: effectivePadding, sliver: sliver);
}
return <Widget>[ sliver ];
}
/// Subclasses should override this method to build the layout model.
@protected
Widget buildChildLayout(BuildContext context);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('padding', padding, defaultValue: null));
}
}
/// A scrollable list of widgets arranged linearly.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=KJpkjHGiI5A}
///
/// [ListView] is the most commonly used scrolling widget. It displays its
/// children one after another in the scroll direction. In the cross axis, the
/// children are required to fill the [ListView].
///
/// If non-null, the [itemExtent] forces the children to have the given extent
/// in the scroll direction.
///
/// If non-null, the [prototypeItem] forces the children to have the same extent
/// as the given widget in the scroll direction.
///
/// Specifying an [itemExtent] or an [prototypeItem] is more efficient than
/// letting the children determine their own extent because the scrolling
/// machinery can make use of the foreknowledge of the children's extent to save
/// work, for example when the scroll position changes drastically.
///
/// You can't specify both [itemExtent] and [prototypeItem], only one or none of
/// them.
///
/// There are four options for constructing a [ListView]:
///
/// 1. The default constructor takes an explicit [List<Widget>] of children. This
/// constructor is appropriate for list views with a small number of
/// children because constructing the [List] requires doing work for every
/// child that could possibly be displayed in the list view instead of just
/// those children that are actually visible.
///
/// 2. The [ListView.builder] constructor takes an [IndexedWidgetBuilder], which
/// builds the children on demand. This constructor is appropriate for list views
/// with a large (or infinite) number of children because the builder is called
/// only for those children that are actually visible.
///
/// 3. The [ListView.separated] constructor takes two [IndexedWidgetBuilder]s:
/// `itemBuilder` builds child items on demand, and `separatorBuilder`
/// similarly builds separator children which appear in between the child items.
/// This constructor is appropriate for list views with a fixed number of children.
///
/// 4. The [ListView.custom] constructor takes a [SliverChildDelegate], which provides
/// the ability to customize additional aspects of the child model. For example,
/// a [SliverChildDelegate] can control the algorithm used to estimate the
/// size of children that are not actually visible.
///
/// To control the initial scroll offset of the scroll view, provide a
/// [controller] with its [ScrollController.initialScrollOffset] property set.
///
/// By default, [ListView] will automatically pad the list's scrollable
/// extremities to avoid partial obstructions indicated by [MediaQuery]'s
/// padding. To avoid this behavior, override with a zero [padding] property.
///
/// {@tool snippet}
/// This example uses the default constructor for [ListView] which takes an
/// explicit [List<Widget>] of children. This [ListView]'s children are made up
/// of [Container]s with [Text].
///
/// 
///
/// ```dart
/// ListView(
/// padding: const EdgeInsets.all(8),
/// children: <Widget>[
/// Container(
/// height: 50,
/// color: Colors.amber[600],
/// child: const Center(child: Text('Entry A')),
/// ),
/// Container(
/// height: 50,
/// color: Colors.amber[500],
/// child: const Center(child: Text('Entry B')),
/// ),
/// Container(
/// height: 50,
/// color: Colors.amber[100],
/// child: const Center(child: Text('Entry C')),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
///
/// {@tool snippet}
/// This example mirrors the previous one, creating the same list using the
/// [ListView.builder] constructor. Using the [IndexedWidgetBuilder], children
/// are built lazily and can be infinite in number.
///
/// 
///
/// ```dart
/// final List<String> entries = <String>['A', 'B', 'C'];
/// final List<int> colorCodes = <int>[600, 500, 100];
///
/// Widget build(BuildContext context) {
/// return ListView.builder(
/// padding: const EdgeInsets.all(8),
/// itemCount: entries.length,
/// itemBuilder: (BuildContext context, int index) {
/// return Container(
/// height: 50,
/// color: Colors.amber[colorCodes[index]],
/// child: Center(child: Text('Entry ${entries[index]}')),
/// );
/// }
/// );
/// }
/// ```
/// {@end-tool}
///
/// {@tool snippet}
/// This example continues to build from our the previous ones, creating a
/// similar list using [ListView.separated]. Here, a [Divider] is used as a
/// separator.
///
/// 
///
/// ```dart
/// final List<String> entries = <String>['A', 'B', 'C'];
/// final List<int> colorCodes = <int>[600, 500, 100];
///
/// Widget build(BuildContext context) {
/// return ListView.separated(
/// padding: const EdgeInsets.all(8),
/// itemCount: entries.length,
/// itemBuilder: (BuildContext context, int index) {
/// return Container(
/// height: 50,
/// color: Colors.amber[colorCodes[index]],
/// child: Center(child: Text('Entry ${entries[index]}')),
/// );
/// },
/// separatorBuilder: (BuildContext context, int index) => const Divider(),
/// );
/// }
/// ```
/// {@end-tool}
///
/// ## Child elements' lifecycle
///
/// ### Creation
///
/// While laying out the list, visible children's elements, states and render
/// objects will be created lazily based on existing widgets (such as when using
/// the default constructor) or lazily provided ones (such as when using the
/// [ListView.builder] constructor).
///
/// ### Destruction
///
/// When a child is scrolled out of view, the associated element subtree,
/// states and render objects are destroyed. A new child at the same position
/// in the list will be lazily recreated along with new elements, states and
/// render objects when it is scrolled back.
///
/// ### Destruction mitigation
///
/// In order to preserve state as child elements are scrolled in and out of
/// view, the following options are possible:
///
/// * Moving the ownership of non-trivial UI-state-driving business logic
/// out of the list child subtree. For instance, if a list contains posts
/// with their number of upvotes coming from a cached network response, store
/// the list of posts and upvote number in a data model outside the list. Let
/// the list child UI subtree be easily recreate-able from the
/// source-of-truth model object. Use [StatefulWidget]s in the child
/// widget subtree to store instantaneous UI state only.
///
/// * Letting [KeepAlive] be the root widget of the list child widget subtree
/// that needs to be preserved. The [KeepAlive] widget marks the child
/// subtree's top render object child for keepalive. When the associated top
/// render object is scrolled out of view, the list keeps the child's render
/// object (and by extension, its associated elements and states) in a cache
/// list instead of destroying them. When scrolled back into view, the render
/// object is repainted as-is (if it wasn't marked dirty in the interim).
///
/// This only works if `addAutomaticKeepAlives` and `addRepaintBoundaries`
/// are false since those parameters cause the [ListView] to wrap each child
/// widget subtree with other widgets.
///
/// * Using [AutomaticKeepAlive] widgets (inserted by default when
/// `addAutomaticKeepAlives` is true). [AutomaticKeepAlive] allows descendant
/// widgets to control whether the subtree is actually kept alive or not.
/// This behavior is in contrast with [KeepAlive], which will unconditionally keep
/// the subtree alive.
///
/// As an example, the [EditableText] widget signals its list child element
/// subtree to stay alive while its text field has input focus. If it doesn't
/// have focus and no other descendants signaled for keepalive via a
/// [KeepAliveNotification], the list child element subtree will be destroyed
/// when scrolled away.
///
/// [AutomaticKeepAlive] descendants typically signal it to be kept alive
/// by using the [AutomaticKeepAliveClientMixin], then implementing the
/// [AutomaticKeepAliveClientMixin.wantKeepAlive] getter and calling
/// [AutomaticKeepAliveClientMixin.updateKeepAlive].
///
/// ## Transitioning to [CustomScrollView]
///
/// A [ListView] is basically a [CustomScrollView] with a single [SliverList] in
/// its [CustomScrollView.slivers] property.
///
/// If [ListView] is no longer sufficient, for example because the scroll view
/// is to have both a list and a grid, or because the list is to be combined
/// with a [SliverAppBar], etc, it is straight-forward to port code from using
/// [ListView] to using [CustomScrollView] directly.
///
/// The [key], [scrollDirection], [reverse], [controller], [primary], [physics],
/// and [shrinkWrap] properties on [ListView] map directly to the identically
/// named properties on [CustomScrollView].
///
/// The [CustomScrollView.slivers] property should be a list containing either:
/// * a [SliverList] if both [itemExtent] and [prototypeItem] were null;
/// * a [SliverFixedExtentList] if [itemExtent] was not null; or
/// * a [SliverPrototypeExtentList] if [prototypeItem] was not null.
///
/// The [childrenDelegate] property on [ListView] corresponds to the
/// [SliverList.delegate] (or [SliverFixedExtentList.delegate]) property. The
/// [ListView] constructor's `children` argument corresponds to the
/// [childrenDelegate] being a [SliverChildListDelegate] with that same
/// argument. The [ListView.builder] constructor's `itemBuilder` and
/// `itemCount` arguments correspond to the [childrenDelegate] being a
/// [SliverChildBuilderDelegate] with the equivalent arguments.
///
/// The [padding] property corresponds to having a [SliverPadding] in the
/// [CustomScrollView.slivers] property instead of the list itself, and having
/// the [SliverList] instead be a child of the [SliverPadding].
///
/// [CustomScrollView]s don't automatically avoid obstructions from [MediaQuery]
/// like [ListView]s do. To reproduce the behavior, wrap the slivers in
/// [SliverSafeArea]s.
///
/// Once code has been ported to use [CustomScrollView], other slivers, such as
/// [SliverGrid] or [SliverAppBar], can be put in the [CustomScrollView.slivers]
/// list.
///
/// {@tool snippet}
///
/// Here are two brief snippets showing a [ListView] and its equivalent using
/// [CustomScrollView]:
///
/// ```dart
/// ListView(
/// padding: const EdgeInsets.all(20.0),
/// children: const <Widget>[
/// Text("I'm dedicating every day to you"),
/// Text('Domestic life was never quite my style'),
/// Text('When you smile, you knock me out, I fall apart'),
/// Text('And I thought I was so smart'),
/// ],
/// )
/// ```
/// {@end-tool}
/// {@tool snippet}
///
/// ```dart
/// CustomScrollView(
/// slivers: <Widget>[
/// SliverPadding(
/// padding: const EdgeInsets.all(20.0),
/// sliver: SliverList(
/// delegate: SliverChildListDelegate(
/// <Widget>[
/// const Text("I'm dedicating every day to you"),
/// const Text('Domestic life was never quite my style'),
/// const Text('When you smile, you knock me out, I fall apart'),
/// const Text('And I thought I was so smart'),
/// ],
/// ),
/// ),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
///
/// ## Special handling for an empty list
///
/// A common design pattern is to have a custom UI for an empty list. The best
/// way to achieve this in Flutter is just conditionally replacing the
/// [ListView] at build time with whatever widgets you need to show for the
/// empty list state:
///
/// {@tool snippet}
///
/// Example of simple empty list interface:
///
/// ```dart
/// Widget build(BuildContext context) {
/// return Scaffold(
/// appBar: AppBar(title: const Text('Empty List Test')),
/// body: itemCount > 0
/// ? ListView.builder(
/// itemCount: itemCount,
/// itemBuilder: (BuildContext context, int index) {
/// return ListTile(
/// title: Text('Item ${index + 1}'),
/// );
/// },
/// )
/// : const Center(child: Text('No items')),
/// );
/// }
/// ```
/// {@end-tool}
///
/// ## Selection of list items
///
/// [ListView] has no built-in notion of a selected item or items. For a small
/// example of how a caller might wire up basic item selection, see
/// [ListTile.selected].
///
/// {@tool dartpad}
/// This example shows a custom implementation of [ListTile] selection in a [ListView] or [GridView].
/// Long press any [ListTile] to enable selection mode.
///
/// ** See code in examples/api/lib/widgets/scroll_view/list_view.0.dart **
/// {@end-tool}
///
/// {@macro flutter.widgets.BoxScroll.scrollBehaviour}
///
/// {@macro flutter.widgets.ScrollView.PageStorage}
///
/// See also:
///
/// * [SingleChildScrollView], which is a scrollable widget that has a single
/// child.
/// * [PageView], which is a scrolling list of child widgets that are each the
/// size of the viewport.
/// * [GridView], which is a scrollable, 2D array of widgets.
/// * [CustomScrollView], which is a scrollable widget that creates custom
/// scroll effects using slivers.
/// * [ListBody], which arranges its children in a similar manner, but without
/// scrolling.
/// * [ScrollNotification] and [NotificationListener], which can be used to watch
/// the scroll position without using a [ScrollController].
/// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
/// * Cookbook: [Use lists](https://flutter.dev/docs/cookbook/lists/basic-list)
/// * Cookbook: [Work with long lists](https://flutter.dev/docs/cookbook/lists/long-lists)
/// * Cookbook: [Create a horizontal list](https://flutter.dev/docs/cookbook/lists/horizontal-list)
/// * Cookbook: [Create lists with different types of items](https://flutter.dev/docs/cookbook/lists/mixed-list)
/// * Cookbook: [Implement swipe to dismiss](https://flutter.dev/docs/cookbook/gestures/dismissible)
class ListView extends BoxScrollView {
/// Creates a scrollable, linear array of widgets from an explicit [List].
///
/// This constructor is appropriate for list views with a small number of
/// children because constructing the [List] requires doing work for every
/// child that could possibly be displayed in the list view instead of just
/// those children that are actually visible.
///
/// Like other widgets in the framework, this widget expects that
/// the [children] list will not be mutated after it has been passed in here.
/// See the documentation at [SliverChildListDelegate.children] for more details.
///
/// It is usually more efficient to create children on demand using
/// [ListView.builder] because it will create the widget children lazily as necessary.
///
/// The `addAutomaticKeepAlives` argument corresponds to the
/// [SliverChildListDelegate.addAutomaticKeepAlives] property. The
/// `addRepaintBoundaries` argument corresponds to the
/// [SliverChildListDelegate.addRepaintBoundaries] property. The
/// `addSemanticIndexes` argument corresponds to the
/// [SliverChildListDelegate.addSemanticIndexes] property. None
/// may be null.
ListView({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
this.itemExtent,
this.itemExtentBuilder,
this.prototypeItem,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
super.cacheExtent,
List<Widget> children = const <Widget>[],
int? semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
}) : assert(
(itemExtent == null && prototypeItem == null) ||
(itemExtent == null && itemExtentBuilder == null) ||
(prototypeItem == null && itemExtentBuilder == null),
'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.',
),
childrenDelegate = SliverChildListDelegate(
children,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
),
super(
semanticChildCount: semanticChildCount ?? children.length,
);
/// Creates a scrollable, linear array of widgets that are created on demand.
///
/// This constructor is appropriate for list views with a large (or infinite)
/// number of children because the builder is called only for those children
/// that are actually visible.
///
/// Providing a non-null `itemCount` improves the ability of the [ListView] to
/// estimate the maximum scroll extent.
///
/// The `itemBuilder` callback will be called only with indices greater than
/// or equal to zero and less than `itemCount`.
///
/// {@template flutter.widgets.ListView.builder.itemBuilder}
/// It is legal for `itemBuilder` to return `null`. If it does, the scroll view
/// will stop calling `itemBuilder`, even if it has yet to reach `itemCount`.
/// By returning `null`, the [ScrollPosition.maxScrollExtent] will not be accurate
/// unless the user has reached the end of the [ScrollView]. This can also cause the
/// [Scrollbar] to grow as the user scrolls.
///
/// For more accurate [ScrollMetrics], consider specifying `itemCount`.
/// {@endtemplate}
///
/// The `itemBuilder` should always create the widget instances when called.
/// Avoid using a builder that returns a previously-constructed widget; if the
/// list view's children are created in advance, or all at once when the
/// [ListView] itself is created, it is more efficient to use the [ListView]
/// constructor. Even more efficient, however, is to create the instances on
/// demand using this constructor's `itemBuilder` callback.
///
/// {@macro flutter.widgets.PageView.findChildIndexCallback}
///
/// The `addAutomaticKeepAlives` argument corresponds to the
/// [SliverChildBuilderDelegate.addAutomaticKeepAlives] property. The
/// `addRepaintBoundaries` argument corresponds to the
/// [SliverChildBuilderDelegate.addRepaintBoundaries] property. The
/// `addSemanticIndexes` argument corresponds to the
/// [SliverChildBuilderDelegate.addSemanticIndexes] property. None may be
/// null.
ListView.builder({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
this.itemExtent,
this.itemExtentBuilder,
this.prototypeItem,
required NullableIndexedWidgetBuilder itemBuilder,
ChildIndexGetter? findChildIndexCallback,
int? itemCount,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
super.cacheExtent,
int? semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
}) : assert(itemCount == null || itemCount >= 0),
assert(semanticChildCount == null || semanticChildCount <= itemCount!),
assert(
(itemExtent == null && prototypeItem == null) ||
(itemExtent == null && itemExtentBuilder == null) ||
(prototypeItem == null && itemExtentBuilder == null),
'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.',
),
childrenDelegate = SliverChildBuilderDelegate(
itemBuilder,
findChildIndexCallback: findChildIndexCallback,
childCount: itemCount,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
),
super(
semanticChildCount: semanticChildCount ?? itemCount,
);
/// Creates a fixed-length scrollable linear array of list "items" separated
/// by list item "separators".
///
/// This constructor is appropriate for list views with a large number of
/// item and separator children because the builders are only called for
/// the children that are actually visible.
///
/// The `itemBuilder` callback will be called with indices greater than
/// or equal to zero and less than `itemCount`.
///
/// Separators only appear between list items: separator 0 appears after item
/// 0 and the last separator appears before the last item.
///
/// The `separatorBuilder` callback will be called with indices greater than
/// or equal to zero and less than `itemCount - 1`.
///
/// The `itemBuilder` and `separatorBuilder` callbacks should always
/// actually create widget instances when called. Avoid using a builder that
/// returns a previously-constructed widget; if the list view's children are
/// created in advance, or all at once when the [ListView] itself is created,
/// it is more efficient to use the [ListView] constructor.
///
/// {@macro flutter.widgets.ListView.builder.itemBuilder}
///
/// {@macro flutter.widgets.PageView.findChildIndexCallback}
///
/// {@tool snippet}
///
/// This example shows how to create [ListView] whose [ListTile] list items
/// are separated by [Divider]s.
///
/// ```dart
/// ListView.separated(
/// itemCount: 25,
/// separatorBuilder: (BuildContext context, int index) => const Divider(),
/// itemBuilder: (BuildContext context, int index) {
/// return ListTile(
/// title: Text('item $index'),
/// );
/// },
/// )
/// ```
/// {@end-tool}
///
/// The `addAutomaticKeepAlives` argument corresponds to the
/// [SliverChildBuilderDelegate.addAutomaticKeepAlives] property. The
/// `addRepaintBoundaries` argument corresponds to the
/// [SliverChildBuilderDelegate.addRepaintBoundaries] property. The
/// `addSemanticIndexes` argument corresponds to the
/// [SliverChildBuilderDelegate.addSemanticIndexes] property. None may be
/// null.
ListView.separated({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
required NullableIndexedWidgetBuilder itemBuilder,
ChildIndexGetter? findChildIndexCallback,
required IndexedWidgetBuilder separatorBuilder,
required int itemCount,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
super.cacheExtent,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
}) : assert(itemCount >= 0),
itemExtent = null,
itemExtentBuilder = null,
prototypeItem = null,
childrenDelegate = SliverChildBuilderDelegate(
(BuildContext context, int index) {
final int itemIndex = index ~/ 2;
if (index.isEven) {
return itemBuilder(context, itemIndex);
}
return separatorBuilder(context, itemIndex);
},
findChildIndexCallback: findChildIndexCallback,
childCount: _computeActualChildCount(itemCount),
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
semanticIndexCallback: (Widget widget, int index) {
return index.isEven ? index ~/ 2 : null;
},
),
super(
semanticChildCount: itemCount,
);
/// Creates a scrollable, linear array of widgets with a custom child model.
///
/// For example, a custom child model can control the algorithm used to
/// estimate the size of children that are not actually visible.
///
/// {@tool dartpad}
/// This example shows a [ListView] that uses a custom [SliverChildBuilderDelegate] to support child
/// reordering.
///
/// ** See code in examples/api/lib/widgets/scroll_view/list_view.1.dart **
/// {@end-tool}
const ListView.custom({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
this.itemExtent,
this.prototypeItem,
this.itemExtentBuilder,
required this.childrenDelegate,
super.cacheExtent,
super.semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
}) : assert(
(itemExtent == null && prototypeItem == null) ||
(itemExtent == null && itemExtentBuilder == null) ||
(prototypeItem == null && itemExtentBuilder == null),
'You can only pass one of itemExtent, prototypeItem and itemExtentBuilder.',
);
/// {@template flutter.widgets.list_view.itemExtent}
/// If non-null, forces the children to have the given extent in the scroll
/// direction.
///
/// Specifying an [itemExtent] is more efficient than letting the children
/// determine their own extent because the scrolling machinery can make use of
/// the foreknowledge of the children's extent to save work, for example when
/// the scroll position changes drastically.
///
/// See also:
///
/// * [SliverFixedExtentList], the sliver used internally when this property
/// is provided. It constrains its box children to have a specific given
/// extent along the main axis.
/// * The [prototypeItem] property, which allows forcing the children's
/// extent to be the same as the given widget.
/// * The [itemExtentBuilder] property, which allows forcing the children's
/// extent to be the value returned by the callback.
/// {@endtemplate}
final double? itemExtent;
/// {@template flutter.widgets.list_view.itemExtentBuilder}
/// If non-null, forces the children to have the corresponding extent returned
/// by the builder.
///
/// Specifying an [itemExtentBuilder] is more efficient than letting the children
/// determine their own extent because the scrolling machinery can make use of
/// the foreknowledge of the children's extent to save work, for example when
/// the scroll position changes drastically.
///
/// This will be called multiple times during the layout phase of a frame to find
/// the items that should be loaded by the lazy loading process.
///
/// Should return null if asked to build an item extent with a greater index than
/// exists.
///
/// Unlike [itemExtent] or [prototypeItem], this allows children to have
/// different extents.
///
/// See also:
///
/// * [SliverVariedExtentList], the sliver used internally when this property
/// is provided. It constrains its box children to have a specific given
/// extent along the main axis.
/// * The [itemExtent] property, which allows forcing the children's extent
/// to a given value.
/// * The [prototypeItem] property, which allows forcing the children's
/// extent to be the same as the given widget.
/// {@endtemplate}
final ItemExtentBuilder? itemExtentBuilder;
/// {@template flutter.widgets.list_view.prototypeItem}
/// If non-null, forces the children to have the same extent as the given
/// widget in the scroll direction.
///
/// Specifying an [prototypeItem] is more efficient than letting the children
/// determine their own extent because the scrolling machinery can make use of
/// the foreknowledge of the children's extent to save work, for example when
/// the scroll position changes drastically.
///
/// See also:
///
/// * [SliverPrototypeExtentList], the sliver used internally when this
/// property is provided. It constrains its box children to have the same
/// extent as a prototype item along the main axis.
/// * The [itemExtent] property, which allows forcing the children's extent
/// to a given value.
/// * The [itemExtentBuilder] property, which allows forcing the children's
/// extent to be the value returned by the callback.
/// {@endtemplate}
final Widget? prototypeItem;
/// A delegate that provides the children for the [ListView].
///
/// The [ListView.custom] constructor lets you specify this delegate
/// explicitly. The [ListView] and [ListView.builder] constructors create a
/// [childrenDelegate] that wraps the given [List] and [IndexedWidgetBuilder],
/// respectively.
final SliverChildDelegate childrenDelegate;
@override
Widget buildChildLayout(BuildContext context) {
if (itemExtent != null) {
return SliverFixedExtentList(
delegate: childrenDelegate,
itemExtent: itemExtent!,
);
} else if (itemExtentBuilder != null) {
return SliverVariedExtentList(
delegate: childrenDelegate,
itemExtentBuilder: itemExtentBuilder!,
);
} else if (prototypeItem != null) {
return SliverPrototypeExtentList(
delegate: childrenDelegate,
prototypeItem: prototypeItem!,
);
}
return SliverList(delegate: childrenDelegate);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty('itemExtent', itemExtent, defaultValue: null));
}
// Helper method to compute the actual child count for the separated constructor.
static int _computeActualChildCount(int itemCount) {
return math.max(0, itemCount * 2 - 1);
}
}
/// A scrollable, 2D array of widgets.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=bLOtZDTm4H8}
///
/// The main axis direction of a grid is the direction in which it scrolls (the
/// [scrollDirection]).
///
/// The most commonly used grid layouts are [GridView.count], which creates a
/// layout with a fixed number of tiles in the cross axis, and
/// [GridView.extent], which creates a layout with tiles that have a maximum
/// cross-axis extent. A custom [SliverGridDelegate] can produce an arbitrary 2D
/// arrangement of children, including arrangements that are unaligned or
/// overlapping.
///
/// To create a grid with a large (or infinite) number of children, use the
/// [GridView.builder] constructor with either a
/// [SliverGridDelegateWithFixedCrossAxisCount] or a
/// [SliverGridDelegateWithMaxCrossAxisExtent] for the [gridDelegate].
///
/// To use a custom [SliverChildDelegate], use [GridView.custom].
///
/// To create a linear array of children, use a [ListView].
///
/// To control the initial scroll offset of the scroll view, provide a
/// [controller] with its [ScrollController.initialScrollOffset] property set.
///
/// ## Transitioning to [CustomScrollView]
///
/// A [GridView] is basically a [CustomScrollView] with a single [SliverGrid] in
/// its [CustomScrollView.slivers] property.
///
/// If [GridView] is no longer sufficient, for example because the scroll view
/// is to have both a grid and a list, or because the grid is to be combined
/// with a [SliverAppBar], etc, it is straight-forward to port code from using
/// [GridView] to using [CustomScrollView] directly.
///
/// The [key], [scrollDirection], [reverse], [controller], [primary], [physics],
/// and [shrinkWrap] properties on [GridView] map directly to the identically
/// named properties on [CustomScrollView].
///
/// The [CustomScrollView.slivers] property should be a list containing just a
/// [SliverGrid].
///
/// The [childrenDelegate] property on [GridView] corresponds to the
/// [SliverGrid.delegate] property, and the [gridDelegate] property on the
/// [GridView] corresponds to the [SliverGrid.gridDelegate] property.
///
/// The [GridView], [GridView.count], and [GridView.extent]
/// constructors' `children` arguments correspond to the [childrenDelegate]
/// being a [SliverChildListDelegate] with that same argument. The
/// [GridView.builder] constructor's `itemBuilder` and `childCount` arguments
/// correspond to the [childrenDelegate] being a [SliverChildBuilderDelegate]
/// with the matching arguments.
///
/// The [GridView.count] and [GridView.extent] constructors create
/// custom grid delegates, and have equivalently named constructors on
/// [SliverGrid] to ease the transition: [SliverGrid.count] and
/// [SliverGrid.extent] respectively.
///
/// The [padding] property corresponds to having a [SliverPadding] in the
/// [CustomScrollView.slivers] property instead of the grid itself, and having
/// the [SliverGrid] instead be a child of the [SliverPadding].
///
/// Once code has been ported to use [CustomScrollView], other slivers, such as
/// [SliverList] or [SliverAppBar], can be put in the [CustomScrollView.slivers]
/// list.
///
/// {@macro flutter.widgets.ScrollView.PageStorage}
///
/// ## Examples
///
/// {@tool snippet}
/// This example demonstrates how to create a [GridView] with two columns. The
/// children are spaced apart using the `crossAxisSpacing` and `mainAxisSpacing`
/// properties.
///
/// 
///
/// ```dart
/// GridView.count(
/// primary: false,
/// padding: const EdgeInsets.all(20),
/// crossAxisSpacing: 10,
/// mainAxisSpacing: 10,
/// crossAxisCount: 2,
/// children: <Widget>[
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.teal[100],
/// child: const Text("He'd have you all unravel at the"),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.teal[200],
/// child: const Text('Heed not the rabble'),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.teal[300],
/// child: const Text('Sound of screams but the'),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.teal[400],
/// child: const Text('Who scream'),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.teal[500],
/// child: const Text('Revolution is coming...'),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.teal[600],
/// child: const Text('Revolution, they...'),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
///
/// {@tool snippet}
/// This example shows how to create the same grid as the previous example
/// using a [CustomScrollView] and a [SliverGrid].
///
/// 
///
/// ```dart
/// CustomScrollView(
/// primary: false,
/// slivers: <Widget>[
/// SliverPadding(
/// padding: const EdgeInsets.all(20),
/// sliver: SliverGrid.count(
/// crossAxisSpacing: 10,
/// mainAxisSpacing: 10,
/// crossAxisCount: 2,
/// children: <Widget>[
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.green[100],
/// child: const Text("He'd have you all unravel at the"),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.green[200],
/// child: const Text('Heed not the rabble'),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.green[300],
/// child: const Text('Sound of screams but the'),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.green[400],
/// child: const Text('Who scream'),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.green[500],
/// child: const Text('Revolution is coming...'),
/// ),
/// Container(
/// padding: const EdgeInsets.all(8),
/// color: Colors.green[600],
/// child: const Text('Revolution, they...'),
/// ),
/// ],
/// ),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows a custom implementation of selection in list and grid views.
/// Use the button in the top right (possibly hidden under the DEBUG banner) to toggle between
/// [ListView] and [GridView].
/// Long press any [ListTile] or [GridTile] to enable selection mode.
///
/// ** See code in examples/api/lib/widgets/scroll_view/list_view.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows a custom [SliverGridDelegate].
///
/// ** See code in examples/api/lib/widgets/scroll_view/grid_view.0.dart **
/// {@end-tool}
///
/// ## Troubleshooting
///
/// ### Padding
///
/// By default, [GridView] will automatically pad the limits of the
/// grid's scrollable to avoid partial obstructions indicated by
/// [MediaQuery]'s padding. To avoid this behavior, override with a
/// zero [padding] property.
///
/// {@tool snippet}
/// The following example demonstrates how to override the default top padding
/// using [MediaQuery.removePadding].
///
/// ```dart
/// Widget myWidget(BuildContext context) {
/// return MediaQuery.removePadding(
/// context: context,
/// removeTop: true,
/// child: GridView.builder(
/// gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
/// crossAxisCount: 3,
/// ),
/// itemCount: 300,
/// itemBuilder: (BuildContext context, int index) {
/// return Card(
/// color: Colors.amber,
/// child: Center(child: Text('$index')),
/// );
/// }
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [SingleChildScrollView], which is a scrollable widget that has a single
/// child.
/// * [ListView], which is scrollable, linear list of widgets.
/// * [PageView], which is a scrolling list of child widgets that are each the
/// size of the viewport.
/// * [CustomScrollView], which is a scrollable widget that creates custom
/// scroll effects using slivers.
/// * [SliverGridDelegateWithFixedCrossAxisCount], which creates a layout with
/// a fixed number of tiles in the cross axis.
/// * [SliverGridDelegateWithMaxCrossAxisExtent], which creates a layout with
/// tiles that have a maximum cross-axis extent.
/// * [ScrollNotification] and [NotificationListener], which can be used to watch
/// the scroll position without using a [ScrollController].
/// * The [catalog of layout widgets](https://flutter.dev/widgets/layout/).
class GridView extends BoxScrollView {
/// Creates a scrollable, 2D array of widgets with a custom
/// [SliverGridDelegate].
///
/// The `addAutomaticKeepAlives` argument corresponds to the
/// [SliverChildListDelegate.addAutomaticKeepAlives] property. The
/// `addRepaintBoundaries` argument corresponds to the
/// [SliverChildListDelegate.addRepaintBoundaries] property. Both must not be
/// null.
GridView({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
required this.gridDelegate,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
super.cacheExtent,
List<Widget> children = const <Widget>[],
int? semanticChildCount,
super.dragStartBehavior,
super.clipBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.hitTestBehavior,
}) : childrenDelegate = SliverChildListDelegate(
children,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
),
super(
semanticChildCount: semanticChildCount ?? children.length,
);
/// Creates a scrollable, 2D array of widgets that are created on demand.
///
/// This constructor is appropriate for grid views with a large (or infinite)
/// number of children because the builder is called only for those children
/// that are actually visible.
///
/// Providing a non-null `itemCount` improves the ability of the [GridView] to
/// estimate the maximum scroll extent.
///
/// `itemBuilder` will be called only with indices greater than or equal to
/// zero and less than `itemCount`.
///
/// {@macro flutter.widgets.ListView.builder.itemBuilder}
///
/// {@macro flutter.widgets.PageView.findChildIndexCallback}
///
/// The [gridDelegate] argument is required.
///
/// The `addAutomaticKeepAlives` argument corresponds to the
/// [SliverChildBuilderDelegate.addAutomaticKeepAlives] property. The
/// `addRepaintBoundaries` argument corresponds to the
/// [SliverChildBuilderDelegate.addRepaintBoundaries] property. The
/// `addSemanticIndexes` argument corresponds to the
/// [SliverChildBuilderDelegate.addSemanticIndexes] property.
GridView.builder({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
required this.gridDelegate,
required NullableIndexedWidgetBuilder itemBuilder,
ChildIndexGetter? findChildIndexCallback,
int? itemCount,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
super.cacheExtent,
int? semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
}) : childrenDelegate = SliverChildBuilderDelegate(
itemBuilder,
findChildIndexCallback: findChildIndexCallback,
childCount: itemCount,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
),
super(
semanticChildCount: semanticChildCount ?? itemCount,
);
/// Creates a scrollable, 2D array of widgets with both a custom
/// [SliverGridDelegate] and a custom [SliverChildDelegate].
///
/// To use an [IndexedWidgetBuilder] callback to build children, either use
/// a [SliverChildBuilderDelegate] or use the [GridView.builder] constructor.
const GridView.custom({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
required this.gridDelegate,
required this.childrenDelegate,
super.cacheExtent,
super.semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
});
/// Creates a scrollable, 2D array of widgets with a fixed number of tiles in
/// the cross axis.
///
/// Uses a [SliverGridDelegateWithFixedCrossAxisCount] as the [gridDelegate].
///
/// The `addAutomaticKeepAlives` argument corresponds to the
/// [SliverChildListDelegate.addAutomaticKeepAlives] property. The
/// `addRepaintBoundaries` argument corresponds to the
/// [SliverChildListDelegate.addRepaintBoundaries] property. Both must not be
/// null.
///
/// See also:
///
/// * [SliverGrid.count], the equivalent constructor for [SliverGrid].
GridView.count({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
required int crossAxisCount,
double mainAxisSpacing = 0.0,
double crossAxisSpacing = 0.0,
double childAspectRatio = 1.0,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
super.cacheExtent,
List<Widget> children = const <Widget>[],
int? semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
}) : gridDelegate = SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
mainAxisSpacing: mainAxisSpacing,
crossAxisSpacing: crossAxisSpacing,
childAspectRatio: childAspectRatio,
),
childrenDelegate = SliverChildListDelegate(
children,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
),
super(
semanticChildCount: semanticChildCount ?? children.length,
);
/// Creates a scrollable, 2D array of widgets with tiles that each have a
/// maximum cross-axis extent.
///
/// Uses a [SliverGridDelegateWithMaxCrossAxisExtent] as the [gridDelegate].
///
/// The `addAutomaticKeepAlives` argument corresponds to the
/// [SliverChildListDelegate.addAutomaticKeepAlives] property. The
/// `addRepaintBoundaries` argument corresponds to the
/// [SliverChildListDelegate.addRepaintBoundaries] property. Both must not be
/// null.
///
/// See also:
///
/// * [SliverGrid.extent], the equivalent constructor for [SliverGrid].
GridView.extent({
super.key,
super.scrollDirection,
super.reverse,
super.controller,
super.primary,
super.physics,
super.shrinkWrap,
super.padding,
required double maxCrossAxisExtent,
double mainAxisSpacing = 0.0,
double crossAxisSpacing = 0.0,
double childAspectRatio = 1.0,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
super.cacheExtent,
List<Widget> children = const <Widget>[],
int? semanticChildCount,
super.dragStartBehavior,
super.keyboardDismissBehavior,
super.restorationId,
super.clipBehavior,
super.hitTestBehavior,
}) : gridDelegate = SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: maxCrossAxisExtent,
mainAxisSpacing: mainAxisSpacing,
crossAxisSpacing: crossAxisSpacing,
childAspectRatio: childAspectRatio,
),
childrenDelegate = SliverChildListDelegate(
children,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
),
super(
semanticChildCount: semanticChildCount ?? children.length,
);
/// A delegate that controls the layout of the children within the [GridView].
///
/// The [GridView], [GridView.builder], and [GridView.custom] constructors let you specify this
/// delegate explicitly. The other constructors create a [gridDelegate]
/// implicitly.
final SliverGridDelegate gridDelegate;
/// A delegate that provides the children for the [GridView].
///
/// The [GridView.custom] constructor lets you specify this delegate
/// explicitly. The other constructors create a [childrenDelegate] that wraps
/// the given child list.
final SliverChildDelegate childrenDelegate;
@override
Widget buildChildLayout(BuildContext context) {
return SliverGrid(
delegate: childrenDelegate,
gridDelegate: gridDelegate,
);
}
}
| flutter/packages/flutter/lib/src/widgets/scroll_view.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/scroll_view.dart",
"repo_id": "flutter",
"token_count": 26563
} | 258 |
// Copyright 2014 The Flutter Authors. 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 'framework.dart';
import 'scroll_delegate.dart';
import 'sliver.dart';
/// A sliver that places its box children in a linear array and constrains them
/// to have the same extent as a prototype item along the main axis.
///
/// _To learn more about slivers, see [CustomScrollView.slivers]._
///
/// [SliverPrototypeExtentList] arranges its children in a line along
/// the main axis starting at offset zero and without gaps. Each child is
/// constrained to the same extent as the [prototypeItem] along the main axis
/// and the [SliverConstraints.crossAxisExtent] along the cross axis.
///
/// [SliverPrototypeExtentList] is more efficient than [SliverList] because
/// [SliverPrototypeExtentList] does not need to lay out its children to obtain
/// their extent along the main axis. It's a little more flexible than
/// [SliverFixedExtentList] because there's no need to determine the appropriate
/// item extent in pixels.
///
/// See also:
///
/// * [SliverFixedExtentList], whose children are forced to a given pixel
/// extent.
/// * [SliverVariedExtentList], which supports children with varying (but known
/// upfront) extents.
/// * [SliverList], which does not require its children to have the same
/// extent in the main axis.
/// * [SliverFillViewport], which sizes its children based on the
/// size of the viewport, regardless of what else is in the scroll view.
class SliverPrototypeExtentList extends SliverMultiBoxAdaptorWidget {
/// Creates a sliver that places its box children in a linear array and
/// constrains them to have the same extent as a prototype item along
/// the main axis.
const SliverPrototypeExtentList({
super.key,
required super.delegate,
required this.prototypeItem,
});
/// A sliver that places its box children in a linear array and constrains them
/// to have the same extent as a prototype item along the main axis.
///
/// This constructor is appropriate for sliver lists with a large (or
/// infinite) number of children whose extent is already determined.
///
/// Providing a non-null `itemCount` improves the ability of the [SliverGrid]
/// to estimate the maximum scroll extent.
///
/// `itemBuilder` will be called only with indices greater than or equal to
/// zero and less than `itemCount`.
///
/// {@macro flutter.widgets.ListView.builder.itemBuilder}
///
/// The `prototypeItem` argument is used to determine the extent of each item.
///
/// {@macro flutter.widgets.PageView.findChildIndexCallback}
///
/// The `addAutomaticKeepAlives` argument corresponds to the
/// [SliverChildBuilderDelegate.addAutomaticKeepAlives] property. The
/// `addRepaintBoundaries` argument corresponds to the
/// [SliverChildBuilderDelegate.addRepaintBoundaries] property. The
/// `addSemanticIndexes` argument corresponds to the
/// [SliverChildBuilderDelegate.addSemanticIndexes] property.
///
/// {@tool snippet}
/// This example, which would be inserted into a [CustomScrollView.slivers]
/// list, shows an infinite number of items in varying shades of blue:
///
/// ```dart
/// SliverPrototypeExtentList.builder(
/// prototypeItem: Container(
/// alignment: Alignment.center,
/// child: const Text('list item prototype'),
/// ),
/// itemBuilder: (BuildContext context, int index) {
/// return Container(
/// alignment: Alignment.center,
/// color: Colors.lightBlue[100 * (index % 9)],
/// child: Text('list item $index'),
/// );
/// },
/// )
/// ```
/// {@end-tool}
SliverPrototypeExtentList.builder({
super.key,
required NullableIndexedWidgetBuilder itemBuilder,
required this.prototypeItem,
ChildIndexGetter? findChildIndexCallback,
int? itemCount,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
}) : super(delegate: SliverChildBuilderDelegate(
itemBuilder,
findChildIndexCallback: findChildIndexCallback,
childCount: itemCount,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
));
/// A sliver that places multiple box children in a linear array along the main
/// axis.
///
/// This constructor uses a list of [Widget]s to build the sliver.
///
/// The `addAutomaticKeepAlives` argument corresponds to the
/// [SliverChildBuilderDelegate.addAutomaticKeepAlives] property. The
/// `addRepaintBoundaries` argument corresponds to the
/// [SliverChildBuilderDelegate.addRepaintBoundaries] property. The
/// `addSemanticIndexes` argument corresponds to the
/// [SliverChildBuilderDelegate.addSemanticIndexes] property.
///
/// {@tool snippet}
/// This example, which would be inserted into a [CustomScrollView.slivers]
/// list, shows an infinite number of items in varying shades of blue:
///
/// ```dart
/// SliverPrototypeExtentList.list(
/// prototypeItem: const Text('Hello'),
/// children: const <Widget>[
/// Text('Hello'),
/// Text('World!'),
/// ],
/// );
/// ```
/// {@end-tool}
SliverPrototypeExtentList.list({
super.key,
required List<Widget> children,
required this.prototypeItem,
bool addAutomaticKeepAlives = true,
bool addRepaintBoundaries = true,
bool addSemanticIndexes = true,
}) : super(delegate: SliverChildListDelegate(
children,
addAutomaticKeepAlives: addAutomaticKeepAlives,
addRepaintBoundaries: addRepaintBoundaries,
addSemanticIndexes: addSemanticIndexes,
));
/// Defines the main axis extent of all of this sliver's children.
///
/// The [prototypeItem] is laid out before the rest of the sliver's children
/// and its size along the main axis fixes the size of each child. The
/// [prototypeItem] is essentially [Offstage]: it is not painted and it
/// cannot respond to input.
final Widget prototypeItem;
@override
RenderSliverMultiBoxAdaptor createRenderObject(BuildContext context) {
final _SliverPrototypeExtentListElement element = context as _SliverPrototypeExtentListElement;
return _RenderSliverPrototypeExtentList(childManager: element);
}
@override
SliverMultiBoxAdaptorElement createElement() => _SliverPrototypeExtentListElement(this);
}
class _SliverPrototypeExtentListElement extends SliverMultiBoxAdaptorElement {
_SliverPrototypeExtentListElement(SliverPrototypeExtentList super.widget);
@override
_RenderSliverPrototypeExtentList get renderObject => super.renderObject as _RenderSliverPrototypeExtentList;
Element? _prototype;
static final Object _prototypeSlot = Object();
@override
void insertRenderObjectChild(covariant RenderObject child, covariant Object slot) {
if (slot == _prototypeSlot) {
assert(child is RenderBox);
renderObject.child = child as RenderBox;
} else {
super.insertRenderObjectChild(child, slot as int);
}
}
@override
void didAdoptChild(RenderBox child) {
if (child != renderObject.child) {
super.didAdoptChild(child);
}
}
@override
void moveRenderObjectChild(RenderBox child, Object oldSlot, Object newSlot) {
if (newSlot == _prototypeSlot) {
// There's only one prototype child so it cannot be moved.
assert(false);
} else {
super.moveRenderObjectChild(child, oldSlot as int, newSlot as int);
}
}
@override
void removeRenderObjectChild(RenderBox child, Object slot) {
if (renderObject.child == child) {
renderObject.child = null;
} else {
super.removeRenderObjectChild(child, slot as int);
}
}
@override
void visitChildren(ElementVisitor visitor) {
if (_prototype != null) {
visitor(_prototype!);
}
super.visitChildren(visitor);
}
@override
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
_prototype = updateChild(_prototype, (widget as SliverPrototypeExtentList).prototypeItem, _prototypeSlot);
}
@override
void update(SliverPrototypeExtentList newWidget) {
super.update(newWidget);
assert(widget == newWidget);
_prototype = updateChild(_prototype, (widget as SliverPrototypeExtentList).prototypeItem, _prototypeSlot);
}
}
class _RenderSliverPrototypeExtentList extends RenderSliverFixedExtentBoxAdaptor {
_RenderSliverPrototypeExtentList({
required _SliverPrototypeExtentListElement childManager,
}) : super(childManager: childManager);
RenderBox? _child;
RenderBox? get child => _child;
set child(RenderBox? value) {
if (_child != null) {
dropChild(_child!);
}
_child = value;
if (_child != null) {
adoptChild(_child!);
}
markNeedsLayout();
}
@override
void performLayout() {
child!.layout(constraints.asBoxConstraints(), parentUsesSize: true);
super.performLayout();
}
@override
void attach(PipelineOwner owner) {
super.attach(owner);
if (_child != null) {
_child!.attach(owner);
}
}
@override
void detach() {
super.detach();
if (_child != null) {
_child!.detach();
}
}
@override
void redepthChildren() {
if (_child != null) {
redepthChild(_child!);
}
super.redepthChildren();
}
@override
void visitChildren(RenderObjectVisitor visitor) {
if (_child != null) {
visitor(_child!);
}
super.visitChildren(visitor);
}
@override
double get itemExtent {
assert(child != null && child!.hasSize);
return constraints.axis == Axis.vertical ? child!.size.height : child!.size.width;
}
}
| flutter/packages/flutter/lib/src/widgets/sliver_prototype_extent_list.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/sliver_prototype_extent_list.dart",
"repo_id": "flutter",
"token_count": 3168
} | 259 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'framework.dart';
export 'package:flutter/scheduler.dart' show TickerProvider;
// Examples can assume:
// late BuildContext context;
/// Enables or disables tickers (and thus animation controllers) in the widget
/// subtree.
///
/// This only works if [AnimationController] objects are created using
/// widget-aware ticker providers. For example, using a
/// [TickerProviderStateMixin] or a [SingleTickerProviderStateMixin].
class TickerMode extends StatefulWidget {
/// Creates a widget that enables or disables tickers.
const TickerMode({
super.key,
required this.enabled,
required this.child,
});
/// The requested ticker mode for this subtree.
///
/// The effective ticker mode of this subtree may differ from this value
/// if there is an ancestor [TickerMode] with this field set to false.
///
/// If true and all ancestor [TickerMode]s are also enabled, then tickers in
/// this subtree will tick.
///
/// If false, then tickers in this subtree will not tick regardless of any
/// ancestor [TickerMode]s. Animations driven by such tickers are not paused,
/// they just don't call their callbacks. Time still elapses.
final bool enabled;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// Whether tickers in the given subtree should be enabled or disabled.
///
/// This is used automatically by [TickerProviderStateMixin] and
/// [SingleTickerProviderStateMixin] to decide if their tickers should be
/// enabled or disabled.
///
/// In the absence of a [TickerMode] widget, this function defaults to true.
///
/// Typical usage is as follows:
///
/// ```dart
/// bool tickingEnabled = TickerMode.of(context);
/// ```
static bool of(BuildContext context) {
final _EffectiveTickerMode? widget = context.dependOnInheritedWidgetOfExactType<_EffectiveTickerMode>();
return widget?.enabled ?? true;
}
/// Obtains a [ValueListenable] from the [TickerMode] surrounding the `context`,
/// which indicates whether tickers are enabled in the given subtree.
///
/// When that [TickerMode] enabled or disabled tickers, the listenable notifies
/// its listeners.
///
/// While the [ValueListenable] is stable for the lifetime of the surrounding
/// [TickerMode], calling this method does not establish a dependency between
/// the `context` and the [TickerMode] and the widget owning the `context`
/// does not rebuild when the ticker mode changes from true to false or vice
/// versa. This is preferable when the ticker mode does not impact what is
/// currently rendered on screen, e.g. because it is only used to mute/unmute a
/// [Ticker]. Since no dependency is established, the widget owning the
/// `context` is also not informed when it is moved to a new location in the
/// tree where it may have a different [TickerMode] ancestor. When this
/// happens, the widget must manually unsubscribe from the old listenable,
/// obtain a new one from the new ancestor [TickerMode] by calling this method
/// again, and re-subscribe to it. [StatefulWidget]s can, for example, do this
/// in [State.activate], which is called after the widget has been moved to
/// a new location.
///
/// Alternatively, [of] can be used instead of this method to create a
/// dependency between the provided `context` and the ancestor [TickerMode].
/// In this case, the widget automatically rebuilds when the ticker mode
/// changes or when it is moved to a new [TickerMode] ancestor, which
/// simplifies the management cost in the widget at the expensive of some
/// potential unnecessary rebuilds.
///
/// In the absence of a [TickerMode] widget, this function returns a
/// [ValueListenable], whose [ValueListenable.value] is always true.
static ValueListenable<bool> getNotifier(BuildContext context) {
final _EffectiveTickerMode? widget = context.getInheritedWidgetOfExactType<_EffectiveTickerMode>();
return widget?.notifier ?? const _ConstantValueListenable<bool>(true);
}
@override
State<TickerMode> createState() => _TickerModeState();
}
class _TickerModeState extends State<TickerMode> {
bool _ancestorTicketMode = true;
final ValueNotifier<bool> _effectiveMode = ValueNotifier<bool>(true);
@override
void didChangeDependencies() {
super.didChangeDependencies();
_ancestorTicketMode = TickerMode.of(context);
_updateEffectiveMode();
}
@override
void didUpdateWidget(TickerMode oldWidget) {
super.didUpdateWidget(oldWidget);
_updateEffectiveMode();
}
@override
void dispose() {
_effectiveMode.dispose();
super.dispose();
}
void _updateEffectiveMode() {
_effectiveMode.value = _ancestorTicketMode && widget.enabled;
}
@override
Widget build(BuildContext context) {
return _EffectiveTickerMode(
enabled: _effectiveMode.value,
notifier: _effectiveMode,
child: widget.child,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('requested mode', value: widget.enabled, ifTrue: 'enabled', ifFalse: 'disabled', showName: true));
}
}
class _EffectiveTickerMode extends InheritedWidget {
const _EffectiveTickerMode({
required this.enabled,
required this.notifier,
required super.child,
});
final bool enabled;
final ValueNotifier<bool> notifier;
@override
bool updateShouldNotify(_EffectiveTickerMode oldWidget) => enabled != oldWidget.enabled;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('effective mode', value: enabled, ifTrue: 'enabled', ifFalse: 'disabled', showName: true));
}
}
/// Provides a single [Ticker] that is configured to only tick while the current
/// tree is enabled, as defined by [TickerMode].
///
/// To create the [AnimationController] in a [State] that only uses a single
/// [AnimationController], mix in this class, then pass `vsync: this`
/// to the animation controller constructor.
///
/// This mixin only supports vending a single ticker. If you might have multiple
/// [AnimationController] objects over the lifetime of the [State], use a full
/// [TickerProviderStateMixin] instead.
@optionalTypeArgs
mixin SingleTickerProviderStateMixin<T extends StatefulWidget> on State<T> implements TickerProvider {
Ticker? _ticker;
@override
Ticker createTicker(TickerCallback onTick) {
assert(() {
if (_ticker == null) {
return true;
}
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('$runtimeType is a SingleTickerProviderStateMixin but multiple tickers were created.'),
ErrorDescription('A SingleTickerProviderStateMixin can only be used as a TickerProvider once.'),
ErrorHint(
'If a State is used for multiple AnimationController objects, or if it is passed to other '
'objects and those objects might use it more than one time in total, then instead of '
'mixing in a SingleTickerProviderStateMixin, use a regular TickerProviderStateMixin.',
),
]);
}());
_ticker = Ticker(onTick, debugLabel: kDebugMode ? 'created by ${describeIdentity(this)}' : null);
_updateTickerModeNotifier();
_updateTicker(); // Sets _ticker.mute correctly.
return _ticker!;
}
@override
void dispose() {
assert(() {
if (_ticker == null || !_ticker!.isActive) {
return true;
}
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('$this was disposed with an active Ticker.'),
ErrorDescription(
'$runtimeType created a Ticker via its SingleTickerProviderStateMixin, but at the time '
'dispose() was called on the mixin, that Ticker was still active. The Ticker must '
'be disposed before calling super.dispose().',
),
ErrorHint(
'Tickers used by AnimationControllers '
'should be disposed by calling dispose() on the AnimationController itself. '
'Otherwise, the ticker will leak.',
),
_ticker!.describeForError('The offending ticker was'),
]);
}());
_tickerModeNotifier?.removeListener(_updateTicker);
_tickerModeNotifier = null;
super.dispose();
}
ValueListenable<bool>? _tickerModeNotifier;
@override
void activate() {
super.activate();
// We may have a new TickerMode ancestor.
_updateTickerModeNotifier();
_updateTicker();
}
void _updateTicker() {
if (_ticker != null) {
_ticker!.muted = !_tickerModeNotifier!.value;
}
}
void _updateTickerModeNotifier() {
final ValueListenable<bool> newNotifier = TickerMode.getNotifier(context);
if (newNotifier == _tickerModeNotifier) {
return;
}
_tickerModeNotifier?.removeListener(_updateTicker);
newNotifier.addListener(_updateTicker);
_tickerModeNotifier = newNotifier;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
final String? tickerDescription = switch ((_ticker?.isActive, _ticker?.muted)) {
(true, true) => 'active but muted',
(true, _) => 'active',
(false, true) => 'inactive and muted',
(false, _) => 'inactive',
(null, _) => null,
};
properties.add(DiagnosticsProperty<Ticker>('ticker', _ticker, description: tickerDescription, showSeparator: false, defaultValue: null));
}
}
/// Provides [Ticker] objects that are configured to only tick while the current
/// tree is enabled, as defined by [TickerMode].
///
/// To create an [AnimationController] in a class that uses this mixin, pass
/// `vsync: this` to the animation controller constructor whenever you
/// create a new animation controller.
///
/// If you only have a single [Ticker] (for example only a single
/// [AnimationController]) for the lifetime of your [State], then using a
/// [SingleTickerProviderStateMixin] is more efficient. This is the common case.
@optionalTypeArgs
mixin TickerProviderStateMixin<T extends StatefulWidget> on State<T> implements TickerProvider {
Set<Ticker>? _tickers;
@override
Ticker createTicker(TickerCallback onTick) {
if (_tickerModeNotifier == null) {
// Setup TickerMode notifier before we vend the first ticker.
_updateTickerModeNotifier();
}
assert(_tickerModeNotifier != null);
_tickers ??= <_WidgetTicker>{};
final _WidgetTicker result = _WidgetTicker(onTick, this, debugLabel: kDebugMode ? 'created by ${describeIdentity(this)}' : null)
..muted = !_tickerModeNotifier!.value;
_tickers!.add(result);
return result;
}
void _removeTicker(_WidgetTicker ticker) {
assert(_tickers != null);
assert(_tickers!.contains(ticker));
_tickers!.remove(ticker);
}
ValueListenable<bool>? _tickerModeNotifier;
@override
void activate() {
super.activate();
// We may have a new TickerMode ancestor, get its Notifier.
_updateTickerModeNotifier();
_updateTickers();
}
void _updateTickers() {
if (_tickers != null) {
final bool muted = !_tickerModeNotifier!.value;
for (final Ticker ticker in _tickers!) {
ticker.muted = muted;
}
}
}
void _updateTickerModeNotifier() {
final ValueListenable<bool> newNotifier = TickerMode.getNotifier(context);
if (newNotifier == _tickerModeNotifier) {
return;
}
_tickerModeNotifier?.removeListener(_updateTickers);
newNotifier.addListener(_updateTickers);
_tickerModeNotifier = newNotifier;
}
@override
void dispose() {
assert(() {
if (_tickers != null) {
for (final Ticker ticker in _tickers!) {
if (ticker.isActive) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('$this was disposed with an active Ticker.'),
ErrorDescription(
'$runtimeType created a Ticker via its TickerProviderStateMixin, but at the time '
'dispose() was called on the mixin, that Ticker was still active. All Tickers must '
'be disposed before calling super.dispose().',
),
ErrorHint(
'Tickers used by AnimationControllers '
'should be disposed by calling dispose() on the AnimationController itself. '
'Otherwise, the ticker will leak.',
),
ticker.describeForError('The offending ticker was'),
]);
}
}
}
return true;
}());
_tickerModeNotifier?.removeListener(_updateTickers);
_tickerModeNotifier = null;
super.dispose();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Set<Ticker>>(
'tickers',
_tickers,
description: _tickers != null ?
'tracking ${_tickers!.length} ticker${_tickers!.length == 1 ? "" : "s"}' :
null,
defaultValue: null,
));
}
}
// This class should really be called _DisposingTicker or some such, but this
// class name leaks into stack traces and error messages and that name would be
// confusing. Instead we use the less precise but more anodyne "_WidgetTicker",
// which attracts less attention.
class _WidgetTicker extends Ticker {
_WidgetTicker(super.onTick, this._creator, { super.debugLabel });
final TickerProviderStateMixin _creator;
@override
void dispose() {
_creator._removeTicker(this);
super.dispose();
}
}
class _ConstantValueListenable<T> implements ValueListenable<T> {
const _ConstantValueListenable(this.value);
@override
void addListener(VoidCallback listener) {
// Intentionally left empty: Value cannot change, so we never have to
// notify registered listeners.
}
@override
void removeListener(VoidCallback listener) {
// Intentionally left empty: Value cannot change, so we never have to
// notify registered listeners.
}
@override
final T value;
}
| flutter/packages/flutter/lib/src/widgets/ticker_provider.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/ticker_provider.dart",
"repo_id": "flutter",
"token_count": 4783
} | 260 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'framework.dart';
import 'navigator.dart';
import 'routes.dart';
/// Registers a callback to veto attempts by the user to dismiss the enclosing
/// [ModalRoute].
///
/// See also:
///
/// * [ModalRoute.addScopedWillPopCallback] and [ModalRoute.removeScopedWillPopCallback],
/// which this widget uses to register and unregister [onWillPop].
/// * [Form], which provides an `onWillPop` callback that enables the form
/// to veto a `pop` initiated by the app's back button.
@Deprecated(
'Use PopScope instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
class WillPopScope extends StatefulWidget {
/// Creates a widget that registers a callback to veto attempts by the user to
/// dismiss the enclosing [ModalRoute].
@Deprecated(
'Use PopScope instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
const WillPopScope({
super.key,
required this.child,
required this.onWillPop,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// Called to veto attempts by the user to dismiss the enclosing [ModalRoute].
///
/// If the callback returns a Future that resolves to false, the enclosing
/// route will not be popped.
final WillPopCallback? onWillPop;
@override
State<WillPopScope> createState() => _WillPopScopeState();
}
class _WillPopScopeState extends State<WillPopScope> {
ModalRoute<dynamic>? _route;
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (widget.onWillPop != null) {
_route?.removeScopedWillPopCallback(widget.onWillPop!);
}
_route = ModalRoute.of(context);
if (widget.onWillPop != null) {
_route?.addScopedWillPopCallback(widget.onWillPop!);
}
}
@override
void didUpdateWidget(WillPopScope oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.onWillPop != oldWidget.onWillPop && _route != null) {
if (oldWidget.onWillPop != null) {
_route!.removeScopedWillPopCallback(oldWidget.onWillPop!);
}
if (widget.onWillPop != null) {
_route!.addScopedWillPopCallback(widget.onWillPop!);
}
}
}
@override
void dispose() {
if (widget.onWillPop != null) {
_route?.removeScopedWillPopCallback(widget.onWillPop!);
}
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
| flutter/packages/flutter/lib/src/widgets/will_pop_scope.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/will_pop_scope.dart",
"repo_id": "flutter",
"token_count": 891
} | 261 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('AnimationLocalStatusListenersMixin with AnimationLazyListenerMixin - removing unregistered listener is no-op', () {
final _TestAnimationLocalStatusListeners uut = _TestAnimationLocalStatusListeners();
void fakeListener(AnimationStatus status) { }
uut.removeStatusListener(fakeListener);
expect(uut.callsToStart, 0);
expect(uut.callsToStop, 0);
});
test('AnimationLocalListenersMixin with AnimationLazyListenerMixin - removing unregistered listener is no-op', () {
final _TestAnimationLocalListeners uut = _TestAnimationLocalListeners();
void fakeListener() { }
uut.removeListener(fakeListener);
expect(uut.callsToStart, 0);
expect(uut.callsToStop, 0);
});
}
class _TestAnimationLocalStatusListeners with AnimationLocalStatusListenersMixin, AnimationLazyListenerMixin {
int callsToStart = 0;
int callsToStop = 0;
@override
void didStartListening() {
callsToStart += 1;
}
@override
void didStopListening() {
callsToStop += 1;
}
}
class _TestAnimationLocalListeners with AnimationLocalListenersMixin, AnimationLazyListenerMixin {
int callsToStart = 0;
int callsToStop = 0;
@override
void didStartListening() {
callsToStart += 1;
}
@override
void didStopListening() {
callsToStop += 1;
}
}
| flutter/packages/flutter/test/animation/listener_helpers_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/animation/listener_helpers_test.dart",
"repo_id": "flutter",
"token_count": 504
} | 262 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
testWidgets('can press', (WidgetTester tester) async {
bool pressed = false;
await tester.pumpWidget(
CupertinoApp(
home: Center(
child: CupertinoDesktopTextSelectionToolbarButton(
onPressed: () {
pressed = true;
},
child: const Text('Tap me'),
),
),
),
);
expect(pressed, false);
await tester.tap(find.byType(CupertinoDesktopTextSelectionToolbarButton));
expect(pressed, true);
});
testWidgets('keeps contrast with background on hover',
(WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: Center(
child: CupertinoDesktopTextSelectionToolbarButton.text(
text: 'Tap me',
onPressed: () {},
),
),
),
);
final BuildContext context =
tester.element(find.byType(CupertinoDesktopTextSelectionToolbarButton));
// The Text color is a CupertinoDynamicColor so we have to compare the color
// values instead of just comparing the colors themselves.
expect(
(tester.firstWidget(find.text('Tap me')) as Text).style!.color!.value,
CupertinoColors.black.value,
);
// Hover gesture
final TestGesture gesture =
await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
addTearDown(gesture.removePointer);
await tester.pump();
await gesture.moveTo(tester
.getCenter(find.byType(CupertinoDesktopTextSelectionToolbarButton)));
await tester.pumpAndSettle();
// The color here should be a standard Color, there's no need to use value.
expect(
(tester.firstWidget(find.text('Tap me')) as Text).style!.color,
CupertinoTheme.of(context).primaryContrastingColor,
);
});
testWidgets('pressedOpacity defaults to 0.1', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: Center(
child: CupertinoDesktopTextSelectionToolbarButton(
onPressed: () { },
child: const Text('Tap me'),
),
),
),
);
// Original at full opacity.
FadeTransition opacity = tester.widget(find.descendant(
of: find.byType(CupertinoDesktopTextSelectionToolbarButton),
matching: find.byType(FadeTransition),
));
expect(opacity.opacity.value, 1.0);
// Make a "down" gesture on the button.
final Offset center = tester
.getCenter(find.byType(CupertinoDesktopTextSelectionToolbarButton));
final TestGesture gesture = await tester.startGesture(center);
await tester.pumpAndSettle();
// Opacity reduces during the down gesture.
opacity = tester.widget(find.descendant(
of: find.byType(CupertinoDesktopTextSelectionToolbarButton),
matching: find.byType(FadeTransition),
));
expect(opacity.opacity.value, 0.7);
// Release the down gesture.
await gesture.up();
await tester.pumpAndSettle();
// Opacity is back to normal.
opacity = tester.widget(find.descendant(
of: find.byType(CupertinoDesktopTextSelectionToolbarButton),
matching: find.byType(FadeTransition),
));
expect(opacity.opacity.value, 1.0);
});
testWidgets('passing null to onPressed disables the button', (WidgetTester tester) async {
await tester.pumpWidget(
const CupertinoApp(
home: Center(
child: CupertinoDesktopTextSelectionToolbarButton(
onPressed: null,
child: Text('Tap me'),
),
),
),
);
expect(find.byType(CupertinoButton), findsOneWidget);
final CupertinoButton button = tester.widget(find.byType(CupertinoButton));
expect(button.enabled, isFalse);
});
}
| flutter/packages/flutter/test/cupertino/desktop_text_selection_toolbar_button_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/desktop_text_selection_toolbar_button_test.dart",
"repo_id": "flutter",
"token_count": 1647
} | 263 |
// Copyright 2014 The Flutter Authors. 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/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() {
testWidgets('Radio control test', (WidgetTester tester) async {
final Key key = UniqueKey();
final List<int?> log = <int?>[];
await tester.pumpWidget(CupertinoApp(
home: Center(
child: CupertinoRadio<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(CupertinoApp(
home: Center(
child: CupertinoRadio<int>(
key: key,
value: 1,
groupValue: 1,
onChanged: log.add,
activeColor: CupertinoColors.systemGreen,
),
),
));
await tester.tap(find.byKey(key));
expect(log, isEmpty);
await tester.pumpWidget(CupertinoApp(
home: Center(
child: CupertinoRadio<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(CupertinoApp(
home: Center(
child: CupertinoRadio<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(CupertinoApp(
home: Center(
child: CupertinoRadio<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(CupertinoApp(
home: Center(
child: CupertinoRadio<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 selected semantics - platform adaptive', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(CupertinoApp(
home: Center(
child: CupertinoRadio<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(CupertinoApp(
home: Center(
child: CupertinoRadio<int>(
value: 1,
groupValue: 2,
onChanged: (int? i) { },
),
),
));
expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isEnabled: true,
hasTapAction: true,
isFocusable: true,
isInMutuallyExclusiveGroup: true,
));
await tester.pumpWidget(CupertinoApp(
home: Center(
child: CupertinoRadio<int>(
value: 2,
groupValue: 2,
onChanged: (int? i) { },
),
),
));
expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isEnabled: true,
hasTapAction: true,
isFocusable: true,
isInMutuallyExclusiveGroup: true,
isChecked: true,
));
await tester.pumpWidget(const CupertinoApp(
home: Center(
child: CupertinoRadio<int>(
value: 1,
groupValue: 2,
onChanged: null,
),
),
));
expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isFocusable: true,
isInMutuallyExclusiveGroup: true,
));
await tester.pump();
// Now the isFocusable should be gone.
expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isInMutuallyExclusiveGroup: true,
));
await tester.pumpWidget(const CupertinoApp(
home: Center(
child: CupertinoRadio<int>(
value: 2,
groupValue: 2,
onChanged: null,
),
),
));
expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics(
hasCheckedState: true,
hasEnabledState: true,
isChecked: true,
isInMutuallyExclusiveGroup: 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(CupertinoApp(
home: Center(
child: CupertinoRadio<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('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');
addTearDown(focusNode2.dispose);
Widget buildApp({bool enabled = true}) {
return CupertinoApp(
home: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return SizedBox(
width: 200,
height: 100,
child: Row(
children: <Widget>[
CupertinoRadio<int>(
key: radioKey0,
value: 0,
onChanged: enabled ? (int? newValue) {
setState(() {
groupValue = newValue;
});
} : null,
groupValue: groupValue,
autofocus: true,
),
CupertinoRadio<int>(
key: radioKey1,
value: 1,
onChanged: enabled ? (int? newValue) {
setState(() {
groupValue = newValue;
});
} : null,
groupValue: groupValue,
),
CupertinoRadio<int>(
key: radioKey2,
value: 2,
onChanged: enabled ? (int? newValue) {
setState(() {
groupValue = newValue;
});
} : null,
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));
});
testWidgets('Show a checkmark when useCheckmarkStyle is true', (WidgetTester tester) async {
await tester.pumpWidget(CupertinoApp(
home: Center(
child: CupertinoRadio<int>(
value: 1,
groupValue: 1,
onChanged: (int? i) { },
),
),
));
await tester.pumpAndSettle();
// Has no checkmark when useCheckmarkStyle is false
expect(
tester.firstRenderObject<RenderBox>(find.byType(CupertinoRadio<int>)),
isNot(paints..path())
);
await tester.pumpWidget(CupertinoApp(
home: Center(
child: CupertinoRadio<int>(
value: 1,
groupValue: 2,
useCheckmarkStyle: true,
onChanged: (int? i) { },
),
),
));
await tester.pumpAndSettle();
// Has no checkmark when group value doesn't match the value
expect(
tester.firstRenderObject<RenderBox>(find.byType(CupertinoRadio<int>)),
isNot(paints..path())
);
await tester.pumpWidget(CupertinoApp(
home: Center(
child: CupertinoRadio<int>(
value: 1,
groupValue: 1,
useCheckmarkStyle: true,
onChanged: (int? i) { },
),
),
));
await tester.pumpAndSettle();
// Draws a path to show the checkmark when toggled on
expect(
tester.firstRenderObject<RenderBox>(find.byType(CupertinoRadio<int>)),
paints..path()
);
});
testWidgets('Do not crash when widget disappears while pointer is down', (WidgetTester tester) async {
final Key key = UniqueKey();
Widget buildRadio(bool show) {
return CupertinoApp(
home: Center(
child: show ? CupertinoRadio<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();
});
}
| flutter/packages/flutter/test/cupertino/radio_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/radio_test.dart",
"repo_id": "flutter",
"token_count": 5522
} | 264 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
const String text = 'Hello World! How are you? Life is good!';
const String alternativeText = 'Everything is awesome!!';
void main() {
testWidgets('CupertinoTextFormFieldRow restoration', (WidgetTester tester) async {
await tester.pumpWidget(
const CupertinoApp(
restorationScopeId: 'app',
home: RestorableTestWidget(),
),
);
await restoreAndVerify(tester);
});
testWidgets('CupertinoTextFormFieldRow restoration with external controller', (WidgetTester tester) async {
await tester.pumpWidget(
const CupertinoApp(
restorationScopeId: 'root',
home: RestorableTestWidget(
useExternalController: true,
),
),
);
await restoreAndVerify(tester);
});
testWidgets('State restoration (No Form ancestor) - onUserInteraction error text validation', (WidgetTester tester) async {
String? errorText(String? value) => '$value/error';
late GlobalKey<FormFieldState<String>> formState;
Widget builder() {
return CupertinoApp(
restorationScopeId: 'app',
home: MediaQuery(
data: const MediaQueryData(),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter state) {
formState = GlobalKey<FormFieldState<String>>();
return Material(
child: CupertinoTextFormFieldRow(
key: formState,
autovalidateMode: AutovalidateMode.onUserInteraction,
restorationId: 'text_form_field',
initialValue: 'foo',
validator: errorText,
),
);
},
),
),
),
),
);
}
await tester.pumpWidget(builder());
// No error text is visible yet.
expect(find.text(errorText('foo')!), findsNothing);
await tester.enterText(find.byType(CupertinoTextFormFieldRow), 'bar');
await tester.pumpAndSettle();
expect(find.text(errorText('bar')!), findsOneWidget);
final TestRestorationData data = await tester.getRestorationData();
await tester.restartAndRestore();
// Error text should be present after restart and restore.
expect(find.text(errorText('bar')!), findsOneWidget);
// Resetting the form state should remove the error text.
formState.currentState!.reset();
await tester.pumpAndSettle();
expect(find.text(errorText('bar')!), findsNothing);
await tester.restartAndRestore();
// Error text should still be removed after restart and restore.
expect(find.text(errorText('bar')!), findsNothing);
await tester.restoreFrom(data);
expect(find.text(errorText('bar')!), findsOneWidget);
});
testWidgets('State Restoration (No Form ancestor) - validator sets the error text only when validate is called', (WidgetTester tester) async {
String? errorText(String? value) => '$value/error';
late GlobalKey<FormFieldState<String>> formState;
Widget builder(AutovalidateMode mode) {
return CupertinoApp(
restorationScopeId: 'app',
home: MediaQuery(
data: const MediaQueryData(),
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter state) {
formState = GlobalKey<FormFieldState<String>>();
return Material(
child: CupertinoTextFormFieldRow(
key: formState,
restorationId: 'form_field',
autovalidateMode: mode,
initialValue: 'foo',
validator: errorText,
),
);
},
),
),
),
),
);
}
// Start off not autovalidating.
await tester.pumpWidget(builder(AutovalidateMode.disabled));
Future<void> checkErrorText(String testValue) async {
formState.currentState!.reset();
await tester.pumpWidget(builder(AutovalidateMode.disabled));
await tester.enterText(find.byType(CupertinoTextFormFieldRow), testValue);
await tester.pump();
// We have to manually validate if we're not autovalidating.
expect(find.text(errorText(testValue)!), findsNothing);
formState.currentState!.validate();
await tester.pump();
expect(find.text(errorText(testValue)!), findsOneWidget);
final TestRestorationData data = await tester.getRestorationData();
await tester.restartAndRestore();
// Error text should be present after restart and restore.
expect(find.text(errorText(testValue)!), findsOneWidget);
formState.currentState!.reset();
await tester.pumpAndSettle();
expect(find.text(errorText(testValue)!), findsNothing);
await tester.restoreFrom(data);
expect(find.text(errorText(testValue)!), findsOneWidget);
// Try again with autovalidation. Should validate immediately.
formState.currentState!.reset();
await tester.pumpWidget(builder(AutovalidateMode.always));
await tester.enterText(find.byType(CupertinoTextFormFieldRow), testValue);
await tester.pump();
expect(find.text(errorText(testValue)!), findsOneWidget);
await tester.restartAndRestore();
// Error text should be present after restart and restore.
expect(find.text(errorText(testValue)!), findsOneWidget);
}
await checkErrorText('Test');
await checkErrorText('');
});
}
Future<void> restoreAndVerify(WidgetTester tester) async {
expect(find.text(text), findsNothing);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 0);
await tester.enterText(find.byType(CupertinoTextFormFieldRow), text);
await skipPastScrollingAnimation(tester);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 0);
await tester.drag(find.byType(Scrollable), const Offset(0, -80));
await skipPastScrollingAnimation(tester);
expect(find.text(text), findsOneWidget);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 60);
await tester.restartAndRestore();
expect(find.text(text), findsOneWidget);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 60);
final TestRestorationData data = await tester.getRestorationData();
await tester.enterText(find.byType(CupertinoTextFormFieldRow), alternativeText);
await skipPastScrollingAnimation(tester);
await tester.drag(find.byType(Scrollable), const Offset(0, 80));
await skipPastScrollingAnimation(tester);
expect(find.text(text), findsNothing);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, isNot(60));
await tester.restoreFrom(data);
expect(find.text(text), findsOneWidget);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 60);
}
class RestorableTestWidget extends StatefulWidget {
const RestorableTestWidget({super.key, this.useExternalController = false});
final bool useExternalController;
@override
RestorableTestWidgetState createState() => RestorableTestWidgetState();
}
class RestorableTestWidgetState extends State<RestorableTestWidget> with RestorationMixin {
final RestorableTextEditingController controller = RestorableTextEditingController();
@override
String get restorationId => 'widget';
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(controller, 'controller');
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Material(
child: Align(
child: SizedBox(
width: 50,
child: CupertinoTextFormFieldRow(
restorationId: 'text',
maxLines: 3,
controller: widget.useExternalController ? controller.value : null,
),
),
),
);
}
}
Future<void> skipPastScrollingAnimation(WidgetTester tester) async {
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
}
| flutter/packages/flutter/test/cupertino/text_form_field_row_restoration_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/text_form_field_row_restoration_test.dart",
"repo_id": "flutter",
"token_count": 3342
} | 265 |
// Copyright 2014 The Flutter Authors. 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/basic_types.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('lerp Duration', () {
test('linearly interpolates between positive Durations', () {
expect(
lerpDuration(const Duration(seconds: 1), const Duration(seconds: 2), 0.5),
const Duration(milliseconds: 1500),
);
});
test('linearly interpolates between negative Durations', () {
expect(
lerpDuration(const Duration(seconds: -1), const Duration(seconds: -2), 0.5),
const Duration(milliseconds: -1500),
);
});
test('linearly interpolates between positive and negative Durations', () {
expect(
lerpDuration(const Duration(seconds: -1), const Duration(seconds:2), 0.5),
const Duration(milliseconds: 500),
);
});
test('starts at first Duration', () {
expect(
lerpDuration(const Duration(seconds: 1), const Duration(seconds: 2), 0),
const Duration(seconds: 1),
);
});
test('ends at second Duration', () {
expect(
lerpDuration(const Duration(seconds: 1), const Duration(seconds: 2), 1),
const Duration(seconds: 2),
);
});
test('time values beyond 1.0 have a multiplier effect', () {
expect(
lerpDuration(const Duration(seconds: 1), const Duration(seconds: 2), 5),
const Duration(seconds: 6),
);
expect(
lerpDuration(const Duration(seconds: -1), const Duration(seconds: -2), 5),
const Duration(seconds: -6),
);
});
});
}
| flutter/packages/flutter/test/foundation/basic_types_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/basic_types_test.dart",
"repo_id": "flutter",
"token_count": 661
} | 266 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'dart:isolate';
import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:platform/platform.dart';
final Matcher throwsRemoteError = throwsA(isA<RemoteError>());
int test1(int value) {
return value + 1;
}
int test2(int value) {
throw 2;
}
int test3(int value) {
Isolate.exit();
}
int test4(int value) {
Isolate.current.kill();
return value + 1;
}
int test5(int value) {
Isolate.current.kill(priority: Isolate.immediate);
return value + 1;
}
Future<int> test1Async(int value) async {
return value + 1;
}
Future<int> test2Async(int value) async {
throw 2;
}
Future<int> test3Async(int value) async {
Isolate.exit();
}
Future<int> test4Async(int value) async {
Isolate.current.kill();
return value + 1;
}
Future<int> test5Async(int value) async {
Isolate.current.kill(priority: Isolate.immediate);
return value + 1;
}
Future<int> test1CallCompute(int value) {
return compute(test1, value);
}
Future<int> test2CallCompute(int value) {
return compute(test2, value);
}
Future<int> test3CallCompute(int value) {
return compute(test3, value);
}
Future<int> test4CallCompute(int value) {
return compute(test4, value);
}
Future<int> test5CallCompute(int value) {
return compute(test5, value);
}
Future<void> expectFileSuccessfullyCompletes(String filename) async {
// Run a Dart script that calls compute().
// The Dart process will terminate only if the script exits cleanly with
// all isolate ports closed.
const FileSystem fs = LocalFileSystem();
const Platform platform = LocalPlatform();
final String flutterRoot = platform.environment['FLUTTER_ROOT']!;
final String dartPath =
fs.path.join(flutterRoot, 'bin', 'cache', 'dart-sdk', 'bin', 'dart');
final String scriptPath =
fs.path.join(flutterRoot, 'packages', 'flutter', 'test', 'foundation', filename);
// Enable asserts to also catch potentially invalid assertions.
final ProcessResult result = await Process.run(
dartPath, <String>['run', '--enable-asserts', scriptPath]);
expect(result.exitCode, 0);
}
class ComputeTestSubject {
ComputeTestSubject(this.base, [this.additional]);
final int base;
final dynamic additional;
int method(int x) {
return base * x;
}
static int staticMethod(int square) {
return square * square;
}
}
Future<int> computeStaticMethod(int square) {
return compute(ComputeTestSubject.staticMethod, square);
}
Future<int> computeClosure(int square) {
return compute((_) => square * square, null);
}
Future<int> computeInvalidClosure(int square) {
final ReceivePort r = ReceivePort();
return compute((_) {
r.sendPort.send('Computing!');
return square * square;
}, null);
}
Future<int> computeInstanceMethod(int square) {
final ComputeTestSubject subject = ComputeTestSubject(square);
return compute(subject.method, square);
}
Future<int> computeInvalidInstanceMethod(int square) {
final ComputeTestSubject subject = ComputeTestSubject(square, ReceivePort());
expect(subject.additional, isA<ReceivePort>());
return compute(subject.method, square);
}
dynamic testInvalidResponse(int square) {
final ReceivePort r = ReceivePort();
try {
return r;
} finally {
r.close();
}
}
dynamic testInvalidError(int square) {
final ReceivePort r = ReceivePort();
try {
throw r;
} finally {
r.close();
}
}
String? testDebugName(_) {
return Isolate.current.debugName;
}
int? testReturnNull(_) {
return null;
}
void main() {
test('compute()', () async {
expect(await compute(test1, 0), 1);
expect(compute(test2, 0), throwsA(2));
expect(compute(test3, 0), throwsRemoteError);
expect(await compute(test4, 0), 1);
expect(compute(test5, 0), throwsRemoteError);
expect(await compute(test1Async, 0), 1);
expect(compute(test2Async, 0), throwsA(2));
expect(compute(test3Async, 0), throwsRemoteError);
expect(await compute(test4Async, 0), 1);
expect(compute(test5Async, 0), throwsRemoteError);
expect(await compute(test1CallCompute, 0), 1);
expect(compute(test2CallCompute, 0), throwsA(2));
expect(compute(test3CallCompute, 0), throwsRemoteError);
expect(await compute(test4CallCompute, 0), 1);
expect(compute(test5CallCompute, 0), throwsRemoteError);
expect(compute(testInvalidResponse, 0), throwsRemoteError);
expect(compute(testInvalidError, 0), throwsRemoteError);
expect(await computeStaticMethod(10), 100);
expect(await computeClosure(10), 100);
expect(computeInvalidClosure(10), throwsArgumentError);
expect(await computeInstanceMethod(10), 100);
expect(computeInvalidInstanceMethod(10), throwsArgumentError);
expect(await compute(testDebugName, null, debugLabel: 'debug_name'),
'debug_name');
expect(await compute(testReturnNull, null), null);
}, skip: kIsWeb); // [intended] isn't supported on the web.
group('compute() closes all ports', () {
test('with valid message', () async {
await expectFileSuccessfullyCompletes('_compute_caller.dart');
});
test('with invalid message', () async {
await expectFileSuccessfullyCompletes(
'_compute_caller_invalid_message.dart');
});
test('with valid error', () async {
await expectFileSuccessfullyCompletes('_compute_caller.dart');
});
test('with invalid error', () async {
await expectFileSuccessfullyCompletes(
'_compute_caller_invalid_message.dart');
});
}, skip: kIsWeb); // [intended] isn't supported on the web.
}
| flutter/packages/flutter/test/foundation/isolates_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/isolates_test.dart",
"repo_id": "flutter",
"token_count": 1990
} | 267 |
// Copyright 2014 The Flutter Authors. 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_test/flutter_test.dart';
void main() {
testWidgets('debugPrintGestureArenaDiagnostics', (WidgetTester tester) async {
PointerEvent event;
debugPrintGestureArenaDiagnostics = true;
final DebugPrintCallback oldCallback = debugPrint;
final List<String> log = <String>[];
debugPrint = (String? s, { int? wrapWidth }) { log.add(s ?? ''); };
final TapGestureRecognizer tap = TapGestureRecognizer()
..onTapDown = (TapDownDetails details) { }
..onTapUp = (TapUpDetails details) { }
..onTap = () { }
..onTapCancel = () { };
expect(log, isEmpty);
event = const PointerDownEvent(pointer: 1, position: Offset(10.0, 10.0));
tap.addPointer(event as PointerDownEvent);
expect(log, hasLength(2));
expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 β β
Opening new gesture arena.'));
expect(log[1], equalsIgnoringHashCodes('Gesture arena 1 β Adding: TapGestureRecognizer#00000(state: ready, button: 1)'));
log.clear();
GestureBinding.instance.gestureArena.close(1);
expect(log, hasLength(1));
expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 β Closing with 1 member.'));
log.clear();
GestureBinding.instance.pointerRouter.route(event);
expect(log, isEmpty);
event = const PointerUpEvent(pointer: 1, position: Offset(12.0, 8.0));
GestureBinding.instance.pointerRouter.route(event);
expect(log, isEmpty);
GestureBinding.instance.gestureArena.sweep(1);
expect(log, hasLength(2));
expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 β Sweeping with 1 member.'));
expect(log[1], equalsIgnoringHashCodes('Gesture arena 1 β Winner: TapGestureRecognizer#00000(state: ready, finalPosition: Offset(12.0, 8.0), button: 1)'));
log.clear();
tap.dispose();
expect(log, isEmpty);
debugPrintGestureArenaDiagnostics = false;
debugPrint = oldCallback;
});
testWidgets('debugPrintRecognizerCallbacksTrace', (WidgetTester tester) async {
PointerEvent event;
debugPrintRecognizerCallbacksTrace = true;
final DebugPrintCallback oldCallback = debugPrint;
final List<String> log = <String>[];
debugPrint = (String? s, { int? wrapWidth }) { log.add(s ?? ''); };
final TapGestureRecognizer tap = TapGestureRecognizer()
..onTapDown = (TapDownDetails details) { }
..onTapUp = (TapUpDetails details) { }
..onTap = () { }
..onTapCancel = () { };
expect(log, isEmpty);
event = const PointerDownEvent(pointer: 1, position: Offset(10.0, 10.0));
tap.addPointer(event as PointerDownEvent);
expect(log, isEmpty);
GestureBinding.instance.gestureArena.close(1);
expect(log, isEmpty);
GestureBinding.instance.pointerRouter.route(event);
expect(log, isEmpty);
event = const PointerUpEvent(pointer: 1, position: Offset(12.0, 8.0));
GestureBinding.instance.pointerRouter.route(event);
expect(log, isEmpty);
GestureBinding.instance.gestureArena.sweep(1);
expect(log, hasLength(3));
expect(log[0], equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: ready, finalPosition: Offset(12.0, 8.0), button: 1) calling onTapDown callback.'));
expect(log[1], equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: ready, won arena, finalPosition: Offset(12.0, 8.0), button: 1, sent tap down) calling onTapUp callback.'));
expect(log[2], equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: ready, won arena, finalPosition: Offset(12.0, 8.0), button: 1, sent tap down) calling onTap callback.'));
log.clear();
tap.dispose();
expect(log, isEmpty);
debugPrintRecognizerCallbacksTrace = false;
debugPrint = oldCallback;
});
testWidgets('debugPrintGestureArenaDiagnostics and debugPrintRecognizerCallbacksTrace', (WidgetTester tester) async {
PointerEvent event;
debugPrintGestureArenaDiagnostics = true;
debugPrintRecognizerCallbacksTrace = true;
final DebugPrintCallback oldCallback = debugPrint;
final List<String> log = <String>[];
debugPrint = (String? s, { int? wrapWidth }) { log.add(s ?? ''); };
final TapGestureRecognizer tap = TapGestureRecognizer()
..onTapDown = (TapDownDetails details) { }
..onTapUp = (TapUpDetails details) { }
..onTap = () { }
..onTapCancel = () { };
expect(log, isEmpty);
event = const PointerDownEvent(pointer: 1, position: Offset(10.0, 10.0));
tap.addPointer(event as PointerDownEvent);
expect(log, hasLength(2));
expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 β β
Opening new gesture arena.'));
expect(log[1], equalsIgnoringHashCodes('Gesture arena 1 β Adding: TapGestureRecognizer#00000(state: ready, button: 1)'));
log.clear();
GestureBinding.instance.gestureArena.close(1);
expect(log, hasLength(1));
expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 β Closing with 1 member.'));
log.clear();
GestureBinding.instance.pointerRouter.route(event);
expect(log, isEmpty);
event = const PointerUpEvent(pointer: 1, position: Offset(12.0, 8.0));
GestureBinding.instance.pointerRouter.route(event);
expect(log, isEmpty);
GestureBinding.instance.gestureArena.sweep(1);
expect(log, hasLength(5));
expect(log[0], equalsIgnoringHashCodes('Gesture arena 1 β Sweeping with 1 member.'));
expect(log[1], equalsIgnoringHashCodes('Gesture arena 1 β Winner: TapGestureRecognizer#00000(state: ready, finalPosition: Offset(12.0, 8.0), button: 1)'));
expect(log[2], equalsIgnoringHashCodes(' β TapGestureRecognizer#00000(state: ready, finalPosition: Offset(12.0, 8.0), button: 1) calling onTapDown callback.'));
expect(log[3], equalsIgnoringHashCodes(' β TapGestureRecognizer#00000(state: ready, won arena, finalPosition: Offset(12.0, 8.0), button: 1, sent tap down) calling onTapUp callback.'));
expect(log[4], equalsIgnoringHashCodes(' β TapGestureRecognizer#00000(state: ready, won arena, finalPosition: Offset(12.0, 8.0), button: 1, sent tap down) calling onTap callback.'));
log.clear();
tap.dispose();
expect(log, isEmpty);
debugPrintGestureArenaDiagnostics = false;
debugPrintRecognizerCallbacksTrace = false;
debugPrint = oldCallback;
});
test('TapGestureRecognizer _sentTapDown toString', () {
final TapGestureRecognizer tap = TapGestureRecognizer()
..onTap = () {}; // Add a callback so that event can be added
expect(tap.toString(), equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: ready)'));
const PointerDownEvent event = PointerDownEvent(pointer: 1, position: Offset(10.0, 10.0));
tap.addPointer(event);
tap.didExceedDeadline();
expect(tap.toString(), equalsIgnoringHashCodes('TapGestureRecognizer#00000(state: possible, button: 1, sent tap down)'));
GestureBinding.instance.gestureArena.close(1);
tap.dispose();
});
}
| flutter/packages/flutter/test/gestures/debug_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/debug_test.dart",
"repo_id": "flutter",
"token_count": 2686
} | 268 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter_test/flutter_test.dart';
import 'gesture_tester.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
testGesture('Should recognize pan', (GestureTester tester) {
final MultiTapGestureRecognizer tap = MultiTapGestureRecognizer(longTapDelay: kLongPressTimeout);
final List<String> log = <String>[];
tap.onTapDown = (int pointer, TapDownDetails details) { log.add('tap-down $pointer'); };
tap.onTapUp = (int pointer, TapUpDetails details) { log.add('tap-up $pointer'); };
tap.onTap = (int pointer) { log.add('tap $pointer'); };
tap.onLongTapDown = (int pointer, TapDownDetails details) { log.add('long-tap-down $pointer'); };
tap.onTapCancel = (int pointer) { log.add('tap-cancel $pointer'); };
final TestPointer pointer5 = TestPointer(5);
final PointerDownEvent down5 = pointer5.down(const Offset(10.0, 10.0));
tap.addPointer(down5);
tester.closeArena(5);
expect(log, <String>['tap-down 5']);
log.clear();
tester.route(down5);
expect(log, isEmpty);
final TestPointer pointer6 = TestPointer(6);
final PointerDownEvent down6 = pointer6.down(const Offset(15.0, 15.0));
tap.addPointer(down6);
tester.closeArena(6);
expect(log, <String>['tap-down 6']);
log.clear();
tester.route(down6);
expect(log, isEmpty);
tester.route(pointer5.move(const Offset(11.0, 12.0)));
expect(log, isEmpty);
tester.route(pointer6.move(const Offset(14.0, 13.0)));
expect(log, isEmpty);
tester.route(pointer5.up());
expect(log, <String>[
'tap-up 5',
'tap 5',
]);
log.clear();
tester.async.elapse(kLongPressTimeout + kPressTimeout);
expect(log, <String>['long-tap-down 6']);
log.clear();
tester.route(pointer6.move(const Offset(40.0, 30.0))); // move more than kTouchSlop from 15.0,15.0
expect(log, <String>['tap-cancel 6']);
log.clear();
tester.route(pointer6.up());
expect(log, isEmpty);
tap.dispose();
});
testGesture('Can filter based on device kind', (GestureTester tester) {
final MultiTapGestureRecognizer tap = MultiTapGestureRecognizer(
longTapDelay: kLongPressTimeout,
supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.touch },
);
final List<String> log = <String>[];
tap.onTapDown = (int pointer, TapDownDetails details) { log.add('tap-down $pointer'); };
tap.onTapUp = (int pointer, TapUpDetails details) { log.add('tap-up $pointer'); };
tap.onTap = (int pointer) { log.add('tap $pointer'); };
tap.onLongTapDown = (int pointer, TapDownDetails details) { log.add('long-tap-down $pointer'); };
tap.onTapCancel = (int pointer) { log.add('tap-cancel $pointer'); };
final TestPointer touchPointer5 = TestPointer(5);
final PointerDownEvent down5 = touchPointer5.down(const Offset(10.0, 10.0));
tap.addPointer(down5);
tester.closeArena(5);
expect(log, <String>['tap-down 5']);
log.clear();
tester.route(down5);
expect(log, isEmpty);
final TestPointer mousePointer6 = TestPointer(6, PointerDeviceKind.mouse);
final PointerDownEvent down6 = mousePointer6.down(const Offset(20.0, 20.0));
tap.addPointer(down6);
tester.closeArena(6);
// Mouse down should be ignored by the recognizer.
expect(log, isEmpty);
final TestPointer touchPointer7 = TestPointer(7);
final PointerDownEvent down7 = touchPointer7.down(const Offset(15.0, 15.0));
tap.addPointer(down7);
tester.closeArena(7);
expect(log, <String>['tap-down 7']);
log.clear();
tester.route(down7);
expect(log, isEmpty);
tester.route(touchPointer5.move(const Offset(11.0, 12.0)));
expect(log, isEmpty);
// Move within the [kTouchSlop] range.
tester.route(mousePointer6.move(const Offset(21.0, 18.0)));
// Move beyond the slop range.
tester.route(mousePointer6.move(const Offset(50.0, 40.0)));
// Neither triggers any event because they originate from a mouse.
expect(log, isEmpty);
tester.route(touchPointer7.move(const Offset(14.0, 13.0)));
expect(log, isEmpty);
tester.route(touchPointer5.up());
expect(log, <String>[
'tap-up 5',
'tap 5',
]);
log.clear();
// Mouse up should be ignored.
tester.route(mousePointer6.up());
expect(log, isEmpty);
tester.async.elapse(kLongPressTimeout + kPressTimeout);
// Only the touch pointer (7) triggers a long-tap, not the mouse pointer (6).
expect(log, <String>['long-tap-down 7']);
log.clear();
tester.route(touchPointer7.move(const Offset(40.0, 30.0))); // move more than kTouchSlop from 15.0,15.0
expect(log, <String>['tap-cancel 7']);
log.clear();
tap.dispose();
});
}
| flutter/packages/flutter/test/gestures/multitap_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/multitap_test.dart",
"repo_id": "flutter",
"token_count": 1932
} | 269 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter_test/flutter_test.dart';
import 'velocity_tracker_data.dart';
bool _withinTolerance(double actual, double expected) {
const double kTolerance = 0.001; // Within .1% of expected value
final double diff = (actual - expected)/expected;
return diff.abs() < kTolerance;
}
bool _checkVelocity(Velocity actual, Offset expected) {
return _withinTolerance(actual.pixelsPerSecond.dx, expected.dx)
&& _withinTolerance(actual.pixelsPerSecond.dy, expected.dy);
}
void main() {
const List<Offset> expected = <Offset>[
Offset(219.59280094228163, 1304.701682306001),
Offset(355.71046950050845, 967.2112857054104),
Offset(12.657970884022308, -36.90447839251946),
Offset(714.1399654786744, -2561.534447931869),
Offset(-19.668121066218564, -2910.105747052462),
Offset(646.8690114934209, 2976.977762577527),
Offset(396.6988447819592, 2106.225572911095),
Offset(298.31594440044495, -3660.8315955215294),
Offset(-1.7334232785165882, -3288.13174127454),
Offset(384.6361280392334, -2645.6612524779835),
Offset(176.37900397918557, 2711.2542876273264),
Offset(396.9328560260098, 4280.651578291764),
Offset(-71.51939428321249, 3716.7385187526947),
];
testWidgets('Velocity tracker gives expected results', (WidgetTester tester) async {
final VelocityTracker tracker = VelocityTracker.withKind(PointerDeviceKind.touch);
int i = 0;
for (final PointerEvent event in velocityEventData) {
if (event is PointerDownEvent || event is PointerMoveEvent) {
tracker.addPosition(event.timeStamp, event.position);
}
if (event is PointerUpEvent) {
expect(_checkVelocity(tracker.getVelocity(), expected[i]), isTrue);
i += 1;
}
}
});
testWidgets('Velocity control test', (WidgetTester tester) async {
const Velocity velocity1 = Velocity(pixelsPerSecond: Offset(7.0, 0.0));
const Velocity velocity2 = Velocity(pixelsPerSecond: Offset(12.0, 0.0));
expect(velocity1, equals(const Velocity(pixelsPerSecond: Offset(7.0, 0.0))));
expect(velocity1, isNot(equals(velocity2)));
expect(velocity2 - velocity1, equals(const Velocity(pixelsPerSecond: Offset(5.0, 0.0))));
expect((-velocity1).pixelsPerSecond, const Offset(-7.0, 0.0));
expect(velocity1 + velocity2, equals(const Velocity(pixelsPerSecond: Offset(19.0, 0.0))));
expect(velocity1.hashCode, isNot(equals(velocity2.hashCode)));
expect(velocity1, hasOneLineDescription);
});
testWidgets('Interrupted velocity estimation', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/pull/7510
final VelocityTracker tracker = VelocityTracker.withKind(PointerDeviceKind.touch);
for (final PointerEvent event in interruptedVelocityEventData) {
if (event is PointerDownEvent || event is PointerMoveEvent) {
tracker.addPosition(event.timeStamp, event.position);
}
if (event is PointerUpEvent) {
expect(_checkVelocity(tracker.getVelocity(), const Offset(649.5, 3890.3)), isTrue);
}
}
});
testWidgets('No data velocity estimation', (WidgetTester tester) async {
final VelocityTracker tracker = VelocityTracker.withKind(PointerDeviceKind.touch);
expect(tracker.getVelocity(), Velocity.zero);
});
testWidgets('FreeScrollStartVelocityTracker.getVelocity throws when no points', (WidgetTester tester) async {
final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch);
AssertionError? exception;
try {
tracker.getVelocity();
} on AssertionError catch (e) {
exception = e;
}
expect(exception?.toString(), contains('at least 1 point'));
});
testWidgets('FreeScrollStartVelocityTracker.getVelocity throws when the new point precedes the previous point', (WidgetTester tester) async {
final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch);
AssertionError? exception;
tracker.addPosition(const Duration(hours: 1), Offset.zero);
try {
tracker.getVelocity();
tracker.addPosition(const Duration(seconds: 1), Offset.zero);
} on AssertionError catch (e) {
exception = e;
}
expect(exception?.toString(), contains('has a smaller timestamp'));
});
testWidgets('Estimate does not throw when there are more than 1 point', (WidgetTester tester) async {
final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch);
Offset position = Offset.zero;
Duration time = Duration.zero;
const Offset positionDelta = Offset(0, -1);
const Duration durationDelta = Duration(seconds: 1);
AssertionError? exception;
for (int i = 0; i < 5; i+=1) {
position += positionDelta;
time += durationDelta;
tracker.addPosition(time, position);
try {
tracker.getVelocity();
} on AssertionError catch (e) {
exception = e;
}
expect(exception, isNull);
}
});
testWidgets('Makes consistent velocity estimates with consistent velocity', (WidgetTester tester) async {
final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch);
Offset position = Offset.zero;
Duration time = Duration.zero;
const Offset positionDelta = Offset(0, -1);
const Duration durationDelta = Duration(seconds: 1);
for (int i = 0; i < 10; i+=1) {
position += positionDelta;
time += durationDelta;
tracker.addPosition(time, position);
if (i >= 3) {
expect(tracker.getVelocity().pixelsPerSecond, positionDelta);
}
}
});
testWidgets('Assume zero velocity when there are no recent samples - base VelocityTracker', (WidgetTester tester) async {
final VelocityTracker tracker = VelocityTracker.withKind(PointerDeviceKind.touch);
Offset position = Offset.zero;
Duration time = Duration.zero;
const Offset positionDelta = Offset(0, -1);
const Duration durationDelta = Duration(seconds: 1);
for (int i = 0; i < 10; i+=1) {
position += positionDelta;
time += durationDelta;
tracker.addPosition(time, position);
}
await tester.pumpAndSettle();
expect(tracker.getVelocity().pixelsPerSecond, Offset.zero);
});
testWidgets('Assume zero velocity when there are no recent samples - IOS', (WidgetTester tester) async {
final IOSScrollViewFlingVelocityTracker tracker = IOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch);
Offset position = Offset.zero;
Duration time = Duration.zero;
const Offset positionDelta = Offset(0, -1);
const Duration durationDelta = Duration(seconds: 1);
for (int i = 0; i < 10; i+=1) {
position += positionDelta;
time += durationDelta;
tracker.addPosition(time, position);
}
await tester.pumpAndSettle();
expect(tracker.getVelocity().pixelsPerSecond, Offset.zero);
});
testWidgets('Assume zero velocity when there are no recent samples - MacOS', (WidgetTester tester) async {
final MacOSScrollViewFlingVelocityTracker tracker = MacOSScrollViewFlingVelocityTracker(PointerDeviceKind.touch);
Offset position = Offset.zero;
Duration time = Duration.zero;
const Offset positionDelta = Offset(0, -1);
const Duration durationDelta = Duration(seconds: 1);
for (int i = 0; i < 10; i+=1) {
position += positionDelta;
time += durationDelta;
tracker.addPosition(time, position);
}
await tester.pumpAndSettle();
expect(tracker.getVelocity().pixelsPerSecond, Offset.zero);
});
}
| flutter/packages/flutter/test/gestures/velocity_tracker_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/velocity_tracker_test.dart",
"repo_id": "flutter",
"token_count": 2808
} | 270 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
class User {
const User({
required this.email,
required this.name,
});
final String email;
final String name;
@override
String toString() {
return '$name, $email';
}
}
void main() {
const List<String> kOptions = <String>[
'aardvark',
'bobcat',
'chameleon',
'dingo',
'elephant',
'flamingo',
'goose',
'hippopotamus',
'iguana',
'jaguar',
'koala',
'lemur',
'mouse',
'northern white rhinoceros',
];
const List<User> kOptionsUsers = <User>[
User(name: 'Alice', email: 'alice@example.com'),
User(name: 'Bob', email: 'bob@example.com'),
User(name: 'Charlie', email: 'charlie123@gmail.com'),
];
testWidgets('can filter and select a list of string options', (WidgetTester tester) async {
late String lastSelection;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Autocomplete<String>(
onSelected: (String selection) {
lastSelection = selection;
},
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
),
),
),
);
// The field is always rendered, but the options are not unless needed.
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsNothing);
// Focus the empty field. All the options are displayed.
await tester.tap(find.byType(TextFormField));
await tester.pump();
expect(find.byType(ListView), findsOneWidget);
ListView list = find.byType(ListView).evaluate().first.widget as ListView;
expect(list.semanticChildCount, kOptions.length);
// Enter text. The options are filtered by the text.
await tester.enterText(find.byType(TextFormField), 'ele');
await tester.pump();
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
list = find.byType(ListView).evaluate().first.widget as ListView;
// 'chameleon' and 'elephant' are displayed.
expect(list.semanticChildCount, 2);
// Select a option. The options hide and the field updates to show the
// selection.
await tester.tap(find.byType(InkWell).first);
await tester.pump();
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsNothing);
final TextFormField field = find.byType(TextFormField).evaluate().first.widget as TextFormField;
expect(field.controller!.text, 'chameleon');
expect(lastSelection, 'chameleon');
// Modify the field text. The options appear again and are filtered.
await tester.enterText(find.byType(TextFormField), 'e');
await tester.pump();
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
list = find.byType(ListView).evaluate().first.widget as ListView;
// 'chameleon', 'elephant', 'goose', 'lemur', 'mouse', and
// 'northern white rhinoceros' are displayed.
expect(list.semanticChildCount, 6);
});
testWidgets('can filter and select a list of custom User options', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Autocomplete<User>(
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptionsUsers.where((User option) {
return option.toString().contains(textEditingValue.text.toLowerCase());
});
},
),
),
),
);
// The field is always rendered, but the options are not unless needed.
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsNothing);
// Focus the empty field. All the options are displayed.
await tester.tap(find.byType(TextFormField));
await tester.pump();
expect(find.byType(ListView), findsOneWidget);
ListView list = find.byType(ListView).evaluate().first.widget as ListView;
expect(list.semanticChildCount, kOptionsUsers.length);
// Enter text. The options are filtered by the text.
await tester.enterText(find.byType(TextFormField), 'example');
await tester.pump();
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
list = find.byType(ListView).evaluate().first.widget as ListView;
// 'Alice' and 'Bob' are displayed because they have "example.com" emails.
expect(list.semanticChildCount, 2);
// Select a option. The options hide and the field updates to show the
// selection.
await tester.tap(find.byType(InkWell).first);
await tester.pump();
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsNothing);
final TextFormField field = find.byType(TextFormField).evaluate().first.widget as TextFormField;
expect(field.controller!.text, 'Alice, alice@example.com');
// Modify the field text. The options appear again and are filtered.
await tester.enterText(find.byType(TextFormField), 'B');
await tester.pump();
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsOneWidget);
list = find.byType(ListView).evaluate().first.widget as ListView;
// 'Bob' is displayed.
expect(list.semanticChildCount, 1);
});
testWidgets('displayStringForOption is displayed in the options', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Autocomplete<User>(
displayStringForOption: (User option) {
return option.name;
},
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptionsUsers.where((User option) {
return option.toString().contains(textEditingValue.text.toLowerCase());
});
},
),
),
),
);
// The field is always rendered, but the options are not unless needed.
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsNothing);
// Focus the empty field. All the options are displayed, and the string that
// is used comes from displayStringForOption.
await tester.tap(find.byType(TextFormField));
await tester.pump();
expect(find.byType(ListView), findsOneWidget);
final ListView list = find.byType(ListView).evaluate().first.widget as ListView;
expect(list.semanticChildCount, kOptionsUsers.length);
for (int i = 0; i < kOptionsUsers.length; i++) {
expect(find.text(kOptionsUsers[i].name), findsOneWidget);
}
// Select a option. The options hide and the field updates to show the
// selection. The text in the field is given by displayStringForOption.
await tester.tap(find.byType(InkWell).first);
await tester.pump();
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsNothing);
final TextFormField field = find.byType(TextFormField).evaluate().first.widget as TextFormField;
expect(field.controller!.text, kOptionsUsers.first.name);
});
testWidgets('can build a custom field', (WidgetTester tester) async {
final GlobalKey fieldKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Autocomplete<String>(
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
fieldViewBuilder: (BuildContext context, TextEditingController textEditingController, FocusNode focusNode, VoidCallback onFieldSubmitted) {
return Container(key: fieldKey);
},
),
),
),
);
// The custom field is rendered and not the default TextFormField.
expect(find.byKey(fieldKey), findsOneWidget);
expect(find.byType(TextFormField), findsNothing);
});
testWidgets('can build custom options', (WidgetTester tester) async {
final GlobalKey optionsKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Autocomplete<String>(
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
optionsViewBuilder: (BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) {
return Container(key: optionsKey);
},
),
),
),
);
// The default field is rendered but not the options, yet.
expect(find.byKey(optionsKey), findsNothing);
expect(find.byType(TextFormField), findsOneWidget);
// Focus the empty field. The custom options is displayed.
await tester.tap(find.byType(TextFormField));
await tester.pump();
expect(find.byKey(optionsKey), findsOneWidget);
});
testWidgets('the default Autocomplete options widget has a maximum height of 200', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(home: Scaffold(
body: Autocomplete<String>(
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
),
)));
final Finder listFinder = find.byType(ListView);
final Finder inputFinder = find.byType(TextFormField);
await tester.tap(inputFinder);
await tester.enterText(inputFinder, '');
await tester.pump();
final Size baseSize = tester.getSize(listFinder);
final double resultingHeight = baseSize.height;
expect(resultingHeight, equals(200));
});
testWidgets('the options height restricts to max desired height', (WidgetTester tester) async {
const double desiredHeight = 150.0;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Autocomplete<String>(
optionsMaxHeight: desiredHeight,
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
),
)));
/// entering "a" returns 9 items from kOptions so basically the
/// height of 9 options would be beyond `desiredHeight=150`,
/// so height gets restricted to desiredHeight.
final Finder listFinder = find.byType(ListView);
final Finder inputFinder = find.byType(TextFormField);
await tester.tap(inputFinder);
await tester.enterText(inputFinder, 'a');
await tester.pump();
final Size baseSize = tester.getSize(listFinder);
final double resultingHeight = baseSize.height;
/// expected desired Height =150.0
expect(resultingHeight, equals(desiredHeight));
});
testWidgets('The height of options shrinks to height of resulting items, if less than maxHeight', (WidgetTester tester) async {
// Returns a Future with the height of the default [Autocomplete] options widget
// after the provided text had been entered into the [Autocomplete] field.
Future<double> getDefaultOptionsHeight(
WidgetTester tester, String enteredText) async {
final Finder listFinder = find.byType(ListView);
final Finder inputFinder = find.byType(TextFormField);
final TextFormField field = inputFinder.evaluate().first.widget as TextFormField;
field.controller!.clear();
await tester.tap(inputFinder);
await tester.enterText(inputFinder, enteredText);
await tester.pump();
final Size baseSize = tester.getSize(listFinder);
return baseSize.height;
}
const double maxOptionsHeight = 250.0;
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Autocomplete<String>(
optionsMaxHeight: maxOptionsHeight,
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
),
)));
final Finder listFinder = find.byType(ListView);
expect(listFinder, findsNothing);
// Entering `a` returns 9 items(height > `maxOptionsHeight`) from the kOptions
// so height gets restricted to `maxOptionsHeight =250`.
final double nineItemsHeight = await getDefaultOptionsHeight(tester, 'a');
expect(nineItemsHeight, equals(maxOptionsHeight));
// Returns 2 Items (height < `maxOptionsHeight`)
// so options height shrinks to 2 Items combined height.
final double twoItemsHeight = await getDefaultOptionsHeight(tester, 'el');
expect(twoItemsHeight, lessThan(maxOptionsHeight));
// Returns 1 item (height < `maxOptionsHeight`) from `kOptions`
// so options height shrinks to 1 items height.
final double oneItemsHeight = await getDefaultOptionsHeight(tester, 'elep');
expect(oneItemsHeight, lessThan(twoItemsHeight));
});
testWidgets('initialValue sets initial text field value', (WidgetTester tester) async {
late String lastSelection;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Autocomplete<String>(
initialValue: const TextEditingValue(text: 'lem'),
onSelected: (String selection) {
lastSelection = selection;
},
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
),
),
),
);
// The field is always rendered, but the options are not unless needed.
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsNothing);
expect(
tester.widget<TextFormField>(find.byType(TextFormField)).controller!.text,
'lem',
);
// Focus the empty field. All the options are displayed.
await tester.tap(find.byType(TextFormField));
await tester.pump();
expect(find.byType(ListView), findsOneWidget);
final ListView list = find.byType(ListView).evaluate().first.widget as ListView;
// Displays just one option ('lemur').
expect(list.semanticChildCount, 1);
// Select a option. The options hide and the field updates to show the
// selection.
await tester.tap(find.byType(InkWell).first);
await tester.pump();
expect(find.byType(TextFormField), findsOneWidget);
expect(find.byType(ListView), findsNothing);
final TextFormField field = find.byType(TextFormField).evaluate().first.widget as TextFormField;
expect(field.controller!.text, 'lemur');
expect(lastSelection, 'lemur');
});
// Ensures that the option with the given label has a given background color
// if given, or no background if color is null.
void checkOptionHighlight(WidgetTester tester, String label, Color? color) {
final RenderBox renderBox = tester.renderObject<RenderBox>(find.ancestor(matching: find.byType(Container), of: find.text(label)));
if (color != null) {
// Check to see that the container is painted with the highlighted background color.
expect(renderBox, paints..rect(color: color));
} else {
// There should only be a paragraph painted.
expect(renderBox, paintsExactlyCountTimes(const Symbol('drawRect'), 0));
expect(renderBox, paints..paragraph());
}
}
testWidgets('keyboard navigation of the options properly highlights the option', (WidgetTester tester) async {
const Color highlightColor = Color(0xFF112233);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.light().copyWith(
focusColor: highlightColor,
),
home: Scaffold(
body: Autocomplete<String>(
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
),
),
),
);
await tester.tap(find.byType(TextFormField));
await tester.enterText(find.byType(TextFormField), 'el');
await tester.pump();
expect(find.byType(ListView), findsOneWidget);
final ListView list = find.byType(ListView).evaluate().first.widget as ListView;
expect(list.semanticChildCount, 2);
// Initially the first option should be highlighted
checkOptionHighlight(tester, 'chameleon', highlightColor);
checkOptionHighlight(tester, 'elephant', null);
// Move the selection down
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
// Highlight should be moved to the second item
checkOptionHighlight(tester, 'chameleon', null);
checkOptionHighlight(tester, 'elephant', highlightColor);
});
testWidgets('keyboard navigation keeps the highlighted option scrolled into view', (WidgetTester tester) async {
const Color highlightColor = Color(0xFF112233);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.light().copyWith(focusColor: highlightColor),
home: Scaffold(
body: Autocomplete<String>(
optionsBuilder: (TextEditingValue textEditingValue) {
return kOptions.where((String option) {
return option.contains(textEditingValue.text.toLowerCase());
});
},
),
),
),
);
await tester.tap(find.byType(TextFormField));
await tester.enterText(find.byType(TextFormField), 'e');
await tester.pump();
expect(find.byType(ListView), findsOneWidget);
final ListView list = find.byType(ListView).evaluate().first.widget as ListView;
expect(list.semanticChildCount, 6);
final Rect optionsGroupRect = tester.getRect(find.byType(ListView));
const double optionsGroupPadding = 16.0;
// Highlighted item should be at the top.
checkOptionHighlight(tester, 'chameleon', highlightColor);
expect(
tester.getTopLeft(find.text('chameleon')).dy,
equals(optionsGroupRect.top + optionsGroupPadding),
);
// Move down the list of options.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Select 'elephant'.
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Select 'goose'.
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Select 'lemur'.
await tester.pumpAndSettle();
// Highlighted item 'lemur' should be centered in the options popup.
checkOptionHighlight(tester, 'lemur', highlightColor);
expect(
tester.getCenter(find.text('lemur')).dy,
equals(optionsGroupRect.center.dy),
);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Select 'mouse'.
await tester.pumpAndSettle();
checkOptionHighlight(tester, 'mouse', highlightColor);
// First item should have scrolled off the top, and not be selected.
expect(find.text('chameleon'), findsNothing);
// The other items on screen should not be selected.
checkOptionHighlight(tester, 'goose', null);
checkOptionHighlight(tester, 'lemur', null);
checkOptionHighlight(tester, 'northern white rhinoceros', null);
});
group('optionsViewOpenDirection', () {
testWidgets('default (down)', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Autocomplete<String>(
optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'],
),
),
),
);
final OptionsViewOpenDirection actual = tester.widget<RawAutocomplete<String>>(find.byType(RawAutocomplete<String>))
.optionsViewOpenDirection;
expect(actual, equals(OptionsViewOpenDirection.down));
});
testWidgets('down', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Autocomplete<String>(
optionsViewOpenDirection: OptionsViewOpenDirection.down, // ignore: avoid_redundant_argument_values
optionsBuilder: (TextEditingValue textEditingValue) => <String>['a'],
),
),
),
);
final OptionsViewOpenDirection actual = tester.widget<RawAutocomplete<String>>(find.byType(RawAutocomplete<String>))
.optionsViewOpenDirection;
expect(actual, equals(OptionsViewOpenDirection.down));
});
testWidgets('up', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: Autocomplete<String>(
optionsViewOpenDirection: OptionsViewOpenDirection.up,
optionsBuilder: (TextEditingValue textEditingValue) => <String>['aa'],
),
),
),
),
);
final OptionsViewOpenDirection actual = tester.widget<RawAutocomplete<String>>(find.byType(RawAutocomplete<String>))
.optionsViewOpenDirection;
expect(actual, equals(OptionsViewOpenDirection.up));
await tester.tap(find.byType(RawAutocomplete<String>));
await tester.enterText(find.byType(RawAutocomplete<String>), 'a');
expect(find.text('aa').hitTestable(), findsOneWidget);
});
});
}
| flutter/packages/flutter/test/material/autocomplete_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/autocomplete_test.dart",
"repo_id": "flutter",
"token_count": 8260
} | 271 |
// Copyright 2014 The Flutter Authors. 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/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/feedback_tester.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final Finder nextMonthIcon = find.byWidgetPredicate((Widget w) => w is IconButton && (w.tooltip?.startsWith('Next month') ?? false));
final Finder previousMonthIcon = find.byWidgetPredicate((Widget w) => w is IconButton && (w.tooltip?.startsWith('Previous month') ?? false));
Widget calendarDatePicker({
Key? key,
DateTime? initialDate,
DateTime? firstDate,
DateTime? lastDate,
DateTime? currentDate,
ValueChanged<DateTime>? onDateChanged,
ValueChanged<DateTime>? onDisplayedMonthChanged,
DatePickerMode initialCalendarMode = DatePickerMode.day,
SelectableDayPredicate? selectableDayPredicate,
TextDirection textDirection = TextDirection.ltr,
ThemeData? theme,
bool? useMaterial3,
}) {
return MaterialApp(
theme: theme ?? ThemeData(useMaterial3: useMaterial3),
home: Material(
child: Directionality(
textDirection: textDirection,
child: CalendarDatePicker(
key: key,
initialDate: initialDate,
firstDate: firstDate ?? DateTime(2001),
lastDate: lastDate ?? DateTime(2031, DateTime.december, 31),
currentDate: currentDate ?? DateTime(2016, DateTime.january, 3),
onDateChanged: onDateChanged ?? (DateTime date) {},
onDisplayedMonthChanged: onDisplayedMonthChanged,
initialCalendarMode: initialCalendarMode,
selectableDayPredicate: selectableDayPredicate,
),
),
),
);
}
Widget yearPicker({
Key? key,
DateTime? selectedDate,
DateTime? initialDate,
DateTime? firstDate,
DateTime? lastDate,
DateTime? currentDate,
ValueChanged<DateTime>? onChanged,
TextDirection textDirection = TextDirection.ltr,
}) {
return MaterialApp(
home: Material(
child: Directionality(
textDirection: textDirection,
child: YearPicker(
key: key,
selectedDate: selectedDate ?? DateTime(2016, DateTime.january, 15),
firstDate: firstDate ?? DateTime(2001),
lastDate: lastDate ?? DateTime(2031, DateTime.december, 31),
currentDate: currentDate ?? DateTime(2016, DateTime.january, 3),
onChanged: onChanged ?? (DateTime date) {},
),
),
),
);
}
group('CalendarDatePicker', () {
testWidgets('Can select a day', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
onDateChanged: (DateTime date) => selectedDate = date,
));
await tester.tap(find.text('12'));
expect(selectedDate, equals(DateTime(2016, DateTime.january, 12)));
});
testWidgets('Can select a day with nothing first selected', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
onDateChanged: (DateTime date) => selectedDate = date,
));
await tester.tap(find.text('12'));
expect(selectedDate, equals(DateTime(2016, DateTime.january, 12)));
});
testWidgets('Can select a month', (WidgetTester tester) async {
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
expect(find.text('January 2016'), findsOneWidget);
// Go back two months
await tester.tap(previousMonthIcon);
await tester.pumpAndSettle();
expect(find.text('December 2015'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2015, DateTime.december)));
await tester.tap(previousMonthIcon);
await tester.pumpAndSettle();
expect(find.text('November 2015'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2015, DateTime.november)));
// Go forward a month
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle();
expect(find.text('December 2015'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2015, DateTime.december)));
});
testWidgets('Can select a month with nothing first selected', (WidgetTester tester) async {
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
expect(find.text('January 2016'), findsOneWidget);
// Go back two months
await tester.tap(previousMonthIcon);
await tester.pumpAndSettle();
expect(find.text('December 2015'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2015, DateTime.december)));
await tester.tap(previousMonthIcon);
await tester.pumpAndSettle();
expect(find.text('November 2015'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2015, DateTime.november)));
// Go forward a month
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle();
expect(find.text('December 2015'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2015, DateTime.december)));
});
testWidgets('Can select a year', (WidgetTester tester) async {
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
await tester.tap(find.text('January 2016')); // Switch to year mode.
await tester.pumpAndSettle();
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
expect(find.text('January 2018'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2018)));
});
testWidgets('Can select a year with nothing first selected', (WidgetTester tester) async {
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
await tester.tap(find.text('January 2016')); // Switch to year mode.
await tester.pumpAndSettle();
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
expect(find.text('January 2018'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2018)));
});
testWidgets('Selecting date does not change displayed month', (WidgetTester tester) async {
DateTime? selectedDate;
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2020, DateTime.march, 15),
onDateChanged: (DateTime date) => selectedDate = date,
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle();
expect(find.text('April 2020'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2020, DateTime.april)));
await tester.tap(find.text('25'));
await tester.pumpAndSettle();
expect(find.text('April 2020'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2020, DateTime.april)));
expect(selectedDate, equals(DateTime(2020, DateTime.april, 25)));
// There isn't a 31 in April so there shouldn't be one if it is showing April.
expect(find.text('31'), findsNothing);
});
testWidgets('Changing year does change selected date', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
onDateChanged: (DateTime date) => selectedDate = date,
));
await tester.tap(find.text('4'));
expect(selectedDate, equals(DateTime(2016, DateTime.january, 4)));
await tester.tap(find.text('January 2016'));
await tester.pumpAndSettle();
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
expect(selectedDate, equals(DateTime(2018, DateTime.january, 4)));
});
testWidgets('Changing year for february 29th', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2020, DateTime.february, 29),
onDateChanged: (DateTime date) => selectedDate = date,
));
await tester.tap(find.text('February 2020'));
await tester.pumpAndSettle();
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
expect(selectedDate, equals(DateTime(2018, DateTime.february, 28)));
await tester.tap(find.text('February 2018'));
await tester.pumpAndSettle();
await tester.tap(find.text('2020'));
await tester.pumpAndSettle();
// Changing back to 2020 the 29th is not selected anymore.
expect(selectedDate, equals(DateTime(2020, DateTime.february, 28)));
});
testWidgets('Changing year does not change the month', (WidgetTester tester) async {
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle();
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle();
await tester.tap(find.text('March 2016'));
await tester.pumpAndSettle();
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
expect(find.text('March 2018'), findsOneWidget);
expect(displayedMonth, equals(DateTime(2018, DateTime.march)));
});
testWidgets('Can select a year and then a day', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
onDateChanged: (DateTime date) => selectedDate = date,
));
await tester.tap(find.text('January 2016')); // Switch to year mode.
await tester.pumpAndSettle();
await tester.tap(find.text('2017'));
await tester.pumpAndSettle();
await tester.tap(find.text('19'));
expect(selectedDate, equals(DateTime(2017, DateTime.january, 19)));
});
testWidgets('Cannot select a day outside bounds', (WidgetTester tester) async {
final DateTime validDate = DateTime(2017, DateTime.january, 15);
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
initialDate: validDate,
firstDate: validDate,
lastDate: validDate,
onDateChanged: (DateTime date) => selectedDate = date,
));
// Earlier than firstDate. Should be ignored.
await tester.tap(find.text('10'));
expect(selectedDate, isNull);
// Later than lastDate. Should be ignored.
await tester.tap(find.text('20'));
expect(selectedDate, isNull);
// This one is just right.
await tester.tap(find.text('15'));
expect(selectedDate, validDate);
});
testWidgets('Cannot navigate to a month outside bounds', (WidgetTester tester) async {
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
firstDate: DateTime(2016, DateTime.december, 15),
initialDate: DateTime(2017, DateTime.january, 15),
lastDate: DateTime(2017, DateTime.february, 15),
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle();
expect(displayedMonth, equals(DateTime(2017, DateTime.february)));
// Shouldn't be possible to keep going forward into March.
expect(nextMonthIcon, findsNothing);
await tester.tap(previousMonthIcon);
await tester.pumpAndSettle();
await tester.tap(previousMonthIcon);
await tester.pumpAndSettle();
expect(displayedMonth, equals(DateTime(2016, DateTime.december)));
// Shouldn't be possible to keep going backward into November.
expect(previousMonthIcon, findsNothing);
});
testWidgets('Cannot select disabled year', (WidgetTester tester) async {
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
firstDate: DateTime(2018, DateTime.june, 9),
initialDate: DateTime(2018, DateTime.july, 4),
lastDate: DateTime(2018, DateTime.december, 15),
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
await tester.tap(find.text('July 2018')); // Switch to year mode.
await tester.pumpAndSettle();
await tester.tap(find.text('2016')); // Disabled, doesn't change the year.
await tester.pumpAndSettle();
await tester.tap(find.text('2020')); // Disabled, doesn't change the year.
await tester.pumpAndSettle();
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
// Nothing should have changed.
expect(displayedMonth, isNull);
});
testWidgets('Selecting firstDate year respects firstDate', (WidgetTester tester) async {
DateTime? selectedDate;
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
firstDate: DateTime(2016, DateTime.june, 9),
initialDate: DateTime(2018, DateTime.may, 4),
lastDate: DateTime(2019, DateTime.january, 15),
onDateChanged: (DateTime date) => selectedDate = date,
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
await tester.tap(find.text('May 2018'));
await tester.pumpAndSettle();
await tester.tap(find.text('2016'));
await tester.pumpAndSettle();
// Month should be clamped to June as the range starts at June 2016.
expect(find.text('June 2016'), findsOneWidget);
expect(displayedMonth, DateTime(2016, DateTime.june));
expect(selectedDate, DateTime(2016, DateTime.june, 9));
});
testWidgets('Selecting lastDate year respects lastDate', (WidgetTester tester) async {
DateTime? selectedDate;
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
firstDate: DateTime(2016, DateTime.june, 9),
initialDate: DateTime(2018, DateTime.may, 4),
lastDate: DateTime(2019, DateTime.january, 15),
onDateChanged: (DateTime date) => selectedDate = date,
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
// Selected date is now 2018-05-04 (initialDate).
await tester.tap(find.text('May 2018'));
// Selected date is still 2018-05-04.
await tester.pumpAndSettle();
await tester.tap(find.text('2019'));
// Selected date would become 2019-05-04 but gets clamped to the month of lastDate, so 2019-01-04.
await tester.pumpAndSettle();
expect(find.text('January 2019'), findsOneWidget);
expect(displayedMonth, DateTime(2019));
expect(selectedDate, DateTime(2019, DateTime.january, 4));
});
testWidgets('Selecting lastDate year respects lastDate', (WidgetTester tester) async {
DateTime? selectedDate;
DateTime? displayedMonth;
await tester.pumpWidget(calendarDatePicker(
firstDate: DateTime(2016, DateTime.june, 9),
initialDate: DateTime(2018, DateTime.may, 15),
lastDate: DateTime(2019, DateTime.january, 4),
onDateChanged: (DateTime date) => selectedDate = date,
onDisplayedMonthChanged: (DateTime date) => displayedMonth = date,
));
// Selected date is now 2018-05-15 (initialDate).
await tester.tap(find.text('May 2018'));
// Selected date is still 2018-05-15.
await tester.pumpAndSettle();
await tester.tap(find.text('2019'));
// Selected date would become 2019-05-15 but gets clamped to the month of lastDate, so 2019-01-15.
// Day is now beyond the lastDate so that also gets clamped, to 2019-01-04.
await tester.pumpAndSettle();
expect(find.text('January 2019'), findsOneWidget);
expect(displayedMonth, DateTime(2019));
expect(selectedDate, DateTime(2019, DateTime.january, 4));
});
testWidgets('Only predicate days are selectable', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
firstDate: DateTime(2017, DateTime.january, 10),
initialDate: DateTime(2017, DateTime.january, 16),
lastDate: DateTime(2017, DateTime.january, 20),
onDateChanged: (DateTime date) => selectedDate = date,
selectableDayPredicate: (DateTime date) => date.day.isEven,
));
await tester.tap(find.text('13')); // Odd, doesn't work.
expect(selectedDate, isNull);
await tester.tap(find.text('10')); // Even, works.
expect(selectedDate, DateTime(2017, DateTime.january, 10));
await tester.tap(find.text('17')); // Odd, doesn't work.
expect(selectedDate, DateTime(2017, DateTime.january, 10));
});
testWidgets('Can select initial calendar picker mode', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2014, DateTime.january, 15),
initialCalendarMode: DatePickerMode.year,
));
// 2018 wouldn't be available if the year picker wasn't showing.
// The initial current year is 2014.
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
expect(find.text('January 2018'), findsOneWidget);
});
testWidgets('Material2 - currentDate is highlighted', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
useMaterial3: false,
initialDate: DateTime(2016, DateTime.january, 15),
currentDate: DateTime(2016, 1, 2),
));
const Color todayColor = Color(0xff2196f3); // default primary color
expect(
Material.of(tester.element(find.text('2'))),
// The current day should be painted with a circle outline.
paints..circle(
color: todayColor,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
),
);
});
testWidgets('Material3 - currentDate is highlighted', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
useMaterial3: true,
initialDate: DateTime(2016, DateTime.january, 15),
currentDate: DateTime(2016, 1, 2),
));
const Color todayColor = Color(0xff6750a4); // default primary color
expect(
Material.of(tester.element(find.text('2'))),
// The current day should be painted with a circle outline.
paints..circle(
color: todayColor,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
),
);
});
testWidgets('Material2 - currentDate is highlighted even if it is disabled', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
useMaterial3: false,
firstDate: DateTime(2016, 1, 3),
lastDate: DateTime(2016, 1, 31),
currentDate: DateTime(2016, 1, 2), // not between first and last
initialDate: DateTime(2016, 1, 5),
));
const Color disabledColor = Color(0x61000000); // default disabled color
expect(
Material.of(tester.element(find.text('2'))),
// The current day should be painted with a circle outline.
paints
..circle(
color: disabledColor,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
),
);
});
testWidgets('Material3 - currentDate is highlighted even if it is disabled', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
useMaterial3: true,
firstDate: DateTime(2016, 1, 3),
lastDate: DateTime(2016, 1, 31),
currentDate: DateTime(2016, 1, 2), // not between first and last
initialDate: DateTime(2016, 1, 5),
));
const Color disabledColor = Color(0x616750a4); // default disabled color
expect(
Material.of(tester.element(find.text('2'))),
// The current day should be painted with a circle outline.
paints
..circle(
color: disabledColor,
style: PaintingStyle.stroke,
strokeWidth: 1.0,
),
);
});
testWidgets('Selecting date does not switch picker to year selection', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2020, DateTime.may, 10),
initialCalendarMode: DatePickerMode.year,
));
await tester.tap(find.text('2017'));
await tester.pumpAndSettle();
expect(find.text('May 2017'), findsOneWidget);
await tester.tap(find.text('10'));
await tester.pumpAndSettle();
expect(find.text('May 2017'), findsOneWidget);
expect(find.text('2017'), findsNothing);
});
testWidgets('Selecting disabled date does not change current selection', (WidgetTester tester) async {
DateTime day(int day) => DateTime(2020, DateTime.may, day);
DateTime selection = day(2);
await tester.pumpWidget(calendarDatePicker(
initialDate: selection,
firstDate: day(2),
lastDate: day(3),
onDateChanged: (DateTime date) {
selection = date;
},
));
await tester.tap(find.text('3'));
await tester.pumpAndSettle();
expect(selection, day(3));
await tester.tap(find.text('4'));
await tester.pumpAndSettle();
expect(selection, day(3));
await tester.tap(find.text('5'));
await tester.pumpAndSettle();
expect(selection, day(3));
});
for (final bool useMaterial3 in <bool>[false, true]) {
testWidgets('Updates to initialDate parameter are not reflected in the state (useMaterial3=$useMaterial3)', (WidgetTester tester) async {
final Key pickerKey = UniqueKey();
final DateTime initialDate = DateTime(2020, 1, 21);
final DateTime updatedDate = DateTime(1976, 2, 23);
final DateTime firstDate = DateTime(1970);
final DateTime lastDate = DateTime(2099, 31, 12);
final Color selectedColor = useMaterial3 ? const Color(0xff6750a4) : const Color(0xff2196f3); // default primary color
await tester.pumpWidget(calendarDatePicker(
key: pickerKey,
useMaterial3: useMaterial3,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
onDateChanged: (DateTime value) {},
));
await tester.pumpAndSettle();
// Month should show as January 2020.
expect(find.text('January 2020'), findsOneWidget);
// Selected date should be painted with a colored circle.
expect(
Material.of(tester.element(find.text('21'))),
paints..circle(color: selectedColor, style: PaintingStyle.fill),
);
// Change to the updated initialDate.
// This should have no effect, the initialDate is only the _initial_ date.
await tester.pumpWidget(calendarDatePicker(
key: pickerKey,
useMaterial3: useMaterial3,
initialDate: updatedDate,
firstDate: firstDate,
lastDate: lastDate,
onDateChanged: (DateTime value) {},
));
// Wait for the page scroll animation to finish.
await tester.pumpAndSettle(const Duration(milliseconds: 200));
// Month should show as January 2020 still.
expect(find.text('January 2020'), findsOneWidget);
expect(find.text('February 1976'), findsNothing);
// Selected date should be painted with a colored circle.
expect(
Material.of(tester.element(find.text('21'))),
paints..circle(color: selectedColor, style: PaintingStyle.fill),
);
});
}
testWidgets('Updates to initialCalendarMode parameter is not reflected in the state', (WidgetTester tester) async {
final Key pickerKey = UniqueKey();
await tester.pumpWidget(calendarDatePicker(
key: pickerKey,
initialDate: DateTime(2016, DateTime.january, 15),
initialCalendarMode: DatePickerMode.year,
));
await tester.pumpAndSettle();
// Should be in year mode.
expect(find.text('January 2016'), findsOneWidget); // Day/year selector
expect(find.text('15'), findsNothing); // day 15 in grid
expect(find.text('2016'), findsOneWidget); // 2016 in year grid
await tester.pumpWidget(calendarDatePicker(
key: pickerKey,
initialDate: DateTime(2016, DateTime.january, 15),
));
await tester.pumpAndSettle();
// Should be in year mode still; updating an _initial_ parameter has no effect.
expect(find.text('January 2016'), findsOneWidget); // Day/year selector
expect(find.text('15'), findsNothing); // day 15 in grid
expect(find.text('2016'), findsOneWidget); // 2016 in year grid
});
testWidgets('Dragging more than half the width should not cause a jump', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
));
await tester.pumpAndSettle();
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(PageView)));
// This initial drag is required for the PageView to recognize the gesture, as it uses DragStartBehavior.start.
// It does not count towards the drag distance.
await gesture.moveBy(const Offset(100, 0));
// Dragging for a bit less than half the width should reveal the previous month.
await gesture.moveBy(const Offset(800 / 2 - 1, 0));
await tester.pumpAndSettle();
expect(find.text('January 2016'), findsOneWidget);
expect(find.text('1'), findsNWidgets(2));
// Dragging a bit over the half should still show both.
await gesture.moveBy(const Offset(2, 0));
await tester.pumpAndSettle();
expect(find.text('December 2015'), findsOneWidget);
expect(find.text('1'), findsNWidgets(2));
});
group('Keyboard navigation', () {
testWidgets('Can toggle to year mode', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
));
expect(find.text('2016'), findsNothing);
expect(find.text('January 2016'), findsOneWidget);
// Navigate to the year selector and activate it.
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// The years should be visible.
expect(find.text('2016'), findsOneWidget);
expect(find.text('January 2016'), findsOneWidget);
});
testWidgets('Can navigate next/previous months', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
));
expect(find.text('January 2016'), findsOneWidget);
// Navigate to the previous month button and activate it twice.
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should be showing Nov 2015
expect(find.text('November 2015'), findsOneWidget);
// Navigate to the next month button and activate it four times.
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should be on Mar 2016.
expect(find.text('March 2016'), findsOneWidget);
});
testWidgets('Can navigate date grid with arrow keys', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
onDateChanged: (DateTime date) => selectedDate = date,
));
// Navigate to the grid.
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
// Navigate from Jan 15 to Jan 18 with arrow keys.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pumpAndSettle();
// Activate it.
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should have selected Jan 18.
expect(selectedDate, DateTime(2016, DateTime.january, 18));
});
testWidgets('Navigating with arrow keys scrolls months', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
onDateChanged: (DateTime date) => selectedDate = date,
));
// Navigate to the grid.
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
// Navigate from Jan 15 to Dec 31 with arrow keys
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pumpAndSettle();
// Should have scrolled to Dec 2015.
expect(find.text('December 2015'), findsOneWidget);
// Navigate from Dec 31 to Nov 26 with arrow keys.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pumpAndSettle();
// Should have scrolled to Nov 2015.
expect(find.text('November 2015'), findsOneWidget);
// Activate it
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should have selected Jan 18.
expect(selectedDate, DateTime(2015, DateTime.november, 26));
});
testWidgets('RTL text direction reverses the horizontal arrow key navigation', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
onDateChanged: (DateTime date) => selectedDate = date,
textDirection: TextDirection.rtl,
));
// Navigate to the grid.
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
// Navigate from Jan 15 to 19 with arrow keys.
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pumpAndSettle();
// Activate it.
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should have selected Jan 19.
expect(selectedDate, DateTime(2016, DateTime.january, 19));
});
});
group('Haptic feedback', () {
const Duration hapticFeedbackInterval = Duration(milliseconds: 10);
late FeedbackTester feedback;
setUp(() {
feedback = FeedbackTester();
});
tearDown(() {
feedback.dispose();
});
testWidgets('Selecting date vibrates', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
));
await tester.tap(find.text('10'));
await tester.pump(hapticFeedbackInterval);
expect(feedback.hapticCount, 1);
await tester.tap(find.text('12'));
await tester.pump(hapticFeedbackInterval);
expect(feedback.hapticCount, 2);
await tester.tap(find.text('14'));
await tester.pump(hapticFeedbackInterval);
expect(feedback.hapticCount, 3);
});
testWidgets('Tapping unselectable date does not vibrate', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 10),
selectableDayPredicate: (DateTime date) => date.day.isEven,
));
await tester.tap(find.text('11'));
await tester.pump(hapticFeedbackInterval);
expect(feedback.hapticCount, 0);
await tester.tap(find.text('13'));
await tester.pump(hapticFeedbackInterval);
expect(feedback.hapticCount, 0);
await tester.tap(find.text('15'));
await tester.pump(hapticFeedbackInterval);
expect(feedback.hapticCount, 0);
});
testWidgets('Changing modes and year vibrates', (WidgetTester tester) async {
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
));
await tester.tap(find.text('January 2016'));
await tester.pump(hapticFeedbackInterval);
expect(feedback.hapticCount, 1);
await tester.tap(find.text('2018'));
await tester.pump(hapticFeedbackInterval);
expect(feedback.hapticCount, 2);
});
});
group('Semantics', () {
testWidgets('day mode', (WidgetTester tester) async {
final SemanticsHandle semantics = tester.ensureSemantics();
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
));
// Year mode drop down button.
expect(tester.getSemantics(find.text('January 2016')), matchesSemantics(
label: 'Select year',
isButton: true,
));
// Prev/Next month buttons.
expect(tester.getSemantics(previousMonthIcon), matchesSemantics(
tooltip: 'Previous month',
isButton: true,
hasTapAction: true,
isEnabled: true,
hasEnabledState: true,
isFocusable: true,
));
expect(tester.getSemantics(nextMonthIcon), matchesSemantics(
tooltip: 'Next month',
isButton: true,
hasTapAction: true,
isEnabled: true,
hasEnabledState: true,
isFocusable: true,
));
// Day grid.
expect(tester.getSemantics(find.text('1')), matchesSemantics(
label: '1, Friday, January 1, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('2')), matchesSemantics(
label: '2, Saturday, January 2, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('3')), matchesSemantics(
label: '3, Sunday, January 3, 2016, Today',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('4')), matchesSemantics(
label: '4, Monday, January 4, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('5')), matchesSemantics(
label: '5, Tuesday, January 5, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('6')), matchesSemantics(
label: '6, Wednesday, January 6, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('7')), matchesSemantics(
label: '7, Thursday, January 7, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('8')), matchesSemantics(
label: '8, Friday, January 8, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('9')), matchesSemantics(
label: '9, Saturday, January 9, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('10')), matchesSemantics(
label: '10, Sunday, January 10, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('11')), matchesSemantics(
label: '11, Monday, January 11, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('12')), matchesSemantics(
label: '12, Tuesday, January 12, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('13')), matchesSemantics(
label: '13, Wednesday, January 13, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('14')), matchesSemantics(
label: '14, Thursday, January 14, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('15')), matchesSemantics(
label: '15, Friday, January 15, 2016',
isButton: true,
hasTapAction: true,
isSelected: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('16')), matchesSemantics(
label: '16, Saturday, January 16, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('17')), matchesSemantics(
label: '17, Sunday, January 17, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('18')), matchesSemantics(
label: '18, Monday, January 18, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('19')), matchesSemantics(
label: '19, Tuesday, January 19, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('20')), matchesSemantics(
label: '20, Wednesday, January 20, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('21')), matchesSemantics(
label: '21, Thursday, January 21, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('22')), matchesSemantics(
label: '22, Friday, January 22, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('23')), matchesSemantics(
label: '23, Saturday, January 23, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('24')), matchesSemantics(
label: '24, Sunday, January 24, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('25')), matchesSemantics(
label: '25, Monday, January 25, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('26')), matchesSemantics(
label: '26, Tuesday, January 26, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('27')), matchesSemantics(
label: '27, Wednesday, January 27, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('28')), matchesSemantics(
label: '28, Thursday, January 28, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('29')), matchesSemantics(
label: '29, Friday, January 29, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('30')), matchesSemantics(
label: '30, Saturday, January 30, 2016',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
semantics.dispose();
});
testWidgets('calendar year mode', (WidgetTester tester) async {
final SemanticsHandle semantics = tester.ensureSemantics();
await tester.pumpWidget(calendarDatePicker(
initialDate: DateTime(2016, DateTime.january, 15),
initialCalendarMode: DatePickerMode.year,
));
// Year mode drop down button.
expect(tester.getSemantics(find.text('January 2016')), matchesSemantics(
label: 'Select year',
isButton: true,
));
// Year grid only shows 2010 - 2024.
for (int year = 2010; year <= 2024; year++) {
expect(tester.getSemantics(find.text('$year')), matchesSemantics(
label: '$year',
hasTapAction: true,
isSelected: year == 2016,
isFocusable: true,
isButton: true,
));
}
semantics.dispose();
});
// This is a regression test for https://github.com/flutter/flutter/issues/143439.
testWidgets('Selected date Semantics announcement on onDateChanged', (WidgetTester tester) async {
final SemanticsHandle semantics = tester.ensureSemantics();
const DefaultMaterialLocalizations localizations = DefaultMaterialLocalizations();
final DateTime initialDate = DateTime(2016, DateTime.january, 15);
DateTime? selectedDate;
await tester.pumpWidget(calendarDatePicker(
initialDate: initialDate,
onDateChanged: (DateTime value) {
selectedDate = value;
},
));
final bool isToday = DateUtils.isSameDay(initialDate, selectedDate);
final String semanticLabelSuffix = isToday ? ', ${localizations.currentDateLabel}' : '';
// The initial date should be announced.
expect(
tester.takeAnnouncements().last.message,
'${localizations.formatFullDate(initialDate)}$semanticLabelSuffix',
);
// Select a new date.
await tester.tap(find.text('20'));
await tester.pumpAndSettle();
// The selected date should be announced.
expect(
tester.takeAnnouncements().last.message,
'${localizations.selectedDateLabel} ${localizations.formatFullDate(selectedDate!)}$semanticLabelSuffix',
);
// Select the initial date.
await tester.tap(find.text('15'));
// The initial date should be announced as selected.
expect(
tester.takeAnnouncements().first.message,
'${localizations.selectedDateLabel} ${localizations.formatFullDate(initialDate)}$semanticLabelSuffix',
);
semantics.dispose();
}, variant: TargetPlatformVariant.desktop());
});
// This is a regression test for https://github.com/flutter/flutter/issues/141350.
testWidgets('Default day selection overlay', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(calendarDatePicker(
firstDate: DateTime(2016, DateTime.december, 15),
initialDate: DateTime(2017, DateTime.january, 15),
lastDate: DateTime(2017, DateTime.february, 15),
onDisplayedMonthChanged: (DateTime date) {},
theme: theme,
));
RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, isNot(paints..circle(radius: 35.0, color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08))));
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.text('25')));
await tester.pumpAndSettle();
inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..circle(radius: 35.0, color: theme.colorScheme.onSurfaceVariant.withOpacity(0.08)));
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 1));
final Rect expectedClipRect = Rect.fromCircle(center: const Offset(400.0, 241.0), radius: 35.0);
final Path expectedClipPath = Path()..addRect(expectedClipRect);
expect(
inkFeatures,
paints..clipPath(pathMatcher: coversSameAreaAs(
expectedClipPath,
areaToCompare: expectedClipRect,
sampleSize: 100,
)),
);
});
});
group('YearPicker', () {
testWidgets('Current year is visible in year picker', (WidgetTester tester) async {
await tester.pumpWidget(yearPicker());
expect(find.text('2016'), findsOneWidget);
});
testWidgets('Can select a year', (WidgetTester tester) async {
DateTime? selectedDate;
await tester.pumpWidget(yearPicker(
onChanged: (DateTime date) => selectedDate = date,
));
await tester.pumpAndSettle();
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
expect(selectedDate, equals(DateTime(2018)));
});
testWidgets('Cannot select disabled year', (WidgetTester tester) async {
DateTime? selectedYear;
await tester.pumpWidget(yearPicker(
firstDate: DateTime(2018, DateTime.june, 9),
selectedDate: DateTime(2018, DateTime.july, 4),
lastDate: DateTime(2018, DateTime.december, 15),
onChanged: (DateTime date) => selectedYear = date,
));
await tester.tap(find.text('2016')); // Disabled, doesn't change the year.
await tester.pumpAndSettle();
expect(selectedYear, isNull);
await tester.tap(find.text('2020')); // Disabled, doesn't change the year.
await tester.pumpAndSettle();
expect(selectedYear, isNull);
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
expect(selectedYear, equals(DateTime(2018, DateTime.july)));
});
testWidgets('Selecting year with no selected month uses earliest month', (WidgetTester tester) async {
DateTime? selectedYear;
await tester.pumpWidget(yearPicker(
firstDate: DateTime(2018, DateTime.june, 9),
lastDate: DateTime(2019, DateTime.december, 15),
onChanged: (DateTime date) => selectedYear = date,
));
await tester.tap(find.text('2018'));
expect(selectedYear, equals(DateTime(2018, DateTime.june)));
await tester.pumpWidget(yearPicker(
firstDate: DateTime(2018, DateTime.june, 9),
lastDate: DateTime(2019, DateTime.december, 15),
selectedDate: DateTime(2018, DateTime.june),
onChanged: (DateTime date) => selectedYear = date,
));
await tester.tap(find.text('2019'));
expect(selectedYear, equals(DateTime(2019, DateTime.june)));
});
testWidgets('Selecting year with no selected month uses January', (WidgetTester tester) async {
DateTime? selectedYear;
await tester.pumpWidget(yearPicker(
firstDate: DateTime(2018, DateTime.june, 9),
lastDate: DateTime(2019, DateTime.december, 15),
onChanged: (DateTime date) => selectedYear = date,
));
await tester.tap(find.text('2019'));
expect(selectedYear, equals(DateTime(2019))); // january implied
await tester.pumpWidget(yearPicker(
firstDate: DateTime(2018, DateTime.june, 9),
lastDate: DateTime(2019, DateTime.december, 15),
selectedDate: DateTime(2018),
onChanged: (DateTime date) => selectedYear = date,
));
await tester.tap(find.text('2018'));
expect(selectedYear, equals(DateTime(2018, DateTime.june)));
});
});
}
| flutter/packages/flutter/test/material/calendar_date_picker_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/calendar_date_picker_test.dart",
"repo_id": "flutter",
"token_count": 20691
} | 272 |
// Copyright 2014 The Flutter 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/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/clipboard_utils.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late DateTime firstDate;
late DateTime lastDate;
late DateTime? initialDate;
late DateTime today;
late SelectableDayPredicate? selectableDayPredicate;
late DatePickerEntryMode initialEntryMode;
late DatePickerMode initialCalendarMode;
late DatePickerEntryMode currentMode;
String? cancelText;
String? confirmText;
String? errorFormatText;
String? errorInvalidText;
String? fieldHintText;
String? fieldLabelText;
String? helpText;
TextInputType? keyboardType;
final Finder nextMonthIcon = find.byWidgetPredicate((Widget w) => w is IconButton && (w.tooltip?.startsWith('Next month') ?? false));
final Finder previousMonthIcon = find.byWidgetPredicate((Widget w) => w is IconButton && (w.tooltip?.startsWith('Previous month') ?? false));
final Finder switchToInputIcon = find.byIcon(Icons.edit);
final Finder switchToCalendarIcon = find.byIcon(Icons.calendar_today);
TextField textField(WidgetTester tester) {
return tester.widget<TextField>(find.byType(TextField));
}
setUp(() {
firstDate = DateTime(2001);
lastDate = DateTime(2031, DateTime.december, 31);
initialDate = DateTime(2016, DateTime.january, 15);
today = DateTime(2016, DateTime.january, 3);
selectableDayPredicate = null;
initialEntryMode = DatePickerEntryMode.calendar;
initialCalendarMode = DatePickerMode.day;
cancelText = null;
confirmText = null;
errorFormatText = null;
errorInvalidText = null;
fieldHintText = null;
fieldLabelText = null;
helpText = null;
keyboardType = null;
currentMode = initialEntryMode;
});
const Size wideWindowSize = Size(1920.0, 1080.0);
const Size narrowWindowSize = Size(1070.0, 1770.0);
Future<void> prepareDatePicker(
WidgetTester tester,
Future<void> Function(Future<DateTime?> date) callback, {
TextDirection textDirection = TextDirection.ltr,
bool useMaterial3 = false,
ThemeData? theme,
TextScaler textScaler = TextScaler.noScaling,
}) async {
late BuildContext buttonContext;
await tester.pumpWidget(MaterialApp(
theme: theme ?? ThemeData(useMaterial3: useMaterial3),
home: MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: Material(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
onPressed: () {
buttonContext = context;
},
child: const Text('Go'),
);
},
),
),
),
));
await tester.tap(find.text('Go'));
expect(buttonContext, isNotNull);
final Future<DateTime?> date = showDatePicker(
context: buttonContext,
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
currentDate: today,
selectableDayPredicate: selectableDayPredicate,
initialDatePickerMode: initialCalendarMode,
initialEntryMode: initialEntryMode,
cancelText: cancelText,
confirmText: confirmText,
errorFormatText: errorFormatText,
errorInvalidText: errorInvalidText,
fieldHintText: fieldHintText,
fieldLabelText: fieldLabelText,
helpText: helpText,
keyboardType: keyboardType,
onDatePickerModeChange: (DatePickerEntryMode value) {
currentMode = value;
},
builder: (BuildContext context, Widget? child) {
return Directionality(
textDirection: textDirection,
child: child ?? const SizedBox(),
);
},
);
await tester.pumpAndSettle(const Duration(seconds: 1));
await callback(date);
}
group('showDatePicker Dialog', () {
testWidgets('Default dialog size', (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 prepareDatePicker(tester, (Future<DateTime?> date) async {}, useMaterial3: true);
}
const Size calendarLandscapeDialogSize = Size(496.0, 346.0);
const Size calendarPortraitDialogSizeM3 = Size(328.0, 512.0);
// Test landscape layout.
await showPicker(tester, wideWindowSize);
Size dialogContainerSize = tester.getSize(find.byType(AnimatedContainer));
expect(dialogContainerSize, calendarLandscapeDialogSize);
// Close the dialog.
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
// Test portrait layout.
await showPicker(tester, narrowWindowSize);
dialogContainerSize = tester.getSize(find.byType(AnimatedContainer));
expect(dialogContainerSize, calendarPortraitDialogSizeM3);
});
testWidgets('Default dialog properties', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final Material dialogMaterial = tester.widget<Material>(
find.descendant(of: find.byType(Dialog),
matching: find.byType(Material),
).first);
expect(dialogMaterial.color, theme.colorScheme.surfaceContainerHigh);
expect(dialogMaterial.shadowColor, Colors.transparent);
expect(dialogMaterial.surfaceTintColor, Colors.transparent);
expect(dialogMaterial.elevation, 6.0);
expect(
dialogMaterial.shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))),
);
expect(dialogMaterial.clipBehavior, Clip.antiAlias);
final Dialog dialog = tester.widget<Dialog>(find.byType(Dialog));
expect(dialog.insetPadding, const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0));
}, useMaterial3: theme.useMaterial3);
});
testWidgets('Material3 uses sentence case labels', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.text('Select date'), findsOneWidget);
}, useMaterial3: true);
});
testWidgets('Cancel, confirm, and help text is used', (WidgetTester tester) async {
cancelText = 'nope';
confirmText = 'yep';
helpText = 'help';
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.text(cancelText!), findsOneWidget);
expect(find.text(confirmText!), findsOneWidget);
expect(find.text(helpText!), findsOneWidget);
});
});
testWidgets('Initial date is the default', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('OK'));
expect(await date, DateTime(2016, DateTime.january, 15));
});
});
testWidgets('Can cancel', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('CANCEL'));
expect(await date, isNull);
});
});
testWidgets('Can switch from calendar to input entry mode', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.byType(TextField), findsNothing);
await tester.tap(find.byIcon(Icons.edit));
await tester.pumpAndSettle();
expect(find.byType(TextField), findsOneWidget);
});
});
testWidgets('Can switch from input to calendar entry mode', (WidgetTester tester) async {
initialEntryMode = DatePickerEntryMode.input;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.byType(TextField), findsOneWidget);
await tester.tap(find.byIcon(Icons.calendar_today));
await tester.pumpAndSettle();
expect(find.byType(TextField), findsNothing);
});
});
testWidgets('Can not switch out of calendarOnly mode', (WidgetTester tester) async {
initialEntryMode = DatePickerEntryMode.calendarOnly;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.byType(TextField), findsNothing);
expect(find.byIcon(Icons.edit), findsNothing);
});
});
testWidgets('Can not switch out of inputOnly mode', (WidgetTester tester) async {
initialEntryMode = DatePickerEntryMode.inputOnly;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.byType(TextField), findsOneWidget);
expect(find.byIcon(Icons.calendar_today), findsNothing);
});
});
testWidgets('Switching to input mode keeps selected date', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('12'));
await tester.tap(find.byIcon(Icons.edit));
await tester.pumpAndSettle();
await tester.tap(find.text('OK'));
expect(await date, DateTime(2016, DateTime.january, 12));
});
});
testWidgets('Input only mode should validate date', (WidgetTester tester) async {
initialEntryMode = DatePickerEntryMode.inputOnly;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
// Enter text input mode and type an invalid date to get error.
await tester.enterText(find.byType(TextField), '1234567');
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
expect(find.text('Invalid format.'), findsOneWidget);
});
});
testWidgets('Switching to input mode resets input error state', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
// Enter text input mode and type an invalid date to get error.
await tester.tap(find.byIcon(Icons.edit));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), '1234567');
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
expect(find.text('Invalid format.'), findsOneWidget);
// Toggle to calendar mode and then back to input mode
await tester.tap(find.byIcon(Icons.calendar_today));
await tester.pumpAndSettle();
await tester.tap(find.byIcon(Icons.edit));
await tester.pumpAndSettle();
expect(find.text('Invalid format.'), findsNothing);
// Edit the text, the error should not be showing until ok is tapped
await tester.enterText(find.byType(TextField), '1234567');
await tester.pumpAndSettle();
expect(find.text('Invalid format.'), findsNothing);
});
});
testWidgets('builder parameter', (WidgetTester tester) async {
Widget buildFrame(TextDirection textDirection) {
return MaterialApp(
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
builder: (BuildContext context, Widget? child) {
return Directionality(
textDirection: textDirection,
child: child ?? const SizedBox(),
);
},
);
},
);
},
),
),
),
);
}
await tester.pumpWidget(buildFrame(TextDirection.ltr));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final double ltrOkRight = tester.getBottomRight(find.text('OK')).dx;
await tester.tap(find.text('OK')); // Dismiss the dialog.
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(TextDirection.rtl));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
// Verify that the time picker is being laid out RTL.
// We expect the left edge of the 'OK' button in the RTL
// layout to match the gap between right edge of the 'OK'
// button and the right edge of the 800 wide view.
expect(tester.getBottomLeft(find.text('OK')).dx, moreOrLessEquals(800 - ltrOkRight));
});
group('Barrier dismissible', () {
late _DatePickerObserver rootObserver;
setUp(() {
rootObserver = _DatePickerObserver();
});
testWidgets('Barrier is dismissible with default parameter', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () =>
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
builder: (BuildContext context,
Widget? child) => const SizedBox(),
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(rootObserver.datePickerCount, 1);
// Tap on the barrier.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle();
expect(rootObserver.datePickerCount, 0);
});
testWidgets('Barrier is not dismissible with barrierDismissible is false', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () =>
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
barrierDismissible: false,
builder: (BuildContext context,
Widget? child) => const SizedBox(),
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(rootObserver.datePickerCount, 1);
// Tap on the barrier, which shouldn't do anything this time.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle();
expect(rootObserver.datePickerCount, 1);
});
});
testWidgets('Barrier color', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () =>
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
builder: (BuildContext context,
Widget? child) => const SizedBox(),
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).color, Colors.black54);
// Dismiss the dialog.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () =>
showDatePicker(
context: context,
barrierColor: Colors.pink,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
builder: (BuildContext context,
Widget? child) => const SizedBox(),
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).color, Colors.pink);
});
testWidgets('Barrier Label', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () =>
showDatePicker(
context: context,
barrierLabel: 'Custom Label',
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
builder: (BuildContext context,
Widget? child) => const SizedBox(),
),
);
},
),
),
),
),
);
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(tester.widget<ModalBarrier>(find.byType(ModalBarrier).last).semanticsLabel, 'Custom Label');
});
testWidgets('uses nested navigator if useRootNavigator is false', (WidgetTester tester) async {
final _DatePickerObserver rootObserver = _DatePickerObserver();
final _DatePickerObserver nestedObserver = _DatePickerObserver();
await tester.pumpWidget(MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Navigator(
observers: <NavigatorObserver>[nestedObserver],
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return ElevatedButton(
onPressed: () {
showDatePicker(
context: context,
useRootNavigator: false,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
builder: (BuildContext context, Widget? child) => const SizedBox(),
);
},
child: const Text('Show Date Picker'),
);
},
);
},
),
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
expect(rootObserver.datePickerCount, 0);
expect(nestedObserver.datePickerCount, 1);
});
testWidgets('honors DialogTheme for shape and elevation', (WidgetTester tester) async {
// Test that the defaults work
const DialogTheme datePickerDefaultDialogTheme = DialogTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
elevation: 24,
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
);
},
);
},
),
),
),
);
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
final Material defaultDialogMaterial = tester.widget<Material>(find.descendant(
of: find.byType(Dialog), matching: find.byType(Material)).first);
expect(defaultDialogMaterial.shape, datePickerDefaultDialogTheme.shape);
expect(defaultDialogMaterial.elevation, datePickerDefaultDialogTheme.elevation);
// Test that it honors ThemeData.dialogTheme settings
const DialogTheme customDialogTheme = DialogTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(40.0)),
),
elevation: 50,
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.fallback(useMaterial3: false).copyWith(dialogTheme: customDialogTheme),
home: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
);
},
);
},
),
),
),
);
await tester.pump(); // start theme animation
await tester.pump(const Duration(seconds: 5)); // end theme animation
final Material themeDialogMaterial = tester.widget<Material>(find.descendant(of: find.byType(Dialog), matching: find.byType(Material)).first);
expect(themeDialogMaterial.shape, customDialogTheme.shape);
expect(themeDialogMaterial.elevation, customDialogTheme.elevation);
});
testWidgets('OK Cancel button layout', (WidgetTester tester) async {
Widget buildFrame(TextDirection textDirection) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Center(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('X'),
onPressed: () {
showDatePicker(
context: context,
initialDate: DateTime(2016, DateTime.january, 15),
firstDate:DateTime(2001),
lastDate: DateTime(2031, DateTime.december, 31),
builder: (BuildContext context, Widget? child) {
return Directionality(
textDirection: textDirection,
child: child ?? const SizedBox(),
);
},
);
},
);
},
),
),
),
);
}
// Default landscape layout.
await tester.pumpWidget(buildFrame(TextDirection.ltr));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(tester.getBottomRight(find.text('OK')).dx, 622);
expect(tester.getBottomLeft(find.text('OK')).dx, 594);
expect(tester.getBottomRight(find.text('CANCEL')).dx, 560);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(TextDirection.rtl));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(tester.getBottomRight(find.text('OK')).dx, 206);
expect(tester.getBottomLeft(find.text('OK')).dx, 178);
expect(tester.getBottomRight(find.text('CANCEL')).dx, 324);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
// Portrait layout.
addTearDown(tester.view.reset);
tester.view.physicalSize = const Size(900, 1200);
await tester.pumpWidget(buildFrame(TextDirection.ltr));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(tester.getBottomRight(find.text('OK')).dx, 258);
expect(tester.getBottomLeft(find.text('OK')).dx, 230);
expect(tester.getBottomRight(find.text('CANCEL')).dx, 196);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(TextDirection.rtl));
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(tester.getBottomRight(find.text('OK')).dx, 70);
expect(tester.getBottomLeft(find.text('OK')).dx, 42);
expect(tester.getBottomRight(find.text('CANCEL')).dx, 188);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
});
testWidgets('honors switchToInputEntryModeIcon', (WidgetTester tester) async {
Widget buildApp({bool? useMaterial3, Icon? switchToInputEntryModeIcon}) {
return MaterialApp(
theme: ThemeData(
useMaterial3: useMaterial3 ?? false,
),
home: Material(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('Click X'),
onPressed: () {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
switchToInputEntryModeIcon: switchToInputEntryModeIcon,
);
},
);
},
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.edit), findsOneWidget);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
await tester.pumpWidget(buildApp(useMaterial3: true));
await tester.pumpAndSettle();
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.edit_outlined), findsOneWidget);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
await tester.pumpWidget(
buildApp(
switchToInputEntryModeIcon: const Icon(Icons.keyboard),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.keyboard), findsOneWidget);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
});
testWidgets('honors switchToCalendarEntryModeIcon', (WidgetTester tester) async {
Widget buildApp({bool? useMaterial3, Icon? switchToCalendarEntryModeIcon}) {
return MaterialApp(
theme: ThemeData(
useMaterial3: useMaterial3 ?? false,
),
home: Material(
child: Builder(
builder: (BuildContext context) {
return ElevatedButton(
child: const Text('Click X'),
onPressed: () {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
switchToCalendarEntryModeIcon: switchToCalendarEntryModeIcon,
initialEntryMode: DatePickerEntryMode.input,
);
},
);
},
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.calendar_today), findsOneWidget);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
await tester.pumpWidget(buildApp(useMaterial3: true));
await tester.pumpAndSettle();
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.calendar_today), findsOneWidget);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
await tester.pumpWidget(
buildApp(
switchToCalendarEntryModeIcon: const Icon(Icons.favorite),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byType(ElevatedButton));
await tester.pumpAndSettle();
expect(find.byIcon(Icons.favorite), findsOneWidget);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
});
});
group('Calendar mode', () {
testWidgets('Default Calendar mode layout (Landscape)', (WidgetTester tester) async {
final Finder helpText = find.text('Select date');
final Finder headerText = find.text('Fri, Jan 15');
final Finder subHeaderText = find.text('January 2016');
final Finder cancelButtonText = find.text('Cancel');
final Finder okButtonText = find.text('OK');
const EdgeInsets insetPadding = EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0);
tester.view.physicalSize = wideWindowSize;
addTearDown(tester.view.reset);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Material(
child: DatePickerDialog(
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
),
),
));
expect(helpText, findsOneWidget);
expect(headerText, findsOneWidget);
expect(subHeaderText, findsOneWidget);
expect(cancelButtonText, findsOneWidget);
expect(okButtonText, findsOneWidget);
// Test help text position.
final Offset dialogTopLeft = tester.getTopLeft(find.byType(AnimatedContainer));
final Offset helpTextTopLeft = tester.getTopLeft(helpText);
expect(helpTextTopLeft.dx, dialogTopLeft.dx + (insetPadding.horizontal / 2));
expect(helpTextTopLeft.dy, dialogTopLeft.dy + 16.0);
// Test header text position.
final Offset headerTextTopLeft = tester.getTopLeft(headerText);
final Offset helpTextBottomLeft = tester.getBottomLeft(helpText);
expect(headerTextTopLeft.dx, dialogTopLeft.dx + (insetPadding.horizontal / 2));
expect(headerTextTopLeft.dy, helpTextBottomLeft.dy + 16.0);
// Test switch button position.
final Finder switchButtonM3 = find.widgetWithIcon(IconButton, Icons.edit_outlined);
final Offset switchButtonTopLeft = tester.getTopLeft(switchButtonM3);
final Offset switchButtonBottomLeft = tester.getBottomLeft(switchButtonM3);
final Offset headerTextBottomLeft = tester.getBottomLeft(headerText);
final Offset dialogBottomLeft = tester.getBottomLeft(find.byType(AnimatedContainer));
expect(switchButtonTopLeft.dx, dialogTopLeft.dx + 8.0);
expect(switchButtonTopLeft.dy, headerTextBottomLeft.dy);
expect(switchButtonBottomLeft.dx, dialogTopLeft.dx + 8.0);
expect(switchButtonBottomLeft.dy, dialogBottomLeft.dy - 6.0);
// Test vertical divider position.
final Finder divider = find.byType(VerticalDivider);
final Offset dividerTopLeft = tester.getTopLeft(divider);
final Offset headerTextTopRight = tester.getTopRight(headerText);
expect(dividerTopLeft.dx, headerTextTopRight.dx + 16.0);
expect(dividerTopLeft.dy, dialogTopLeft.dy);
// Test sub header text position.
final Offset subHeaderTextTopLeft = tester.getTopLeft(subHeaderText);
final Offset dividerTopRight = tester.getTopRight(divider);
expect(subHeaderTextTopLeft.dx, dividerTopRight.dx + 24.0);
if (!kIsWeb || isSkiaWeb) { // https://github.com/flutter/flutter/issues/99933
expect(subHeaderTextTopLeft.dy, dialogTopLeft.dy + 16.0);
}
// Test sub header icon position.
final Finder subHeaderIcon = find.byIcon(Icons.arrow_drop_down);
final Offset subHeaderIconTopLeft = tester.getTopLeft(subHeaderIcon);
final Offset subHeaderTextTopRight = tester.getTopRight(subHeaderText);
expect(subHeaderIconTopLeft.dx, subHeaderTextTopRight.dx);
expect(subHeaderIconTopLeft.dy, dialogTopLeft.dy + 14.0);
// Test calendar page view position.
final Finder calendarPageView = find.byType(PageView);
final Offset calendarPageViewTopLeft = tester.getTopLeft(calendarPageView);
final Offset subHeaderTextBottomLeft = tester.getBottomLeft(subHeaderText);
expect(calendarPageViewTopLeft.dx, dividerTopRight.dx);
if (!kIsWeb || isSkiaWeb) { // https://github.com/flutter/flutter/issues/99933
expect(calendarPageViewTopLeft.dy, subHeaderTextBottomLeft.dy + 16.0);
}
// Test month navigation icons position.
final Finder previousMonthButton = find.widgetWithIcon(IconButton, Icons.chevron_left);
final Finder nextMonthButton = find.widgetWithIcon(IconButton, Icons.chevron_right);
final Offset previousMonthButtonTopRight = tester.getTopRight(previousMonthButton);
final Offset nextMonthButtonTopRight = tester.getTopRight(nextMonthButton);
final Offset dialogTopRight = tester.getTopRight(find.byType(AnimatedContainer));
expect(nextMonthButtonTopRight.dx, dialogTopRight.dx - 4.0);
expect(nextMonthButtonTopRight.dy, dialogTopRight.dy + 2.0);
expect(previousMonthButtonTopRight.dx, nextMonthButtonTopRight.dx - 48.0);
// Test action buttons position.
final Offset dialogBottomRight = tester.getBottomRight(find.byType(AnimatedContainer));
final Offset okButtonTopRight = tester.getTopRight(find.widgetWithText(TextButton, 'OK'));
final Offset cancelButtonTopRight = tester.getTopRight(find.widgetWithText(TextButton, 'Cancel'));
final Offset calendarPageViewBottomRight = tester.getBottomRight(calendarPageView);
expect(okButtonTopRight.dx, dialogBottomRight.dx - 8);
expect(okButtonTopRight.dy, calendarPageViewBottomRight.dy + 2);
final Offset okButtonTopLeft = tester.getTopLeft(find.widgetWithText(TextButton, 'OK'));
expect(cancelButtonTopRight.dx, okButtonTopLeft.dx - 8);
});
testWidgets('Default Calendar mode layout (Portrait)', (WidgetTester tester) async {
final Finder helpText = find.text('Select date');
final Finder headerText = find.text('Fri, Jan 15');
final Finder subHeaderText = find.text('January 2016');
final Finder cancelButtonText = find.text('Cancel');
final Finder okButtonText = find.text('OK');
tester.view.physicalSize = narrowWindowSize;
addTearDown(tester.view.reset);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Material(
child: DatePickerDialog(
initialDate: initialDate,
firstDate: firstDate,
lastDate: lastDate,
),
),
));
expect(helpText, findsOneWidget);
expect(headerText, findsOneWidget);
expect(subHeaderText, findsOneWidget);
expect(cancelButtonText, findsOneWidget);
expect(okButtonText, findsOneWidget);
// Test help text position.
final Offset dialogTopLeft = tester.getTopLeft(find.byType(AnimatedContainer));
final Offset helpTextTopLeft = tester.getTopLeft(helpText);
expect(helpTextTopLeft.dx, dialogTopLeft.dx + 24.0);
expect(helpTextTopLeft.dy, dialogTopLeft.dy + 16.0);
// Test header text position
final Offset headerTextTextTopLeft = tester.getTopLeft(headerText);
final Offset helpTextBottomLeft = tester.getBottomLeft(helpText);
expect(headerTextTextTopLeft.dx, dialogTopLeft.dx + 24.0);
if (!kIsWeb || isSkiaWeb) { // https://github.com/flutter/flutter/issues/99933
expect(headerTextTextTopLeft.dy, helpTextBottomLeft.dy + 28.0);
}
// Test switch button position.
final Finder switchButtonM3 = find.widgetWithIcon(IconButton, Icons.edit_outlined);
final Offset switchButtonTopRight = tester.getTopRight(switchButtonM3);
final Offset dialogTopRight = tester.getTopRight(find.byType(AnimatedContainer));
expect(switchButtonTopRight.dx, dialogTopRight.dx - 12.0);
expect(switchButtonTopRight.dy, headerTextTextTopLeft.dy - 4.0);
// Test horizontal divider position.
final Finder divider = find.byType(Divider);
final Offset dividerTopLeft = tester.getTopLeft(divider);
final Offset headerTextBottomLeft = tester.getBottomLeft(headerText);
expect(dividerTopLeft.dx, dialogTopLeft.dx);
expect(dividerTopLeft.dy, headerTextBottomLeft.dy + 16.0);
// Test subHeaderText position.
final Offset subHeaderTextTopLeft = tester.getTopLeft(subHeaderText);
final Offset dividerBottomLeft = tester.getBottomLeft(divider);
expect(subHeaderTextTopLeft.dx, dialogTopLeft.dx + 24.0);
if (!kIsWeb || isSkiaWeb) { // https://github.com/flutter/flutter/issues/99933
expect(subHeaderTextTopLeft.dy, dividerBottomLeft.dy + 16.0);
}
// Test sub header icon position.
final Finder subHeaderIcon = find.byIcon(Icons.arrow_drop_down);
final Offset subHeaderIconTopLeft = tester.getTopLeft(subHeaderIcon);
final Offset subHeaderTextTopRight = tester.getTopRight(subHeaderText);
expect(subHeaderIconTopLeft.dx, subHeaderTextTopRight.dx);
expect(subHeaderIconTopLeft.dy, dividerBottomLeft.dy + 14.0);
// Test month navigation icons position.
final Finder previousMonthButton = find.widgetWithIcon(IconButton, Icons.chevron_left);
final Finder nextMonthButton = find.widgetWithIcon(IconButton, Icons.chevron_right);
final Offset previousMonthButtonTopRight = tester.getTopRight(previousMonthButton);
final Offset nextMonthButtonTopRight = tester.getTopRight(nextMonthButton);
expect(nextMonthButtonTopRight.dx, dialogTopRight.dx - 4.0);
expect(nextMonthButtonTopRight.dy, dividerBottomLeft.dy + 2.0);
expect(previousMonthButtonTopRight.dx, nextMonthButtonTopRight.dx - 48.0);
// Test calendar page view position.
final Finder calendarPageView = find.byType(PageView);
final Offset calendarPageViewTopLeft = tester.getTopLeft(calendarPageView);
final Offset subHeaderTextBottomLeft = tester.getBottomLeft(subHeaderText);
expect(calendarPageViewTopLeft.dx, dialogTopLeft.dx);
if (!kIsWeb || isSkiaWeb) { // https://github.com/flutter/flutter/issues/99933
expect(calendarPageViewTopLeft.dy, subHeaderTextBottomLeft.dy + 16.0);
}
// Test action buttons position.
final Offset dialogBottomRight = tester.getBottomRight(find.byType(AnimatedContainer));
final Offset okButtonTopRight = tester.getTopRight(find.widgetWithText(TextButton, 'OK'));
final Offset cancelButtonTopRight = tester.getTopRight(find.widgetWithText(TextButton, 'Cancel'));
final Offset calendarPageViewBottomRight = tester.getBottomRight(calendarPageView);
final Offset okButtonTopLeft = tester.getTopLeft(find.widgetWithText(TextButton, 'OK'));
expect(okButtonTopRight.dx, dialogBottomRight.dx - 8);
expect(okButtonTopRight.dy, calendarPageViewBottomRight.dy + 2);
expect(cancelButtonTopRight.dx, okButtonTopLeft.dx - 8);
});
testWidgets('Can select a day', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('12'));
await tester.tap(find.text('OK'));
expect(await date, equals(DateTime(2016, DateTime.january, 12)));
});
});
testWidgets('Can select a month', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(previousMonthIcon);
await tester.pumpAndSettle(const Duration(seconds: 1));
await tester.tap(find.text('25'));
await tester.tap(find.text('OK'));
expect(await date, DateTime(2015, DateTime.december, 25));
});
});
testWidgets('Can select a year', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('January 2016')); // Switch to year mode.
await tester.pump();
await tester.tap(find.text('2018'));
await tester.pump();
expect(find.text('January 2018'), findsOneWidget);
});
});
testWidgets('Can select a day with no initial date', (WidgetTester tester) async {
initialDate = null;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('12'));
await tester.tap(find.text('OK'));
expect(await date, equals(DateTime(2016, DateTime.january, 12)));
});
});
testWidgets('Can select a month with no initial date', (WidgetTester tester) async {
initialDate = null;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(previousMonthIcon);
await tester.pumpAndSettle(const Duration(seconds: 1));
await tester.tap(find.text('25'));
await tester.tap(find.text('OK'));
expect(await date, DateTime(2015, DateTime.december, 25));
});
});
testWidgets('Can select a year with no initial date', (WidgetTester tester) async {
initialDate = null;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('January 2016')); // Switch to year mode.
await tester.pump();
await tester.tap(find.text('2018'));
await tester.pump();
expect(find.text('January 2018'), findsOneWidget);
});
});
testWidgets('Selecting date does not change displayed month', (WidgetTester tester) async {
initialDate = DateTime(2020, DateTime.march, 15);
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle(const Duration(seconds: 1));
expect(find.text('April 2020'), findsOneWidget);
await tester.tap(find.text('25'));
await tester.pumpAndSettle();
expect(find.text('April 2020'), findsOneWidget);
// There isn't a 31 in April so there shouldn't be one if it is showing April
expect(find.text('31'), findsNothing);
});
});
testWidgets('Changing year does change selected date', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('January 2016'));
await tester.pump();
await tester.tap(find.text('2018'));
await tester.pump();
await tester.tap(find.text('OK'));
expect(await date, equals(DateTime(2018, DateTime.january, 15)));
});
});
testWidgets('Changing year does not change the month', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle();
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle();
await tester.tap(find.text('March 2016'));
await tester.pumpAndSettle();
await tester.tap(find.text('2018'));
await tester.pumpAndSettle();
expect(find.text('March 2018'), findsOneWidget);
});
});
testWidgets('Can select a year and then a day', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('January 2016')); // Switch to year mode.
await tester.pump();
await tester.tap(find.text('2017'));
await tester.pump();
await tester.tap(find.text('19'));
await tester.tap(find.text('OK'));
expect(await date, DateTime(2017, DateTime.january, 19));
});
});
testWidgets('Current year is visible in year picker', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('January 2016')); // Switch to year mode.
await tester.pump();
expect(find.text('2016'), findsOneWidget);
});
});
testWidgets('Cannot select a day outside bounds', (WidgetTester tester) async {
initialDate = DateTime(2017, DateTime.january, 15);
firstDate = initialDate!;
lastDate = initialDate!;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
// Earlier than firstDate. Should be ignored.
await tester.tap(find.text('10'));
// Later than lastDate. Should be ignored.
await tester.tap(find.text('20'));
await tester.tap(find.text('OK'));
// We should still be on the initial date.
expect(await date, initialDate);
});
});
testWidgets('Cannot select a month past last date', (WidgetTester tester) async {
initialDate = DateTime(2017, DateTime.january, 15);
firstDate = initialDate!;
lastDate = DateTime(2017, DateTime.february, 20);
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(nextMonthIcon);
await tester.pumpAndSettle(const Duration(seconds: 1));
// Shouldn't be possible to keep going into March.
expect(nextMonthIcon, findsNothing);
});
});
testWidgets('Cannot select a month before first date', (WidgetTester tester) async {
initialDate = DateTime(2017, DateTime.january, 15);
firstDate = DateTime(2016, DateTime.december, 10);
lastDate = initialDate!;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(previousMonthIcon);
await tester.pumpAndSettle(const Duration(seconds: 1));
// Shouldn't be possible to keep going into November.
expect(previousMonthIcon, findsNothing);
});
});
testWidgets('Cannot select disabled year', (WidgetTester tester) async {
initialDate = DateTime(2018, DateTime.july, 4);
firstDate = DateTime(2018, DateTime.june, 9);
lastDate = DateTime(2018, DateTime.december, 15);
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('July 2018')); // Switch to year mode.
await tester.pumpAndSettle();
await tester.tap(find.text('2016')); // Disabled, doesn't change the year.
await tester.pumpAndSettle();
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
expect(await date, DateTime(2018, DateTime.july, 4));
});
});
testWidgets('Selecting firstDate year respects firstDate', (WidgetTester tester) async {
initialDate = DateTime(2018, DateTime.may, 4);
firstDate = DateTime(2016, DateTime.june, 9);
lastDate = DateTime(2019, DateTime.january, 15);
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('May 2018'));
await tester.pumpAndSettle();
await tester.tap(find.text('2016'));
await tester.pumpAndSettle();
// Month should be clamped to June as the range starts at June 2016
expect(find.text('June 2016'), findsOneWidget);
});
});
testWidgets('Selecting lastDate year respects lastDate', (WidgetTester tester) async {
initialDate = DateTime(2018, DateTime.may, 4);
firstDate = DateTime(2016, DateTime.june, 9);
lastDate = DateTime(2019, DateTime.january, 15);
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('May 2018'));
await tester.pumpAndSettle();
await tester.tap(find.text('2019'));
await tester.pumpAndSettle();
// Month should be clamped to January as the range ends at January 2019
expect(find.text('January 2019'), findsOneWidget);
});
});
testWidgets('Only predicate days are selectable', (WidgetTester tester) async {
initialDate = DateTime(2017, DateTime.january, 16);
firstDate = DateTime(2017, DateTime.january, 10);
lastDate = DateTime(2017, DateTime.january, 20);
selectableDayPredicate = (DateTime day) => day.day.isEven;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('13')); // Odd, doesn't work.
await tester.tap(find.text('10')); // Even, works.
await tester.tap(find.text('17')); // Odd, doesn't work.
await tester.tap(find.text('OK'));
expect(await date, DateTime(2017, DateTime.january, 10));
});
});
testWidgets('Can select initial calendar picker mode', (WidgetTester tester) async {
initialDate = DateTime(2014, DateTime.january, 15);
initialCalendarMode = DatePickerMode.year;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.pump();
// 2018 wouldn't be available if the year picker wasn't showing.
// The initial current year is 2014.
await tester.tap(find.text('2018'));
await tester.pump();
expect(find.text('January 2018'), findsOneWidget);
});
});
testWidgets('currentDate is highlighted', (WidgetTester tester) async {
today = DateTime(2016, 1, 2);
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.pump();
const Color todayColor = Color(0xff2196f3); // default primary color
expect(
Material.of(tester.element(find.text('2'))),
// The current day should be painted with a circle outline
paints..circle(color: todayColor, style: PaintingStyle.stroke, strokeWidth: 1.0),
);
});
});
testWidgets('Date picker dayOverlayColor resolves pressed state', (WidgetTester tester) async {
today = DateTime(2023, 5, 4);
final ThemeData theme = ThemeData();
final bool material3 = theme.useMaterial3;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.pump();
// Hovered.
final Offset center = tester.getCenter(find.text('30'));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.mouse,
);
await gesture.addPointer();
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.text('30'))),
paints..circle(color: material3 ? theme.colorScheme.onSurfaceVariant.withOpacity(0.08) : theme.colorScheme.onSurfaceVariant.withOpacity(0.08)),
);
// Highlighted (pressed).
await gesture.down(center);
await tester.pumpAndSettle();
expect(
Material.of(tester.element(find.text('30'))),
paints..circle()..circle(color: material3 ? theme.colorScheme.onSurfaceVariant.withOpacity(0.1) : theme.colorScheme.onSurfaceVariant.withOpacity(0.12))
);
await gesture.up();
await tester.pumpAndSettle();
}, theme: theme);
});
testWidgets('Selecting date does not switch picker to year selection', (WidgetTester tester) async {
initialDate = DateTime(2020, DateTime.may, 10);
initialCalendarMode = DatePickerMode.year;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.pump();
await tester.tap(find.text('2017'));
await tester.pump();
expect(find.text('May 2017'), findsOneWidget);
await tester.tap(find.text('10'));
await tester.pump();
expect(find.text('May 2017'), findsOneWidget);
expect(find.text('2017'), findsNothing);
});
});
});
group('Input mode', () {
setUp(() {
firstDate = DateTime(2015);
lastDate = DateTime(2017, DateTime.december, 31);
initialDate = DateTime(2016, DateTime.january, 15);
initialEntryMode = DatePickerEntryMode.input;
});
testWidgets('Default InputDecoration', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final InputDecoration decoration = tester.widget<TextField>(
find.byType(TextField)).decoration!;
expect(decoration.border, const OutlineInputBorder());
expect(decoration.filled, false);
expect(decoration.hintText, 'mm/dd/yyyy');
expect(decoration.labelText, 'Enter Date');
expect(decoration.errorText, null);
}, useMaterial3: true);
});
testWidgets('Initial entry mode is used', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.byType(TextField), findsOneWidget);
});
});
testWidgets('Hint, label, and help text is used', (WidgetTester tester) async {
cancelText = 'nope';
confirmText = 'yep';
fieldHintText = 'hint';
fieldLabelText = 'label';
helpText = 'help';
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.text(cancelText!), findsOneWidget);
expect(find.text(confirmText!), findsOneWidget);
expect(find.text(fieldHintText!), findsOneWidget);
expect(find.text(fieldLabelText!), findsOneWidget);
expect(find.text(helpText!), findsOneWidget);
});
});
testWidgets('KeyboardType is used', (WidgetTester tester) async {
keyboardType = TextInputType.text;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final TextField field = textField(tester);
expect(field.keyboardType, TextInputType.text);
});
});
testWidgets('Initial date is the default', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('OK'));
expect(await date, DateTime(2016, DateTime.january, 15));
});
});
testWidgets('Can toggle to calendar entry mode', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.byType(TextField), findsOneWidget);
await tester.tap(find.byIcon(Icons.calendar_today));
await tester.pumpAndSettle();
expect(find.byType(TextField), findsNothing);
});
});
testWidgets('Toggle to calendar mode keeps selected date', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final TextField field = textField(tester);
field.controller!.clear();
await tester.enterText(find.byType(TextField), '12/25/2016');
await tester.tap(find.byIcon(Icons.calendar_today));
await tester.pumpAndSettle();
await tester.tap(find.text('OK'));
expect(await date, DateTime(2016, DateTime.december, 25));
});
});
testWidgets('Entered text returns date', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final TextField field = textField(tester);
field.controller!.clear();
await tester.enterText(find.byType(TextField), '12/25/2016');
await tester.tap(find.text('OK'));
expect(await date, DateTime(2016, DateTime.december, 25));
});
});
testWidgets('Too short entered text shows error', (WidgetTester tester) async {
errorFormatText = 'oops';
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final TextField field = textField(tester);
field.controller!.clear();
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), '1225');
expect(find.text(errorFormatText!), findsNothing);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
expect(find.text(errorFormatText!), findsOneWidget);
});
});
testWidgets('Bad format entered text shows error', (WidgetTester tester) async {
errorFormatText = 'oops';
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final TextField field = textField(tester);
field.controller!.clear();
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), '20 days, 3 months, 2003');
expect(find.text('20 days, 3 months, 2003'), findsOneWidget);
expect(find.text(errorFormatText!), findsNothing);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
expect(find.text(errorFormatText!), findsOneWidget);
});
});
testWidgets('Invalid entered text shows error', (WidgetTester tester) async {
errorInvalidText = 'oops';
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final TextField field = textField(tester);
field.controller!.clear();
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), '08/10/1969');
expect(find.text(errorInvalidText!), findsNothing);
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
expect(find.text(errorInvalidText!), findsOneWidget);
});
});
testWidgets('Invalid entered text shows error on autovalidate', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/126397.
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final TextField field = textField(tester);
field.controller!.clear();
// Enter some text to trigger autovalidate.
await tester.enterText(find.byType(TextField), 'xyz');
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
// Invalid format validation error should be shown.
expect(find.text('Invalid format.'), findsOneWidget);
// Clear the text.
field.controller!.clear();
// Enter an invalid date that is too long while autovalidate is still on.
await tester.enterText(find.byType(TextField), '10/05/2023666777889');
await tester.pump();
// Invalid format validation error should be shown.
expect(find.text('Invalid format.'), findsOneWidget);
// Should not throw an exception.
expect(tester.takeException(), null);
});
});
// This is a regression test for https://github.com/flutter/flutter/issues/131989.
testWidgets('Dialog contents do not overflow when resized during orientation change',
(WidgetTester tester) async {
addTearDown(tester.view.reset);
// Initial window size is wide for landscape mode.
tester.view.physicalSize = wideWindowSize;
tester.view.devicePixelRatio = 1.0;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
// Change window size to narrow for portrait mode.
tester.view.physicalSize = narrowWindowSize;
await tester.pump();
expect(tester.takeException(), null);
});
});
// This is a regression test for https://github.com/flutter/flutter/issues/139120.
testWidgets('Dialog contents are visible - textScaler 0.88, 1.0, 2.0',
(WidgetTester tester) async {
addTearDown(tester.view.reset);
tester.view.physicalSize = const Size(400, 800);
tester.view.devicePixelRatio = 1.0;
final List<double> scales = <double>[0.88, 1.0, 2.0];
for (final double scale in scales) {
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: MediaQueryData(textScaler: TextScaler.linear(scale)),
child: Material(
child: DatePickerDialog(
firstDate: DateTime(2001),
lastDate: DateTime(2031, DateTime.december, 31),
initialDate: DateTime(2016, DateTime.january, 15),
initialEntryMode: DatePickerEntryMode.input,
),
),
),
),
);
await tester.pumpAndSettle();
await expectLater(find.byType(Dialog), matchesGoldenFile('date_picker.dialog.contents.visible.$scale.png'));
}
});
});
group('Semantics', () {
testWidgets('calendar mode', (WidgetTester tester) async {
final SemanticsHandle semantics = tester.ensureSemantics();
await prepareDatePicker(tester, (Future<DateTime?> date) async {
// Header
expect(tester.getSemantics(find.text('SELECT DATE')), matchesSemantics(
label: 'SELECT DATE\nFri, Jan 15',
));
expect(tester.getSemantics(find.text('3')), matchesSemantics(
label: '3, Sunday, January 3, 2016, Today',
isButton: true,
hasTapAction: true,
isFocusable: true,
));
// Input mode toggle button
expect(tester.getSemantics(switchToInputIcon), matchesSemantics(
tooltip: 'Switch to input',
isButton: true,
hasTapAction: true,
isEnabled: true,
hasEnabledState: true,
isFocusable: true,
));
// The semantics of the CalendarDatePicker are tested in its tests.
// Ok/Cancel buttons
expect(tester.getSemantics(find.text('OK')), matchesSemantics(
label: 'OK',
isButton: true,
hasTapAction: true,
isEnabled: true,
hasEnabledState: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('CANCEL')), matchesSemantics(
label: 'CANCEL',
isButton: true,
hasTapAction: true,
isEnabled: true,
hasEnabledState: true,
isFocusable: true,
));
});
semantics.dispose();
});
testWidgets('input mode', (WidgetTester tester) async {
// Fill the clipboard so that the Paste option is available in the text
// selection menu.
final MockClipboard mockClipboard = MockClipboard();
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
await Clipboard.setData(const ClipboardData(text: 'Clipboard data'));
addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null));
final SemanticsHandle semantics = tester.ensureSemantics();
initialEntryMode = DatePickerEntryMode.input;
await prepareDatePicker(tester, (Future<DateTime?> date) async {
// Header
expect(tester.getSemantics(find.text('SELECT DATE')), matchesSemantics(
label: 'SELECT DATE\nFri, Jan 15',
));
// Input mode toggle button
expect(tester.getSemantics(switchToCalendarIcon), matchesSemantics(
tooltip: 'Switch to calendar',
isButton: true,
hasTapAction: true,
isEnabled: true,
hasEnabledState: true,
isFocusable: true,
));
expect(tester.getSemantics(find.byType(EditableText)), matchesSemantics(
label: 'Enter Date',
isEnabled: true,
hasEnabledState: true,
isTextField: true,
isFocused: true,
value: '01/15/2016',
hasTapAction: true,
hasSetTextAction: true,
hasSetSelectionAction: true,
hasCopyAction: true,
hasCutAction: true,
hasPasteAction: true,
hasMoveCursorBackwardByCharacterAction: true,
hasMoveCursorBackwardByWordAction: true,
));
// Ok/Cancel buttons
expect(tester.getSemantics(find.text('OK')), matchesSemantics(
label: 'OK',
isButton: true,
hasTapAction: true,
isEnabled: true,
hasEnabledState: true,
isFocusable: true,
));
expect(tester.getSemantics(find.text('CANCEL')), matchesSemantics(
label: 'CANCEL',
isButton: true,
hasTapAction: true,
isEnabled: true,
hasEnabledState: true,
isFocusable: true,
));
});
semantics.dispose();
});
});
group('Keyboard navigation', () {
testWidgets('Can toggle to calendar entry mode', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.byType(TextField), findsNothing);
// Navigate to the entry toggle button and activate it
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should be in the input mode
expect(find.byType(TextField), findsOneWidget);
});
});
testWidgets('Can toggle to year mode', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.text('2016'), findsNothing);
// Navigate to the year selector and activate it
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// The years should be visible
expect(find.text('2016'), findsOneWidget);
});
});
testWidgets('Can navigate next/previous months', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
expect(find.text('January 2016'), findsOneWidget);
// Navigate to the previous month button and activate it twice
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should be showing Nov 2015
expect(find.text('November 2015'), findsOneWidget);
// Navigate to the next month button and activate it four times
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should be on Mar 2016
expect(find.text('March 2016'), findsOneWidget);
});
});
testWidgets('Can navigate date grid with arrow keys', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
// Navigate to the grid
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
// Navigate from Jan 15 to Jan 18 with arrow keys
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pumpAndSettle();
// Activate it
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Navigate out of the grid and to the OK button
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
// Activate OK
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should have selected Jan 18
expect(await date, DateTime(2016, DateTime.january, 18));
});
});
testWidgets('Navigating with arrow keys scrolls months', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
// Navigate to the grid
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
// Navigate from Jan 15 to Dec 31 with arrow keys
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pumpAndSettle();
// Should have scrolled to Dec 2015
expect(find.text('December 2015'), findsOneWidget);
// Navigate from Dec 31 to Nov 26 with arrow keys
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pumpAndSettle();
// Should have scrolled to Nov 2015
expect(find.text('November 2015'), findsOneWidget);
// Activate it
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Navigate out of the grid and to the OK button
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
// Activate OK
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should have selected Jan 18
expect(await date, DateTime(2015, DateTime.november, 26));
});
});
testWidgets('RTL text direction reverses the horizontal arrow key navigation', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
// Navigate to the grid
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
// Navigate from Jan 15 to 19 with arrow keys
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
await tester.pumpAndSettle();
// Activate it
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Navigate out of the grid and to the OK button
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
// Activate OK
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
// Should have selected Jan 18
expect(await date, DateTime(2016, DateTime.january, 19));
}, textDirection: TextDirection.rtl);
});
});
group('Screen configurations', () {
// Test various combinations of screen sizes, orientations and text scales
// to ensure the layout doesn't overflow and cause an exception to be thrown.
// Regression tests for https://github.com/flutter/flutter/issues/21383
// Regression tests for https://github.com/flutter/flutter/issues/19744
// Regression tests for https://github.com/flutter/flutter/issues/17745
// Common screen size roughly based on a Pixel 1
const Size kCommonScreenSizePortrait = Size(1070, 1770);
const Size kCommonScreenSizeLandscape = Size(1770, 1070);
// Small screen size based on a LG K130
const Size kSmallScreenSizePortrait = Size(320, 521);
const Size kSmallScreenSizeLandscape = Size(521, 320);
Future<void> showPicker(WidgetTester tester, Size size, [double textScaleFactor = 1.0]) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.text('OK'));
});
await tester.pumpAndSettle();
}
testWidgets('common screen size - portrait', (WidgetTester tester) async {
await showPicker(tester, kCommonScreenSizePortrait);
expect(tester.takeException(), isNull);
});
testWidgets('common screen size - landscape', (WidgetTester tester) async {
await showPicker(tester, kCommonScreenSizeLandscape);
expect(tester.takeException(), isNull);
});
testWidgets('common screen size - portrait - textScale 1.3', (WidgetTester tester) async {
await showPicker(tester, kCommonScreenSizePortrait, 1.3);
expect(tester.takeException(), isNull);
});
testWidgets('common screen size - landscape - textScale 1.3', (WidgetTester tester) async {
await showPicker(tester, kCommonScreenSizeLandscape, 1.3);
expect(tester.takeException(), isNull);
});
testWidgets('small screen size - portrait', (WidgetTester tester) async {
await showPicker(tester, kSmallScreenSizePortrait);
expect(tester.takeException(), isNull);
});
testWidgets('small screen size - landscape', (WidgetTester tester) async {
await showPicker(tester, kSmallScreenSizeLandscape);
expect(tester.takeException(), isNull);
});
testWidgets('small screen size - portrait -textScale 1.3', (WidgetTester tester) async {
await showPicker(tester, kSmallScreenSizePortrait, 1.3);
expect(tester.takeException(), isNull);
});
testWidgets('small screen size - landscape - textScale 1.3', (WidgetTester tester) async {
await showPicker(tester, kSmallScreenSizeLandscape, 1.3);
expect(tester.takeException(), isNull);
});
});
group('showDatePicker avoids overlapping display features', () {
testWidgets('positioning with anchorPoint', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
builder: (BuildContext context, Widget? child) {
return MediaQuery(
// Display has a vertical hinge down the middle
data: const MediaQueryData(
size: Size(800, 600),
displayFeatures: <DisplayFeature>[
DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
],
),
child: child!,
);
},
home: const Center(child: Text('Test')),
),
);
final BuildContext context = tester.element(find.text('Test'));
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
anchorPoint: const Offset(1000, 0),
);
await tester.pumpAndSettle();
// Should take the right side of the screen
expect(tester.getTopLeft(find.byType(DatePickerDialog)), const Offset(410.0, 0.0));
expect(tester.getBottomRight(find.byType(DatePickerDialog)), const Offset(800.0, 600.0));
});
testWidgets('positioning with Directionality', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
builder: (BuildContext context, Widget? child) {
return MediaQuery(
// Display has a vertical hinge down the middle
data: const MediaQueryData(
size: Size(800, 600),
displayFeatures: <DisplayFeature>[
DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
],
),
child: Directionality(
textDirection: TextDirection.rtl,
child: child!,
),
);
},
home: const Center(child: Text('Test')),
),
);
final BuildContext context = tester.element(find.text('Test'));
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
);
await tester.pumpAndSettle();
// By default it should place the dialog on the right screen
expect(tester.getTopLeft(find.byType(DatePickerDialog)), const Offset(410.0, 0.0));
expect(tester.getBottomRight(find.byType(DatePickerDialog)), const Offset(800.0, 600.0));
});
testWidgets('positioning with defaults', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
builder: (BuildContext context, Widget? child) {
return MediaQuery(
// Display has a vertical hinge down the middle
data: const MediaQueryData(
size: Size(800, 600),
displayFeatures: <DisplayFeature>[
DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
],
),
child: child!,
);
},
home: const Center(child: Text('Test')),
),
);
final BuildContext context = tester.element(find.text('Test'));
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2018),
lastDate: DateTime(2030),
);
await tester.pumpAndSettle();
// By default it should place the dialog on the left screen
expect(tester.getTopLeft(find.byType(DatePickerDialog)), Offset.zero);
expect(tester.getBottomRight(find.byType(DatePickerDialog)), const Offset(390.0, 600.0));
});
});
testWidgets('DatePickerDialog is state restorable', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
restorationScopeId: 'app',
home: _RestorableDatePickerDialogTestWidget(),
),
);
// The date picker should be closed.
expect(find.byType(DatePickerDialog), findsNothing);
expect(find.text('25/7/2021'), findsOneWidget);
// Open the date picker.
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(find.byType(DatePickerDialog), findsOneWidget);
final TestRestorationData restorationData = await tester.getRestorationData();
await tester.restartAndRestore();
// The date picker should be open after restoring.
expect(find.byType(DatePickerDialog), findsOneWidget);
// Tap on the barrier.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle();
// The date picker should be closed, the text value updated to the
// newly selected date.
expect(find.byType(DatePickerDialog), findsNothing);
expect(find.text('25/7/2021'), findsOneWidget);
// The date picker should be open after restoring.
await tester.restoreFrom(restorationData);
expect(find.byType(DatePickerDialog), findsOneWidget);
// Select a different date.
await tester.tap(find.text('30'));
await tester.pumpAndSettle();
// Restart after the new selection. It should remain selected.
await tester.restartAndRestore();
// Close the date picker.
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
// The date picker should be closed, the text value updated to the
// newly selected date.
expect(find.byType(DatePickerDialog), findsNothing);
expect(find.text('30/7/2021'), findsOneWidget);
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615
testWidgets('DatePickerDialog state restoration - DatePickerEntryMode', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
restorationScopeId: 'app',
home: _RestorableDatePickerDialogTestWidget(
datePickerEntryMode: DatePickerEntryMode.calendarOnly,
),
),
);
// The date picker should be closed.
expect(find.byType(DatePickerDialog), findsNothing);
expect(find.text('25/7/2021'), findsOneWidget);
// Open the date picker.
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(find.byType(DatePickerDialog), findsOneWidget);
// Only in calendar mode and cannot switch out.
expect(find.byType(TextField), findsNothing);
expect(find.byIcon(Icons.edit), findsNothing);
final TestRestorationData restorationData = await tester.getRestorationData();
await tester.restartAndRestore();
// The date picker should be open after restoring.
expect(find.byType(DatePickerDialog), findsOneWidget);
// Only in calendar mode and cannot switch out.
expect(find.byType(TextField), findsNothing);
expect(find.byIcon(Icons.edit), findsNothing);
// Tap on the barrier.
await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle();
// The date picker should be closed, the text value should be the same
// as before.
expect(find.byType(DatePickerDialog), findsNothing);
expect(find.text('25/7/2021'), findsOneWidget);
// The date picker should be open after restoring.
await tester.restoreFrom(restorationData);
expect(find.byType(DatePickerDialog), findsOneWidget);
// Only in calendar mode and cannot switch out.
expect(find.byType(TextField), findsNothing);
expect(find.byIcon(Icons.edit), findsNothing);
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615
testWidgets('Test Callback on Toggle of DatePicker Mode', (WidgetTester tester) async {
prepareDatePicker(tester, (Future<DateTime?> date) async {
await tester.tap(find.byIcon(Icons.edit));
expect(currentMode, DatePickerEntryMode.input);
await tester.pumpAndSettle();
expect(find.byType(TextField), findsOneWidget);
await tester.tap(find.byIcon(Icons.calendar_today));
expect(currentMode, DatePickerEntryMode.calendar);
await tester.pumpAndSettle();
expect(find.byType(TextField), findsNothing);
});
});
group('Landscape input-only date picker headers use headlineSmall', () {
// Regression test for https://github.com/flutter/flutter/issues/122056
// Common screen size roughly based on a Pixel 1
const Size kCommonScreenSizePortrait = Size(1070, 1770);
const Size kCommonScreenSizeLandscape = Size(1770, 1070);
Future<void> showPicker(WidgetTester tester, Size size) async {
addTearDown(tester.view.reset);
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1.0;
initialEntryMode = DatePickerEntryMode.input;
await prepareDatePicker(tester, (Future<DateTime?> date) async { }, useMaterial3: true);
}
testWidgets('portrait', (WidgetTester tester) async {
await showPicker(tester, kCommonScreenSizePortrait);
expect(tester.widget<Text>(find.text('Fri, Jan 15')).style?.fontSize, 32);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
});
testWidgets('landscape', (WidgetTester tester) async {
await showPicker(tester, kCommonScreenSizeLandscape);
expect(tester.widget<Text>(find.text('Fri, Jan 15')).style?.fontSize, 24);
await tester.tap(find.text('Cancel'));
await tester.pumpAndSettle();
});
});
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.
group('showDatePicker Dialog', () {
testWidgets('Default dialog size', (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 prepareDatePicker(tester, (Future<DateTime?> date) async {});
}
const Size wideWindowSize = Size(1920.0, 1080.0);
const Size narrowWindowSize = Size(1070.0, 1770.0);
const Size calendarLandscapeDialogSize = Size(496.0, 346.0);
const Size calendarPortraitDialogSizeM2 = Size(330.0, 518.0);
// Test landscape layout.
await showPicker(tester, wideWindowSize);
Size dialogContainerSize = tester.getSize(find.byType(AnimatedContainer));
expect(dialogContainerSize, calendarLandscapeDialogSize);
// Close the dialog.
await tester.tap(find.text('OK'));
await tester.pumpAndSettle();
// Test portrait layout.
await showPicker(tester, narrowWindowSize);
dialogContainerSize = tester.getSize(find.byType(AnimatedContainer));
expect(dialogContainerSize, calendarPortraitDialogSizeM2);
});
testWidgets('Default dialog properties', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final Material dialogMaterial = tester.widget<Material>(
find.descendant(of: find.byType(Dialog),
matching: find.byType(Material),
).first);
expect(dialogMaterial.color, theme.colorScheme.surface);
expect(dialogMaterial.shadowColor, theme.shadowColor);
expect(dialogMaterial.elevation, 24.0);
expect(
dialogMaterial.shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))),
);
expect(dialogMaterial.clipBehavior, Clip.antiAlias);
final Dialog dialog = tester.widget<Dialog>(find.byType(Dialog));
expect(dialog.insetPadding, const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0));
}, useMaterial3: theme.useMaterial3);
});
});
group('Input mode', () {
setUp(() {
firstDate = DateTime(2015);
lastDate = DateTime(2017, DateTime.december, 31);
initialDate = DateTime(2016, DateTime.january, 15);
initialEntryMode = DatePickerEntryMode.input;
});
testWidgets('Default InputDecoration', (WidgetTester tester) async {
await prepareDatePicker(tester, (Future<DateTime?> date) async {
final InputDecoration decoration = tester.widget<TextField>(
find.byType(TextField)).decoration!;
expect(decoration.border, const UnderlineInputBorder());
expect(decoration.filled, false);
expect(decoration.hintText, 'mm/dd/yyyy');
expect(decoration.labelText, 'Enter Date');
expect(decoration.errorText, null);
});
});
});
});
}
class _RestorableDatePickerDialogTestWidget extends StatefulWidget {
const _RestorableDatePickerDialogTestWidget({
this.datePickerEntryMode = DatePickerEntryMode.calendar,
});
final DatePickerEntryMode datePickerEntryMode;
@override
_RestorableDatePickerDialogTestWidgetState createState() => _RestorableDatePickerDialogTestWidgetState();
}
class _RestorableDatePickerDialogTestWidgetState extends State<_RestorableDatePickerDialogTestWidget> with RestorationMixin {
@override
String? get restorationId => 'scaffold_state';
final RestorableDateTime _selectedDate = RestorableDateTime(DateTime(2021, 7, 25));
late final RestorableRouteFuture<DateTime?> _restorableDatePickerRouteFuture = RestorableRouteFuture<DateTime?>(
onComplete: _selectDate,
onPresent: (NavigatorState navigator, Object? arguments) {
return navigator.restorablePush(
_datePickerRoute,
arguments: <String, dynamic>{
'selectedDate': _selectedDate.value.millisecondsSinceEpoch,
'datePickerEntryMode': widget.datePickerEntryMode.index,
},
);
},
);
@override
void dispose() {
_selectedDate.dispose();
_restorableDatePickerRouteFuture.dispose();
super.dispose();
}
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_selectedDate, 'selected_date');
registerForRestoration(_restorableDatePickerRouteFuture, 'date_picker_route_future');
}
void _selectDate(DateTime? newSelectedDate) {
if (newSelectedDate != null) {
setState(() { _selectedDate.value = newSelectedDate; });
}
}
@pragma('vm:entry-point')
static Route<DateTime> _datePickerRoute(
BuildContext context,
Object? arguments,
) {
return DialogRoute<DateTime>(
context: context,
builder: (BuildContext context) {
final Map<dynamic, dynamic> args = arguments! as Map<dynamic, dynamic>;
return DatePickerDialog(
restorationId: 'date_picker_dialog',
initialEntryMode: DatePickerEntryMode.values[args['datePickerEntryMode'] as int],
initialDate: DateTime.fromMillisecondsSinceEpoch(args['selectedDate'] as int),
firstDate: DateTime(2021),
lastDate: DateTime(2022),
);
},
);
}
@override
Widget build(BuildContext context) {
final DateTime selectedDateTime = _selectedDate.value;
// Example: "25/7/1994"
final String selectedDateTimeString = '${selectedDateTime.day}/${selectedDateTime.month}/${selectedDateTime.year}';
return Scaffold(
body: Center(
child: Column(
children: <Widget>[
OutlinedButton(
onPressed: () {
_restorableDatePickerRouteFuture.present();
},
child: const Text('X'),
),
Text(selectedDateTimeString),
],
),
),
);
}
}
class _DatePickerObserver extends NavigatorObserver {
int datePickerCount = 0;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (route is DialogRoute) {
datePickerCount++;
}
super.didPush(route, previousRoute);
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (route is DialogRoute) {
datePickerCount--;
}
super.didPop(route, previousRoute);
}
}
| flutter/packages/flutter/test/material/date_picker_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/date_picker_test.dart",
"repo_id": "flutter",
"token_count": 39309
} | 273 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// no-shuffle:
// //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=456"
// reduced-test-set:
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set', 'no-shuffle'])
library;
import 'dart:math' as math;
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/feedback_tester.dart';
import '../widgets/semantics_tester.dart';
const List<String> menuItems = <String>['one', 'two', 'three', 'four'];
void onChanged<T>(T _) { }
final Type dropdownButtonType = DropdownButton<String>(
onChanged: (_) { },
items: const <DropdownMenuItem<String>>[],
).runtimeType;
Finder _iconRichText(Key iconKey) {
return find.descendant(
of: find.byKey(iconKey),
matching: find.byType(RichText),
);
}
Widget buildDropdown({
required bool isFormField,
Key? buttonKey,
String? value = 'two',
ValueChanged<String?>? onChanged,
VoidCallback? onTap,
Widget? icon,
Color? iconDisabledColor,
Color? iconEnabledColor,
double iconSize = 24.0,
bool isDense = false,
bool isExpanded = false,
Widget? hint,
Widget? disabledHint,
Widget? underline,
List<String>? items = menuItems,
List<Widget> Function(BuildContext)? selectedItemBuilder,
double? itemHeight = kMinInteractiveDimension,
double? menuWidth,
AlignmentDirectional alignment = AlignmentDirectional.centerStart,
TextDirection textDirection = TextDirection.ltr,
Size? mediaSize,
FocusNode? focusNode,
bool autofocus = false,
Color? focusColor,
Color? dropdownColor,
double? menuMaxHeight,
EdgeInsetsGeometry? padding,
}) {
final List<DropdownMenuItem<String>>? listItems = items?.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>(item),
value: item,
child: Text(item, key: ValueKey<String>('${item}Text')),
);
}).toList();
if (isFormField) {
return Form(
child: DropdownButtonFormField<String>(
key: buttonKey,
value: value,
hint: hint,
disabledHint: disabledHint,
onChanged: onChanged,
onTap: onTap,
icon: icon,
iconSize: iconSize,
iconDisabledColor: iconDisabledColor,
iconEnabledColor: iconEnabledColor,
isDense: isDense,
isExpanded: isExpanded,
// No underline attribute
focusNode: focusNode,
autofocus: autofocus,
focusColor: focusColor,
dropdownColor: dropdownColor,
items: listItems,
selectedItemBuilder: selectedItemBuilder,
itemHeight: itemHeight,
alignment: alignment,
menuMaxHeight: menuMaxHeight,
padding: padding,
),
);
}
return DropdownButton<String>(
key: buttonKey,
value: value,
hint: hint,
disabledHint: disabledHint,
onChanged: onChanged,
onTap: onTap,
icon: icon,
iconSize: iconSize,
iconDisabledColor: iconDisabledColor,
iconEnabledColor: iconEnabledColor,
isDense: isDense,
isExpanded: isExpanded,
underline: underline,
focusNode: focusNode,
autofocus: autofocus,
focusColor: focusColor,
dropdownColor: dropdownColor,
items: listItems,
selectedItemBuilder: selectedItemBuilder,
itemHeight: itemHeight,
menuWidth: menuWidth,
alignment: alignment,
menuMaxHeight: menuMaxHeight,
padding: padding,
);
}
Widget buildFrame({
Key? buttonKey,
String? value = 'two',
ValueChanged<String?>? onChanged,
VoidCallback? onTap,
Widget? icon,
Color? iconDisabledColor,
Color? iconEnabledColor,
double iconSize = 24.0,
bool isDense = false,
bool isExpanded = false,
Widget? hint,
Widget? disabledHint,
Widget? underline,
List<String>? items = menuItems,
List<Widget> Function(BuildContext)? selectedItemBuilder,
double? itemHeight = kMinInteractiveDimension,
double? menuWidth,
AlignmentDirectional alignment = AlignmentDirectional.centerStart,
TextDirection textDirection = TextDirection.ltr,
Size? mediaSize,
FocusNode? focusNode,
bool autofocus = false,
Color? focusColor,
Color? dropdownColor,
bool isFormField = false,
double? menuMaxHeight,
EdgeInsetsGeometry? padding,
Alignment dropdownAlignment = Alignment.center,
bool? useMaterial3,
}) {
return Theme(
data: ThemeData(useMaterial3: useMaterial3),
child: TestApp(
textDirection: textDirection,
mediaSize: mediaSize,
child: Material(
child: Align(
alignment: dropdownAlignment,
child: RepaintBoundary(
child: buildDropdown(
isFormField: isFormField,
buttonKey: buttonKey,
value: value,
hint: hint,
disabledHint: disabledHint,
onChanged: onChanged,
onTap: onTap,
icon: icon,
iconSize: iconSize,
iconDisabledColor: iconDisabledColor,
iconEnabledColor: iconEnabledColor,
isDense: isDense,
isExpanded: isExpanded,
underline: underline,
focusNode: focusNode,
autofocus: autofocus,
focusColor: focusColor,
dropdownColor: dropdownColor,
items: items,
selectedItemBuilder: selectedItemBuilder,
itemHeight: itemHeight,
menuWidth: menuWidth,
alignment: alignment,
menuMaxHeight: menuMaxHeight,
padding: padding,
),
),
),
),
),
);
}
Widget buildDropdownWithHint({
required AlignmentDirectional alignment,
required bool isExpanded,
bool enableSelectedItemBuilder = false,
}){
return buildFrame(
useMaterial3: false,
mediaSize: const Size(800, 600),
itemHeight: 100.0,
alignment: alignment,
isExpanded: isExpanded,
selectedItemBuilder: enableSelectedItemBuilder
? (BuildContext context) {
return menuItems.map<Widget>((String item) {
return ColoredBox(
color: const Color(0xff00ff00),
child: Text(item),
);
}).toList();
}
: null,
hint: const Text('hint'),
);
}
class TestApp extends StatefulWidget {
const TestApp({
super.key,
required this.textDirection,
required this.child,
this.mediaSize,
});
final TextDirection textDirection;
final Widget child;
final Size? mediaSize;
@override
State<TestApp> createState() => _TestAppState();
}
class _TestAppState extends State<TestApp> {
@override
Widget build(BuildContext context) {
return Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultWidgetsLocalizations.delegate,
DefaultMaterialLocalizations.delegate,
],
child: MediaQuery(
data: MediaQueryData.fromView(View.of(context)).copyWith(size: widget.mediaSize),
child: Directionality(
textDirection: widget.textDirection,
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
assert(settings.name == '/');
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) => widget.child,
);
},
),
),
),
);
}
}
// When the dropdown's menu is popped up, a RenderParagraph for the selected
// menu's text item will appear both in the dropdown button and in the menu.
// The RenderParagraphs should be aligned, i.e. they should have the same
// size and location.
void checkSelectedItemTextGeometry(WidgetTester tester, String value) {
final List<RenderBox> boxes = tester.renderObjectList<RenderBox>(find.byKey(ValueKey<String>('${value}Text'))).toList();
expect(boxes.length, equals(2));
final RenderBox box0 = boxes[0];
final RenderBox box1 = boxes[1];
expect(box0.localToGlobal(Offset.zero), equals(box1.localToGlobal(Offset.zero)));
expect(box0.size, equals(box1.size));
}
// The dropdown menu isn't readily accessible. To find it we're assuming that it
// contains a ListView and that it's an instance of _DropdownMenu.
Rect getMenuRect(WidgetTester tester) {
late Rect menuRect;
tester.element(find.byType(ListView)).visitAncestorElements((Element element) {
if (element.toString().startsWith('_DropdownMenu')) {
final RenderBox box = element.findRenderObject()! as RenderBox;
menuRect = box.localToGlobal(Offset.zero) & box.size;
return false;
}
return true;
});
return menuRect;
}
Future<void> checkDropdownColor(WidgetTester tester, {Color? color, bool isFormField = false }) async {
const String text = 'foo';
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: isFormField
? Form(
child: DropdownButtonFormField<String>(
dropdownColor: color,
value: text,
items: const <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
value: text,
child: Text(text),
),
],
onChanged: (_) {},
),
)
: DropdownButton<String>(
dropdownColor: color,
value: text,
items: const <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
value: text,
child: Text(text),
),
],
onChanged: (_) {},
),
),
),
);
await tester.tap(find.text(text));
await tester.pump();
expect(
find.ancestor(
of: find.text(text).last,
matching: find.byType(CustomPaint),
).at(2),
paints
..save()
..rrect()
..rrect()
..rrect()
..rrect(color: color ?? Colors.grey[50], hasMaskFilter: false),
);
}
void main() {
testWidgets('Default dropdown golden', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build() => buildFrame(buttonKey: buttonKey, onChanged: onChanged, useMaterial3: false);
await tester.pumpWidget(build());
final Finder buttonFinder = find.byKey(buttonKey);
assert(tester.renderObject(buttonFinder).attached);
await expectLater(
find.ancestor(of: buttonFinder, matching: find.byType(RepaintBoundary)).first,
matchesGoldenFile('dropdown_test.default.png'),
);
});
testWidgets('Expanded dropdown golden', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build() => buildFrame(buttonKey: buttonKey, isExpanded: true, onChanged: onChanged, useMaterial3: false);
await tester.pumpWidget(build());
final Finder buttonFinder = find.byKey(buttonKey);
assert(tester.renderObject(buttonFinder).attached);
await expectLater(
find.ancestor(of: buttonFinder, matching: find.byType(RepaintBoundary)).first,
matchesGoldenFile('dropdown_test.expanded.png'),
);
});
testWidgets('Dropdown button control test', (WidgetTester tester) async {
String? value = 'one';
void didChangeValue(String? newValue) {
value = newValue;
}
Widget build() => buildFrame(value: value, onChanged: didChangeValue);
await tester.pumpWidget(build());
await tester.tap(find.text('one'));
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('one'));
await tester.tap(find.text('three').last);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('three'));
await tester.tap(find.text('three', skipOffstage: false), warnIfMissed: false);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('three'));
await tester.pumpWidget(build());
await tester.tap(find.text('two').last);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('two'));
});
testWidgets('Dropdown button with no app', (WidgetTester tester) async {
String? value = 'one';
void didChangeValue(String? newValue) {
value = newValue;
}
Widget build() {
return Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: MediaQueryData.fromView(tester.view),
child: Navigator(
initialRoute: '/',
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) {
return Material(
child: buildFrame(value: 'one', onChanged: didChangeValue),
);
},
);
},
),
),
);
}
await tester.pumpWidget(build());
await tester.tap(find.text('one'));
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('one'));
await tester.tap(find.text('three').last);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('three'));
await tester.tap(find.text('three', skipOffstage: false), warnIfMissed: false);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('three'));
await tester.pumpWidget(build());
await tester.tap(find.text('two').last);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('two'));
});
testWidgets('DropdownButton does not allow duplicate item values', (WidgetTester tester) async {
final List<DropdownMenuItem<String>> itemsWithDuplicateValues = <String>['a', 'b', 'c', 'c']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList();
await expectLater(
() => tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DropdownButton<String>(
value: 'c',
onChanged: (String? newValue) {},
items: itemsWithDuplicateValues,
),
),
),
),
throwsA(isAssertionError.having(
(AssertionError error) => error.toString(),
'.toString()',
contains("There should be exactly one item with [DropdownButton]'s value"),
)),
);
});
testWidgets('DropdownButton value should only appear in one menu item', (WidgetTester tester) async {
final List<DropdownMenuItem<String>> itemsWithDuplicateValues = <String>['a', 'b', 'c', 'd']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList();
await expectLater(
() => tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DropdownButton<String>(
value: 'e',
onChanged: (String? newValue) {},
items: itemsWithDuplicateValues,
),
),
),
),
throwsA(isAssertionError.having(
(AssertionError error) => error.toString(),
'.toString()',
contains("There should be exactly one item with [DropdownButton]'s value"),
)),
);
});
testWidgets('Dropdown form field uses form field state', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
String? value;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Material(
child: Form(
key: formKey,
child: DropdownButtonFormField<String>(
key: buttonKey,
value: value,
hint: const Text('Select Value'),
decoration: const InputDecoration(
prefixIcon: Icon(Icons.fastfood),
),
items: menuItems.map((String val) {
return DropdownMenuItem<String>(
value: val,
child: Text(val),
);
}).toList(),
validator: (String? v) => v == null ? 'Must select value' : null,
onChanged: (String? newValue) {},
onSaved: (String? v) {
setState(() {
value = v;
});
},
),
),
),
);
},
),
);
int getIndex() {
final IndexedStack stack = tester.element(find.byType(IndexedStack)).widget as IndexedStack;
return stack.index!;
}
// Initial value of null displays hint
expect(value, equals(null));
expect(getIndex(), 4);
await tester.tap(find.text('Select Value', skipOffstage: false), warnIfMissed: false);
await tester.pumpAndSettle();
await tester.tap(find.text('three').last);
await tester.pumpAndSettle();
expect(getIndex(), 2);
// Changes only made to FormField state until form saved
expect(value, equals(null));
final FormState form = formKey.currentState!;
form.save();
expect(value, equals('three'));
});
testWidgets('Dropdown in ListView', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/12053
// Positions a DropdownButton at the left and right edges of the screen,
// forcing it to be sized down to the viewport width
const String value = 'foo';
final UniqueKey itemKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: ListView(
children: <Widget>[
DropdownButton<String>(
value: value,
items: <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
key: itemKey,
value: value,
child: const Text(value),
),
],
onChanged: (_) { },
),
],
),
),
),
);
await tester.tap(find.text(value));
await tester.pump();
final List<RenderBox> itemBoxes = tester.renderObjectList<RenderBox>(find.byKey(itemKey)).toList();
expect(itemBoxes[0].localToGlobal(Offset.zero).dx, equals(0.0));
expect(itemBoxes[1].localToGlobal(Offset.zero).dx, equals(16.0));
expect(itemBoxes[1].size.width, equals(800.0 - 16.0 * 2));
});
testWidgets('Dropdown menu can position correctly inside a nested navigator', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/66870
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
appBar: AppBar(),
body: Column(
children: <Widget>[
ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 500, maxHeight: 200),
child: Navigator(
onGenerateRoute: (RouteSettings s) {
return MaterialPageRoute<void>(builder: (BuildContext context) {
return Center(
child: DropdownButton<int>(
value: 1,
items: const <DropdownMenuItem<int>>[
DropdownMenuItem<int>(
value: 1,
child: Text('First Item'),
),
DropdownMenuItem<int>(
value: 2,
child: Text('Second Item'),
),
],
onChanged: (_) { },
),
);
});
},
),
),
],
),
),
),
);
await tester.tap(find.text('First Item'));
await tester.pump();
final RenderBox secondItem = tester.renderObjectList<RenderBox>(find.text('Second Item', skipOffstage: false)).toList()[1];
expect(secondItem.localToGlobal(Offset.zero).dx, equals(150.0));
expect(secondItem.localToGlobal(Offset.zero).dy, equals(176.0));
});
testWidgets('Dropdown screen edges', (WidgetTester tester) async {
int? value = 4;
final List<DropdownMenuItem<int>> items = <DropdownMenuItem<int>>[
for (int i = 0; i < 20; ++i) DropdownMenuItem<int>(value: i, child: Text('$i')),
];
void handleChanged(int? newValue) {
value = newValue;
}
final DropdownButton<int> button = DropdownButton<int>(
value: value,
onChanged: handleChanged,
items: items,
);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Align(
alignment: Alignment.topCenter,
child: button,
),
),
),
);
await tester.tap(find.text('4'));
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
// We should have two copies of item 5, one in the menu and one in the
// button itself.
expect(tester.elementList(find.text('5', skipOffstage: false)), hasLength(2));
expect(value, 4);
await tester.tap(find.byWidget(button, skipOffstage: false), warnIfMissed: false);
expect(value, 4);
// this waits for the route's completer to complete, which calls handleChanged
await tester.idle();
expect(value, 4);
});
for (final TextDirection textDirection in TextDirection.values) {
testWidgets('Dropdown button aligns selected menu item ($textDirection)', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build() => buildFrame(buttonKey: buttonKey, textDirection: textDirection, onChanged: onChanged, useMaterial3: false);
await tester.pumpWidget(build());
final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBox.attached);
final Offset buttonOriginBeforeTap = buttonBox.localToGlobal(Offset.zero);
await tester.tap(find.text('two'));
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
// Tapping the dropdown button should not cause it to move.
expect(buttonBox.localToGlobal(Offset.zero), equals(buttonOriginBeforeTap));
// The selected dropdown item is both in menu we just popped up, and in
// the IndexedStack contained by the dropdown button. Both of them should
// have the same origin and height as the dropdown button.
final List<RenderBox> itemBoxes = tester.renderObjectList<RenderBox>(find.byKey(const ValueKey<String>('two'))).toList();
expect(itemBoxes.length, equals(2));
for (final RenderBox itemBox in itemBoxes) {
assert(itemBox.attached);
switch (textDirection) {
case TextDirection.rtl:
expect(
buttonBox.localToGlobal(buttonBox.size.bottomRight(Offset.zero)),
equals(itemBox.localToGlobal(itemBox.size.bottomRight(Offset.zero))),
);
case TextDirection.ltr:
expect(buttonBox.localToGlobal(Offset.zero), equals(itemBox.localToGlobal(Offset.zero)));
}
expect(buttonBox.size.height, equals(itemBox.size.height));
}
// The two RenderParagraph objects, for the 'two' items' Text children,
// should have the same size and location.
checkSelectedItemTextGeometry(tester, 'two');
await tester.pumpWidget(Container()); // reset test
});
}
testWidgets('Arrow icon aligns with the edge of button when expanded', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build() => buildFrame(buttonKey: buttonKey, isExpanded: true, onChanged: onChanged);
await tester.pumpWidget(build());
final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBox.attached);
final RenderBox arrowIcon = tester.renderObject<RenderBox>(find.byIcon(Icons.arrow_drop_down));
assert(arrowIcon.attached);
// Arrow icon should be aligned with far right of button when expanded
expect(
arrowIcon.localToGlobal(Offset.zero).dx,
buttonBox.size.centerRight(Offset(-arrowIcon.size.width, 0.0)).dx,
);
});
testWidgets('Dropdown button icon will accept widgets as icons', (WidgetTester tester) async {
final Widget customWidget = Container(
decoration: ShapeDecoration(
shape: CircleBorder(
side: BorderSide(
width: 5.0,
color: Colors.grey.shade700,
),
),
),
);
await tester.pumpWidget(buildFrame(
icon: customWidget,
onChanged: onChanged,
));
expect(find.byWidget(customWidget), findsOneWidget);
expect(find.byIcon(Icons.arrow_drop_down), findsNothing);
await tester.pumpWidget(buildFrame(
icon: const Icon(Icons.assessment),
onChanged: onChanged,
));
expect(find.byIcon(Icons.assessment), findsOneWidget);
expect(find.byIcon(Icons.arrow_drop_down), findsNothing);
});
testWidgets('Dropdown button icon should have default size and colors when not defined', (WidgetTester tester) async {
final Key iconKey = UniqueKey();
final Icon customIcon = Icon(Icons.assessment, key: iconKey);
await tester.pumpWidget(buildFrame(
icon: customIcon,
onChanged: onChanged,
));
// test for size
final RenderBox icon = tester.renderObject(find.byKey(iconKey));
expect(icon.size, const Size(24.0, 24.0));
// test for enabled color
final RichText enabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
expect(enabledRichText.text.style!.color, Colors.grey.shade700);
// test for disabled color
await tester.pumpWidget(buildFrame(
icon: customIcon,
));
final RichText disabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
expect(disabledRichText.text.style!.color, Colors.grey.shade400);
});
testWidgets('Dropdown button icon should have the passed in size and color instead of defaults', (WidgetTester tester) async {
final Key iconKey = UniqueKey();
final Icon customIcon = Icon(Icons.assessment, key: iconKey);
await tester.pumpWidget(buildFrame(
icon: customIcon,
iconSize: 30.0,
iconEnabledColor: Colors.pink,
iconDisabledColor: Colors.orange,
onChanged: onChanged,
));
// test for size
final RenderBox icon = tester.renderObject(find.byKey(iconKey));
expect(icon.size, const Size(30.0, 30.0));
// test for enabled color
final RichText enabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
expect(enabledRichText.text.style!.color, Colors.pink);
// test for disabled color
await tester.pumpWidget(buildFrame(
icon: customIcon,
iconSize: 30.0,
iconEnabledColor: Colors.pink,
iconDisabledColor: Colors.orange,
));
final RichText disabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
expect(disabledRichText.text.style!.color, Colors.orange);
});
testWidgets('Dropdown button should use its own size and color properties over those defined by the theme', (WidgetTester tester) async {
final Key iconKey = UniqueKey();
final Icon customIcon = Icon(
Icons.assessment,
key: iconKey,
size: 40.0,
color: Colors.yellow,
);
await tester.pumpWidget(buildFrame(
icon: customIcon,
iconSize: 30.0,
iconEnabledColor: Colors.pink,
iconDisabledColor: Colors.orange,
onChanged: onChanged,
));
// test for size
final RenderBox icon = tester.renderObject(find.byKey(iconKey));
expect(icon.size, const Size(40.0, 40.0));
// test for enabled color
final RichText enabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
expect(enabledRichText.text.style!.color, Colors.yellow);
// test for disabled color
await tester.pumpWidget(buildFrame(
icon: customIcon,
iconSize: 30.0,
iconEnabledColor: Colors.pink,
iconDisabledColor: Colors.orange,
));
final RichText disabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
expect(disabledRichText.text.style!.color, Colors.yellow);
});
testWidgets('Dropdown button with isDense:true aligns selected menu item', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build() => buildFrame(buttonKey: buttonKey, isDense: true, onChanged: onChanged);
await tester.pumpWidget(build());
final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBox.attached);
await tester.tap(find.text('two'));
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
// The selected dropdown item is both in menu we just popped up, and in
// the IndexedStack contained by the dropdown button. Both of them should
// have the same vertical center as the button.
final List<RenderBox> itemBoxes = tester.renderObjectList<RenderBox>(find.byKey(const ValueKey<String>('two'))).toList();
expect(itemBoxes.length, equals(2));
// When isDense is true, the button's height is reduced. The menu items'
// heights are not.
final double menuItemHeight = itemBoxes.map<double>((RenderBox box) => box.size.height).reduce(math.max);
expect(menuItemHeight, greaterThan(buttonBox.size.height));
for (final RenderBox itemBox in itemBoxes) {
assert(itemBox.attached);
final Offset buttonBoxCenter = buttonBox.size.center(buttonBox.localToGlobal(Offset.zero));
final Offset itemBoxCenter = itemBox.size.center(itemBox.localToGlobal(Offset.zero));
expect(buttonBoxCenter.dy, equals(itemBoxCenter.dy));
}
// The two RenderParagraph objects, for the 'two' items' Text children,
// should have the same size and location.
checkSelectedItemTextGeometry(tester, 'two');
});
testWidgets('Dropdown button can have a text style with no fontSize specified', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/33425
const String value = 'foo';
final UniqueKey itemKey = UniqueKey();
await tester.pumpWidget(TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButton<String>(
value: value,
items: <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
key: itemKey,
value: 'foo',
child: const Text(value),
),
],
isDense: true,
onChanged: (_) { },
style: const TextStyle(color: Colors.blue),
),
),
));
expect(tester.takeException(), isNull);
});
testWidgets('Dropdown menu scrolls to first item in long lists', (WidgetTester tester) async {
// Open the dropdown menu
final Key buttonKey = UniqueKey();
await tester.pumpWidget(buildFrame(
buttonKey: buttonKey,
value: null, // nothing selected
items: List<String>.generate(/*length=*/ 100, (int index) => index.toString()),
onChanged: onChanged,
));
await tester.tap(find.byKey(buttonKey));
await tester.pump();
await tester.pumpAndSettle(); // finish the menu animation
// Find the first item in the scrollable dropdown list
final Finder menuItemFinder = find.byType(Scrollable);
final RenderBox menuItemContainer = tester.renderObject<RenderBox>(menuItemFinder);
final RenderBox firstItem = tester.renderObject<RenderBox>(
find.descendant(of: menuItemFinder, matching: find.byKey(const ValueKey<String>('0'))),
);
// List should be scrolled so that the first item is at the top. Menu items
// are offset 8.0 from the top edge of the scrollable menu.
const Offset selectedItemOffset = Offset(0.0, -8.0);
expect(
firstItem.size.topCenter(firstItem.localToGlobal(selectedItemOffset)).dy,
equals(menuItemContainer.size.topCenter(menuItemContainer.localToGlobal(Offset.zero)).dy),
);
});
testWidgets('Dropdown menu aligns selected item with button in long lists', (WidgetTester tester) async {
// Open the dropdown menu
final Key buttonKey = UniqueKey();
await tester.pumpWidget(buildFrame(
buttonKey: buttonKey,
value: '50',
items: List<String>.generate(/*length=*/ 100, (int index) => index.toString()),
onChanged: onChanged,
));
final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle(); // finish the menu animation
// Find the selected item in the scrollable dropdown list
final RenderBox selectedItem = tester.renderObject<RenderBox>(
find.descendant(of: find.byType(Scrollable), matching: find.byKey(const ValueKey<String>('50'))),
);
// List should be scrolled so that the selected item is in line with the button
expect(
selectedItem.size.center(selectedItem.localToGlobal(Offset.zero)).dy,
equals(buttonBox.size.center(buttonBox.localToGlobal(Offset.zero)).dy),
);
});
testWidgets('Dropdown menu scrolls to last item in long lists', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
await tester.pumpWidget(buildFrame(
buttonKey: buttonKey,
value: '99',
items: List<String>.generate(/*length=*/ 100, (int index) => index.toString()),
onChanged: onChanged,
));
await tester.tap(find.byKey(buttonKey));
await tester.pump();
final ScrollController scrollController = PrimaryScrollController.of(tester.element(find.byType(ListView)));
// Make sure there is no overscroll
expect(scrollController.offset, scrollController.position.maxScrollExtent);
// Find the selected item in the scrollable dropdown list
final Finder menuItemFinder = find.byType(Scrollable);
final RenderBox menuItemContainer = tester.renderObject<RenderBox>(menuItemFinder);
final RenderBox selectedItem = tester.renderObject<RenderBox>(
find.descendant(
of: menuItemFinder,
matching: find.byKey(const ValueKey<String>('99')),
),
);
// kMaterialListPadding.vertical is 8.
const Offset menuPaddingOffset = Offset(0.0, -8.0);
final Offset selectedItemOffset = selectedItem.localToGlobal(Offset.zero);
final Offset menuItemContainerOffset = menuItemContainer.localToGlobal(menuPaddingOffset);
// Selected item should be aligned to the bottom of the dropdown menu.
expect(
selectedItem.size.bottomCenter(selectedItemOffset).dy,
menuItemContainer.size.bottomCenter(menuItemContainerOffset).dy,
);
});
testWidgets('Size of DropdownButton with null value', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
String? value;
Widget build() => buildFrame(buttonKey: buttonKey, value: value, onChanged: onChanged);
await tester.pumpWidget(build());
final RenderBox buttonBoxNullValue = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBoxNullValue.attached);
value = 'three';
await tester.pumpWidget(build());
final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBox.attached);
// A Dropdown button with a null value should be the same size as a
// one with a non-null value.
expect(buttonBox.localToGlobal(Offset.zero), equals(buttonBoxNullValue.localToGlobal(Offset.zero)));
expect(buttonBox.size, equals(buttonBoxNullValue.size));
});
testWidgets('Size of DropdownButton with no items', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/26419
final Key buttonKey = UniqueKey();
List<String>? items;
Widget build() => buildFrame(buttonKey: buttonKey, items: items, onChanged: onChanged);
await tester.pumpWidget(build());
final RenderBox buttonBoxNullItems = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBoxNullItems.attached);
items = <String>[];
await tester.pumpWidget(build());
final RenderBox buttonBoxEmptyItems = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBoxEmptyItems.attached);
items = <String>['one', 'two', 'three', 'four'];
await tester.pumpWidget(build());
final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBox.attached);
// A Dropdown button with a null value should be the same size as a
// one with a non-null value.
expect(buttonBox.localToGlobal(Offset.zero), equals(buttonBoxNullItems.localToGlobal(Offset.zero)));
expect(buttonBox.size, equals(buttonBoxNullItems.size));
});
testWidgets('Layout of a DropdownButton with null value', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
String? value;
void onChanged(String? newValue) {
value = newValue;
}
Widget build() => buildFrame(buttonKey: buttonKey, value: value, onChanged: onChanged);
await tester.pumpWidget(build());
final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBox.attached);
// Show the menu.
await tester.tap(find.byKey(buttonKey));
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
// Tap on item 'one', which must appear over the button.
await tester.tap(find.byKey(buttonKey, skipOffstage: false), warnIfMissed: false);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
await tester.pumpWidget(build());
expect(value, equals('one'));
});
testWidgets('Size of DropdownButton with null value and a hint', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
String? value;
// The hint will define the dropdown's width
Widget build() => buildFrame(buttonKey: buttonKey, value: value, hint: const Text('onetwothree'));
await tester.pumpWidget(build());
expect(find.text('onetwothree'), findsOneWidget);
final RenderBox buttonBoxHintValue = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBoxHintValue.attached);
value = 'three';
await tester.pumpWidget(build());
final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBox.attached);
// A Dropdown button with a null value and a hint should be the same size as a
// one with a non-null value.
expect(buttonBox.localToGlobal(Offset.zero), equals(buttonBoxHintValue.localToGlobal(Offset.zero)));
expect(buttonBox.size, equals(buttonBoxHintValue.size));
});
testWidgets('Dropdown menus must fit within the screen', (WidgetTester tester) async {
// In all of the tests that follow we're assuming that the dropdown menu
// is horizontally aligned with the center of the dropdown button and padded
// on the top, left, and right.
const EdgeInsets buttonPadding = EdgeInsets.only(top: 8.0, left: 16.0, right: 24.0);
Rect getExpandedButtonRect() {
final RenderBox box = tester.renderObject<RenderBox>(find.byType(dropdownButtonType));
final Rect buttonRect = box.localToGlobal(Offset.zero) & box.size;
return buttonPadding.inflateRect(buttonRect);
}
late Rect buttonRect;
late Rect menuRect;
Future<void> popUpAndDown(Widget frame) async {
await tester.pumpWidget(frame);
await tester.tap(find.byType(dropdownButtonType));
await tester.pumpAndSettle();
menuRect = getMenuRect(tester);
buttonRect = getExpandedButtonRect();
await tester.tap(find.byType(dropdownButtonType, skipOffstage: false), warnIfMissed: false);
}
// Dropdown button is along the top of the app. The top of the menu is
// aligned with the top of the expanded button and shifted horizontally
// so that it fits within the frame.
await popUpAndDown(
buildFrame(dropdownAlignment: Alignment.topLeft, value: menuItems.last, onChanged: onChanged),
);
expect(menuRect.topLeft, Offset.zero);
expect(menuRect.topRight, Offset(menuRect.width, 0.0));
await popUpAndDown(
buildFrame(dropdownAlignment: Alignment.topCenter, value: menuItems.last, onChanged: onChanged),
);
expect(menuRect.topLeft, Offset(buttonRect.left, 0.0));
expect(menuRect.topRight, Offset(buttonRect.right, 0.0));
await popUpAndDown(
buildFrame(dropdownAlignment: Alignment.topRight, value: menuItems.last, onChanged: onChanged),
);
expect(menuRect.topLeft, Offset(800.0 - menuRect.width, 0.0));
expect(menuRect.topRight, const Offset(800.0, 0.0));
// Dropdown button is along the middle of the app. The top of the menu is
// aligned with the top of the expanded button (because the 1st item
// is selected) and shifted horizontally so that it fits within the frame.
await popUpAndDown(
buildFrame(dropdownAlignment: Alignment.centerLeft, value: menuItems.first, onChanged: onChanged),
);
expect(menuRect.topLeft, Offset(0.0, buttonRect.top));
expect(menuRect.topRight, Offset(menuRect.width, buttonRect.top));
await popUpAndDown(
buildFrame(value: menuItems.first, onChanged: onChanged),
);
expect(menuRect.topLeft, buttonRect.topLeft);
expect(menuRect.topRight, buttonRect.topRight);
await popUpAndDown(
buildFrame(dropdownAlignment: Alignment.centerRight, value: menuItems.first, onChanged: onChanged),
);
expect(menuRect.topLeft, Offset(800.0 - menuRect.width, buttonRect.top));
expect(menuRect.topRight, Offset(800.0, buttonRect.top));
// Dropdown button is along the bottom of the app. The bottom of the menu is
// aligned with the bottom of the expanded button and shifted horizontally
// so that it fits within the frame.
await popUpAndDown(
buildFrame(dropdownAlignment: Alignment.bottomLeft, value: menuItems.first, onChanged: onChanged),
);
expect(menuRect.bottomLeft, const Offset(0.0, 600.0));
expect(menuRect.bottomRight, Offset(menuRect.width, 600.0));
await popUpAndDown(
buildFrame(dropdownAlignment: Alignment.bottomCenter, value: menuItems.first, onChanged: onChanged),
);
expect(menuRect.bottomLeft, Offset(buttonRect.left, 600.0));
expect(menuRect.bottomRight, Offset(buttonRect.right, 600.0));
await popUpAndDown(
buildFrame(dropdownAlignment: Alignment.bottomRight, value: menuItems.first, onChanged: onChanged),
);
expect(menuRect.bottomLeft, Offset(800.0 - menuRect.width, 600.0));
expect(menuRect.bottomRight, const Offset(800.0, 600.0));
});
testWidgets('Dropdown menus are dismissed on screen orientation changes, but not on keyboard hide', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(onChanged: onChanged, mediaSize: const Size(800, 600)));
await tester.tap(find.byType(dropdownButtonType));
await tester.pumpAndSettle();
expect(find.byType(ListView), findsOneWidget);
// Show a keyboard (simulate by shortening the height).
await tester.pumpWidget(buildFrame(onChanged: onChanged, mediaSize: const Size(800, 300)));
await tester.pump();
expect(find.byType(ListView, skipOffstage: false), findsOneWidget);
// Hide a keyboard again (simulate by increasing the height).
await tester.pumpWidget(buildFrame(onChanged: onChanged, mediaSize: const Size(800, 600)));
await tester.pump();
expect(find.byType(ListView, skipOffstage: false), findsOneWidget);
// Rotate the device (simulate by changing the aspect ratio).
await tester.pumpWidget(buildFrame(onChanged: onChanged, mediaSize: const Size(600, 800)));
await tester.pump();
expect(find.byType(ListView, skipOffstage: false), findsNothing);
});
testWidgets('Semantics Tree contains only selected element', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(buildFrame(onChanged: onChanged));
expect(semantics, isNot(includesNodeWith(label: menuItems[0])));
expect(semantics, includesNodeWith(label: menuItems[1]));
expect(semantics, isNot(includesNodeWith(label: menuItems[2])));
expect(semantics, isNot(includesNodeWith(label: menuItems[3])));
semantics.dispose();
});
testWidgets('Dropdown button includes semantics', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
const Key key = Key('test');
await tester.pumpWidget(buildFrame(
buttonKey: key,
value: null,
onChanged: (String? _) { },
hint: const Text('test'),
));
// By default the hint contributes the label.
expect(tester.getSemantics(find.byKey(key)), matchesSemantics(
isButton: true,
label: 'test',
hasTapAction: true,
isFocusable: true,
));
await tester.pumpWidget(buildFrame(
buttonKey: key,
value: 'three',
onChanged: onChanged,
hint: const Text('test'),
));
// Displays label of select item and is no longer tappable.
expect(tester.getSemantics(find.byKey(key)), matchesSemantics(
isButton: true,
label: 'three',
hasTapAction: true,
isFocusable: true,
));
handle.dispose();
});
testWidgets('Dropdown menu includes semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
const Key key = Key('test');
await tester.pumpWidget(buildFrame(
buttonKey: key,
value: null,
onChanged: onChanged,
));
await tester.tap(find.byKey(key));
await tester.pumpAndSettle();
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
label: 'Dismiss',
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.scopesRoute,
SemanticsFlag.namesRoute,
],
label: 'Popup menu',
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.hasImplicitScrolling,
],
children: <TestSemantics>[
TestSemantics(
label: 'one',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[
SemanticsFlag.isFocused,
SemanticsFlag.isFocusable,
],
tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')],
actions: <SemanticsAction>[SemanticsAction.tap],
),
TestSemantics(
label: 'two',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isFocusable],
tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')],
actions: <SemanticsAction>[SemanticsAction.tap],
),
TestSemantics(
label: 'three',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isFocusable],
tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')],
actions: <SemanticsAction>[SemanticsAction.tap],
),
TestSemantics(
label: 'four',
textDirection: TextDirection.ltr,
flags: <SemanticsFlag>[SemanticsFlag.isFocusable],
tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')],
actions: <SemanticsAction>[SemanticsAction.tap],
),
],
),
],
),
],
),
],
),
],
), ignoreId: true, ignoreRect: true, ignoreTransform: true));
semantics.dispose();
});
testWidgets('disabledHint displays on empty items or onChanged', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build({ List<String>? items, ValueChanged<String?>? onChanged }) => buildFrame(
items: items,
onChanged: onChanged,
buttonKey: buttonKey,
value: null,
hint: const Text('enabled'),
disabledHint: const Text('disabled'),
);
// [disabledHint] should display when [items] is null
await tester.pumpWidget(build(onChanged: onChanged));
expect(find.text('enabled'), findsNothing);
expect(find.text('disabled'), findsOneWidget);
// [disabledHint] should display when [items] is an empty list.
await tester.pumpWidget(build(items: <String>[], onChanged: onChanged));
expect(find.text('enabled'), findsNothing);
expect(find.text('disabled'), findsOneWidget);
// [disabledHint] should display when [onChanged] is null
await tester.pumpWidget(build(items: menuItems));
expect(find.text('enabled'), findsNothing);
expect(find.text('disabled'), findsOneWidget);
final RenderBox disabledHintBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
// A Dropdown button with a disabled hint should be the same size as a
// one with a regular enabled hint.
await tester.pumpWidget(build(items: menuItems, onChanged: onChanged));
expect(find.text('disabled'), findsNothing);
expect(find.text('enabled'), findsOneWidget);
final RenderBox enabledHintBox = tester.renderObject<RenderBox>(find.byKey(buttonKey));
expect(enabledHintBox.localToGlobal(Offset.zero), equals(disabledHintBox.localToGlobal(Offset.zero)));
expect(enabledHintBox.size, equals(disabledHintBox.size));
});
// Regression test for https://github.com/flutter/flutter/issues/70177
testWidgets('disabledHint behavior test', (WidgetTester tester) async {
Widget build({ List<String>? items, ValueChanged<String?>? onChanged, String? value, Widget? hint, Widget? disabledHint }) => buildFrame(
items: items,
onChanged: onChanged,
value: value,
hint: hint,
disabledHint: disabledHint,
);
// The selected value should be displayed when the button is disabled.
await tester.pumpWidget(build(items: menuItems, value: 'two'));
// The dropdown icon and the selected menu item are vertically aligned.
expect(tester.getCenter(find.text('two')).dy, tester.getCenter(find.byType(Icon)).dy);
// If [value] is null, the button is enabled, hint is displayed.
await tester.pumpWidget(build(
items: menuItems,
onChanged: onChanged,
hint: const Text('hint'),
disabledHint: const Text('disabledHint'),
));
expect(tester.getCenter(find.text('hint')).dy, tester.getCenter(find.byType(Icon)).dy);
// If [value] is null, the button is disabled, [disabledHint] is displayed when [disabledHint] is non-null.
await tester.pumpWidget(build(
items: menuItems,
hint: const Text('hint'),
disabledHint: const Text('disabledHint'),
));
expect(tester.getCenter(find.text('disabledHint')).dy, tester.getCenter(find.byType(Icon)).dy);
// If [value] is null, the button is disabled, [hint] is displayed when [disabledHint] is null.
await tester.pumpWidget(build(
items: menuItems,
hint: const Text('hint'),
));
expect(tester.getCenter(find.text('hint')).dy, tester.getCenter(find.byType(Icon)).dy);
int? getIndex() {
final IndexedStack stack = tester.element(find.byType(IndexedStack)).widget as IndexedStack;
return stack.index;
}
// If [value], [hint] and [disabledHint] are null, the button is disabled, nothing displayed.
await tester.pumpWidget(build(
items: menuItems,
));
expect(getIndex(), null);
// If [value], [hint] and [disabledHint] are null, the button is enabled, nothing displayed.
await tester.pumpWidget(build(
items: menuItems,
onChanged: onChanged,
));
expect(getIndex(), null);
});
testWidgets('DropdownButton selected item color test', (WidgetTester tester) async {
Widget build({ ValueChanged<String?>? onChanged, String? value, Widget? hint, Widget? disabledHint }) {
return MaterialApp(
theme: ThemeData(
disabledColor: Colors.pink,
),
home: Scaffold(
body: Center(
child: Column(children: <Widget>[
DropdownButtonFormField<String>(
style: const TextStyle(
color: Colors.yellow,
),
disabledHint: disabledHint,
hint: hint,
items: const <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
value: 'one',
child: Text('one'),
),
DropdownMenuItem<String>(
value: 'two',
child: Text('two'),
),
],
value: value,
onChanged: onChanged,
),
]),
),
),
);
}
Color textColor(String text) {
return tester.renderObject<RenderParagraph>(find.text(text)).text.style!.color!;
}
// The selected value should be displayed when the button is enabled.
await tester.pumpWidget(build(onChanged: onChanged, value: 'two'));
// The dropdown icon and the selected menu item are vertically aligned.
expect(tester.getCenter(find.text('two')).dy, tester.getCenter(find.byType(Icon)).dy);
// Selected item has a normal color from [DropdownButtonFormField.style]
// when the button is enabled.
expect(textColor('two'), Colors.yellow);
// The selected value should be displayed when the button is disabled.
await tester.pumpWidget(build(value: 'two'));
expect(tester.getCenter(find.text('two')).dy, tester.getCenter(find.byType(Icon)).dy);
// Selected item has a disabled color from [theme.disabledColor]
// when the button is disable.
expect(textColor('two'), Colors.pink);
});
testWidgets(
'DropdownButton hint displays when the items list is empty, '
'items is null, and disabledHint is null',
(WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build({ List<String>? items }) {
return buildFrame(
items: items,
buttonKey: buttonKey,
value: null,
hint: const Text('hint used when disabled'),
);
}
// [hint] should display when [items] is null and [disabledHint] is not defined
await tester.pumpWidget(build());
expect(find.text('hint used when disabled'), findsOneWidget);
// [hint] should display when [items] is an empty list and [disabledHint] is not defined.
await tester.pumpWidget(build(items: <String>[]));
expect(find.text('hint used when disabled'), findsOneWidget);
},
);
testWidgets('DropdownButton disabledHint is null by default', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build({ List<String>? items }) {
return buildFrame(
items: items,
buttonKey: buttonKey,
value: null,
hint: const Text('hint used when disabled'),
);
}
// [hint] should display when [items] is null and [disabledHint] is not defined
await tester.pumpWidget(build());
expect(find.text('hint used when disabled'), findsOneWidget);
// [hint] should display when [items] is an empty list and [disabledHint] is not defined.
await tester.pumpWidget(build(items: <String>[]));
expect(find.text('hint used when disabled'), findsOneWidget);
});
testWidgets('Size of largest widget is used DropdownButton when selectedItemBuilder is non-null', (WidgetTester tester) async {
final List<String> items = <String>['25', '50', '100'];
const String selectedItem = '25';
await tester.pumpWidget(buildFrame(
// To test the size constraints, the selected item should not be the
// largest item. This validates that the button sizes itself according
// to the largest item regardless of which one is selected.
value: selectedItem,
items: items,
itemHeight: null,
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return SizedBox(
height: double.parse(item),
width: double.parse(item),
child: Center(child: Text(item)),
);
}).toList();
},
onChanged: (String? newValue) {},
));
final RenderBox dropdownButtonRenderBox = tester.renderObject<RenderBox>(
find.widgetWithText(Row, '25'),
);
// DropdownButton should be the height of the largest item
expect(dropdownButtonRenderBox.size.height, 100);
// DropdownButton should be width of largest item added to the icon size
expect(dropdownButtonRenderBox.size.width, 100 + 24.0);
});
testWidgets(
'Enabled button - Size of largest widget is used DropdownButton when selectedItemBuilder '
'is non-null and hint is defined, but smaller than largest selected item widget',
(WidgetTester tester) async {
final List<String> items = <String>['25', '50', '100'];
await tester.pumpWidget(buildFrame(
value: null,
// [hint] widget is smaller than largest selected item widget
hint: const SizedBox(
height: 50,
width: 50,
child: Text('hint'),
),
items: items,
itemHeight: null,
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return SizedBox(
height: double.parse(item),
width: double.parse(item),
child: Center(child: Text(item)),
);
}).toList();
},
onChanged: (String? newValue) {},
));
final RenderBox dropdownButtonRenderBox = tester.renderObject<RenderBox>(
find.widgetWithText(Row, 'hint'),
);
// DropdownButton should be the height of the largest item
expect(dropdownButtonRenderBox.size.height, 100);
// DropdownButton should be width of largest item added to the icon size
expect(dropdownButtonRenderBox.size.width, 100 + 24.0);
},
);
testWidgets(
'Enabled button - Size of largest widget is used DropdownButton when selectedItemBuilder '
'is non-null and hint is defined, but larger than largest selected item widget',
(WidgetTester tester) async {
final List<String> items = <String>['25', '50', '100'];
const String selectedItem = '25';
await tester.pumpWidget(buildFrame(
// To test the size constraints, the selected item should not be the
// largest item. This validates that the button sizes itself according
// to the largest item regardless of which one is selected.
value: selectedItem,
// [hint] widget is larger than largest selected item widget
hint: const SizedBox(
height: 125,
width: 125,
child: Text('hint'),
),
items: items,
itemHeight: null,
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return SizedBox(
height: double.parse(item),
width: double.parse(item),
child: Center(child: Text(item)),
);
}).toList();
},
onChanged: (String? newValue) {},
));
final RenderBox dropdownButtonRenderBox = tester.renderObject<RenderBox>(
find.widgetWithText(Row, '25'),
);
// DropdownButton should be the height of the largest item (hint inclusive)
expect(dropdownButtonRenderBox.size.height, 125);
// DropdownButton should be width of largest item (hint inclusive) added to the icon size
expect(dropdownButtonRenderBox.size.width, 125 + 24.0);
},
);
testWidgets(
'Disabled button - Size of largest widget is used DropdownButton when selectedItemBuilder '
'is non-null, and hint is defined, but smaller than largest selected item widget',
(WidgetTester tester) async {
final List<String> items = <String>['25', '50', '100'];
await tester.pumpWidget(buildFrame(
value: null,
// [hint] widget is smaller than largest selected item widget
hint: const SizedBox(
height: 50,
width: 50,
child: Text('hint'),
),
items: items,
itemHeight: null,
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return SizedBox(
height: double.parse(item),
width: double.parse(item),
child: Center(child: Text(item)),
);
}).toList();
},
));
final RenderBox dropdownButtonRenderBox = tester.renderObject<RenderBox>(
find.widgetWithText(Row, 'hint'),
);
// DropdownButton should be the height of the largest item
expect(dropdownButtonRenderBox.size.height, 100);
// DropdownButton should be width of largest item added to the icon size
expect(dropdownButtonRenderBox.size.width, 100 + 24.0);
},
);
testWidgets(
'Disabled button - Size of largest widget is used DropdownButton when selectedItemBuilder '
'is non-null and hint is defined, but larger than largest selected item widget',
(WidgetTester tester) async {
final List<String> items = <String>['25', '50', '100'];
await tester.pumpWidget(buildFrame(
value: null,
// [hint] widget is larger than largest selected item widget
hint: const SizedBox(
height: 125,
width: 125,
child: Text('hint'),
),
items: items,
itemHeight: null,
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return SizedBox(
height: double.parse(item),
width: double.parse(item),
child: Center(child: Text(item)),
);
}).toList();
},
));
final RenderBox dropdownButtonRenderBox = tester.renderObject<RenderBox>(
find.widgetWithText(Row, '25', skipOffstage: false),
);
// DropdownButton should be the height of the largest item (hint inclusive)
expect(dropdownButtonRenderBox.size.height, 125);
// DropdownButton should be width of largest item (hint inclusive) added to the icon size
expect(dropdownButtonRenderBox.size.width, 125 + 24.0);
},
);
testWidgets(
'Disabled button - Size of largest widget is used DropdownButton when selectedItemBuilder '
'is non-null, and disabledHint is defined, but smaller than largest selected item widget',
(WidgetTester tester) async {
final List<String> items = <String>['25', '50', '100'];
await tester.pumpWidget(buildFrame(
value: null,
// [hint] widget is smaller than largest selected item widget
disabledHint: const SizedBox(
height: 50,
width: 50,
child: Text('hint'),
),
items: items,
itemHeight: null,
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return SizedBox(
height: double.parse(item),
width: double.parse(item),
child: Center(child: Text(item)),
);
}).toList();
},
));
final RenderBox dropdownButtonRenderBox = tester.renderObject<RenderBox>(
find.widgetWithText(Row, 'hint'),
);
// DropdownButton should be the height of the largest item
expect(dropdownButtonRenderBox.size.height, 100);
// DropdownButton should be width of largest item added to the icon size
expect(dropdownButtonRenderBox.size.width, 100 + 24.0);
},
);
testWidgets(
'Disabled button - Size of largest widget is used DropdownButton when selectedItemBuilder '
'is non-null and disabledHint is defined, but larger than largest selected item widget',
(WidgetTester tester) async {
final List<String> items = <String>['25', '50', '100'];
await tester.pumpWidget(buildFrame(
value: null,
// [hint] widget is larger than largest selected item widget
disabledHint: const SizedBox(
height: 125,
width: 125,
child: Text('hint'),
),
items: items,
itemHeight: null,
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return SizedBox(
height: double.parse(item),
width: double.parse(item),
child: Center(child: Text(item)),
);
}).toList();
},
));
final RenderBox dropdownButtonRenderBox = tester.renderObject<RenderBox>(
find.widgetWithText(Row, '25', skipOffstage: false),
);
// DropdownButton should be the height of the largest item (hint inclusive)
expect(dropdownButtonRenderBox.size.height, 125);
// DropdownButton should be width of largest item (hint inclusive) added to the icon size
expect(dropdownButtonRenderBox.size.width, 125 + 24.0);
},
);
testWidgets('Menu width is correct when set', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/133267.
final List<String> items = <String>['25', '50', '100'];
const String selectedItem = '25';
await tester.pumpWidget(buildFrame(
value: selectedItem,
items: items,
menuWidth: 200,
selectedItemBuilder: (BuildContext context) {
return items.map<Widget>((String item) {
return SizedBox(
height: double.parse(item),
width: double.parse(item),
child: Center(child: Text(item)),
);
}).toList();
},
onChanged: (String? newValue) {},
));
await tester.tap(find.text('25'));
await tester.pumpAndSettle();
expect(getMenuRect(tester).width, 200);
});
testWidgets('Dropdown in middle showing middle item', (WidgetTester tester) async {
final List<DropdownMenuItem<int>> items = List<DropdownMenuItem<int>>.generate(
100,
(int i) => DropdownMenuItem<int>(value: i, child: Text('$i')),
);
final DropdownButton<int> button = DropdownButton<int>(
value: 50,
onChanged: (int? newValue) { },
items: items,
);
double getMenuScroll() {
double scrollPosition;
final ScrollController scrollController = PrimaryScrollController.of(tester.element(find.byType(ListView)));
scrollPosition = scrollController.position.pixels;
return scrollPosition;
}
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Align(
child: button,
),
),
),
);
await tester.tap(find.text('50'));
await tester.pumpAndSettle();
expect(getMenuScroll(), 2180.0);
});
testWidgets('Dropdown in top showing bottom item', (WidgetTester tester) async {
final List<DropdownMenuItem<int>> items = List<DropdownMenuItem<int>>.generate(
100,
(int i) => DropdownMenuItem<int>(value: i, child: Text('$i')),
);
final DropdownButton<int> button = DropdownButton<int>(
value: 99,
onChanged: (int? newValue) { },
items: items,
);
double getMenuScroll() {
double scrollPosition;
final ScrollController scrollController = PrimaryScrollController.of(tester.element(find.byType(ListView)));
scrollPosition = scrollController.position.pixels;
return scrollPosition;
}
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Align(
alignment: Alignment.topCenter,
child: button,
),
),
),
);
await tester.tap(find.text('99'));
await tester.pumpAndSettle();
expect(getMenuScroll(), 4312.0);
});
testWidgets('Dropdown in bottom showing top item', (WidgetTester tester) async {
final List<DropdownMenuItem<int>> items = List<DropdownMenuItem<int>>.generate(
100,
(int i) => DropdownMenuItem<int>(value: i, child: Text('$i')),
);
final DropdownButton<int> button = DropdownButton<int>(
value: 0,
onChanged: (int? newValue) { },
items: items,
);
double getMenuScroll() {
double scrollPosition;
final ScrollController scrollController = PrimaryScrollController.of(tester.element(find.byType(ListView)));
scrollPosition = scrollController.position.pixels;
return scrollPosition;
}
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Align(
alignment: Alignment.bottomCenter,
child: button,
),
),
),
);
await tester.tap(find.text('0'));
await tester.pumpAndSettle();
expect(getMenuScroll(), 0.0);
});
testWidgets('Dropdown in center showing bottom item', (WidgetTester tester) async {
final List<DropdownMenuItem<int>> items = List<DropdownMenuItem<int>>.generate(
100,
(int i) => DropdownMenuItem<int>(value: i, child: Text('$i')),
);
final DropdownButton<int> button = DropdownButton<int>(
value: 99,
onChanged: (int? newValue) { },
items: items,
);
double getMenuScroll() {
double scrollPosition;
final ScrollController scrollController = PrimaryScrollController.of(tester.element(find.byType(ListView)));
scrollPosition = scrollController.position.pixels;
return scrollPosition;
}
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Align(
child: button,
),
),
),
);
await tester.tap(find.text('99'));
await tester.pumpAndSettle();
expect(getMenuScroll(), 4312.0);
});
testWidgets('Dropdown menu respects parent size limits', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/24417
int? selectedIndex;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
bottomNavigationBar: const SizedBox(height: 200),
body: Navigator(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<void>(
builder: (BuildContext context) {
return SafeArea(
child: Container(
alignment: Alignment.topLeft,
// From material/dropdown.dart (menus are unaligned by default):
// _kUnalignedMenuMargin = EdgeInsetsDirectional.only(start: 16.0, end: 24.0)
// This padding ensures that the entire menu will be visible
padding: const EdgeInsetsDirectional.only(start: 16.0, end: 24.0),
child: DropdownButton<int>(
value: 12,
onChanged: (int? i) {
selectedIndex = i;
},
items: List<DropdownMenuItem<int>>.generate(100, (int i) {
return DropdownMenuItem<int>(value: i, child: Text('$i'));
}),
),
),
);
},
);
},
),
),
),
);
await tester.tap(find.text('12'));
await tester.pumpAndSettle();
expect(selectedIndex, null);
await tester.tap(find.text('13').last);
await tester.pumpAndSettle();
expect(selectedIndex, 13);
});
testWidgets('Dropdown button will accept widgets as its underline', (WidgetTester tester) async {
const BoxDecoration decoration = BoxDecoration(
border: Border(bottom: BorderSide(color: Color(0xFFCCBB00), width: 4.0)),
);
const BoxDecoration defaultDecoration = BoxDecoration(
border: Border(bottom: BorderSide(color: Color(0xFFBDBDBD), width: 0.0)),
);
final Widget customUnderline = Container(height: 4.0, decoration: decoration);
final Key buttonKey = UniqueKey();
final Finder decoratedBox = find.descendant(
of: find.byKey(buttonKey),
matching: find.byType(DecoratedBox),
);
await tester.pumpWidget(buildFrame(
buttonKey: buttonKey,
underline: customUnderline,
onChanged: onChanged,
));
expect(tester.widgetList<DecoratedBox>(decoratedBox).last.decoration, decoration);
await tester.pumpWidget(buildFrame(buttonKey: buttonKey, onChanged: onChanged));
expect(tester.widgetList<DecoratedBox>(decoratedBox).last.decoration, defaultDecoration);
});
testWidgets('DropdownButton selectedItemBuilder builds custom buttons', (WidgetTester tester) async {
const List<String> items = <String>[
'One',
'Two',
'Three',
];
String? selectedItem = items[0];
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Scaffold(
body: DropdownButton<String>(
value: selectedItem,
onChanged: (String? string) {
setState(() => selectedItem = string);
},
selectedItemBuilder: (BuildContext context) {
int index = 0;
return items.map((String string) {
index += 1;
return Text('$string as an Arabic numeral: $index');
}).toList();
},
items: items.map((String string) {
return DropdownMenuItem<String>(
value: string,
child: Text(string),
);
}).toList(),
),
),
);
},
),
);
expect(find.text('One as an Arabic numeral: 1'), findsOneWidget);
await tester.tap(find.text('One as an Arabic numeral: 1'));
await tester.pumpAndSettle();
await tester.tap(find.text('Two'));
await tester.pumpAndSettle();
expect(find.text('Two as an Arabic numeral: 2'), findsOneWidget);
});
testWidgets('DropdownButton uses default color when expanded', (WidgetTester tester) async {
await checkDropdownColor(tester);
});
testWidgets('DropdownButton uses dropdownColor when expanded', (WidgetTester tester) async {
await checkDropdownColor(tester, color: const Color.fromRGBO(120, 220, 70, 0.8));
});
testWidgets('DropdownButtonFormField uses dropdownColor when expanded', (WidgetTester tester) async {
await checkDropdownColor(tester, color: const Color.fromRGBO(120, 220, 70, 0.8), isFormField: true);
});
testWidgets('DropdownButton hint displays properly when selectedItemBuilder is defined', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/42340
final List<String> items = <String>['1', '2', '3'];
String? selectedItem;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Scaffold(
body: DropdownButton<String>(
hint: const Text('Please select an item'),
value: selectedItem,
onChanged: (String? string) {
setState(() {
selectedItem = string;
});
},
selectedItemBuilder: (BuildContext context) {
return items.map((String item) {
return Text('You have selected: $item');
}).toList();
},
items: items.map((String item) {
return DropdownMenuItem<String>(
value: item,
child: Text(item),
);
}).toList(),
),
),
);
},
),
);
// Initially shows the hint text
expect(find.text('Please select an item'), findsOneWidget);
await tester.tap(find.text('Please select an item', skipOffstage: false), warnIfMissed: false);
await tester.pumpAndSettle();
await tester.tap(find.text('1'));
await tester.pumpAndSettle();
// Selecting an item should display its corresponding item builder
expect(find.text('You have selected: 1'), findsOneWidget);
});
testWidgets('Variable size and oversized menu items', (WidgetTester tester) async {
final List<double> itemHeights = <double>[30, 40, 50, 60];
double? dropdownValue = itemHeights[0];
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
body: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DropdownButton<double>(
onChanged: (double? value) {
setState(() { dropdownValue = value; });
},
value: dropdownValue,
itemHeight: null,
items: itemHeights.map<DropdownMenuItem<double>>((double value) {
return DropdownMenuItem<double>(
key: ValueKey<double>(value),
value: value,
child: Center(
child: Container(
width: 100,
height: value,
color: Colors.blue,
),
),
);
}).toList(),
);
},
),
),
),
);
}
final Finder dropdownIcon = find.byType(Icon);
final Finder item30 = find.byKey(const ValueKey<double>(30), skipOffstage: false);
final Finder item40 = find.byKey(const ValueKey<double>(40), skipOffstage: false);
final Finder item50 = find.byKey(const ValueKey<double>(50), skipOffstage: false);
final Finder item60 = find.byKey(const ValueKey<double>(60), skipOffstage: false);
// Only the DropdownButton is visible. It contains the selected item
// and a dropdown arrow icon.
await tester.pumpWidget(buildFrame());
expect(dropdownIcon, findsOneWidget);
expect(item30, findsOneWidget);
// All menu items have a minimum height of 48. The centers of the
// dropdown icon and the selected menu item are vertically aligned
// and horizontally adjacent.
expect(tester.getSize(item30), const Size(100, 48));
expect(tester.getCenter(item30).dy, tester.getCenter(dropdownIcon).dy);
expect(tester.getTopRight(item30).dx, tester.getTopLeft(dropdownIcon).dx);
// Show the popup menu.
await tester.tap(item30);
await tester.pumpAndSettle();
// Each item appears twice, once in the menu and once
// in the dropdown button's IndexedStack.
expect(item30.evaluate().length, 2);
expect(item40.evaluate().length, 2);
expect(item50.evaluate().length, 2);
expect(item60.evaluate().length, 2);
// Verify that the items have the expected sizes. The width of the items
// that appear in the menu is padded by 16 on the left and right.
expect(tester.getSize(item30.first), const Size(100, 48));
expect(tester.getSize(item40.first), const Size(100, 48));
expect(tester.getSize(item50.first), const Size(100, 50));
expect(tester.getSize(item60.first), const Size(100, 60));
expect(tester.getSize(item30.last), const Size(132, 48));
expect(tester.getSize(item40.last), const Size(132, 48));
expect(tester.getSize(item50.last), const Size(132, 50));
expect(tester.getSize(item60.last), const Size(132, 60));
// The vertical center of the selectedItem (item30) should
// line up with its button counterpart.
expect(tester.getCenter(item30.first).dy, tester.getCenter(item30.last).dy);
// The menu items should be arranged in a column.
expect(tester.getBottomLeft(item30.last), tester.getTopLeft(item40.last));
expect(tester.getBottomLeft(item40.last), tester.getTopLeft(item50.last));
expect(tester.getBottomLeft(item50.last), tester.getTopLeft(item60.last));
// Dismiss the menu by selecting item40 and then show the menu again.
await tester.tap(item40.last);
await tester.pumpAndSettle();
expect(dropdownValue, 40);
await tester.tap(item40.first);
await tester.pumpAndSettle();
// The vertical center of the selectedItem (item40) should
// line up with its button counterpart.
expect(tester.getCenter(item40.first).dy, tester.getCenter(item40.last).dy);
});
testWidgets('DropdownButton menu items do not resize when its route is popped', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/44877.
const List<String> items = <String>[
'one',
'two',
'three',
];
String? item = items[0];
late double textScale;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
builder: (BuildContext context, Widget? child) {
textScale = MediaQuery.of(context).textScaler.scale(14) / 14;
return MediaQuery(
data: MediaQueryData(textScaler: TextScaler.linear(textScale)),
child: child!,
);
},
home: Scaffold(
body: DropdownButton<String>(
value: item,
items: items.map((String item) => DropdownMenuItem<String>(
value: item,
child: Text(item),
)).toList(),
onChanged: (String? newItem) {
setState(() {
item = newItem;
textScale += 0.1;
});
},
),
),
);
},
),
);
// Verify that the first item is showing.
expect(find.text('one'), findsOneWidget);
// Select a different item to trigger setState, which updates mediaQuery
// and forces a performLayout on the popped _DropdownRoute. This operation
// should not cause an exception.
await tester.tap(find.text('one'));
await tester.pumpAndSettle();
await tester.tap(find.text('two').last);
await tester.pumpAndSettle();
expect(find.text('two'), findsOneWidget);
});
testWidgets('DropdownButton hint is selected item', (WidgetTester tester) async {
const double hintPaddingOffset = 8;
const List<String> itemValues = <String>['item0', 'item1', 'item2', 'item3'];
String? selectedItem = 'item0';
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
body: ButtonTheme(
alignedDropdown: true,
child: DropdownButtonHideUnderline(
child: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
// The pretzel below is from an actual app. The price
// of limited configurability is keeping this working.
return DropdownButton<String>(
isExpanded: true,
elevation: 2,
hint: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
// Stack with a positioned widget is used to override the
// hard coded 16px margin in the dropdown code, so that
// this hint aligns "properly" with the menu.
return Stack(
clipBehavior: Clip.none,
alignment: Alignment.topCenter,
children: <Widget>[
PositionedDirectional(
width: constraints.maxWidth + hintPaddingOffset,
start: -hintPaddingOffset,
top: 4.0,
child: Text('-$selectedItem-'),
),
],
);
},
),
onChanged: (String? value) {
setState(() { selectedItem = value; });
},
icon: Container(),
items: itemValues.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
);
},
),
),
),
),
),
);
}
await tester.pumpWidget(buildFrame());
expect(tester.getTopLeft(find.text('-item0-')).dx, 8);
// Show the popup menu.
await tester.tap(find.text('-item0-', skipOffstage: false), warnIfMissed: false);
await tester.pumpAndSettle();
expect(tester.getTopLeft(find.text('-item0-')).dx, 8);
});
testWidgets('DropdownButton can be focused, and has focusColor', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final UniqueKey buttonKey = UniqueKey();
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButton');
addTearDown(focusNode.dispose);
await tester.pumpWidget(buildFrame(buttonKey: buttonKey, onChanged: onChanged, focusNode: focusNode, autofocus: true, useMaterial3: false));
await tester.pumpAndSettle(); // Pump a frame for autofocus to take effect.
expect(focusNode.hasPrimaryFocus, isTrue);
expect(find.byType(Material), paints..rect(rect: const Rect.fromLTRB(348.0, 276.0, 452.0, 324.0), color: const Color(0x1f000000)));
await tester.pumpWidget(buildFrame(buttonKey: buttonKey, onChanged: onChanged, focusNode: focusNode, focusColor: const Color(0xff00ff00), useMaterial3: false));
await tester.pumpAndSettle(); // Pump a frame for autofocus to take effect.
expect(find.byType(Material), paints..rect(rect: const Rect.fromLTRB(348.0, 276.0, 452.0, 324.0), color: const Color(0x1f00ff00)));
});
testWidgets('DropdownButtonFormField can be focused, and has focusColor', (WidgetTester tester) async {
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final UniqueKey buttonKey = UniqueKey();
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButtonFormField');
addTearDown(focusNode.dispose);
await tester.pumpWidget(buildFrame(isFormField: true, buttonKey: buttonKey, onChanged: onChanged, focusNode: focusNode, autofocus: true));
await tester.pumpAndSettle(); // Pump a frame for autofocus to take effect.
expect(focusNode.hasPrimaryFocus, isTrue);
expect(find.byType(Material), paints ..rect(rect: const Rect.fromLTRB(0.0, 268.0, 800.0, 332.0), color: const Color(0x1f000000)));
await tester.pumpWidget(buildFrame(isFormField: true, buttonKey: buttonKey, onChanged: onChanged, focusNode: focusNode, focusColor: const Color(0xff00ff00)));
await tester.pumpAndSettle(); // Pump a frame for autofocus to take effect.
expect(find.byType(Material), paints ..rect(rect: const Rect.fromLTRB(0.0, 268.0, 800.0, 332.0), color: const Color(0x1f00ff00)));
});
testWidgets("DropdownButton won't be focused if not enabled", (WidgetTester tester) async {
final UniqueKey buttonKey = UniqueKey();
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButton');
addTearDown(focusNode.dispose);
await tester.pumpWidget(buildFrame(buttonKey: buttonKey, focusNode: focusNode, autofocus: true, focusColor: const Color(0xff00ff00)));
await tester.pump(); // Pump a frame for autofocus to take effect (although it shouldn't).
expect(focusNode.hasPrimaryFocus, isFalse);
expect(find.byKey(buttonKey), isNot(paints ..rrect(rrect: const RRect.fromLTRBXY(0.0, 0.0, 104.0, 48.0, 4.0, 4.0), color: const Color(0xff00ff00))));
});
testWidgets('DropdownButton is activated with the enter key', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButton');
addTearDown(focusNode.dispose);
String? value = 'one';
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
body: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DropdownButton<String>(
focusNode: focusNode,
autofocus: true,
onChanged: (String? newValue) {
setState(() {
value = newValue;
});
},
value: value,
itemHeight: null,
items: menuItems.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>(item),
value: item,
child: Text(item, key: ValueKey<String>('${item}Text')),
);
}).toList(),
);
},
),
),
),
);
}
await tester.pumpWidget(buildFrame());
await tester.pump(); // Pump a frame for autofocus to take effect.
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('one'));
await tester.sendKeyEvent(LogicalKeyboardKey.tab); // Focus 'two'
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter); // Select 'two'.
await tester.pump();
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('two'));
});
// Regression test for https://github.com/flutter/flutter/issues/77655.
testWidgets('DropdownButton selecting a null valued item should be selected', (WidgetTester tester) async {
final List<MapEntry<String?, String>> items = <MapEntry<String?, String>>[
const MapEntry<String?, String>(null, 'None'),
const MapEntry<String?, String>('one', 'One'),
const MapEntry<String?, String>('two', 'Two'),
];
String? selectedItem = 'one';
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Scaffold(
body: DropdownButton<String>(
value: selectedItem,
onChanged: (String? string) {
setState(() {
selectedItem = string;
});
},
items: items.map((MapEntry<String?, String> item) {
return DropdownMenuItem<String>(
value: item.key,
child: Text(item.value),
);
}).toList(),
),
),
);
},
),
);
await tester.tap(find.text('One'));
await tester.pumpAndSettle();
await tester.tap(find.text('None').last);
await tester.pumpAndSettle();
expect(find.text('None'), findsOneWidget);
});
testWidgets('DropdownButton is activated with the space key', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButton');
addTearDown(focusNode.dispose);
String? value = 'one';
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
body: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DropdownButton<String>(
focusNode: focusNode,
autofocus: true,
onChanged: (String? newValue) {
setState(() {
value = newValue;
});
},
value: value,
itemHeight: null,
items: menuItems.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>(item),
value: item,
child: Text(item, key: ValueKey<String>('${item}Text')),
);
}).toList(),
);
},
),
),
),
);
}
await tester.pumpWidget(buildFrame());
await tester.pump(); // Pump a frame for autofocus to take effect.
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('one'));
await tester.sendKeyEvent(LogicalKeyboardKey.tab); // Focus 'two'
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.space); // Select 'two'.
await tester.pump();
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('two'));
});
testWidgets('Selected element is focused when dropdown is opened', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButton');
addTearDown(focusNode.dispose);
String? value = 'one';
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DropdownButton<String>(
focusNode: focusNode,
autofocus: true,
onChanged: (String? newValue) {
setState(() {
value = newValue;
});
},
value: value,
itemHeight: null,
items: menuItems.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>(item),
value: item,
child: Text(item, key: ValueKey<String>('Text $item')),
);
}).toList(),
);
},
),
),
),
));
await tester.pump(); // Pump a frame for autofocus to take effect.
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu open animation
expect(value, equals('one'));
expect(Focus.of(tester.element(find.byKey(const ValueKey<String>('one')).last)).hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab); // Focus 'two'
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter); // Select 'two' and close the dropdown.
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu close animation
expect(value, equals('two'));
// Now make sure that "two" is focused when we re-open the dropdown.
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu open animation
expect(value, equals('two'));
final Element element = tester.element(find.byKey(const ValueKey<String>('two')).last);
final FocusNode node = Focus.of(element);
expect(node.hasFocus, isTrue);
});
testWidgets('Selected element is correctly focused with dropdown that more items than fit on the screen', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButton');
addTearDown(focusNode.dispose);
int? value = 1;
final List<int> hugeMenuItems = List<int>.generate(50, (int index) => index);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DropdownButton<int>(
focusNode: focusNode,
autofocus: true,
onChanged: (int? newValue) {
setState(() {
value = newValue;
});
},
value: value,
itemHeight: null,
items: hugeMenuItems.map<DropdownMenuItem<int>>((int item) {
return DropdownMenuItem<int>(
key: ValueKey<int>(item),
value: item,
child: Text(item.toString(), key: ValueKey<String>('Text $item')),
);
}).toList(),
);
},
),
),
),
),
);
await tester.pump(); // Pump a frame for autofocus to take effect.
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu open animation
expect(value, equals(1));
expect(Focus.of(tester.element(find.byKey(const ValueKey<int>(1)).last)).hasPrimaryFocus, isTrue);
for (int i = 0; i < 41; ++i) {
await tester.sendKeyEvent(LogicalKeyboardKey.tab); // Move to the next one.
await tester.pumpAndSettle(const Duration(milliseconds: 200)); // Wait for it to animate the menu.
}
await tester.sendKeyEvent(LogicalKeyboardKey.enter); // Select '42' and close the dropdown.
await tester.pumpAndSettle(const Duration(seconds: 1)); // Finish the menu close animation
expect(value, equals(42));
// Now make sure that "42" is focused when we re-open the dropdown.
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu open animation
expect(value, equals(42));
final Element element = tester.element(find.byKey(const ValueKey<int>(42)).last);
final FocusNode node = Focus.of(element);
expect(node.hasFocus, isTrue);
});
testWidgets("Having a focused element doesn't interrupt scroll when flung by touch", (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButton');
addTearDown(focusNode.dispose);
int? value = 1;
final List<int> hugeMenuItems = List<int>.generate(100, (int index) => index);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DropdownButton<int>(
focusNode: focusNode,
autofocus: true,
onChanged: (int? newValue) {
setState(() {
value = newValue;
});
},
value: value,
itemHeight: null,
items: hugeMenuItems.map<DropdownMenuItem<int>>((int item) {
return DropdownMenuItem<int>(
key: ValueKey<int>(item),
value: item,
child: Text(item.toString(), key: ValueKey<String>('Text $item')),
);
}).toList(),
);
},
),
),
),
),
);
await tester.pump(); // Pump a frame for autofocus to take effect.
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(value, equals(1));
expect(Focus.of(tester.element(find.byKey(const ValueKey<int>(1)).last)).hasPrimaryFocus, isTrue);
// Move to an item very far down the menu.
for (int i = 0; i < 90; ++i) {
await tester.sendKeyEvent(LogicalKeyboardKey.tab); // Move to the next one.
await tester.pumpAndSettle(); // Wait for it to animate the menu.
}
expect(Focus.of(tester.element(find.byKey(const ValueKey<int>(91)).last)).hasPrimaryFocus, isTrue);
// Scroll back to the top using touch, and make sure we end up there.
final Finder menu = find.byWidgetPredicate((Widget widget) {
return widget.runtimeType.toString().startsWith('_DropdownMenu<');
});
final Rect menuRect = tester.getRect(menu).shift(tester.getTopLeft(menu));
for (int i = 0; i < 10; ++i) {
await tester.fling(menu, Offset(0.0, menuRect.height), 10.0);
}
await tester.pumpAndSettle();
// Make sure that we made it to the top and something didn't stop the
// scroll.
expect(find.byKey(const ValueKey<int>(1)), findsNWidgets(2));
expect(
tester.getRect(find.byKey(const ValueKey<int>(1)).last),
equals(const Rect.fromLTRB(372.0, 104.0, 436.0, 152.0)),
);
// Scrolling to the top again has removed the one the focus was on from the
// tree, causing it to lose focus.
expect(Focus.of(tester.element(find.byKey(const ValueKey<int>(91), skipOffstage: false).last)).hasPrimaryFocus, isFalse);
});
testWidgets('DropdownButton onTap callback can request focus', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButton')..addListener(() { });
addTearDown(focusNode.dispose);
int? value = 1;
final List<int> hugeMenuItems = List<int>.generate(100, (int index) => index);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DropdownButton<int>(
focusNode: focusNode,
onChanged: (int? newValue) {
setState(() {
value = newValue;
});
},
value: value,
itemHeight: null,
items: hugeMenuItems.map<DropdownMenuItem<int>>((int item) {
return DropdownMenuItem<int>(
key: ValueKey<int>(item),
value: item,
child: Text(item.toString()),
);
}).toList(),
);
},
),
),
),
),
);
await tester.pump(); // Pump a frame for autofocus to take effect.
expect(focusNode.hasPrimaryFocus, isFalse);
await tester.tap(find.text('1'));
await tester.pumpAndSettle();
// Close the dropdown menu.
await tester.tapAt(const Offset(1.0, 1.0));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
});
testWidgets('DropdownButton changes selected item with arrow keys', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'DropdownButton');
addTearDown(focusNode.dispose);
String? value = 'one';
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
body: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DropdownButton<String>(
focusNode: focusNode,
autofocus: true,
onChanged: (String? newValue) {
setState(() {
value = newValue;
});
},
value: value,
itemHeight: null,
items: menuItems.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>(item),
value: item,
child: Text(item, key: ValueKey<String>('${item}Text')),
);
}).toList(),
);
},
),
),
),
);
}
await tester.pumpWidget(buildFrame());
await tester.pump(); // Pump a frame for autofocus to take effect.
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('one'));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Focus 'two'.
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); // Focus 'three'.
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); // Back to 'two'.
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter); // Select 'two'.
await tester.pump();
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(value, equals('two'));
});
testWidgets('DropdownButton onTap callback is called when defined', (WidgetTester tester) async {
int dropdownButtonTapCounter = 0;
String? value = 'one';
void onChanged(String? newValue) { value = newValue; }
void onTap() { dropdownButtonTapCounter += 1; }
Widget build() => buildFrame(
value: value,
onChanged: onChanged,
onTap: onTap,
);
await tester.pumpWidget(build());
expect(dropdownButtonTapCounter, 0);
// Tap dropdown button.
await tester.tap(find.text('one'));
await tester.pumpAndSettle();
expect(value, equals('one'));
expect(dropdownButtonTapCounter, 1); // Should update counter.
// Tap dropdown menu item.
await tester.tap(find.text('three').last);
await tester.pumpAndSettle();
expect(value, equals('three'));
expect(dropdownButtonTapCounter, 1); // Should not change.
// Tap dropdown button again.
await tester.tap(find.text('three', skipOffstage: false), warnIfMissed: false);
await tester.pumpAndSettle();
expect(value, equals('three'));
expect(dropdownButtonTapCounter, 2); // Should update counter.
// Tap dropdown menu item.
await tester.tap(find.text('two').last);
await tester.pumpAndSettle();
expect(value, equals('two'));
expect(dropdownButtonTapCounter, 2); // Should not change.
});
testWidgets('DropdownMenuItem onTap callback is called when defined', (WidgetTester tester) async {
String? value = 'one';
final List<int> menuItemTapCounters = <int>[0, 0, 0, 0];
void onChanged(String? newValue) { value = newValue; }
final List<VoidCallback> onTapCallbacks = <VoidCallback>[
() { menuItemTapCounters[0] += 1; },
() { menuItemTapCounters[1] += 1; },
() { menuItemTapCounters[2] += 1; },
() { menuItemTapCounters[3] += 1; },
];
int currentIndex = -1;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: RepaintBoundary(
child: DropdownButton<String>(
value: value,
onChanged: onChanged,
items: menuItems.map<DropdownMenuItem<String>>((String item) {
currentIndex += 1;
return DropdownMenuItem<String>(
value: item,
onTap: onTapCallbacks[currentIndex],
child: Text(item),
);
}).toList(),
),
),
),
),
);
// Tap dropdown button.
await tester.tap(find.text('one'));
await tester.pumpAndSettle();
expect(value, equals('one'));
// Counters should still be zero.
expect(menuItemTapCounters, <int>[0, 0, 0, 0]);
// Tap dropdown menu item.
await tester.tap(find.text('three').last);
await tester.pumpAndSettle();
// Should update the counter for the third item (second index).
expect(value, equals('three'));
expect(menuItemTapCounters, <int>[0, 0, 1, 0]);
// Tap dropdown button again.
await tester.tap(find.text('three', skipOffstage: false), warnIfMissed: false);
await tester.pumpAndSettle();
// Should not change.
expect(value, equals('three'));
expect(menuItemTapCounters, <int>[0, 0, 1, 0]);
// Tap dropdown menu item.
await tester.tap(find.text('two').last);
await tester.pumpAndSettle();
// Should update the counter for the second item (first index).
expect(value, equals('two'));
expect(menuItemTapCounters, <int>[0, 1, 1, 0]);
// Tap dropdown button again.
await tester.tap(find.text('two', skipOffstage: false), warnIfMissed: false);
await tester.pumpAndSettle();
// Should not change.
expect(value, equals('two'));
expect(menuItemTapCounters, <int>[0, 1, 1, 0]);
// Tap the already selected menu item
await tester.tap(find.text('two').last);
await tester.pumpAndSettle();
// Should update the counter for the second item (first index), even
// though it was already selected.
expect(value, equals('two'));
expect(menuItemTapCounters, <int>[0, 2, 1, 0]);
});
testWidgets('Does not crash when option is selected without waiting for opening animation to complete', (WidgetTester tester) async {
// Regression test for b/171846624.
final List<String> options = <String>['first', 'second', 'third'];
String? value = options.first;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) => DropdownButton<String>(
value: value,
items: options.map((String s) => DropdownMenuItem<String>(
value: s,
child: Text(s),
)).toList(),
onChanged: (String? v) {
setState(() {
value = v;
});
},
),
),
),
),
);
expect(find.text('first').hitTestable(), findsOneWidget);
expect(find.text('second').hitTestable(), findsNothing);
expect(find.text('third').hitTestable(), findsNothing);
// Open dropdown.
await tester.tap(find.text('first').hitTestable());
await tester.pump();
expect(find.text('third').hitTestable(), findsOneWidget);
expect(find.text('first').hitTestable(), findsOneWidget);
expect(find.text('second').hitTestable(), findsOneWidget);
// Deliberately not waiting for opening animation to complete!
// Select an option in dropdown.
await tester.tap(find.text('third').hitTestable());
await tester.pump();
expect(find.text('third').hitTestable(), findsOneWidget);
expect(find.text('first').hitTestable(), findsNothing);
expect(find.text('second').hitTestable(), findsNothing);
});
testWidgets('Dropdown menu should persistently show a scrollbar if it is scrollable', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(
value: '0',
// menu is short enough to fit onto the screen.
items: List<String>.generate(/*length=*/10, (int index) => index.toString()),
onChanged: onChanged,
));
await tester.tap(find.text('0'));
await tester.pumpAndSettle();
ScrollController scrollController = PrimaryScrollController.of(tester.element(find.byType(ListView)));
// The scrollbar shouldn't show if the list fits into the screen.
expect(scrollController.position.maxScrollExtent, 0);
expect(find.byType(Scrollbar), isNot(paints..rect()));
await tester.tap(find.text('0').last);
await tester.pumpAndSettle();
await tester.pumpWidget(buildFrame(
value: '0',
// menu is too long to fit onto the screen.
items: List<String>.generate(/*length=*/100, (int index) => index.toString()),
onChanged: onChanged,
));
await tester.tap(find.text('0'));
await tester.pumpAndSettle();
scrollController = PrimaryScrollController.of(tester.element(find.byType(ListView)));
// The scrollbar is shown when the list is longer than the height of the screen.
expect(scrollController.position.maxScrollExtent > 0, isTrue);
expect(find.byType(Scrollbar), paints..rect());
});
testWidgets("Dropdown menu's maximum height should be influenced by DropdownButton.menuMaxHeight.", (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(
value: '0',
items: List<String>.generate(/*length=*/64, (int index) => index.toString()),
onChanged: onChanged,
));
await tester.tap(find.text('0'));
await tester.pumpAndSettle();
final Element element = tester.element(find.byType(ListView));
double menuHeight = element.size!.height;
// The default maximum height should be one item height from the edge.
// https://material.io/design/components/menus.html#usage
final double mediaHeight = MediaQuery.of(element).size.height;
final double defaultMenuHeight = mediaHeight - (2 * kMinInteractiveDimension);
expect(menuHeight, defaultMenuHeight);
await tester.tap(find.text('0').last);
await tester.pumpAndSettle();
// Set menuMaxHeight which is less than defaultMenuHeight
await tester.pumpWidget(buildFrame(
value: '0',
items: List<String>.generate(/*length=*/64, (int index) => index.toString()),
onChanged: onChanged,
menuMaxHeight: 7 * kMinInteractiveDimension,
));
await tester.tap(find.text('0'));
await tester.pumpAndSettle();
menuHeight = tester.element(find.byType(ListView)).size!.height;
expect(menuHeight == defaultMenuHeight, isFalse);
expect(menuHeight, kMinInteractiveDimension * 7);
await tester.tap(find.text('0').last);
await tester.pumpAndSettle();
// Set menuMaxHeight which is greater than defaultMenuHeight
await tester.pumpWidget(buildFrame(
value: '0',
items: List<String>.generate(/*length=*/64, (int index) => index.toString()),
onChanged: onChanged,
menuMaxHeight: mediaHeight,
));
await tester.tap(find.text('0'));
await tester.pumpAndSettle();
menuHeight = tester.element(find.byType(ListView)).size!.height;
expect(menuHeight, defaultMenuHeight);
});
// Regression test for https://github.com/flutter/flutter/issues/89029
testWidgets('menu position test with `menuMaxHeight`', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
await tester.pumpWidget(buildFrame(
buttonKey: buttonKey,
value: '6',
items: List<String>.generate(/*length=*/64, (int index) => index.toString()),
onChanged: onChanged,
menuMaxHeight: 2 * kMinInteractiveDimension,
));
await tester.tap(find.text('6'));
await tester.pumpAndSettle();
final RenderBox menuBox = tester.renderObject(find.byType(ListView));
final RenderBox buttonBox = tester.renderObject(find.byKey(buttonKey));
// The menu's bottom should align with the drop-button's bottom.
expect(
menuBox.localToGlobal(menuBox.paintBounds.bottomCenter).dy,
buttonBox.localToGlobal(buttonBox.paintBounds.bottomCenter).dy,
);
});
// Regression test for https://github.com/flutter/flutter/issues/76614
testWidgets('Do not crash if used in very short screen', (WidgetTester tester) async {
// The default item height is 48.0 pixels and needs two items padding since
// the menu requires empty space surrounding the menu. Finally, the constraint height
// is 47.0 pixels for the menu rendering.
tester.view.physicalSize = const Size(800.0, 48.0 * 3 - 1.0);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
const String value = 'foo';
final UniqueKey itemKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: DropdownButton<String>(
value: value,
items: <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
key: itemKey,
value: value,
child: const Text(value),
),
],
onChanged: (_) { },
),
),
),
),
);
await tester.tap(find.text(value));
await tester.pumpAndSettle();
final List<RenderBox> itemBoxes = tester.renderObjectList<RenderBox>(find.byKey(itemKey)).toList();
expect(itemBoxes[0].localToGlobal(Offset.zero).dx, 364.0);
expect(itemBoxes[0].localToGlobal(Offset.zero).dy, 47.5);
expect(itemBoxes[1].localToGlobal(Offset.zero).dx, 364.0);
expect(itemBoxes[1].localToGlobal(Offset.zero).dy, 47.5);
expect(
find.ancestor(
of: find.text(value).last,
matching: find.byType(CustomPaint),
).at(2),
paints
..save()
..rrect()
..rrect()
..rrect()
// The height of menu is 47.0.
..rrect(rrect: const RRect.fromLTRBXY(0.0, 0.0, 112.0, 47.0, 2.0, 2.0), color: Colors.grey[50], hasMaskFilter: false),
);
});
testWidgets('Tapping a disabled item should not close DropdownButton', (WidgetTester tester) async {
String? value = 'first';
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) => DropdownButton<String>(
value: value,
items: const <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
enabled: false,
child: Text('disabled'),
),
DropdownMenuItem<String>(
value: 'first',
child: Text('first'),
),
DropdownMenuItem<String>(
value: 'second',
child: Text('second'),
),
],
onChanged: (String? newValue) {
setState(() {
value = newValue;
});
},
),
),
),
),
);
// Open dropdown.
await tester.tap(find.text('first').hitTestable());
await tester.pumpAndSettle();
// Tap on a disabled item.
await tester.tap(find.text('disabled').hitTestable());
await tester.pumpAndSettle();
// The dropdown should still be open, i.e., there should be one widget with 'second' text.
expect(find.text('second').hitTestable(), findsOneWidget);
});
testWidgets('Disabled item should not be focusable', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DropdownButton<String>(
value: 'enabled',
onChanged: onChanged,
items: const <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
enabled: false,
child: Text('disabled'),
),
DropdownMenuItem<String>(
value: 'enabled',
child: Text('enabled'),
),
],
),
),
),
);
// Open dropdown.
await tester.tap(find.text('enabled').hitTestable());
await tester.pumpAndSettle();
// The `FocusNode` of [disabledItem] should be `null` as enabled is false.
final Element disabledItem = tester.element(find.text('disabled').hitTestable());
expect(Focus.maybeOf(disabledItem), null, reason: 'Disabled menu item should not be able to request focus');
});
testWidgets('alignment test', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget buildFrame({AlignmentGeometry? buttonAlignment, AlignmentGeometry? menuAlignment}) {
return MaterialApp(
home: Scaffold(
body: Center(
child: DropdownButton<String>(
key: buttonKey,
alignment: buttonAlignment ?? AlignmentDirectional.centerStart,
value: 'enabled',
onChanged: onChanged,
items: <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
alignment: buttonAlignment ?? AlignmentDirectional.centerStart,
enabled: false,
child: const Text('disabled'),
),
DropdownMenuItem<String>(
alignment: buttonAlignment ?? AlignmentDirectional.centerStart,
value: 'enabled',
child: const Text('enabled'),
),
],
),
),
),
);
}
await tester.pumpWidget(buildFrame());
final RenderBox buttonBox = tester.renderObject(find.byKey(buttonKey));
RenderBox selectedItemBox = tester.renderObject(find.text('enabled'));
// Default to center-start aligned.
expect(
buttonBox.localToGlobal(Offset(0.0, buttonBox.size.height / 2.0)),
selectedItemBox.localToGlobal(Offset(0.0, selectedItemBox.size.height / 2.0)),
);
await tester.pumpWidget(buildFrame(
buttonAlignment: AlignmentDirectional.center,
menuAlignment: AlignmentDirectional.center,
));
selectedItemBox = tester.renderObject(find.text('enabled'));
// Should be center-center aligned, the icon size is 24.0 pixels.
expect(
buttonBox.localToGlobal(Offset((buttonBox.size.width -24.0) / 2.0, buttonBox.size.height / 2.0)),
offsetMoreOrLessEquals(selectedItemBox.localToGlobal(Offset(selectedItemBox.size.width / 2.0, selectedItemBox.size.height / 2.0))),
);
// Open dropdown.
await tester.tap(find.text('enabled').hitTestable());
await tester.pumpAndSettle();
final RenderBox selectedItemBoxInMenu = tester.renderObjectList<RenderBox>(find.text('enabled')).toList()[1];
final Finder menu = find.byWidgetPredicate((Widget widget) {
return widget.runtimeType.toString().startsWith('_DropdownMenu<');
});
final Rect menuRect = tester.getRect(menu);
final Offset center = selectedItemBoxInMenu.localToGlobal(
Offset(selectedItemBoxInMenu.size.width / 2.0, selectedItemBoxInMenu.size.height / 2.0)
);
expect(center.dx, moreOrLessEquals(menuRect.topCenter.dx));
expect(
center.dy,
moreOrLessEquals(selectedItemBox.localToGlobal(Offset(selectedItemBox.size.width / 2.0, selectedItemBox.size.height / 2.0)).dy),
);
});
group('feedback', () {
late FeedbackTester feedback;
setUp(() {
feedback = FeedbackTester();
});
tearDown(() {
feedback.dispose();
});
Widget feedbackBoilerplate({bool? enableFeedback}) {
return MaterialApp(
home : Material(
child: DropdownButton<String>(
value: 'One',
enableFeedback: enableFeedback,
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String? value) {},
items: <String>['One', 'Two'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
);
}
testWidgets('Dropdown with enabled feedback', (WidgetTester tester) async {
const bool enableFeedback = true;
await tester.pumpWidget(feedbackBoilerplate(enableFeedback: enableFeedback));
await tester.tap(find.text('One'));
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(InkWell, 'One').last);
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
});
testWidgets('Dropdown with disabled feedback', (WidgetTester tester) async {
const bool enableFeedback = false;
await tester.pumpWidget(feedbackBoilerplate(enableFeedback: enableFeedback));
await tester.tap(find.text('One'));
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(InkWell, 'One').last);
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 0);
expect(feedback.hapticCount, 0);
});
testWidgets('Dropdown with enabled feedback by default', (WidgetTester tester) async {
await tester.pumpWidget(feedbackBoilerplate());
await tester.tap(find.text('One'));
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(InkWell, 'Two').last);
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
});
});
testWidgets('DropdownButton changes mouse cursor when hovered', (WidgetTester tester) async {
const Key key = Key('testDropdownButton');
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DropdownButton<String>(
key: key,
onChanged: (String? newValue) {},
items: <String>['One', 'Two', 'Three', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList()
),
),
),
);
final Finder dropdownButtonFinder = find.byKey(key);
final Offset onDropdownButton = tester.getCenter(dropdownButtonFinder);
final Offset offDropdownButton = tester.getBottomRight(dropdownButtonFinder) + const Offset(1, 1);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: onDropdownButton);
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
await gesture.moveTo(offDropdownButton);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
// Test that mouse cursor doesn't change when button is disabled
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DropdownButton<String>(
key: key,
onChanged: null,
items: <String>['One', 'Two', 'Three', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
),
),
);
await gesture.moveTo(onDropdownButton);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
await gesture.moveTo(offDropdownButton);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('Conflicting scrollbars are not applied by ScrollBehavior to Dropdown', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/83819
// Open the dropdown menu
final Key buttonKey = UniqueKey();
await tester.pumpWidget(buildFrame(
buttonKey: buttonKey,
value: null, // nothing selected
items: List<String>.generate(100, (int index) => index.toString()),
onChanged: onChanged,
));
await tester.tap(find.byKey(buttonKey));
await tester.pump();
await tester.pumpAndSettle(); // finish the menu animation
// The inherited ScrollBehavior should not apply Scrollbars since they are
// already built in to the widget. For iOS platform, ScrollBar directly returns
// CupertinoScrollbar
expect(find.byType(CupertinoScrollbar), debugDefaultTargetPlatformOverride == TargetPlatform.iOS ? findsOneWidget : findsNothing);
expect(find.byType(Scrollbar), findsOneWidget);
expect(find.byType(RawScrollbar), findsNothing);
}, variant: TargetPlatformVariant.all());
testWidgets('borderRadius property works properly', (WidgetTester tester) async {
const double radius = 20.0;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: DropdownButton<String>(
borderRadius: BorderRadius.circular(radius),
value: 'One',
items: <String>['One', 'Two', 'Three', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (_) { },
),
),
),
),
);
await tester.tap(find.text('One'));
await tester.pumpAndSettle();
expect(
find.ancestor(
of: find.text('One').last,
matching: find.byType(CustomPaint),
).at(2),
paints
..save()
..rrect()
..rrect()
..rrect()
..rrect(rrect: const RRect.fromLTRBXY(0.0, 0.0, 144.0, 208.0, radius, radius)),
);
});
// Regression test for https://github.com/flutter/flutter/issues/88574
testWidgets("specifying itemHeight affects popup menu items' height", (WidgetTester tester) async {
const String value = 'One';
const double itemHeight = 80;
final List<DropdownMenuItem<String>> menuItems = <String>[
value,
'Two',
'Free',
'Four',
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: DropdownButton<String>(
value: value,
itemHeight: itemHeight,
onChanged: (_) {},
items: menuItems,
),
),
),
),
);
await tester.tap(find.text(value));
await tester.pumpAndSettle();
for (final DropdownMenuItem<String> item in menuItems) {
final Iterable<Element> elements = tester.elementList(find.byWidget(item));
for (final Element element in elements){
expect(element.size!.height, itemHeight);
}
}
});
// Regression test for https://github.com/flutter/flutter/issues/92438
testWidgets('Do not throw due to the double precision', (WidgetTester tester) async {
const String value = 'One';
const double itemHeight = 77.701;
final List<DropdownMenuItem<String>> menuItems = <String>[
value,
'Two',
'Free',
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: DropdownButton<String>(
value: value,
itemHeight: itemHeight,
onChanged: (_) {},
items: menuItems,
),
),
),
),
);
await tester.tap(find.text(value));
await tester.pumpAndSettle();
expect(tester.takeException(), null);
});
testWidgets('BorderRadius property works properly for DropdownButtonFormField', (WidgetTester tester) async {
const double radius = 20.0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: DropdownButtonFormField<String>(
borderRadius: BorderRadius.circular(radius),
value: 'One',
items: <String>['One', 'Two', 'Three', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (_) { },
),
),
),
),
);
await tester.tap(find.text('One'));
await tester.pumpAndSettle();
expect(
find.ancestor(
of: find.text('One').last,
matching: find.byType(CustomPaint),
).at(2),
paints
..save()
..rrect()
..rrect()
..rrect()
..rrect(rrect: const RRect.fromLTRBXY(0.0, 0.0, 800.0, 208.0, radius, radius)),
);
});
testWidgets('DropdownButton hint alignment', (WidgetTester tester) async {
const String hintText = 'hint';
// AlignmentDirectional.centerStart (default)
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.centerStart,
isExpanded: false,
));
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dx, 348.0);
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dy, 292.0);
// AlignmentDirectional.topStart
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.topStart,
isExpanded: false,
));
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dx, 348.0);
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dy, 250.0);
// AlignmentDirectional.bottomStart
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.bottomStart,
isExpanded: false,
));
expect(tester.getBottomLeft(find.text(hintText,skipOffstage: false)).dx, 348.0);
expect(tester.getBottomLeft(find.text(hintText,skipOffstage: false)).dy, 350.0);
// AlignmentDirectional.center
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.center,
isExpanded: false,
));
expect(tester.getCenter(find.text(hintText,skipOffstage: false)).dx, 388.0);
expect(tester.getCenter(find.text(hintText,skipOffstage: false)).dy, 300.0);
// AlignmentDirectional.topEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.topEnd,
isExpanded: false,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 428.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 250.0);
// AlignmentDirectional.centerEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.centerEnd,
isExpanded: false,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 428.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 292.0);
// AlignmentDirectional.bottomEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.bottomEnd,
isExpanded: false,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 428.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 334.0);
// DropdownButton with `isExpanded: true`
// AlignmentDirectional.centerStart (default)
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.centerStart,
isExpanded: true,
));
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dx, 0.0);
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dy, 292.0);
// AlignmentDirectional.topStart
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.topStart,
isExpanded: true,
));
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dx, 0.0);
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dy, 250.0);
// AlignmentDirectional.bottomStart
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.bottomStart,
isExpanded: true,
));
expect(tester.getBottomLeft(find.text(hintText,skipOffstage: false)).dx, 0.0);
expect(tester.getBottomLeft(find.text(hintText,skipOffstage: false)).dy, 350.0);
// AlignmentDirectional.center
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.center,
isExpanded: true,
));
expect(tester.getCenter(find.text(hintText,skipOffstage: false)).dx, 388.0);
expect(tester.getCenter(find.text(hintText,skipOffstage: false)).dy, 300.0);
// AlignmentDirectional.topEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.topEnd,
isExpanded: true,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 776.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 250.0);
// AlignmentDirectional.centerEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.centerEnd,
isExpanded: true,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 776.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 292.0);
// AlignmentDirectional.bottomEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.bottomEnd,
isExpanded: true,
));
expect(tester.getBottomRight(find.text(hintText,skipOffstage: false)).dx, 776.0);
expect(tester.getBottomRight(find.text(hintText,skipOffstage: false)).dy, 350.0);
});
testWidgets('DropdownButton hint alignment with selectedItemBuilder', (WidgetTester tester) async {
const String hintText = 'hint';
// AlignmentDirectional.centerStart (default)
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.centerStart,
isExpanded: false,
enableSelectedItemBuilder: true,
));
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dx, 348.0);
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dy, 292.0);
// AlignmentDirectional.topStart
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.topStart,
isExpanded: false,
enableSelectedItemBuilder: true,
));
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dx, 348.0);
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dy, 250.0);
// AlignmentDirectional.bottomStart
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.bottomStart,
isExpanded: false,
enableSelectedItemBuilder: true,
));
expect(tester.getBottomLeft(find.text(hintText,skipOffstage: false)).dx, 348.0);
expect(tester.getBottomLeft(find.text(hintText,skipOffstage: false)).dy, 350.0);
// AlignmentDirectional.center
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.center,
isExpanded: false,
enableSelectedItemBuilder: true,
));
expect(tester.getCenter(find.text(hintText,skipOffstage: false)).dx, 388.0);
expect(tester.getCenter(find.text(hintText,skipOffstage: false)).dy, 300.0);
// AlignmentDirectional.topEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.topEnd,
isExpanded: false,
enableSelectedItemBuilder: true,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 428.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 250.0);
// AlignmentDirectional.centerEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.centerEnd,
isExpanded: false,
enableSelectedItemBuilder: true,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 428.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 292.0);
// AlignmentDirectional.bottomEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.bottomEnd,
isExpanded: false,
enableSelectedItemBuilder: true,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 428.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 334.0);
// DropdownButton with `isExpanded: true`
// AlignmentDirectional.centerStart (default)
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.centerStart,
isExpanded: true,
enableSelectedItemBuilder: true,
));
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dx, 0.0);
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dy, 292.0);
// AlignmentDirectional.topStart
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.topStart,
isExpanded: true,
enableSelectedItemBuilder: true,
));
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dx, 0.0);
expect(tester.getTopLeft(find.text(hintText,skipOffstage: false)).dy, 250.0);
// AlignmentDirectional.bottomStart
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.bottomStart,
isExpanded: true,
enableSelectedItemBuilder: true,
));
expect(tester.getBottomLeft(find.text(hintText,skipOffstage: false)).dx, 0.0);
expect(tester.getBottomLeft(find.text(hintText,skipOffstage: false)).dy, 350.0);
// AlignmentDirectional.center
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.center,
isExpanded: true,
enableSelectedItemBuilder: true,
));
expect(tester.getCenter(find.text(hintText,skipOffstage: false)).dx, 388.0);
expect(tester.getCenter(find.text(hintText,skipOffstage: false)).dy, 300.0);
// AlignmentDirectional.topEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.topEnd,
isExpanded: true,
enableSelectedItemBuilder: true,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 776.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 250.0);
// AlignmentDirectional.centerEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.centerEnd,
isExpanded: true,
enableSelectedItemBuilder: true,
));
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dx, 776.0);
expect(tester.getTopRight(find.text(hintText,skipOffstage: false)).dy, 292.0);
// AlignmentDirectional.bottomEnd
await tester.pumpWidget(buildDropdownWithHint(
alignment: AlignmentDirectional.bottomEnd,
isExpanded: true,
enableSelectedItemBuilder: true,
));
expect(tester.getBottomRight(find.text(hintText,skipOffstage: false)).dx, 776.0);
expect(tester.getBottomRight(find.text(hintText,skipOffstage: false)).dy, 350.0);
});
testWidgets('BorderRadius property clips dropdown button and dropdown menu', (WidgetTester tester) async {
const double radius = 20.0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: DropdownButtonFormField<String>(
borderRadius: BorderRadius.circular(radius),
value: 'One',
items: <String>['One', 'Two', 'Three', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (_) { },
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(DropdownButtonFormField<String>)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..rrect(rrect: RRect.fromLTRBR(0.0, 276.0, 800.0, 324.0, const Radius.circular(radius))));
await tester.tap(find.text('One'));
await tester.pumpAndSettle();
final RenderClipRRect renderClip = tester.allRenderObjects.whereType<RenderClipRRect>().first;
expect(renderClip.borderRadius, BorderRadius.circular(radius));
});
testWidgets('Size of DropdownButton with padding', (WidgetTester tester) async {
const double padVertical = 5;
const double padHorizontal = 10;
final Key buttonKey = UniqueKey();
EdgeInsets? padding;
Widget build() => buildFrame(buttonKey: buttonKey, onChanged: onChanged, padding: padding);
await tester.pumpWidget(build());
final RenderBox buttonBoxNoPadding = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBoxNoPadding.attached);
final Size noPaddingSize = Size.copy(buttonBoxNoPadding.size);
padding = const EdgeInsets.symmetric(vertical: padVertical, horizontal: padHorizontal);
await tester.pumpWidget(build());
final RenderBox buttonBoxPadded = tester.renderObject<RenderBox>(find.byKey(buttonKey));
assert(buttonBoxPadded.attached);
final Size paddedSize = Size.copy(buttonBoxPadded.size);
// dropdowns with padding should be that much larger than with no padding
expect(noPaddingSize.height, equals(paddedSize.height - padVertical * 2));
expect(noPaddingSize.width, equals(paddedSize.width - padHorizontal * 2));
});
}
| flutter/packages/flutter/test/material/dropdown_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/dropdown_test.dart",
"repo_id": "flutter",
"token_count": 61760
} | 274 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('FloatingActionButtonThemeData copyWith, ==, hashCode basics', () {
expect(const FloatingActionButtonThemeData(), const FloatingActionButtonThemeData().copyWith());
expect(const FloatingActionButtonThemeData().hashCode, const FloatingActionButtonThemeData().copyWith().hashCode);
});
test('FloatingActionButtonThemeData lerp special cases', () {
expect(FloatingActionButtonThemeData.lerp(null, null, 0), null);
const FloatingActionButtonThemeData data = FloatingActionButtonThemeData();
expect(identical(FloatingActionButtonThemeData.lerp(data, data, 0.5), data), true);
});
testWidgets('Material3: Default values are used when no FloatingActionButton or FloatingActionButtonThemeData properties are specified', (WidgetTester tester) async {
const ColorScheme colorScheme = ColorScheme.light();
await tester.pumpWidget(MaterialApp(
theme: ThemeData.from(useMaterial3: true, colorScheme: colorScheme),
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () { },
child: const Icon(Icons.add),
),
),
));
expect(_getRawMaterialButton(tester).fillColor, colorScheme.primaryContainer);
expect(_getRichText(tester).text.style!.color, colorScheme.onPrimaryContainer);
// These defaults come directly from the [FloatingActionButton].
expect(_getRawMaterialButton(tester).elevation, 6);
expect(_getRawMaterialButton(tester).highlightElevation, 6);
expect(_getRawMaterialButton(tester).shape, const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))));
expect(_getRawMaterialButton(tester).splashColor, colorScheme.onPrimaryContainer.withOpacity(0.1));
expect(_getRawMaterialButton(tester).constraints, const BoxConstraints.tightFor(width: 56.0, height: 56.0));
expect(_getIconSize(tester).width, 24.0);
expect(_getIconSize(tester).height, 24.0);
});
testWidgets('Material2: Default values are used when no FloatingActionButton or FloatingActionButtonThemeData properties are specified', (WidgetTester tester) async {
const ColorScheme colorScheme = ColorScheme.light();
await tester.pumpWidget(MaterialApp(
theme: ThemeData.from(useMaterial3: false, colorScheme: colorScheme),
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () { },
child: const Icon(Icons.add),
),
),
));
expect(_getRawMaterialButton(tester).fillColor, colorScheme.secondary);
expect(_getRichText(tester).text.style!.color, colorScheme.onSecondary);
// These defaults come directly from the [FloatingActionButton].
expect(_getRawMaterialButton(tester).elevation, 6);
expect(_getRawMaterialButton(tester).highlightElevation, 12);
expect(_getRawMaterialButton(tester).shape, const CircleBorder());
expect(_getRawMaterialButton(tester).splashColor, ThemeData().splashColor);
expect(_getRawMaterialButton(tester).constraints, const BoxConstraints.tightFor(width: 56.0, height: 56.0));
expect(_getIconSize(tester).width, 24.0);
expect(_getIconSize(tester).height, 24.0);
});
testWidgets('FloatingActionButtonThemeData values are used when no FloatingActionButton properties are specified', (WidgetTester tester) async {
const Color backgroundColor = Color(0xBEEFBEEF);
const Color foregroundColor = Color(0xFACEFACE);
const Color splashColor = Color(0xCAFEFEED);
const double elevation = 7;
const double disabledElevation = 1;
const double highlightElevation = 13;
const ShapeBorder shape = StadiumBorder();
const BoxConstraints constraints = BoxConstraints.tightFor(width: 100.0, height: 100.0);
await tester.pumpWidget(MaterialApp(
theme: ThemeData().copyWith(
floatingActionButtonTheme: const FloatingActionButtonThemeData(
backgroundColor: backgroundColor,
foregroundColor: foregroundColor,
splashColor: splashColor,
elevation: elevation,
disabledElevation: disabledElevation,
highlightElevation: highlightElevation,
shape: shape,
sizeConstraints: constraints,
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () { },
child: const Icon(Icons.add),
),
),
));
expect(_getRawMaterialButton(tester).fillColor, backgroundColor);
expect(_getRichText(tester).text.style!.color, foregroundColor);
expect(_getRawMaterialButton(tester).elevation, elevation);
expect(_getRawMaterialButton(tester).disabledElevation, disabledElevation);
expect(_getRawMaterialButton(tester).highlightElevation, highlightElevation);
expect(_getRawMaterialButton(tester).shape, shape);
expect(_getRawMaterialButton(tester).splashColor, splashColor);
expect(_getRawMaterialButton(tester).constraints, constraints);
});
testWidgets('FloatingActionButton values take priority over FloatingActionButtonThemeData values when both properties are specified', (WidgetTester tester) async {
const Color backgroundColor = Color(0x00000001);
const Color foregroundColor = Color(0x00000002);
const Color splashColor = Color(0x00000003);
const double elevation = 7;
const double disabledElevation = 1;
const double highlightElevation = 13;
const ShapeBorder shape = StadiumBorder();
await tester.pumpWidget(MaterialApp(
theme: ThemeData().copyWith(
floatingActionButtonTheme: const FloatingActionButtonThemeData(
backgroundColor: Color(0x00000004),
foregroundColor: Color(0x00000005),
splashColor: Color(0x00000006),
elevation: 23,
disabledElevation: 11,
highlightElevation: 43,
shape: BeveledRectangleBorder(),
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () { },
backgroundColor: backgroundColor,
foregroundColor: foregroundColor,
splashColor: splashColor,
elevation: elevation,
disabledElevation: disabledElevation,
highlightElevation: highlightElevation,
shape: shape,
child: const Icon(Icons.add),
),
),
));
expect(_getRawMaterialButton(tester).fillColor, backgroundColor);
expect(_getRichText(tester).text.style!.color, foregroundColor);
expect(_getRawMaterialButton(tester).elevation, elevation);
expect(_getRawMaterialButton(tester).disabledElevation, disabledElevation);
expect(_getRawMaterialButton(tester).highlightElevation, highlightElevation);
expect(_getRawMaterialButton(tester).shape, shape);
expect(_getRawMaterialButton(tester).splashColor, splashColor);
});
testWidgets('FloatingActionButton uses a custom shape when specified in the theme', (WidgetTester tester) async {
const ShapeBorder customShape = BeveledRectangleBorder();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () { },
shape: customShape,
),
),
));
expect(_getRawMaterialButton(tester).shape, customShape);
});
testWidgets('FloatingActionButton.small uses custom constraints when specified in the theme', (WidgetTester tester) async {
const BoxConstraints constraints = BoxConstraints.tightFor(width: 100.0, height: 100.0);
const double iconSize = 24.0;
await tester.pumpWidget(MaterialApp(
theme: ThemeData().copyWith(
floatingActionButtonTheme: const FloatingActionButtonThemeData(
smallSizeConstraints: constraints,
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton.small(
onPressed: () { },
child: const Icon(Icons.add),
),
),
));
expect(_getRawMaterialButton(tester).constraints, constraints);
expect(_getIconSize(tester).width, iconSize);
expect(_getIconSize(tester).height, iconSize);
});
testWidgets('FloatingActionButton.large uses custom constraints when specified in the theme', (WidgetTester tester) async {
const BoxConstraints constraints = BoxConstraints.tightFor(width: 100.0, height: 100.0);
const double iconSize = 36.0;
await tester.pumpWidget(MaterialApp(
theme: ThemeData().copyWith(
floatingActionButtonTheme: const FloatingActionButtonThemeData(
largeSizeConstraints: constraints,
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton.large(
onPressed: () { },
child: const Icon(Icons.add),
),
),
));
expect(_getRawMaterialButton(tester).constraints, constraints);
expect(_getIconSize(tester).width, iconSize);
expect(_getIconSize(tester).height, iconSize);
});
testWidgets('Material3: FloatingActionButton.extended uses custom properties when specified in the theme', (WidgetTester tester) async {
const ColorScheme colorScheme = ColorScheme.light();
const Key iconKey = Key('icon');
const Key labelKey = Key('label');
const BoxConstraints constraints = BoxConstraints.tightFor(height: 100.0);
const double iconLabelSpacing = 33.0;
const EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(start: 5.0, end: 6.0);
const TextStyle textStyle = TextStyle(letterSpacing: 2.0);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
useMaterial3: true,
colorScheme: colorScheme,
).copyWith(
floatingActionButtonTheme: const FloatingActionButtonThemeData(
extendedSizeConstraints: constraints,
extendedIconLabelSpacing: iconLabelSpacing,
extendedPadding: padding,
extendedTextStyle: textStyle,
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () { },
label: const Text('Extended', key: labelKey),
icon: const Icon(Icons.add, key: iconKey),
),
),
));
expect(_getRawMaterialButton(tester).constraints, constraints);
expect(tester.getTopLeft(find.byKey(labelKey)).dx - tester.getTopRight(find.byKey(iconKey)).dx, iconLabelSpacing);
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);
expect(_getRawMaterialButton(tester).textStyle, textStyle.copyWith(color: colorScheme.onPrimaryContainer));
});
testWidgets('Material2: FloatingActionButton.extended uses custom properties when specified in the theme', (WidgetTester tester) async {
const Key iconKey = Key('icon');
const Key labelKey = Key('label');
const BoxConstraints constraints = BoxConstraints.tightFor(height: 100.0);
const double iconLabelSpacing = 33.0;
const EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(start: 5.0, end: 6.0);
const TextStyle textStyle = TextStyle(letterSpacing: 2.0);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false).copyWith(
floatingActionButtonTheme: const FloatingActionButtonThemeData(
extendedSizeConstraints: constraints,
extendedIconLabelSpacing: iconLabelSpacing,
extendedPadding: padding,
extendedTextStyle: textStyle,
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () { },
label: const Text('Extended', key: labelKey),
icon: const Icon(Icons.add, key: iconKey),
),
),
));
expect(_getRawMaterialButton(tester).constraints, constraints);
expect(tester.getTopLeft(find.byKey(labelKey)).dx - tester.getTopRight(find.byKey(iconKey)).dx, iconLabelSpacing);
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);
// The color comes from the default color scheme's onSecondary value.
expect(_getRawMaterialButton(tester).textStyle, textStyle.copyWith(color: const Color(0xffffffff)));
});
testWidgets('Material3: FloatingActionButton.extended custom properties takes priority over FloatingActionButtonThemeData spacing', (WidgetTester tester) async {
const ColorScheme colorScheme = ColorScheme.light();
const Key iconKey = Key('icon');
const Key labelKey = Key('label');
const double iconLabelSpacing = 33.0;
const EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(start: 5.0, end: 6.0);
const TextStyle textStyle = TextStyle(letterSpacing: 2.0);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
useMaterial3: true,
colorScheme: colorScheme,
).copyWith(
floatingActionButtonTheme: const FloatingActionButtonThemeData(
extendedIconLabelSpacing: 25.0,
extendedPadding: EdgeInsetsDirectional.only(start: 7.0, end: 8.0),
extendedTextStyle: TextStyle(letterSpacing: 3.0),
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () { },
label: const Text('Extended', key: labelKey),
icon: const Icon(Icons.add, key: iconKey),
extendedIconLabelSpacing: iconLabelSpacing,
extendedPadding: padding,
extendedTextStyle: textStyle,
),
),
));
expect(tester.getTopLeft(find.byKey(labelKey)).dx - tester.getTopRight(find.byKey(iconKey)).dx, iconLabelSpacing);
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);
expect(_getRawMaterialButton(tester).textStyle, textStyle.copyWith(color: colorScheme.onPrimaryContainer));
});
testWidgets('Material2: FloatingActionButton.extended custom properties takes priority over FloatingActionButtonThemeData spacing', (WidgetTester tester) async {
const Key iconKey = Key('icon');
const Key labelKey = Key('label');
const double iconLabelSpacing = 33.0;
const EdgeInsetsDirectional padding = EdgeInsetsDirectional.only(start: 5.0, end: 6.0);
const TextStyle textStyle = TextStyle(letterSpacing: 2.0);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false).copyWith(
floatingActionButtonTheme: const FloatingActionButtonThemeData(
extendedIconLabelSpacing: 25.0,
extendedPadding: EdgeInsetsDirectional.only(start: 7.0, end: 8.0),
extendedTextStyle: TextStyle(letterSpacing: 3.0),
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () { },
label: const Text('Extended', key: labelKey),
icon: const Icon(Icons.add, key: iconKey),
extendedIconLabelSpacing: iconLabelSpacing,
extendedPadding: padding,
extendedTextStyle: textStyle,
),
),
));
expect(tester.getTopLeft(find.byKey(labelKey)).dx - tester.getTopRight(find.byKey(iconKey)).dx, iconLabelSpacing);
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);
// The color comes from the default color scheme's onSecondary value.
expect(_getRawMaterialButton(tester).textStyle, textStyle.copyWith(color: const Color(0xffffffff)));
});
testWidgets('default FloatingActionButton debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const FloatingActionButtonThemeData ().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('Material implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const FloatingActionButtonThemeData(
foregroundColor: Color(0xFEEDFEED),
backgroundColor: Color(0xCAFECAFE),
focusColor: Color(0xFEEDFEE1),
hoverColor: Color(0xFEEDFEE2),
splashColor: Color(0xFEEDFEE3),
elevation: 23,
focusElevation: 9,
hoverElevation: 10,
disabledElevation: 11,
highlightElevation: 43,
shape: BeveledRectangleBorder(),
enableFeedback: true,
iconSize: 42,
sizeConstraints: BoxConstraints.tightFor(width: 100.0, height: 100.0),
smallSizeConstraints: BoxConstraints.tightFor(width: 101.0, height: 101.0),
largeSizeConstraints: BoxConstraints.tightFor(width: 102.0, height: 102.0),
extendedSizeConstraints: BoxConstraints(minHeight: 103.0, maxHeight: 103.0),
extendedIconLabelSpacing: 12,
extendedPadding: EdgeInsetsDirectional.only(start: 7.0, end: 8.0),
extendedTextStyle: TextStyle(letterSpacing: 2.0),
mouseCursor: MaterialStateMouseCursor.clickable,
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'foregroundColor: Color(0xfeedfeed)',
'backgroundColor: Color(0xcafecafe)',
'focusColor: Color(0xfeedfee1)',
'hoverColor: Color(0xfeedfee2)',
'splashColor: Color(0xfeedfee3)',
'elevation: 23.0',
'focusElevation: 9.0',
'hoverElevation: 10.0',
'disabledElevation: 11.0',
'highlightElevation: 43.0',
'shape: BeveledRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.zero)',
'enableFeedback: true',
'iconSize: 42.0',
'sizeConstraints: BoxConstraints(w=100.0, h=100.0)',
'smallSizeConstraints: BoxConstraints(w=101.0, h=101.0)',
'largeSizeConstraints: BoxConstraints(w=102.0, h=102.0)',
'extendedSizeConstraints: BoxConstraints(0.0<=w<=Infinity, h=103.0)',
'extendedIconLabelSpacing: 12.0',
'extendedPadding: EdgeInsetsDirectional(7.0, 0.0, 8.0, 0.0)',
'extendedTextStyle: TextStyle(inherit: true, letterSpacing: 2.0)',
'mouseCursor: WidgetStateMouseCursor(clickable)',
]);
});
testWidgets('FloatingActionButton.mouseCursor uses FloatingActionButtonThemeData.mouseCursor when specified.', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData().copyWith(
floatingActionButtonTheme: FloatingActionButtonThemeData(
mouseCursor: MaterialStateProperty.all(SystemMouseCursors.text),
),
),
home: Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () { },
child: const Icon(Icons.add),
),
),
));
await tester.pumpAndSettle();
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(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
});
}
RawMaterialButton _getRawMaterialButton(WidgetTester tester) {
return tester.widget<RawMaterialButton>(
find.descendant(
of: find.byType(FloatingActionButton),
matching: find.byType(RawMaterialButton),
),
);
}
RichText _getRichText(WidgetTester tester) {
return tester.widget<RichText>(
find.descendant(
of: find.byType(FloatingActionButton),
matching: find.byType(RichText),
),
);
}
SizedBox _getIconSize(WidgetTester tester) {
return tester.widget<SizedBox>(
find.descendant(
of: find.descendant(
of: find.byType(FloatingActionButton),
matching: find.byType(Icon),
),
matching: find.byType(SizedBox),
),
);
}
| flutter/packages/flutter/test/material/floating_action_button_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/floating_action_button_theme_test.dart",
"repo_id": "flutter",
"token_count": 7675
} | 275 |
// Copyright 2014 The Flutter Authors. 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('English translations exist for all MaterialLocalizations properties', (WidgetTester tester) async {
const MaterialLocalizations localizations = DefaultMaterialLocalizations();
expect(localizations.openAppDrawerTooltip, isNotNull);
expect(localizations.backButtonTooltip, isNotNull);
expect(localizations.clearButtonTooltip, isNotNull);
expect(localizations.closeButtonTooltip, isNotNull);
expect(localizations.deleteButtonTooltip, isNotNull);
expect(localizations.moreButtonTooltip, isNotNull);
expect(localizations.nextMonthTooltip, isNotNull);
expect(localizations.previousMonthTooltip, isNotNull);
expect(localizations.nextPageTooltip, isNotNull);
expect(localizations.previousPageTooltip, isNotNull);
expect(localizations.firstPageTooltip, isNotNull);
expect(localizations.lastPageTooltip, isNotNull);
expect(localizations.showMenuTooltip, isNotNull);
expect(localizations.licensesPageTitle, isNotNull);
expect(localizations.rowsPerPageTitle, isNotNull);
expect(localizations.cancelButtonLabel, isNotNull);
expect(localizations.closeButtonLabel, isNotNull);
expect(localizations.continueButtonLabel, isNotNull);
expect(localizations.copyButtonLabel, isNotNull);
expect(localizations.cutButtonLabel, isNotNull);
expect(localizations.scanTextButtonLabel, isNotNull);
expect(localizations.lookUpButtonLabel, isNotNull);
expect(localizations.searchWebButtonLabel, isNotNull);
expect(localizations.shareButtonLabel, isNotNull);
expect(localizations.okButtonLabel, isNotNull);
expect(localizations.pasteButtonLabel, isNotNull);
expect(localizations.selectAllButtonLabel, isNotNull);
expect(localizations.viewLicensesButtonLabel, isNotNull);
expect(localizations.anteMeridiemAbbreviation, isNotNull);
expect(localizations.postMeridiemAbbreviation, isNotNull);
expect(localizations.timePickerHourModeAnnouncement, isNotNull);
expect(localizations.timePickerMinuteModeAnnouncement, isNotNull);
expect(localizations.modalBarrierDismissLabel, isNotNull);
expect(localizations.menuDismissLabel, isNotNull);
expect(localizations.drawerLabel, isNotNull);
expect(localizations.menuBarMenuLabel, isNotNull);
expect(localizations.popupMenuLabel, isNotNull);
expect(localizations.dialogLabel, isNotNull);
expect(localizations.alertDialogLabel, isNotNull);
expect(localizations.searchFieldLabel, isNotNull);
expect(localizations.dateSeparator, isNotNull);
expect(localizations.dateHelpText, isNotNull);
expect(localizations.selectYearSemanticsLabel, isNotNull);
expect(localizations.unspecifiedDate, isNotNull);
expect(localizations.unspecifiedDateRange, isNotNull);
expect(localizations.dateInputLabel, isNotNull);
expect(localizations.dateRangeStartLabel, isNotNull);
expect(localizations.dateRangeEndLabel, isNotNull);
expect(localizations.invalidDateFormatLabel, isNotNull);
expect(localizations.invalidDateRangeLabel, isNotNull);
expect(localizations.dateOutOfRangeLabel, isNotNull);
expect(localizations.saveButtonLabel, isNotNull);
expect(localizations.datePickerHelpText, isNotNull);
expect(localizations.dateRangePickerHelpText, isNotNull);
expect(localizations.calendarModeButtonLabel, isNotNull);
expect(localizations.inputDateModeButtonLabel, isNotNull);
expect(localizations.timePickerDialHelpText, isNotNull);
expect(localizations.timePickerInputHelpText, isNotNull);
expect(localizations.timePickerHourLabel, isNotNull);
expect(localizations.timePickerMinuteLabel, isNotNull);
expect(localizations.invalidTimeLabel, isNotNull);
expect(localizations.dialModeButtonLabel, isNotNull);
expect(localizations.inputTimeModeButtonLabel, isNotNull);
expect(localizations.signedInLabel, isNotNull);
expect(localizations.hideAccountsLabel, isNotNull);
expect(localizations.showAccountsLabel, isNotNull);
expect(localizations.reorderItemToStart, isNotNull);
expect(localizations.reorderItemToEnd, isNotNull);
expect(localizations.reorderItemUp, isNotNull);
expect(localizations.reorderItemDown, isNotNull);
expect(localizations.reorderItemLeft, isNotNull);
expect(localizations.reorderItemRight, isNotNull);
expect(localizations.expandedIconTapHint, isNotNull);
expect(localizations.collapsedIconTapHint, isNotNull);
expect(localizations.expansionTileExpandedHint, isNotNull);
expect(localizations.expansionTileCollapsedHint, isNotNull);
expect(localizations.expandedHint, isNotNull);
expect(localizations.collapsedHint, isNotNull);
expect(localizations.keyboardKeyAlt, isNotNull);
expect(localizations.keyboardKeyAltGraph, isNotNull);
expect(localizations.keyboardKeyBackspace, isNotNull);
expect(localizations.keyboardKeyCapsLock, isNotNull);
expect(localizations.keyboardKeyChannelDown, isNotNull);
expect(localizations.keyboardKeyChannelUp, isNotNull);
expect(localizations.keyboardKeyControl, isNotNull);
expect(localizations.keyboardKeyDelete, isNotNull);
expect(localizations.keyboardKeyEject, isNotNull);
expect(localizations.keyboardKeyEnd, isNotNull);
expect(localizations.keyboardKeyEscape, isNotNull);
expect(localizations.keyboardKeyFn, isNotNull);
expect(localizations.keyboardKeyHome, isNotNull);
expect(localizations.keyboardKeyInsert, isNotNull);
expect(localizations.keyboardKeyMeta, isNotNull);
expect(localizations.keyboardKeyMetaMacOs, isNotNull);
expect(localizations.keyboardKeyMetaWindows, isNotNull);
expect(localizations.keyboardKeyNumLock, isNotNull);
expect(localizations.keyboardKeyNumpad1, isNotNull);
expect(localizations.keyboardKeyNumpad2, isNotNull);
expect(localizations.keyboardKeyNumpad3, isNotNull);
expect(localizations.keyboardKeyNumpad4, isNotNull);
expect(localizations.keyboardKeyNumpad5, isNotNull);
expect(localizations.keyboardKeyNumpad6, isNotNull);
expect(localizations.keyboardKeyNumpad7, isNotNull);
expect(localizations.keyboardKeyNumpad8, isNotNull);
expect(localizations.keyboardKeyNumpad9, isNotNull);
expect(localizations.keyboardKeyNumpad0, isNotNull);
expect(localizations.keyboardKeyNumpadAdd, isNotNull);
expect(localizations.keyboardKeyNumpadComma, isNotNull);
expect(localizations.keyboardKeyNumpadDecimal, isNotNull);
expect(localizations.keyboardKeyNumpadDivide, isNotNull);
expect(localizations.keyboardKeyNumpadEnter, isNotNull);
expect(localizations.keyboardKeyNumpadEqual, isNotNull);
expect(localizations.keyboardKeyNumpadMultiply, isNotNull);
expect(localizations.keyboardKeyNumpadParenLeft, isNotNull);
expect(localizations.keyboardKeyNumpadParenRight, isNotNull);
expect(localizations.keyboardKeyNumpadSubtract, isNotNull);
expect(localizations.keyboardKeyPageDown, isNotNull);
expect(localizations.keyboardKeyPageUp, isNotNull);
expect(localizations.keyboardKeyPower, isNotNull);
expect(localizations.keyboardKeyPowerOff, isNotNull);
expect(localizations.keyboardKeyPrintScreen, isNotNull);
expect(localizations.keyboardKeyScrollLock, isNotNull);
expect(localizations.keyboardKeySelect, isNotNull);
expect(localizations.keyboardKeyShift, isNotNull);
expect(localizations.keyboardKeySpace, isNotNull);
expect(localizations.currentDateLabel, isNotNull);
expect(localizations.scrimLabel, isNotNull);
expect(localizations.bottomSheetLabel, isNotNull);
expect(localizations.selectedDateLabel, isNotNull);
expect(localizations.scrimOnTapHint('FOO'), contains('FOO'));
expect(localizations.aboutListTileTitle('FOO'), isNotNull);
expect(localizations.aboutListTileTitle('FOO'), contains('FOO'));
expect(localizations.selectedRowCountTitle(0), isNotNull);
expect(localizations.selectedRowCountTitle(1), isNotNull);
expect(localizations.selectedRowCountTitle(2), isNotNull);
expect(localizations.selectedRowCountTitle(100), isNotNull);
expect(localizations.selectedRowCountTitle(0).contains(r'$selectedRowCount'), isFalse);
expect(localizations.selectedRowCountTitle(1).contains(r'$selectedRowCount'), isFalse);
expect(localizations.selectedRowCountTitle(2).contains(r'$selectedRowCount'), isFalse);
expect(localizations.selectedRowCountTitle(100).contains(r'$selectedRowCount'), isFalse);
expect(localizations.pageRowsInfoTitle(1, 10, 100, true), isNotNull);
expect(localizations.pageRowsInfoTitle(1, 10, 100, false), isNotNull);
expect(localizations.pageRowsInfoTitle(1, 10, 100, true).contains(r'$firstRow'), isFalse);
expect(localizations.pageRowsInfoTitle(1, 10, 100, true).contains(r'$lastRow'), isFalse);
expect(localizations.pageRowsInfoTitle(1, 10, 100, true).contains(r'$rowCount'), isFalse);
expect(localizations.pageRowsInfoTitle(1, 10, 100, false).contains(r'$firstRow'), isFalse);
expect(localizations.pageRowsInfoTitle(1, 10, 100, false).contains(r'$lastRow'), isFalse);
expect(localizations.pageRowsInfoTitle(1, 10, 100, false).contains(r'$rowCount'), isFalse);
expect(localizations.licensesPackageDetailText(0), isNotNull);
expect(localizations.licensesPackageDetailText(1), isNotNull);
expect(localizations.licensesPackageDetailText(2), isNotNull);
expect(localizations.licensesPackageDetailText(100), isNotNull);
expect(localizations.licensesPackageDetailText(1).contains(r'$licensesCount'), isFalse);
expect(localizations.licensesPackageDetailText(2).contains(r'$licensesCount'), isFalse);
expect(localizations.licensesPackageDetailText(100).contains(r'$licensesCount'), isFalse);
});
testWidgets('MaterialLocalizations.of throws', (WidgetTester tester) async {
final GlobalKey noLocalizationsAvailable = GlobalKey();
final GlobalKey localizationsAvailable = GlobalKey();
await tester.pumpWidget(
Container(
key: noLocalizationsAvailable,
child: MaterialApp(
home: Container(
key: localizationsAvailable,
),
),
),
);
expect(() => MaterialLocalizations.of(noLocalizationsAvailable.currentContext!), throwsA(isAssertionError.having(
(AssertionError e) => e.message,
'message',
contains('No MaterialLocalizations found'),
)));
expect(MaterialLocalizations.of(localizationsAvailable.currentContext!), isA<MaterialLocalizations>());
});
testWidgets("parseCompactDate doesn't throw an exception on invalid text", (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/126397.
final GlobalKey localizations = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
key: localizations,
child: const SizedBox.expand(),
),
),
);
final MaterialLocalizations materialLocalizations = MaterialLocalizations.of(localizations.currentContext!);
expect(materialLocalizations.parseCompactDate('10/05/2023'), isNotNull);
expect(tester.takeException(), null);
expect(materialLocalizations.parseCompactDate('10/05/2023666777889'), null);
expect(tester.takeException(), null);
});
}
| flutter/packages/flutter/test/material/localizations_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/localizations_test.dart",
"repo_id": "flutter",
"token_count": 3826
} | 276 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('NavigationDrawerThemeData copyWith, ==, hashCode, basics', () {
expect(const NavigationDrawerThemeData(), const NavigationDrawerThemeData().copyWith());
expect(const NavigationDrawerThemeData().hashCode, const NavigationDrawerThemeData().copyWith().hashCode);
});
test('NavigationDrawerThemeData lerp special cases', () {
expect(NavigationDrawerThemeData.lerp(null, null, 0), null);
const NavigationDrawerThemeData data = NavigationDrawerThemeData();
expect(identical(NavigationDrawerThemeData.lerp(data, data, 0.5), data), true);
});
testWidgets('Default debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const NavigationDrawerThemeData().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('NavigationDrawerThemeData implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const NavigationDrawerThemeData(
tileHeight: 50,
backgroundColor: Color(0x00000099),
elevation: 5.0,
shadowColor: Color(0x00000098),
surfaceTintColor: Color(0x00000097),
indicatorColor: Color(0x00000096),
indicatorShape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))),
indicatorSize: Size(10, 10),
labelTextStyle: MaterialStatePropertyAll<TextStyle>(TextStyle(fontSize: 7.0)),
iconTheme: MaterialStatePropertyAll<IconThemeData>(IconThemeData(color: Color(0x00000095))),
).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>[
'tileHeight: 50.0',
'backgroundColor: Color(0x00000099)',
'elevation: 5.0',
'shadowColor: Color(0x00000098)',
'surfaceTintColor: Color(0x00000097)',
'indicatorColor: Color(0x00000096)',
'indicatorShape: RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(2.0))',
'indicatorSize: Size(10.0, 10.0)',
'labelTextStyle: WidgetStatePropertyAll(TextStyle(inherit: true, size: 7.0))',
'iconTheme: WidgetStatePropertyAll(IconThemeData#00000(color: Color(0x00000095)))'
],
));
});
testWidgets(
'NavigationDrawerThemeData values are used when no NavigationDrawer properties are specified',
(WidgetTester tester) async {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
const NavigationDrawerThemeData navigationDrawerTheme = NavigationDrawerThemeData(
backgroundColor: Color(0x00000001),
elevation: 7.0,
shadowColor: Color(0x00000002),
surfaceTintColor: Color(0x00000003),
indicatorColor: Color(0x00000004),
indicatorShape: RoundedRectangleBorder(borderRadius: BorderRadius.only(topRight: Radius.circular(16.0))),
labelTextStyle:MaterialStatePropertyAll<TextStyle>(TextStyle(fontSize: 7.0)),
iconTheme: MaterialStatePropertyAll<IconThemeData>(IconThemeData(color: Color(0x00000005))),
);
await tester.pumpWidget(
_buildWidget(
scaffoldKey,
NavigationDrawer(
children: const <Widget>[
Text('Headline'),
NavigationDrawerDestination(
icon: Icon(Icons.ac_unit),
label: Text('AC'),
),
NavigationDrawerDestination(
icon: Icon(Icons.access_alarm),
label: Text('Alarm'),
),
],
onDestinationSelected: (int i) {},
),
theme: ThemeData(
navigationDrawerTheme: navigationDrawerTheme,
),
),
);
scaffoldKey.currentState!.openDrawer();
await tester.pump(const Duration(seconds: 1));
// Test drawer Material.
expect(_getMaterial(tester).color, navigationDrawerTheme.backgroundColor);
expect(_getMaterial(tester).surfaceTintColor, navigationDrawerTheme.surfaceTintColor);
expect(_getMaterial(tester).shadowColor, navigationDrawerTheme.shadowColor);
expect(_getMaterial(tester).elevation, 7);
// Test indicator decoration.
expect(_getIndicatorDecoration(tester)?.color, navigationDrawerTheme.indicatorColor);
expect(_getIndicatorDecoration(tester)?.shape, navigationDrawerTheme.indicatorShape);
// Test icon.
expect(
_iconStyle(tester, Icons.ac_unit)?.color,
navigationDrawerTheme.iconTheme?.resolve(<MaterialState>{})?.color,
);
expect(
_iconStyle(tester, Icons.access_alarm)?.color,
navigationDrawerTheme.iconTheme?.resolve(<MaterialState>{})?.color,
);
// Test label.
expect(
_labelStyle(tester, 'AC'),
navigationDrawerTheme.labelTextStyle?.resolve(<MaterialState>{})
);
expect(
_labelStyle(tester, 'Alarm'),
navigationDrawerTheme.labelTextStyle?.resolve(<MaterialState>{})
);
});
testWidgets(
'NavigationDrawer values take priority over NavigationDrawerThemeData values when both properties are specified',
(WidgetTester tester) async {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
const NavigationDrawerThemeData navigationDrawerTheme = NavigationDrawerThemeData(
backgroundColor: Color(0x00000001),
elevation: 7.0,
shadowColor: Color(0x00000002),
surfaceTintColor: Color(0x00000003),
indicatorColor: Color(0x00000004),
indicatorShape: RoundedRectangleBorder(borderRadius: BorderRadius.only(topRight: Radius.circular(16.0))),
labelTextStyle:MaterialStatePropertyAll<TextStyle>(TextStyle(fontSize: 7.0)),
iconTheme: MaterialStatePropertyAll<IconThemeData>(IconThemeData(color: Color(0x00000005))),
);
const Color backgroundColor = Color(0x00000009);
const double elevation = 14.0;
const Color shadowColor = Color(0x00000008);
const Color surfaceTintColor = Color(0x00000007);
const RoundedRectangleBorder indicatorShape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(32.0)));
const Color indicatorColor = Color(0x00000006);
await tester.pumpWidget(
_buildWidget(
scaffoldKey,
NavigationDrawer(
backgroundColor: backgroundColor,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
indicatorShape: indicatorShape,
indicatorColor: indicatorColor,
children: const <Widget>[
Text('Headline'),
NavigationDrawerDestination(
icon: Icon(Icons.ac_unit),
label: Text('AC'),
),
NavigationDrawerDestination(
icon: Icon(Icons.access_alarm),
label: Text('Alarm'),
),
],
onDestinationSelected: (int i) {},
),
theme: ThemeData(
navigationDrawerTheme: navigationDrawerTheme,
),
),
);
scaffoldKey.currentState!.openDrawer();
await tester.pump(const Duration(seconds: 1));
// Test drawer Material.
expect(_getMaterial(tester).color, backgroundColor);
expect(_getMaterial(tester).surfaceTintColor, surfaceTintColor);
expect(_getMaterial(tester).shadowColor, shadowColor);
expect(_getMaterial(tester).elevation, elevation);
// Test indicator decoration.
expect(_getIndicatorDecoration(tester)?.color, indicatorColor);
expect(_getIndicatorDecoration(tester)?.shape, indicatorShape);
});
testWidgets('Local NavigationDrawerTheme takes priority over ThemeData.navigationDrawerTheme', (WidgetTester tester) async {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
const Color backgroundColor = Color(0x00000009);
const double elevation = 7.0;
const Color shadowColor = Color(0x00000008);
const Color surfaceTintColor = Color(0x00000007);
const Color iconColor = Color(0x00000006);
const TextStyle labelStyle = TextStyle(fontSize: 7.0);
const ShapeBorder indicatorShape = CircleBorder();
const Color indicatorColor = Color(0x00000005);
await tester.pumpWidget(
_buildWidget(
scaffoldKey,
NavigationDrawerTheme(
data: const NavigationDrawerThemeData(
backgroundColor: backgroundColor,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
indicatorShape: indicatorShape,
indicatorColor: indicatorColor,
labelTextStyle:MaterialStatePropertyAll<TextStyle>(TextStyle(fontSize: 7.0)),
iconTheme: MaterialStatePropertyAll<IconThemeData>(IconThemeData(color: iconColor)),
),
child: NavigationDrawer(
children: const <Widget>[
Text('Headline'),
NavigationDrawerDestination(
icon: Icon(Icons.ac_unit),
label: Text('AC'),
),
NavigationDrawerDestination(
icon: Icon(Icons.access_alarm),
label: Text('Alarm'),
),
],
onDestinationSelected: (int i) {},
),
),
theme: ThemeData(
navigationDrawerTheme: const NavigationDrawerThemeData(
backgroundColor: Color(0x00000001),
elevation: 7.0,
shadowColor: Color(0x00000002),
surfaceTintColor: Color(0x00000003),
indicatorColor: Color(0x00000004),
indicatorShape: RoundedRectangleBorder(borderRadius: BorderRadius.only(topRight: Radius.circular(16.0))),
labelTextStyle:MaterialStatePropertyAll<TextStyle>(TextStyle(fontSize: 7.0)),
iconTheme: MaterialStatePropertyAll<IconThemeData>(IconThemeData(color: Color(0x00000005))),
),
),
),
);
scaffoldKey.currentState!.openDrawer();
await tester.pump(const Duration(seconds: 1));
// Test drawer Material.
expect(_getMaterial(tester).color, backgroundColor);
expect(_getMaterial(tester).surfaceTintColor, surfaceTintColor);
expect(_getMaterial(tester).shadowColor, shadowColor);
expect(_getMaterial(tester).elevation, elevation);
// Test indicator decoration.
expect(_getIndicatorDecoration(tester)?.color, indicatorColor);
expect(_getIndicatorDecoration(tester)?.shape, indicatorShape);
// Test icon.
expect(_iconStyle(tester, Icons.ac_unit)?.color, iconColor);
expect(_iconStyle(tester, Icons.access_alarm)?.color, iconColor);
// Test label.
expect(_labelStyle(tester, 'AC'), labelStyle);
expect(_labelStyle(tester, 'Alarm'), labelStyle);
});
}
Widget _buildWidget(GlobalKey<ScaffoldState> scaffoldKey, Widget child, { ThemeData? theme }) {
return MaterialApp(
theme: theme,
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),
));
}
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) {
return tester.widget<RichText>(
find.descendant(of: find.byIcon(icon),
matching: find.byType(RichText)),
).text.style;
}
TextStyle? _labelStyle(WidgetTester tester, String label) {
return tester.widget<RichText>(find.descendant(
of: find.text(label),
matching: find.byType(RichText),
)).text.style;
}
| flutter/packages/flutter/test/material/navigation_drawer_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/navigation_drawer_theme_test.dart",
"repo_id": "flutter",
"token_count": 4996
} | 277 |
// Copyright 2014 The Flutter 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)));
addTearDown(gesture.removePointer);
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();
addTearDown(gesture.removePointer);
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();
addTearDown(gesture.removePointer);
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();
addTearDown(gesture.removePointer);
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();
addTearDown(gesture.removePointer);
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();
addTearDown(gesture.removePointer);
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": 28067
} | 278 |
// Copyright 2014 The Flutter Authors. 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
} | 279 |
// Copyright 2014 The Flutter Authors. 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 && !isSkiaWeb); // 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.
});
testWidgets('treats a hovering stylus like a mouse', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
final ThemeData theme = ThemeData(useMaterial3: true);
bool hasBeenHovered = false;
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: Builder(
builder: (BuildContext context) {
return TextButton(
onPressed: () {},
onHover: (bool entered) {
hasBeenHovered = true;
},
focusNode: focusNode,
child: const Text('TextButton'),
);
},
),
),
),
),
);
RenderObject overlayColor() {
return tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
}
final Offset center = tester.getCenter(find.byType(TextButton));
final TestGesture gesture = await tester.createGesture(
kind: PointerDeviceKind.stylus,
);
await gesture.addPointer();
await tester.pumpAndSettle();
expect(hasBeenHovered, isFalse);
await gesture.moveTo(center);
await tester.pumpAndSettle();
expect(overlayColor(), paints..rect(color: theme.colorScheme.primary.withOpacity(0.08)));
expect(hasBeenHovered, isTrue);
});
}
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": 34135
} | 280 |
// Copyright 2014 The Flutter Authors. 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
} | 281 |
// Copyright 2014 The Flutter Authors. 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
} | 282 |
// Copyright 2014 The Flutter Authors. 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
} | 283 |
// Copyright 2014 The Flutter Authors. 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';
import 'no_op_codec.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(createNoOpCodec());
}), isA<MultiFrameImageStreamCompleter>());
expect(await error.future, isStateError);
});
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, noOpDecoderBufferCallback) 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, noOpDecoderBufferCallback) 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, noOpDecoderBufferCallback) 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),
noOpDecoderBufferCallback,
) 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 _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": 2246
} | 284 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import '../rendering/rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('ShapeDecoration constructor', () {
const Color colorR = Color(0xffff0000);
const Color colorG = Color(0xff00ff00);
const Gradient gradient = LinearGradient(colors: <Color>[colorR, colorG]);
expect(const ShapeDecoration(shape: Border()), const ShapeDecoration(shape: Border()));
expect(() => ShapeDecoration(color: colorR, gradient: nonconst(gradient), shape: const Border()), throwsAssertionError);
expect(
ShapeDecoration.fromBoxDecoration(const BoxDecoration(shape: BoxShape.circle)),
const ShapeDecoration(shape: CircleBorder()),
);
expect(
ShapeDecoration.fromBoxDecoration(BoxDecoration(borderRadius: BorderRadiusDirectional.circular(100.0))),
ShapeDecoration(shape: RoundedRectangleBorder(borderRadius: BorderRadiusDirectional.circular(100.0))),
);
expect(
ShapeDecoration.fromBoxDecoration(BoxDecoration(shape: BoxShape.circle, border: Border.all(color: colorG))),
const ShapeDecoration(shape: CircleBorder(side: BorderSide(color: colorG))),
);
expect(
ShapeDecoration.fromBoxDecoration(BoxDecoration(border: Border.all(color: colorR))),
ShapeDecoration(shape: Border.all(color: colorR)),
);
expect(
ShapeDecoration.fromBoxDecoration(const BoxDecoration(border: BorderDirectional(start: BorderSide()))),
const ShapeDecoration(shape: BorderDirectional(start: BorderSide())),
);
});
test('ShapeDecoration.lerp identical a,b', () {
expect(ShapeDecoration.lerp(null, null, 0), null);
const ShapeDecoration shape = ShapeDecoration(shape: CircleBorder());
expect(identical(ShapeDecoration.lerp(shape, shape, 0.5), shape), true);
});
test('ShapeDecoration.lerp null a,b', () {
const Decoration a = ShapeDecoration(shape: CircleBorder());
const Decoration b = ShapeDecoration(shape: RoundedRectangleBorder());
expect(Decoration.lerp(a, null, 0.0), a);
expect(Decoration.lerp(null, b, 0.0), b);
expect(Decoration.lerp(null, null, 0.0), null);
});
test('ShapeDecoration.lerp and hit test', () {
const Decoration a = ShapeDecoration(shape: CircleBorder());
const Decoration b = ShapeDecoration(shape: RoundedRectangleBorder());
const Decoration c = ShapeDecoration(shape: OvalBorder());
expect(Decoration.lerp(a, b, 0.0), a);
expect(Decoration.lerp(a, b, 1.0), b);
expect(Decoration.lerp(a, c, 0.0), a);
expect(Decoration.lerp(a, c, 1.0), c);
expect(Decoration.lerp(b, c, 0.0), b);
expect(Decoration.lerp(b, c, 1.0), c);
const Size size = Size(200.0, 100.0); // at t=0.5, width will be 150 (x=25 to x=175).
expect(a.hitTest(size, const Offset(20.0, 50.0)), isFalse);
expect(c.hitTest(size, const Offset(50, 5.0)), isFalse);
expect(c.hitTest(size, const Offset(5, 30.0)), isFalse);
expect(Decoration.lerp(a, b, 0.1)!.hitTest(size, const Offset(20.0, 50.0)), isFalse);
expect(Decoration.lerp(a, b, 0.5)!.hitTest(size, const Offset(20.0, 50.0)), isFalse);
expect(Decoration.lerp(a, b, 0.9)!.hitTest(size, const Offset(20.0, 50.0)), isTrue);
expect(Decoration.lerp(a, c, 0.1)!.hitTest(size, const Offset(30.0, 50.0)), isFalse);
expect(Decoration.lerp(a, c, 0.5)!.hitTest(size, const Offset(30.0, 50.0)), isTrue);
expect(Decoration.lerp(a, c, 0.9)!.hitTest(size, const Offset(30.0, 50.0)), isTrue);
expect(Decoration.lerp(b, c, 0.1)!.hitTest(size, const Offset(45.0, 10.0)), isTrue);
expect(Decoration.lerp(b, c, 0.5)!.hitTest(size, const Offset(30.0, 10.0)), isTrue);
expect(Decoration.lerp(b, c, 0.9)!.hitTest(size, const Offset(10.0, 30.0)), isTrue);
expect(b.hitTest(size, const Offset(20.0, 50.0)), isTrue);
});
test('ShapeDecoration.image RTL test', () async {
final ui.Image image = await createTestImage(width: 100, height: 200);
final List<int> log = <int>[];
final ShapeDecoration decoration = ShapeDecoration(
shape: const CircleBorder(),
image: DecorationImage(
image: TestImageProvider(image),
alignment: AlignmentDirectional.bottomEnd,
),
);
final BoxPainter painter = decoration.createBoxPainter(() { log.add(0); });
expect((Canvas canvas) => painter.paint(canvas, Offset.zero, const ImageConfiguration(size: Size(100.0, 100.0))), paintsAssertion);
expect(
(Canvas canvas) {
return painter.paint(
canvas,
const Offset(20.0, -40.0),
const ImageConfiguration(
size: Size(1000.0, 1000.0),
textDirection: TextDirection.rtl,
),
);
},
paints
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 100.0, 200.0), destination: const Rect.fromLTRB(20.0, 1000.0 - 40.0 - 200.0, 20.0 + 100.0, 1000.0 - 40.0)),
);
expect(
(Canvas canvas) {
return painter.paint(
canvas,
Offset.zero,
const ImageConfiguration(
size: Size(100.0, 200.0),
textDirection: TextDirection.ltr,
),
);
},
isNot(paints..image()), // we always use drawImageRect
);
expect(log, isEmpty);
});
test('ShapeDecoration.getClipPath', () {
const ShapeDecoration decoration = ShapeDecoration(shape: CircleBorder());
const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0);
final Path clipPath = decoration.getClipPath(rect, TextDirection.ltr);
final Matcher isLookLikeExpectedPath = isPathThat(
includes: const <Offset>[ Offset(50.0, 10.0), ],
excludes: const <Offset>[ Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0), ],
);
expect(clipPath, isLookLikeExpectedPath);
});
test('ShapeDecoration.getClipPath for oval', () {
const ShapeDecoration decoration = ShapeDecoration(shape: OvalBorder());
const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 50.0);
final Path clipPath = decoration.getClipPath(rect, TextDirection.ltr);
final Matcher isLookLikeExpectedPath = isPathThat(
includes: const <Offset>[ Offset(50.0, 10.0), ],
excludes: const <Offset>[ Offset(1.0, 1.0), Offset(15.0, 1.0), Offset(99.0, 19.0), ],
);
expect(clipPath, isLookLikeExpectedPath);
});
}
class TestImageProvider extends ImageProvider<TestImageProvider> {
TestImageProvider(this.image);
final ui.Image image;
@override
Future<TestImageProvider> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<TestImageProvider>(this);
}
@override
ImageStreamCompleter loadImage(TestImageProvider key, ImageDecoderCallback decode) {
return OneFrameImageStreamCompleter(
SynchronousFuture<ImageInfo>(ImageInfo(image: image)),
);
}
}
| flutter/packages/flutter/test/painting/shape_decoration_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/shape_decoration_test.dart",
"repo_id": "flutter",
"token_count": 2757
} | 285 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
final TextSelectionDelegate delegate = _FakeEditableTextState();
test('editable intrinsics', () {
final RenderEditable editable = RenderEditable(
text: const TextSpan(
style: TextStyle(height: 1.0, fontSize: 10.0),
text: '12345',
),
startHandleLayerLink: LayerLink(),
endHandleLayerLink: LayerLink(),
textDirection: TextDirection.ltr,
locale: const Locale('ja', 'JP'),
offset: ViewportOffset.zero(),
textSelectionDelegate: delegate,
);
expect(editable.getMinIntrinsicWidth(double.infinity), 50.0);
// The width includes the width of the cursor (1.0).
expect(editable.getMaxIntrinsicWidth(double.infinity), 52.0);
expect(editable.getMinIntrinsicHeight(double.infinity), 10.0);
expect(editable.getMaxIntrinsicHeight(double.infinity), 10.0);
expect(
editable.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'RenderEditable#00000 NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE DETACHED\n'
' β parentData: MISSING\n'
' β constraints: MISSING\n'
' β size: MISSING\n'
' β cursorColor: null\n'
' β showCursor: ValueNotifier<bool>#00000(false)\n'
' β maxLines: 1\n'
' β minLines: null\n'
' β selectionColor: null\n'
' β locale: ja_JP\n'
' β selection: null\n'
' β offset: _FixedViewportOffset#00000(offset: 0.0)\n'
' βββ¦ββ text βββ\n'
' β TextSpan:\n'
' β inherit: true\n'
' β size: 10.0\n'
' β height: 1.0x\n'
' β "12345"\n'
' ββββββββββββ\n',
),
);
});
test('textScaler affects intrinsics', () {
final RenderEditable editable = RenderEditable(
text: const TextSpan(
style: TextStyle(fontSize: 10),
text: 'Hello World',
),
textDirection: TextDirection.ltr,
startHandleLayerLink: LayerLink(),
endHandleLayerLink: LayerLink(),
offset: ViewportOffset.zero(),
textSelectionDelegate: delegate,
);
expect(editable.getMaxIntrinsicWidth(double.infinity), 110 + 2);
editable.textScaler = const TextScaler.linear(2);
expect(editable.getMaxIntrinsicWidth(double.infinity), 220 + 2);
});
test('maxLines affects intrinsics', () {
final RenderEditable editable = RenderEditable(
text: TextSpan(
style: const TextStyle(fontSize: 10),
text: List<String>.filled(5, 'A').join('\n'),
),
textDirection: TextDirection.ltr,
startHandleLayerLink: LayerLink(),
endHandleLayerLink: LayerLink(),
offset: ViewportOffset.zero(),
textSelectionDelegate: delegate,
maxLines: null,
);
expect(editable.getMaxIntrinsicHeight(double.infinity), 50);
editable.maxLines = 1;
expect(editable.getMaxIntrinsicHeight(double.infinity), 10);
});
test('strutStyle affects intrinsics', () {
final RenderEditable editable = RenderEditable(
text: const TextSpan(
style: TextStyle(fontSize: 10),
text: 'Hello World',
),
textDirection: TextDirection.ltr,
startHandleLayerLink: LayerLink(),
endHandleLayerLink: LayerLink(),
offset: ViewportOffset.zero(),
textSelectionDelegate: delegate,
);
expect(editable.getMaxIntrinsicHeight(double.infinity), 10);
editable.strutStyle = const StrutStyle(fontSize: 100, forceStrutHeight: true);
expect(editable.getMaxIntrinsicHeight(double.infinity), 100);
}, skip: kIsWeb && !isSkiaWeb); // [intended] strut support for HTML renderer https://github.com/flutter/flutter/issues/32243.
}
class _FakeEditableTextState with TextSelectionDelegate {
@override
TextEditingValue textEditingValue = TextEditingValue.empty;
TextSelection? selection;
@override
void hideToolbar([bool hideHandles = true]) { }
@override
void userUpdateTextEditingValue(TextEditingValue value, SelectionChangedCause cause) {
selection = value.selection;
}
@override
void bringIntoView(TextPosition position) { }
@override
void cutSelection(SelectionChangedCause cause) { }
@override
Future<void> pasteText(SelectionChangedCause cause) {
return Future<void>.value();
}
@override
void selectAll(SelectionChangedCause cause) { }
@override
void copySelection(SelectionChangedCause cause) { }
}
| flutter/packages/flutter/test/rendering/editable_intrinsics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/editable_intrinsics_test.dart",
"repo_id": "flutter",
"token_count": 1878
} | 286 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart' show TestDefaultBinaryMessengerBinding;
class _TestHitTester extends RenderBox {
_TestHitTester(this.hitTestOverride);
final BoxHitTest hitTestOverride;
@override
bool hitTest(BoxHitTestResult result, {required ui.Offset position}) {
return hitTestOverride(result, position);
}
}
// A binding used to test MouseTracker, allowing the test to override hit test
// searching.
class TestMouseTrackerFlutterBinding extends BindingBase
with SchedulerBinding, ServicesBinding, GestureBinding, SemanticsBinding, RendererBinding, TestDefaultBinaryMessengerBinding {
@override
void initInstances() {
super.initInstances();
postFrameCallbacks = <void Function(Duration)>[];
}
late final RenderView _renderView = RenderView(
view: platformDispatcher.implicitView!,
);
late final PipelineOwner _pipelineOwner = PipelineOwner(
onSemanticsUpdate: (ui.SemanticsUpdate _) { assert(false); },
);
void setHitTest(BoxHitTest hitTest) {
if (_pipelineOwner.rootNode == null) {
_pipelineOwner.rootNode = _renderView;
rootPipelineOwner.adoptChild(_pipelineOwner);
addRenderView(_renderView);
}
_renderView.child = _TestHitTester(hitTest);
}
SchedulerPhase? _overridePhase;
@override
SchedulerPhase get schedulerPhase => _overridePhase ?? super.schedulerPhase;
// Manually schedule a post-frame check.
//
// In real apps this is done by the renderer binding, but in tests we have to
// bypass the phase assertion of [MouseTracker.schedulePostFrameCheck].
void scheduleMouseTrackerPostFrameCheck() {
final SchedulerPhase? lastPhase = _overridePhase;
_overridePhase = SchedulerPhase.persistentCallbacks;
addPostFrameCallback((_) {
mouseTracker.updateAllDevices();
});
_overridePhase = lastPhase;
}
List<void Function(Duration)> postFrameCallbacks = <void Function(Duration)>[];
// Proxy post-frame callbacks.
@override
void addPostFrameCallback(void Function(Duration) callback, {String debugLabel = 'callback'}) {
postFrameCallbacks.add(callback);
}
void flushPostFrameCallbacks(Duration duration) {
for (final void Function(Duration) callback in postFrameCallbacks) {
callback(duration);
}
postFrameCallbacks.clear();
}
}
// An object that mocks the behavior of a render object with [MouseTrackerAnnotation].
class TestAnnotationTarget with Diagnosticable implements MouseTrackerAnnotation, HitTestTarget {
const TestAnnotationTarget({this.onEnter, this.onHover, this.onExit, this.cursor = MouseCursor.defer, this.validForMouseTracker = true});
@override
final PointerEnterEventListener? onEnter;
final PointerHoverEventListener? onHover;
@override
final PointerExitEventListener? onExit;
@override
final MouseCursor cursor;
@override
final bool validForMouseTracker;
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
if (event is PointerHoverEvent) {
onHover?.call(event);
}
}
}
// A hit test entry that can be assigned with a [TestAnnotationTarget] and an
// optional transform matrix.
class TestAnnotationEntry extends HitTestEntry<TestAnnotationTarget> {
TestAnnotationEntry(super.target, [Matrix4? transform])
: transform = transform ?? Matrix4.identity();
@override
final Matrix4 transform;
}
| flutter/packages/flutter/test/rendering/mouse_tracker_test_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/mouse_tracker_test_utils.dart",
"repo_id": "flutter",
"token_count": 1170
} | 287 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show Gradient, Image, ImageFilter;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('RenderFittedBox handles applying paint transform and hit-testing with empty size', () {
final RenderFittedBox fittedBox = RenderFittedBox(
child: RenderCustomPaint(
painter: TestCallbackPainter(onPaint: () {}),
),
);
layout(fittedBox, phase: EnginePhase.flushSemantics);
final Matrix4 transform = Matrix4.identity();
fittedBox.applyPaintTransform(fittedBox.child!, transform);
expect(transform, Matrix4.zero());
final BoxHitTestResult hitTestResult = BoxHitTestResult();
expect(fittedBox.hitTestChildren(hitTestResult, position: Offset.zero), isFalse);
});
test('RenderFittedBox does not paint with empty sizes', () {
bool painted;
RenderFittedBox makeFittedBox(Size size) {
return RenderFittedBox(
child: RenderCustomPaint(
preferredSize: size,
painter: TestCallbackPainter(onPaint: () {
painted = true;
}),
),
);
}
// The RenderFittedBox paints if both its size and its child's size are nonempty.
painted = false;
layout(makeFittedBox(const Size(1, 1)), phase: EnginePhase.paint);
expect(painted, equals(true));
// The RenderFittedBox should not paint if its child is empty-sized.
painted = false;
layout(makeFittedBox(Size.zero), phase: EnginePhase.paint);
expect(painted, equals(false));
// The RenderFittedBox should not paint if it is empty.
painted = false;
layout(makeFittedBox(const Size(1, 1)), constraints: BoxConstraints.tight(Size.zero), phase: EnginePhase.paint);
expect(painted, equals(false));
});
test('RenderPhysicalModel compositing', () {
final RenderPhysicalModel root = RenderPhysicalModel(color: const Color(0xffff00ff));
layout(root, phase: EnginePhase.composite);
expect(root.needsCompositing, isFalse);
// On Fuchsia, the system compositor is responsible for drawing shadows
// for physical model layers with non-zero elevation.
root.elevation = 1.0;
pumpFrame(phase: EnginePhase.composite);
expect(root.needsCompositing, isFalse);
root.elevation = 0.0;
pumpFrame(phase: EnginePhase.composite);
expect(root.needsCompositing, isFalse);
});
test('RenderSemanticsGestureHandler adds/removes correct semantic actions', () {
final RenderSemanticsGestureHandler renderObj = RenderSemanticsGestureHandler(
onTap: () { },
onHorizontalDragUpdate: (DragUpdateDetails details) { },
);
SemanticsConfiguration config = SemanticsConfiguration();
renderObj.describeSemanticsConfiguration(config);
expect(config.getActionHandler(SemanticsAction.tap), isNotNull);
expect(config.getActionHandler(SemanticsAction.scrollLeft), isNotNull);
expect(config.getActionHandler(SemanticsAction.scrollRight), isNotNull);
config = SemanticsConfiguration();
renderObj.validActions = <SemanticsAction>{SemanticsAction.tap, SemanticsAction.scrollLeft};
renderObj.describeSemanticsConfiguration(config);
expect(config.getActionHandler(SemanticsAction.tap), isNotNull);
expect(config.getActionHandler(SemanticsAction.scrollLeft), isNotNull);
expect(config.getActionHandler(SemanticsAction.scrollRight), isNull);
});
group('RenderPhysicalShape', () {
test('shape change triggers repaint', () {
for (final TargetPlatform platform in TargetPlatform.values) {
debugDefaultTargetPlatformOverride = platform;
final RenderPhysicalShape root = RenderPhysicalShape(
color: const Color(0xffff00ff),
clipper: const ShapeBorderClipper(shape: CircleBorder()),
);
layout(root, phase: EnginePhase.composite);
expect(root.debugNeedsPaint, isFalse);
// Same shape, no repaint.
root.clipper = const ShapeBorderClipper(shape: CircleBorder());
expect(root.debugNeedsPaint, isFalse);
// Different shape triggers repaint.
root.clipper = const ShapeBorderClipper(shape: StadiumBorder());
expect(root.debugNeedsPaint, isTrue);
}
debugDefaultTargetPlatformOverride = null;
});
test('compositing', () {
for (final TargetPlatform platform in TargetPlatform.values) {
debugDefaultTargetPlatformOverride = platform;
final RenderPhysicalShape root = RenderPhysicalShape(
color: const Color(0xffff00ff),
clipper: const ShapeBorderClipper(shape: CircleBorder()),
);
layout(root, phase: EnginePhase.composite);
expect(root.needsCompositing, isFalse);
// On non-Fuchsia platforms, we composite physical shape layers
root.elevation = 1.0;
pumpFrame(phase: EnginePhase.composite);
expect(root.needsCompositing, isFalse);
root.elevation = 0.0;
pumpFrame(phase: EnginePhase.composite);
expect(root.needsCompositing, isFalse);
}
debugDefaultTargetPlatformOverride = null;
});
});
test('RenderRepaintBoundary can capture images of itself', () async {
RenderRepaintBoundary boundary = RenderRepaintBoundary();
layout(boundary, constraints: BoxConstraints.tight(const Size(100.0, 200.0)));
pumpFrame(phase: EnginePhase.composite);
ui.Image image = await boundary.toImage();
expect(image.width, equals(100));
expect(image.height, equals(200));
// Now with pixel ratio set to something other than 1.0.
boundary = RenderRepaintBoundary();
layout(boundary, constraints: BoxConstraints.tight(const Size(100.0, 200.0)));
pumpFrame(phase: EnginePhase.composite);
image = await boundary.toImage(pixelRatio: 2.0);
expect(image.width, equals(200));
expect(image.height, equals(400));
// Try building one with two child layers and make sure it renders them both.
boundary = RenderRepaintBoundary();
final RenderStack stack = RenderStack()..alignment = Alignment.topLeft;
final RenderDecoratedBox blackBox = RenderDecoratedBox(
decoration: const BoxDecoration(color: Color(0xff000000)),
child: RenderConstrainedBox(
additionalConstraints: BoxConstraints.tight(const Size.square(20.0)),
),
);
stack.add(
RenderOpacity()
..opacity = 0.5
..child = blackBox,
);
final RenderDecoratedBox whiteBox = RenderDecoratedBox(
decoration: const BoxDecoration(color: Color(0xffffffff)),
child: RenderConstrainedBox(
additionalConstraints: BoxConstraints.tight(const Size.square(10.0)),
),
);
final RenderPositionedBox positioned = RenderPositionedBox(
widthFactor: 2.0,
heightFactor: 2.0,
alignment: Alignment.topRight,
child: whiteBox,
);
stack.add(positioned);
boundary.child = stack;
layout(boundary, constraints: BoxConstraints.tight(const Size(20.0, 20.0)));
pumpFrame(phase: EnginePhase.composite);
image = await boundary.toImage();
expect(image.width, equals(20));
expect(image.height, equals(20));
ByteData data = (await image.toByteData())!;
int getPixel(int x, int y) => data.getUint32((x + y * image.width) * 4);
expect(data.lengthInBytes, equals(20 * 20 * 4));
expect(data.elementSizeInBytes, equals(1));
expect(getPixel(0, 0), equals(0x00000080));
expect(getPixel(image.width - 1, 0 ), equals(0xffffffff));
final OffsetLayer layer = boundary.debugLayer! as OffsetLayer;
image = await layer.toImage(Offset.zero & const Size(20.0, 20.0));
expect(image.width, equals(20));
expect(image.height, equals(20));
data = (await image.toByteData())!;
expect(getPixel(0, 0), equals(0x00000080));
expect(getPixel(image.width - 1, 0 ), equals(0xffffffff));
// non-zero offsets.
image = await layer.toImage(const Offset(-10.0, -10.0) & const Size(30.0, 30.0));
expect(image.width, equals(30));
expect(image.height, equals(30));
data = (await image.toByteData())!;
expect(getPixel(0, 0), equals(0x00000000));
expect(getPixel(10, 10), equals(0x00000080));
expect(getPixel(image.width - 1, 0), equals(0x00000000));
expect(getPixel(image.width - 1, 10), equals(0xffffffff));
// offset combined with a custom pixel ratio.
image = await layer.toImage(const Offset(-10.0, -10.0) & const Size(30.0, 30.0), pixelRatio: 2.0);
expect(image.width, equals(60));
expect(image.height, equals(60));
data = (await image.toByteData())!;
expect(getPixel(0, 0), equals(0x00000000));
expect(getPixel(20, 20), equals(0x00000080));
expect(getPixel(image.width - 1, 0), equals(0x00000000));
expect(getPixel(image.width - 1, 20), equals(0xffffffff));
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/49857
test('RenderRepaintBoundary can capture images of itself synchronously', () async {
RenderRepaintBoundary boundary = RenderRepaintBoundary();
layout(boundary, constraints: BoxConstraints.tight(const Size(100.0, 200.0)));
pumpFrame(phase: EnginePhase.composite);
ui.Image image = boundary.toImageSync();
expect(image.width, equals(100));
expect(image.height, equals(200));
// Now with pixel ratio set to something other than 1.0.
boundary = RenderRepaintBoundary();
layout(boundary, constraints: BoxConstraints.tight(const Size(100.0, 200.0)));
pumpFrame(phase: EnginePhase.composite);
image = boundary.toImageSync(pixelRatio: 2.0);
expect(image.width, equals(200));
expect(image.height, equals(400));
// Try building one with two child layers and make sure it renders them both.
boundary = RenderRepaintBoundary();
final RenderStack stack = RenderStack()..alignment = Alignment.topLeft;
final RenderDecoratedBox blackBox = RenderDecoratedBox(
decoration: const BoxDecoration(color: Color(0xff000000)),
child: RenderConstrainedBox(
additionalConstraints: BoxConstraints.tight(const Size.square(20.0)),
),
);
stack.add(
RenderOpacity()
..opacity = 0.5
..child = blackBox,
);
final RenderDecoratedBox whiteBox = RenderDecoratedBox(
decoration: const BoxDecoration(color: Color(0xffffffff)),
child: RenderConstrainedBox(
additionalConstraints: BoxConstraints.tight(const Size.square(10.0)),
),
);
final RenderPositionedBox positioned = RenderPositionedBox(
widthFactor: 2.0,
heightFactor: 2.0,
alignment: Alignment.topRight,
child: whiteBox,
);
stack.add(positioned);
boundary.child = stack;
layout(boundary, constraints: BoxConstraints.tight(const Size(20.0, 20.0)));
pumpFrame(phase: EnginePhase.composite);
image = boundary.toImageSync();
expect(image.width, equals(20));
expect(image.height, equals(20));
ByteData data = (await image.toByteData())!;
int getPixel(int x, int y) => data.getUint32((x + y * image.width) * 4);
expect(data.lengthInBytes, equals(20 * 20 * 4));
expect(data.elementSizeInBytes, equals(1));
expect(getPixel(0, 0), equals(0x00000080));
expect(getPixel(image.width - 1, 0 ), equals(0xffffffff));
final OffsetLayer layer = boundary.debugLayer! as OffsetLayer;
image = layer.toImageSync(Offset.zero & const Size(20.0, 20.0));
expect(image.width, equals(20));
expect(image.height, equals(20));
data = (await image.toByteData())!;
expect(getPixel(0, 0), equals(0x00000080));
expect(getPixel(image.width - 1, 0 ), equals(0xffffffff));
// non-zero offsets.
image = layer.toImageSync(const Offset(-10.0, -10.0) & const Size(30.0, 30.0));
expect(image.width, equals(30));
expect(image.height, equals(30));
data = (await image.toByteData())!;
expect(getPixel(0, 0), equals(0x00000000));
expect(getPixel(10, 10), equals(0x00000080));
expect(getPixel(image.width - 1, 0), equals(0x00000000));
expect(getPixel(image.width - 1, 10), equals(0xffffffff));
// offset combined with a custom pixel ratio.
image = layer.toImageSync(const Offset(-10.0, -10.0) & const Size(30.0, 30.0), pixelRatio: 2.0);
expect(image.width, equals(60));
expect(image.height, equals(60));
data = (await image.toByteData())!;
expect(getPixel(0, 0), equals(0x00000000));
expect(getPixel(20, 20), equals(0x00000080));
expect(getPixel(image.width - 1, 0), equals(0x00000000));
expect(getPixel(image.width - 1, 20), equals(0xffffffff));
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/49857
test('RenderOpacity does not composite if it is transparent', () {
final RenderOpacity renderOpacity = RenderOpacity(
opacity: 0.0,
child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter
);
layout(renderOpacity, phase: EnginePhase.composite);
expect(renderOpacity.needsCompositing, false);
});
test('RenderOpacity does composite if it is opaque', () {
final RenderOpacity renderOpacity = RenderOpacity(
child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter
);
layout(renderOpacity, phase: EnginePhase.composite);
expect(renderOpacity.needsCompositing, true);
});
test('RenderOpacity does composite if it is partially opaque', () {
final RenderOpacity renderOpacity = RenderOpacity(
opacity: 0.1,
child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter
);
layout(renderOpacity, phase: EnginePhase.composite);
expect(renderOpacity.needsCompositing, true);
});
test('RenderOpacity reuses its layer', () {
_testLayerReuse<OpacityLayer>(RenderOpacity(
opacity: 0.5, // must not be 0 or 1.0. Otherwise, it won't create a layer
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(1.0, 1.0)),
), // size doesn't matter
));
});
test('RenderAnimatedOpacity does not composite if it is transparent', () async {
final Animation<double> opacityAnimation = AnimationController(
vsync: FakeTickerProvider(),
)..value = 0.0;
final RenderAnimatedOpacity renderAnimatedOpacity = RenderAnimatedOpacity(
opacity: opacityAnimation,
child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter
);
layout(renderAnimatedOpacity, phase: EnginePhase.composite);
expect(renderAnimatedOpacity.needsCompositing, false);
});
test('RenderAnimatedOpacity does composite if it is opaque', () {
final Animation<double> opacityAnimation = AnimationController(
vsync: FakeTickerProvider(),
)..value = 1.0;
final RenderAnimatedOpacity renderAnimatedOpacity = RenderAnimatedOpacity(
opacity: opacityAnimation,
child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter
);
layout(renderAnimatedOpacity, phase: EnginePhase.composite);
expect(renderAnimatedOpacity.needsCompositing, true);
});
test('RenderAnimatedOpacity does composite if it is partially opaque', () {
final Animation<double> opacityAnimation = AnimationController(
vsync: FakeTickerProvider(),
)..value = 0.5;
final RenderAnimatedOpacity renderAnimatedOpacity = RenderAnimatedOpacity(
opacity: opacityAnimation,
child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter
);
layout(renderAnimatedOpacity, phase: EnginePhase.composite);
expect(renderAnimatedOpacity.needsCompositing, true);
});
test('RenderAnimatedOpacity 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
_testLayerReuse<OpacityLayer>(RenderAnimatedOpacity(
opacity: opacityAnimation,
child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter
));
});
test('RenderShaderMask reuses its layer', () {
_testLayerReuse<ShaderMaskLayer>(RenderShaderMask(
shaderCallback: (Rect rect) {
return ui.Gradient.radial(
rect.center,
rect.shortestSide / 2.0,
const <Color>[Color.fromRGBO(0, 0, 0, 1.0), Color.fromRGBO(255, 255, 255, 1.0)],
);
},
child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter
));
});
test('RenderBackdropFilter reuses its layer', () {
_testLayerReuse<BackdropFilterLayer>(RenderBackdropFilter(
filter: ui.ImageFilter.blur(),
child: RenderSizedBox(const Size(1.0, 1.0)), // size doesn't matter
));
});
test('RenderClipRect reuses its layer', () {
_testLayerReuse<ClipRectLayer>(RenderClipRect(
clipper: _TestRectClipper(),
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(1.0, 1.0)),
), // size doesn't matter
));
});
test('RenderClipRRect reuses its layer', () {
_testLayerReuse<ClipRRectLayer>(RenderClipRRect(
clipper: _TestRRectClipper(),
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(1.0, 1.0)),
), // size doesn't matter
));
});
test('RenderClipOval reuses its layer', () {
_testLayerReuse<ClipPathLayer>(RenderClipOval(
clipper: _TestRectClipper(),
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(1.0, 1.0)),
), // size doesn't matter
));
});
test('RenderClipPath reuses its layer', () {
_testLayerReuse<ClipPathLayer>(RenderClipPath(
clipper: _TestPathClipper(),
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(1.0, 1.0)),
), // size doesn't matter
));
});
test('RenderPhysicalModel reuses its layer', () {
_testLayerReuse<ClipRRectLayer>(RenderPhysicalModel(
clipBehavior: Clip.hardEdge,
color: const Color.fromRGBO(0, 0, 0, 1.0),
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(1.0, 1.0)),
), // size doesn't matter
));
});
test('RenderPhysicalShape reuses its layer', () {
_testLayerReuse<ClipPathLayer>(RenderPhysicalShape(
clipper: _TestPathClipper(),
clipBehavior: Clip.hardEdge,
color: const Color.fromRGBO(0, 0, 0, 1.0),
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(1.0, 1.0)),
), // size doesn't matter
));
});
test('RenderTransform reuses its layer', () {
_testLayerReuse<TransformLayer>(RenderTransform(
// Use a 3D transform to force compositing.
transform: Matrix4.rotationX(0.1),
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(1.0, 1.0)),
), // size doesn't matter
));
});
void testFittedBoxWithClipRectLayer() {
_testLayerReuse<ClipRectLayer>(RenderFittedBox(
fit: BoxFit.cover,
clipBehavior: Clip.hardEdge,
// Inject opacity under the clip to force compositing.
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(100.0, 200.0)),
), // size doesn't matter
));
}
void testFittedBoxWithTransformLayer() {
_testLayerReuse<TransformLayer>(RenderFittedBox(
fit: BoxFit.fill,
// Inject opacity under the clip to force compositing.
child: RenderRepaintBoundary(
child: RenderSizedBox(const Size(1, 1)),
), // size doesn't matter
));
}
test('RenderFittedBox reuses ClipRectLayer', () {
testFittedBoxWithClipRectLayer();
});
test('RenderFittedBox reuses TransformLayer', () {
testFittedBoxWithTransformLayer();
});
test('RenderFittedBox switches between ClipRectLayer and TransformLayer, and reuses them', () {
testFittedBoxWithClipRectLayer();
// clip -> transform
testFittedBoxWithTransformLayer();
// transform -> clip
testFittedBoxWithClipRectLayer();
});
test('RenderFittedBox respects clipBehavior', () {
const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 100.0);
for (final Clip? clip in <Clip?>[null, ...Clip.values]) {
final TestClipPaintingContext context = TestClipPaintingContext();
final RenderFittedBox box;
switch (clip) {
case Clip.none:
case Clip.hardEdge:
case Clip.antiAlias:
case Clip.antiAliasWithSaveLayer:
box = RenderFittedBox(child: box200x200, fit: BoxFit.none, clipBehavior: clip!);
case null:
box = RenderFittedBox(child: box200x200, fit: BoxFit.none);
}
layout(box, constraints: viewport, phase: EnginePhase.composite, onErrors: expectNoFlutterErrors);
box.paint(context, Offset.zero);
// By default, clipBehavior should be Clip.none
expect(context.clipBehavior, equals(clip ?? Clip.none));
}
});
test('RenderMouseRegion can change properties when detached', () {
final RenderMouseRegion object = RenderMouseRegion();
object
..opaque = false
..onEnter = (_) {}
..onExit = (_) {}
..onHover = (_) {};
// Passes if no error is thrown
});
test('RenderFractionalTranslation updates its semantics after its translation value is set', () {
final _TestSemanticsUpdateRenderFractionalTranslation box = _TestSemanticsUpdateRenderFractionalTranslation(
translation: const Offset(0.5, 0.5),
);
layout(box, constraints: BoxConstraints.tight(const Size(200.0, 200.0)));
expect(box.markNeedsSemanticsUpdateCallCount, 1);
box.translation = const Offset(0.4, 0.4);
expect(box.markNeedsSemanticsUpdateCallCount, 2);
box.translation = const Offset(0.3, 0.3);
expect(box.markNeedsSemanticsUpdateCallCount, 3);
});
test('RenderFollowerLayer hit test without a leader layer and the showWhenUnlinked is true', () {
final RenderFollowerLayer follower = RenderFollowerLayer(
link: LayerLink(),
child: RenderSizedBox(const Size(1.0, 1.0)),
);
layout(follower, constraints: BoxConstraints.tight(const Size(200.0, 200.0)));
final BoxHitTestResult hitTestResult = BoxHitTestResult();
expect(follower.hitTest(hitTestResult, position: Offset.zero), isTrue);
});
test('RenderFollowerLayer hit test without a leader layer and the showWhenUnlinked is false', () {
final RenderFollowerLayer follower = RenderFollowerLayer(
link: LayerLink(),
showWhenUnlinked: false,
child: RenderSizedBox(const Size(1.0, 1.0)),
);
layout(follower, constraints: BoxConstraints.tight(const Size(200.0, 200.0)));
final BoxHitTestResult hitTestResult = BoxHitTestResult();
expect(follower.hitTest(hitTestResult, position: Offset.zero), isFalse);
});
test('RenderFollowerLayer hit test with a leader layer and the showWhenUnlinked is true', () {
// Creates a layer link with a leader.
final LayerLink link = LayerLink();
final LeaderLayer leader = LeaderLayer(link: link);
leader.attach(Object());
final RenderFollowerLayer follower = RenderFollowerLayer(
link: link,
child: RenderSizedBox(const Size(1.0, 1.0)),
);
layout(follower, constraints: BoxConstraints.tight(const Size(200.0, 200.0)));
final BoxHitTestResult hitTestResult = BoxHitTestResult();
expect(follower.hitTest(hitTestResult, position: Offset.zero), isTrue);
});
test('RenderFollowerLayer hit test with a leader layer and the showWhenUnlinked is false', () {
// Creates a layer link with a leader.
final LayerLink link = LayerLink();
final LeaderLayer leader = LeaderLayer(link: link);
leader.attach(Object());
final RenderFollowerLayer follower = RenderFollowerLayer(
link: link,
showWhenUnlinked: false,
child: RenderSizedBox(const Size(1.0, 1.0)),
);
layout(follower, constraints: BoxConstraints.tight(const Size(200.0, 200.0)));
final BoxHitTestResult hitTestResult = BoxHitTestResult();
// The follower is still hit testable because there is a leader layer.
expect(follower.hitTest(hitTestResult, position: Offset.zero), isTrue);
});
test('RenderObject can become a repaint boundary', () {
final ConditionalRepaintBoundary childBox = ConditionalRepaintBoundary();
final ConditionalRepaintBoundary renderBox = ConditionalRepaintBoundary(child: childBox);
layout(renderBox, phase: EnginePhase.composite);
expect(childBox.paintCount, 1);
expect(renderBox.paintCount, 1);
renderBox.isRepaintBoundary = true;
renderBox.markNeedsCompositingBitsUpdate();
renderBox.markNeedsCompositedLayerUpdate();
pumpFrame(phase: EnginePhase.composite);
// The first time the render object becomes a repaint boundary
// we must repaint from the parent to allow the layer to be
// created.
expect(childBox.paintCount, 2);
expect(renderBox.paintCount, 2);
expect(renderBox.debugLayer, isA<OffsetLayer>());
renderBox.markNeedsCompositedLayerUpdate();
expect(renderBox.debugNeedsPaint, false);
expect(renderBox.debugNeedsCompositedLayerUpdate, true);
pumpFrame(phase: EnginePhase.composite);
// The second time the layer exists and we can skip paint.
expect(childBox.paintCount, 2);
expect(renderBox.paintCount, 2);
expect(renderBox.debugLayer, isA<OffsetLayer>());
renderBox.isRepaintBoundary = false;
renderBox.markNeedsCompositingBitsUpdate();
pumpFrame(phase: EnginePhase.composite);
// Once it stops being a repaint boundary we must repaint to
// remove the layer. its required that the render object
// perform this action in paint.
expect(childBox.paintCount, 3);
expect(renderBox.paintCount, 3);
expect(renderBox.debugLayer, null);
// When the render object is not a repaint boundary, calling
// markNeedsLayerPropertyUpdate is the same as calling
// markNeedsPaint.
renderBox.markNeedsCompositedLayerUpdate();
expect(renderBox.debugNeedsPaint, true);
expect(renderBox.debugNeedsCompositedLayerUpdate, true);
});
test('RenderObject with repaint boundary asserts when a composited layer is replaced during layer property update', () {
final ConditionalRepaintBoundary childBox = ConditionalRepaintBoundary(isRepaintBoundary: true);
final ConditionalRepaintBoundary renderBox = ConditionalRepaintBoundary(child: childBox);
// Ignore old layer.
childBox.offsetLayerFactory = (OffsetLayer? oldLayer) {
return TestOffsetLayerA();
};
layout(renderBox, phase: EnginePhase.composite);
expect(childBox.paintCount, 1);
expect(renderBox.paintCount, 1);
renderBox.markNeedsCompositedLayerUpdate();
pumpFrame(phase: EnginePhase.composite, onErrors: expectAssertionError);
}, skip: kIsWeb); // https://github.com/flutter/flutter/issues/102086
test('RenderObject with repaint boundary asserts when a composited layer is replaced during painting', () {
final ConditionalRepaintBoundary childBox = ConditionalRepaintBoundary(isRepaintBoundary: true);
final ConditionalRepaintBoundary renderBox = ConditionalRepaintBoundary(child: childBox);
// Ignore old layer.
childBox.offsetLayerFactory = (OffsetLayer? oldLayer) {
return TestOffsetLayerA();
};
layout(renderBox, phase: EnginePhase.composite);
expect(childBox.paintCount, 1);
expect(renderBox.paintCount, 1);
renderBox.markNeedsPaint();
pumpFrame(phase: EnginePhase.composite, onErrors: expectAssertionError);
}, skip: kIsWeb); // https://github.com/flutter/flutter/issues/102086
test('RenderObject with repaint boundary asserts when a composited layer tries to update its own offset', () {
final ConditionalRepaintBoundary childBox = ConditionalRepaintBoundary(isRepaintBoundary: true);
final ConditionalRepaintBoundary renderBox = ConditionalRepaintBoundary(child: childBox);
// Ignore old layer.
childBox.offsetLayerFactory = (OffsetLayer? oldLayer) {
return (oldLayer ?? TestOffsetLayerA())..offset = const Offset(2133, 4422);
};
layout(renderBox, phase: EnginePhase.composite);
expect(childBox.paintCount, 1);
expect(renderBox.paintCount, 1);
renderBox.markNeedsPaint();
pumpFrame(phase: EnginePhase.composite, onErrors: expectAssertionError);
}, skip: kIsWeb); // https://github.com/flutter/flutter/issues/102086
test('RenderObject markNeedsPaint while repaint boundary, and then updated to no longer be a repaint boundary with '
'calling markNeedsCompositingBitsUpdate 1', () {
final ConditionalRepaintBoundary childBox = ConditionalRepaintBoundary(isRepaintBoundary: true);
final ConditionalRepaintBoundary renderBox = ConditionalRepaintBoundary(child: childBox);
// Ignore old layer.
childBox.offsetLayerFactory = (OffsetLayer? oldLayer) {
return oldLayer ?? TestOffsetLayerA();
};
layout(renderBox, phase: EnginePhase.composite);
expect(childBox.paintCount, 1);
expect(renderBox.paintCount, 1);
childBox.markNeedsPaint();
childBox.isRepaintBoundary = false;
childBox.markNeedsCompositingBitsUpdate();
expect(() => pumpFrame(phase: EnginePhase.composite), returnsNormally);
});
test('RenderObject markNeedsPaint while repaint boundary, and then updated to no longer be a repaint boundary with '
'calling markNeedsCompositingBitsUpdate 2', () {
final ConditionalRepaintBoundary childBox = ConditionalRepaintBoundary(isRepaintBoundary: true);
final ConditionalRepaintBoundary renderBox = ConditionalRepaintBoundary(child: childBox);
// Ignore old layer.
childBox.offsetLayerFactory = (OffsetLayer? oldLayer) {
return oldLayer ?? TestOffsetLayerA();
};
layout(renderBox, phase: EnginePhase.composite);
expect(childBox.paintCount, 1);
expect(renderBox.paintCount, 1);
childBox.isRepaintBoundary = false;
childBox.markNeedsCompositingBitsUpdate();
childBox.markNeedsPaint();
expect(() => pumpFrame(phase: EnginePhase.composite), returnsNormally);
});
test('RenderObject markNeedsPaint while repaint boundary, and then updated to no longer be a repaint boundary with '
'calling markNeedsCompositingBitsUpdate 3', () {
final ConditionalRepaintBoundary childBox = ConditionalRepaintBoundary(isRepaintBoundary: true);
final ConditionalRepaintBoundary renderBox = ConditionalRepaintBoundary(child: childBox);
// Ignore old layer.
childBox.offsetLayerFactory = (OffsetLayer? oldLayer) {
return oldLayer ?? TestOffsetLayerA();
};
layout(renderBox, phase: EnginePhase.composite);
expect(childBox.paintCount, 1);
expect(renderBox.paintCount, 1);
childBox.isRepaintBoundary = false;
childBox.markNeedsCompositedLayerUpdate();
childBox.markNeedsCompositingBitsUpdate();
expect(() => pumpFrame(phase: EnginePhase.composite), returnsNormally);
});
test('Offstage implements paintsChild correctly', () {
final RenderConstrainedBox box = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 20));
final RenderConstrainedBox parent = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 20));
final RenderOffstage offstage = RenderOffstage(offstage: false, child: box);
parent.child = offstage;
expect(offstage.paintsChild(box), true);
offstage.offstage = true;
expect(offstage.paintsChild(box), false);
});
test('Opacity implements paintsChild correctly', () {
final RenderBox box = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 20));
final RenderOpacity opacity = RenderOpacity(child: box);
expect(opacity.paintsChild(box), true);
opacity.opacity = 0;
expect(opacity.paintsChild(box), false);
});
test('AnimatedOpacity sets paint matrix to zero when alpha == 0', () {
final RenderBox box = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 20));
final AnimationController opacityAnimation = AnimationController(value: 1, vsync: FakeTickerProvider());
final RenderAnimatedOpacity opacity = RenderAnimatedOpacity(opacity: opacityAnimation, child: box);
// Make it listen to the animation.
opacity.attach(PipelineOwner());
expect(opacity.paintsChild(box), true);
opacityAnimation.value = 0;
expect(opacity.paintsChild(box), false);
});
test('AnimatedOpacity sets paint matrix to zero when alpha == 0 (sliver)', () {
final RenderSliver sliver = RenderSliverToBoxAdapter(child: RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 20)));
final AnimationController opacityAnimation = AnimationController(value: 1, vsync: FakeTickerProvider());
final RenderSliverAnimatedOpacity opacity = RenderSliverAnimatedOpacity(opacity: opacityAnimation, sliver: sliver);
// Make it listen to the animation.
opacity.attach(PipelineOwner());
expect(opacity.paintsChild(sliver), true);
opacityAnimation.value = 0;
expect(opacity.paintsChild(sliver), false);
});
test('RenderCustomClip extenders respect clipBehavior when asked to describeApproximateClip', () {
final RenderBox child = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 200, height: 200));
final RenderClipRect renderClipRect = RenderClipRect(clipBehavior: Clip.none, child: child);
layout(renderClipRect);
expect(
renderClipRect.describeApproximatePaintClip(child),
null,
);
renderClipRect.clipBehavior = Clip.hardEdge;
expect(
renderClipRect.describeApproximatePaintClip(child),
Offset.zero & renderClipRect.size,
);
renderClipRect.clipBehavior = Clip.antiAlias;
expect(
renderClipRect.describeApproximatePaintClip(child),
Offset.zero & renderClipRect.size,
);
renderClipRect.clipBehavior = Clip.antiAliasWithSaveLayer;
expect(
renderClipRect.describeApproximatePaintClip(child),
Offset.zero & renderClipRect.size,
);
});
// Simulate painting a RenderBox as if 'debugPaintSizeEnabled == true'
DebugPaintCallback debugPaint(RenderBox renderBox) {
layout(renderBox);
pumpFrame(phase: EnginePhase.compositingBits);
return (PaintingContext context, Offset offset) {
renderBox.paint(context, offset);
renderBox.debugPaintSize(context, offset);
};
}
test('RenderClipPath.debugPaintSize draws a path and a debug text when clipBehavior is not Clip.none', () {
DebugPaintCallback debugPaintClipRect(Clip clip) {
final RenderBox child = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 200, height: 200));
final RenderClipPath renderClipPath = RenderClipPath(clipBehavior: clip, child: child);
return debugPaint(renderClipPath);
}
// RenderClipPath.debugPaintSize draws when clipBehavior is not Clip.none
expect(debugPaintClipRect(Clip.hardEdge), paintsExactlyCountTimes(#drawPath, 1));
expect(debugPaintClipRect(Clip.hardEdge), paintsExactlyCountTimes(#drawParagraph, 1));
// RenderClipPath.debugPaintSize does not draw when clipBehavior is Clip.none
// Regression test for https://github.com/flutter/flutter/issues/105969
expect(debugPaintClipRect(Clip.none), paintsExactlyCountTimes(#drawPath, 0));
expect(debugPaintClipRect(Clip.none), paintsExactlyCountTimes(#drawParagraph, 0));
});
test('RenderClipRect.debugPaintSize draws a rect and a debug text when clipBehavior is not Clip.none', () {
DebugPaintCallback debugPaintClipRect(Clip clip) {
final RenderBox child = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 200, height: 200));
final RenderClipRect renderClipRect = RenderClipRect(clipBehavior: clip, child: child);
return debugPaint(renderClipRect);
}
// RenderClipRect.debugPaintSize draws when clipBehavior is not Clip.none
expect(debugPaintClipRect(Clip.hardEdge), paintsExactlyCountTimes(#drawRect, 1));
expect(debugPaintClipRect(Clip.hardEdge), paintsExactlyCountTimes(#drawParagraph, 1));
// RenderClipRect.debugPaintSize does not draw when clipBehavior is Clip.none
expect(debugPaintClipRect(Clip.none), paintsExactlyCountTimes(#drawRect, 0));
expect(debugPaintClipRect(Clip.none), paintsExactlyCountTimes(#drawParagraph, 0));
});
test('RenderClipRRect.debugPaintSize draws a rounded rect and a debug text when clipBehavior is not Clip.none', () {
DebugPaintCallback debugPaintClipRRect(Clip clip) {
final RenderBox child = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 200, height: 200));
final RenderClipRRect renderClipRRect = RenderClipRRect(clipBehavior: clip, child: child);
return debugPaint(renderClipRRect);
}
// RenderClipRRect.debugPaintSize draws when clipBehavior is not Clip.none
expect(debugPaintClipRRect(Clip.hardEdge), paintsExactlyCountTimes(#drawRRect, 1));
expect(debugPaintClipRRect(Clip.hardEdge), paintsExactlyCountTimes(#drawParagraph, 1));
// RenderClipRRect.debugPaintSize does not draw when clipBehavior is Clip.none
expect(debugPaintClipRRect(Clip.none), paintsExactlyCountTimes(#drawRRect, 0));
expect(debugPaintClipRRect(Clip.none), paintsExactlyCountTimes(#drawParagraph, 0));
});
test('RenderClipOval.debugPaintSize draws a path and a debug text when clipBehavior is not Clip.none', () {
DebugPaintCallback debugPaintClipOval(Clip clip) {
final RenderBox child = RenderConstrainedBox(additionalConstraints: const BoxConstraints.tightFor(width: 200, height: 200));
final RenderClipOval renderClipOval = RenderClipOval(clipBehavior: clip, child: child);
return debugPaint(renderClipOval);
}
// RenderClipOval.debugPaintSize draws when clipBehavior is not Clip.none
expect(debugPaintClipOval(Clip.hardEdge), paintsExactlyCountTimes(#drawPath, 1));
expect(debugPaintClipOval(Clip.hardEdge), paintsExactlyCountTimes(#drawParagraph, 1));
// RenderClipOval.debugPaintSize does not draw when clipBehavior is Clip.none
expect(debugPaintClipOval(Clip.none), paintsExactlyCountTimes(#drawPath, 0));
expect(debugPaintClipOval(Clip.none), paintsExactlyCountTimes(#drawParagraph, 0));
});
test('RenderProxyBox behavior can be mixed in along with another base class', () {
final RenderFancyProxyBox fancyProxyBox = RenderFancyProxyBox(fancy: 6);
// Box has behavior from its base class:
expect(fancyProxyBox.fancyMethod(), 36);
// Box has behavior from RenderProxyBox:
expect(
// ignore: invalid_use_of_protected_member
fancyProxyBox.computeDryLayout(const BoxConstraints(minHeight: 8)),
const Size(0, 8),
);
});
test('computeDryLayout constraints are covariant', () {
final RenderBoxWithTestConstraints box = RenderBoxWithTestConstraints();
const TestConstraints constraints = TestConstraints(testValue: 6);
expect(box.computeDryLayout(constraints), const Size.square(6));
});
}
class _TestRectClipper extends CustomClipper<Rect> {
@override
Rect getClip(Size size) {
return Rect.zero;
}
@override
Rect getApproximateClipRect(Size size) => getClip(size);
@override
bool shouldReclip(_TestRectClipper oldClipper) => true;
}
class _TestRRectClipper extends CustomClipper<RRect> {
@override
RRect getClip(Size size) {
return RRect.zero;
}
@override
Rect getApproximateClipRect(Size size) => getClip(size).outerRect;
@override
bool shouldReclip(_TestRRectClipper oldClipper) => true;
}
// Forces two frames and checks that:
// - a layer is created on the first frame
// - the layer is reused on the second frame
void _testLayerReuse<L extends Layer>(RenderBox renderObject) {
expect(L, isNot(Layer));
expect(renderObject.debugLayer, null);
layout(renderObject, phase: EnginePhase.paint, constraints: BoxConstraints.tight(const Size(10, 10)));
final Layer? layer = renderObject.debugLayer;
expect(layer, isA<L>());
expect(layer, isNotNull);
// Mark for repaint otherwise pumpFrame is a noop.
renderObject.markNeedsPaint();
expect(renderObject.debugNeedsPaint, true);
pumpFrame(phase: EnginePhase.paint);
expect(renderObject.debugNeedsPaint, false);
expect(renderObject.debugLayer, same(layer));
}
class _TestPathClipper extends CustomClipper<Path> {
@override
Path getClip(Size size) {
return Path()
..addRect(const Rect.fromLTWH(50.0, 50.0, 100.0, 100.0));
}
@override
bool shouldReclip(_TestPathClipper oldClipper) => false;
}
class _TestSemanticsUpdateRenderFractionalTranslation extends RenderFractionalTranslation {
_TestSemanticsUpdateRenderFractionalTranslation({
required super.translation,
});
int markNeedsSemanticsUpdateCallCount = 0;
@override
void markNeedsSemanticsUpdate() {
markNeedsSemanticsUpdateCallCount++;
super.markNeedsSemanticsUpdate();
}
}
class ConditionalRepaintBoundary extends RenderProxyBox {
ConditionalRepaintBoundary({this.isRepaintBoundary = false, RenderBox? child}) : super(child);
@override
bool isRepaintBoundary = false;
OffsetLayer Function(OffsetLayer?)? offsetLayerFactory;
int paintCount = 0;
@override
OffsetLayer updateCompositedLayer({required covariant OffsetLayer? oldLayer}) {
return offsetLayerFactory?.call(oldLayer) ?? super.updateCompositedLayer(oldLayer: oldLayer);
}
@override
void paint(PaintingContext context, Offset offset) {
paintCount += 1;
super.paint(context, offset);
}
}
class TestOffsetLayerA extends OffsetLayer {}
class RenderFancyBox extends RenderBox {
RenderFancyBox({required this.fancy}) : super();
late int fancy;
int fancyMethod() {
return fancy * fancy;
}
}
class RenderFancyProxyBox extends RenderFancyBox
with RenderObjectWithChildMixin<RenderBox>, RenderProxyBoxMixin<RenderBox> {
RenderFancyProxyBox({required super.fancy});
}
void expectAssertionError() {
final FlutterErrorDetails errorDetails = TestRenderingFlutterBinding.instance.takeFlutterErrorDetails()!;
final bool asserted = errorDetails.toString().contains('Failed assertion');
if (!asserted) {
FlutterError.reportError(errorDetails);
}
}
typedef DebugPaintCallback = void Function(PaintingContext context, Offset offset);
class TestConstraints extends BoxConstraints {
const TestConstraints({
double extent = 100,
required this.testValue,
}) : super(maxWidth: extent, maxHeight: extent);
final double testValue;
}
class RenderBoxWithTestConstraints extends RenderProxyBox {
@override
Size computeDryLayout(TestConstraints constraints) {
return constraints.constrain(Size.square(constraints.testValue));
}
}
| flutter/packages/flutter/test/rendering/proxy_box_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/proxy_box_test.dart",
"repo_id": "flutter",
"token_count": 14831
} | 288 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Test sliver which always attempts to paint itself whether it is visible or not.
// Use for checking if slivers which take sliver children paints optimally.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class RenderMockSliverToBoxAdapter extends RenderSliverToBoxAdapter {
RenderMockSliverToBoxAdapter({
super.child,
required this.incrementCounter,
});
final void Function() incrementCounter;
@override
void paint(PaintingContext context, Offset offset) {
incrementCounter();
}
}
class MockSliverToBoxAdapter extends SingleChildRenderObjectWidget {
/// Creates a sliver that contains a single box widget.
const MockSliverToBoxAdapter({
super.key,
super.child,
required this.incrementCounter,
});
final void Function() incrementCounter;
@override
RenderMockSliverToBoxAdapter createRenderObject(BuildContext context) =>
RenderMockSliverToBoxAdapter(incrementCounter: incrementCounter);
}
| flutter/packages/flutter/test/rendering/sliver_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/sliver_utils.dart",
"repo_id": "flutter",
"token_count": 323
} | 289 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class TestBinding extends LiveTestWidgetsFlutterBinding {
TestBinding();
int framesBegun = 0;
int framesDrawn = 0;
late bool handleBeginFrameMicrotaskRun;
@override
void handleBeginFrame(Duration? rawTimeStamp) {
handleBeginFrameMicrotaskRun = false;
framesBegun += 1;
Future<void>.microtask(() { handleBeginFrameMicrotaskRun = true; });
super.handleBeginFrame(rawTimeStamp);
}
@override
void handleDrawFrame() {
if (!handleBeginFrameMicrotaskRun) {
throw "Microtasks scheduled by 'handledBeginFrame' must be run before 'handleDrawFrame'.";
}
framesDrawn += 1;
super.handleDrawFrame();
}
}
void main() {
late TestBinding binding;
setUp(() {
binding = TestBinding();
});
test('test pumpBenchmark() only runs one frame', () async {
await benchmarkWidgets(
(WidgetTester tester) async {
const Key root = Key('root');
binding.attachRootWidget(binding.wrapWithDefaultView(Container(key: root)));
await tester.pump();
expect(binding.framesBegun, greaterThan(0));
expect(binding.framesDrawn, greaterThan(0));
final Element appState = tester.element(find.byKey(root));
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.benchmark;
final int startFramesBegun = binding.framesBegun;
final int startFramesDrawn = binding.framesDrawn;
expect(startFramesBegun, equals(startFramesDrawn));
appState.markNeedsBuild();
await tester.pumpBenchmark(const Duration(milliseconds: 16));
final int endFramesBegun = binding.framesBegun;
final int endFramesDrawn = binding.framesDrawn;
expect(endFramesBegun, equals(endFramesDrawn));
expect(endFramesBegun, equals(startFramesBegun + 1));
expect(endFramesDrawn, equals(startFramesDrawn + 1));
},
// We are not interested in the performance of the "benchmark", we are just
// testing the behavior. So it's OK that asserts are enabled.
mayRunWithAsserts: true,
);
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/87871
}
| flutter/packages/flutter/test/scheduler/benchmarks_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/scheduler/benchmarks_test.dart",
"repo_id": "flutter",
"token_count": 843
} | 290 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() {
testWidgets('Traversal order handles touching elements', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
MaterialApp(
home: Column(
children: List<Widget>.generate(3, (int column) {
return Row(
children: List<Widget>.generate(3, (int row) {
return Semantics(
child: SizedBox(
width: 50.0,
height: 50.0,
child: Text('$column - $row'),
),
);
}),
);
}),
),
),
);
final TestSemantics expected = 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,
label: '0 - 0',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 5,
label: '0 - 1',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 6,
label: '0 - 2',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 7,
label: '1 - 0',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 8,
label: '1 - 1',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 9,
label: '1 - 2',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 10,
label: '2 - 0',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 11,
label: '2 - 1',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 12,
label: '2 - 2',
textDirection: TextDirection.ltr,
),
],
),
],
),
],
),
],
);
expect(semantics, hasSemantics(expected, ignoreRect: true, ignoreTransform: true));
semantics.dispose();
});
}
| flutter/packages/flutter/test/semantics/traversal_order_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/semantics/traversal_order_test.dart",
"repo_id": "flutter",
"token_count": 2047
} | 291 |
// Copyright 2014 The Flutter Authors. 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() {
group(PhysicalKeyboardKey, () {
test('Various classes of keys can be looked up by code.', () async {
// Check a letter key
expect(PhysicalKeyboardKey.findKeyByCode(0x00070004), equals(PhysicalKeyboardKey.keyA));
// Check a control key
expect(PhysicalKeyboardKey.findKeyByCode(0x00070029), equals(PhysicalKeyboardKey.escape));
// Check a modifier key
expect(PhysicalKeyboardKey.findKeyByCode(0x000700e1), equals(PhysicalKeyboardKey.shiftLeft));
});
test('Values are equal', () async {
expect(PhysicalKeyboardKey.keyA == PhysicalKeyboardKey(PhysicalKeyboardKey.keyA.usbHidUsage), true);
// ignore: prefer_const_constructors, intentionally test if a const key is equal to a non-const key
expect(const PhysicalKeyboardKey(0x12345) == PhysicalKeyboardKey(0x12345), true);
});
test('debugNames', () async {
expect(PhysicalKeyboardKey.keyA.debugName, 'Key A');
expect(PhysicalKeyboardKey.backslash.debugName, 'Backslash');
expect(const PhysicalKeyboardKey(0x12345).debugName, 'Key with ID 0x00012345');
});
});
group(LogicalKeyboardKey, () {
test('Various classes of keys can be looked up by code', () async {
// Check a letter key
expect(LogicalKeyboardKey.findKeyByKeyId(LogicalKeyboardKey.keyA.keyId), equals(LogicalKeyboardKey.keyA));
// Check a control key
expect(LogicalKeyboardKey.findKeyByKeyId(LogicalKeyboardKey.escape.keyId), equals(LogicalKeyboardKey.escape));
// Check a modifier key
expect(LogicalKeyboardKey.findKeyByKeyId(LogicalKeyboardKey.shiftLeft.keyId), equals(LogicalKeyboardKey.shiftLeft));
});
test('Control characters are recognized as such', () async {
// Check some common control characters
expect(LogicalKeyboardKey.isControlCharacter('\x08'), isTrue); // BACKSPACE
expect(LogicalKeyboardKey.isControlCharacter('\x09'), isTrue); // TAB
expect(LogicalKeyboardKey.isControlCharacter('\x0a'), isTrue); // LINE FEED
expect(LogicalKeyboardKey.isControlCharacter('\x0d'), isTrue); // RETURN
expect(LogicalKeyboardKey.isControlCharacter('\x1b'), isTrue); // ESC
expect(LogicalKeyboardKey.isControlCharacter('\x7f'), isTrue); // DELETE
// Check non-control characters
expect(LogicalKeyboardKey.isControlCharacter('A'), isFalse);
expect(LogicalKeyboardKey.isControlCharacter(' '), isFalse);
expect(LogicalKeyboardKey.isControlCharacter('~'), isFalse);
expect(LogicalKeyboardKey.isControlCharacter('\xa0'), isFalse); // NO-BREAK SPACE
});
test('Control characters are not using incorrect values', () async {
// Check some common control characters to make sure they're using
// their char code values, and not something else.
expect(LogicalKeyboardKey.backspace.keyId, equals(LogicalKeyboardKey.unprintablePlane + 0x08));
expect(LogicalKeyboardKey.tab.keyId, equals(LogicalKeyboardKey.unprintablePlane + 0x09));
expect(LogicalKeyboardKey.enter.keyId, equals(LogicalKeyboardKey.unprintablePlane + 0x0d));
expect(LogicalKeyboardKey.escape.keyId, equals(LogicalKeyboardKey.unprintablePlane + 0x1b));
expect(LogicalKeyboardKey.delete.keyId, equals(LogicalKeyboardKey.unprintablePlane + 0x7f));
});
test('Basic synonyms can be looked up.', () async {
expect(LogicalKeyboardKey.shiftLeft.synonyms.first, equals(LogicalKeyboardKey.shift));
expect(LogicalKeyboardKey.controlLeft.synonyms.first, equals(LogicalKeyboardKey.control));
expect(LogicalKeyboardKey.altLeft.synonyms.first, equals(LogicalKeyboardKey.alt));
expect(LogicalKeyboardKey.metaLeft.synonyms.first, equals(LogicalKeyboardKey.meta));
expect(LogicalKeyboardKey.shiftRight.synonyms.first, equals(LogicalKeyboardKey.shift));
expect(LogicalKeyboardKey.controlRight.synonyms.first, equals(LogicalKeyboardKey.control));
expect(LogicalKeyboardKey.altRight.synonyms.first, equals(LogicalKeyboardKey.alt));
expect(LogicalKeyboardKey.metaRight.synonyms.first, equals(LogicalKeyboardKey.meta));
});
test('Synonyms get collapsed properly.', () async {
expect(LogicalKeyboardKey.collapseSynonyms(<LogicalKeyboardKey>{}), isEmpty);
expect(
LogicalKeyboardKey.collapseSynonyms(<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.metaLeft,
}),
equals(<LogicalKeyboardKey>{
LogicalKeyboardKey.shift,
LogicalKeyboardKey.control,
LogicalKeyboardKey.alt,
LogicalKeyboardKey.meta,
}),
);
expect(
LogicalKeyboardKey.collapseSynonyms(<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.controlRight,
LogicalKeyboardKey.altRight,
LogicalKeyboardKey.metaRight,
}),
equals(<LogicalKeyboardKey>{
LogicalKeyboardKey.shift,
LogicalKeyboardKey.control,
LogicalKeyboardKey.alt,
LogicalKeyboardKey.meta,
}),
);
expect(
LogicalKeyboardKey.collapseSynonyms(<LogicalKeyboardKey>{
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.metaLeft,
LogicalKeyboardKey.shiftRight,
LogicalKeyboardKey.controlRight,
LogicalKeyboardKey.altRight,
LogicalKeyboardKey.metaRight,
}),
equals(<LogicalKeyboardKey>{
LogicalKeyboardKey.shift,
LogicalKeyboardKey.control,
LogicalKeyboardKey.alt,
LogicalKeyboardKey.meta,
}),
);
});
test('Values are equal', () async {
expect(LogicalKeyboardKey.keyA == LogicalKeyboardKey(LogicalKeyboardKey.keyA.keyId), true);
// ignore: prefer_const_constructors, intentionally test if a const key is equal to a non-const key
expect(const PhysicalKeyboardKey(0x12345) == PhysicalKeyboardKey(0x12345), true);
});
test('keyLabel', () async {
expect(LogicalKeyboardKey.keyA.keyLabel, 'A');
expect(LogicalKeyboardKey.backslash.keyLabel, r'\');
expect(const LogicalKeyboardKey(0xD9).keyLabel, 'Γ');
expect(const LogicalKeyboardKey(0xF9).keyLabel, 'Γ');
expect(LogicalKeyboardKey.shiftLeft.keyLabel, 'Shift Left');
expect(LogicalKeyboardKey.numpadDecimal.keyLabel, 'Numpad Decimal');
expect(LogicalKeyboardKey.numpad1.keyLabel, 'Numpad 1');
expect(LogicalKeyboardKey.delete.keyLabel, 'Delete');
expect(LogicalKeyboardKey.f12.keyLabel, 'F12');
expect(LogicalKeyboardKey.mediaPlay.keyLabel, 'Media Play');
expect(const LogicalKeyboardKey(0x100012345).keyLabel, '');
});
test('debugName', () async {
expect(LogicalKeyboardKey.keyA.debugName, 'Key A');
expect(LogicalKeyboardKey.backslash.debugName, 'Backslash');
expect(const LogicalKeyboardKey(0xD9).debugName, 'Key Γ');
expect(LogicalKeyboardKey.mediaPlay.debugName, 'Media Play');
expect(const LogicalKeyboardKey(0x100012345).debugName, 'Key with ID 0x00100012345');
});
});
}
| flutter/packages/flutter/test/services/keyboard_key_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/keyboard_key_test.dart",
"repo_id": "flutter",
"token_count": 2898
} | 292 |
// Copyright 2014 The Flutter Authors. 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() {
// We need a separate test file for this test case (instead of including it
// in platform_channel_test.dart) since we rely on the WidgetsFlutterBinding
// not being initialized and we call ensureInitialized() in the other test
// file.
test('throws assertion error iff WidgetsFlutterBinding is not yet initialized', () {
const MethodChannel methodChannel = MethodChannel('mock');
// Verify an assertion error is thrown before the binary messenger is
// accessed (which would result in a _CastError due to the non-null
// assertion). This way we can hint the caller towards how to fix the error.
expect(() => methodChannel.setMethodCallHandler(null), throwsAssertionError);
// Verify the assertion is not thrown once the binding has been initialized.
// This cannot be a separate test case since the execution order is random.
TestWidgetsFlutterBinding.ensureInitialized();
expect(() => methodChannel.setMethodCallHandler(null), returnsNormally);
});
}
| flutter/packages/flutter/test/services/set_method_call_handler_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/set_method_call_handler_test.dart",
"repo_id": "flutter",
"token_count": 343
} | 293 |
// Copyright 2014 The Flutter Authors. 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('AnimatedContainer.debugFillProperties', (WidgetTester tester) async {
final AnimatedContainer container = AnimatedContainer(
constraints: const BoxConstraints.tightFor(width: 17.0, height: 23.0),
decoration: const BoxDecoration(color: Color(0xFF00FF00)),
foregroundDecoration: const BoxDecoration(color: Color(0x7F0000FF)),
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(7.0),
transform: Matrix4.translationValues(4.0, 3.0, 0.0),
width: 50.0,
height: 75.0,
curve: Curves.ease,
duration: const Duration(milliseconds: 200),
);
expect(container, hasOneLineDescription);
});
testWidgets('AnimatedContainer control test', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
const BoxDecoration decorationA = BoxDecoration(
color: Color(0xFF00FF00),
);
const BoxDecoration decorationB = BoxDecoration(
color: Color(0xFF0000FF),
);
BoxDecoration actualDecoration;
await tester.pumpWidget(
AnimatedContainer(
key: key,
duration: const Duration(milliseconds: 200),
decoration: decorationA,
),
);
final RenderDecoratedBox box = key.currentContext!.findRenderObject()! as RenderDecoratedBox;
actualDecoration = box.decoration as BoxDecoration;
expect(actualDecoration.color, equals(decorationA.color));
await tester.pumpWidget(
AnimatedContainer(
key: key,
duration: const Duration(milliseconds: 200),
decoration: decorationB,
),
);
expect(key.currentContext!.findRenderObject(), equals(box));
actualDecoration = box.decoration as BoxDecoration;
expect(actualDecoration.color, equals(decorationA.color));
await tester.pump(const Duration(seconds: 1));
actualDecoration = box.decoration as BoxDecoration;
expect(actualDecoration.color, equals(decorationB.color));
expect(box, hasAGoodToStringDeep);
expect(
box.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'RenderDecoratedBox#00000\n'
' β parentData: <none>\n'
' β constraints: BoxConstraints(w=800.0, h=600.0)\n'
' β size: Size(800.0, 600.0)\n'
' β decoration: BoxDecoration:\n'
' β color: Color(0xff0000ff)\n'
' β configuration: ImageConfiguration(bundle:\n'
' β PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' β android)\n'
' β\n'
' ββchild: RenderPadding#00000\n'
' β parentData: <none> (can use size)\n'
' β constraints: BoxConstraints(w=800.0, h=600.0)\n'
' β size: Size(800.0, 600.0)\n'
' β padding: EdgeInsets.zero\n'
' β\n'
' ββchild: RenderLimitedBox#00000\n'
' β parentData: offset=Offset(0.0, 0.0) (can use size)\n'
' β constraints: BoxConstraints(w=800.0, h=600.0)\n'
' β size: Size(800.0, 600.0)\n'
' β maxWidth: 0.0\n'
' β maxHeight: 0.0\n'
' β\n'
' ββchild: RenderConstrainedBox#00000\n'
' parentData: <none> (can use size)\n'
' constraints: BoxConstraints(w=800.0, h=600.0)\n'
' size: Size(800.0, 600.0)\n'
' additionalConstraints: BoxConstraints(biggest)\n',
),
);
});
testWidgets('AnimatedContainer overanimate test', (WidgetTester tester) async {
await tester.pumpWidget(
AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: const Color(0xFF00FF00),
),
);
expect(tester.binding.transientCallbackCount, 0);
await tester.pump(const Duration(seconds: 1));
expect(tester.binding.transientCallbackCount, 0);
await tester.pumpWidget(
AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: const Color(0xFF00FF00),
),
);
expect(tester.binding.transientCallbackCount, 0);
await tester.pump(const Duration(seconds: 1));
expect(tester.binding.transientCallbackCount, 0);
await tester.pumpWidget(
AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: const Color(0xFF0000FF),
),
);
expect(tester.binding.transientCallbackCount, 1); // this is the only time an animation should have started!
await tester.pump(const Duration(seconds: 1));
expect(tester.binding.transientCallbackCount, 0);
await tester.pumpWidget(
AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: const Color(0xFF0000FF),
),
);
expect(tester.binding.transientCallbackCount, 0);
});
testWidgets('AnimatedContainer padding visual-to-directional animation', (WidgetTester tester) async {
final Key target = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.only(right: 50.0),
child: SizedBox.expand(key: target),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(750.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(750.0, 0.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsetsDirectional.only(start: 100.0),
child: SizedBox.expand(key: target),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(750.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(750.0, 0.0));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.getSize(find.byKey(target)), const Size(725.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(725.0, 0.0));
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getSize(find.byKey(target)), const Size(700.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(700.0, 0.0));
});
testWidgets('AnimatedContainer alignment visual-to-directional animation', (WidgetTester tester) async {
final Key target = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
alignment: Alignment.topRight,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 0.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
alignment: AlignmentDirectional.bottomStart,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 0.0));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 200.0));
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 400.0));
});
testWidgets('Animation rerun', (WidgetTester tester) async {
await tester.pumpWidget(
Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: 100.0,
height: 100.0,
child: const Text('X', textDirection: TextDirection.ltr),
),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
RenderBox text = tester.renderObject(find.text('X'));
expect(text.size.width, equals(100.0));
expect(text.size.height, equals(100.0));
await tester.pump(const Duration(milliseconds: 1000));
await tester.pumpWidget(
Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: 200.0,
height: 200.0,
child: const Text('X', textDirection: TextDirection.ltr),
),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
text = tester.renderObject(find.text('X'));
expect(text.size.width, greaterThan(110.0));
expect(text.size.width, lessThan(190.0));
expect(text.size.height, greaterThan(110.0));
expect(text.size.height, lessThan(190.0));
await tester.pump(const Duration(milliseconds: 1000));
expect(text.size.width, equals(200.0));
expect(text.size.height, equals(200.0));
await tester.pumpWidget(
Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: 200.0,
height: 100.0,
child: const Text('X', textDirection: TextDirection.ltr),
),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(text.size.width, equals(200.0));
expect(text.size.height, greaterThan(110.0));
expect(text.size.height, lessThan(190.0));
await tester.pump(const Duration(milliseconds: 1000));
expect(text.size.width, equals(200.0));
expect(text.size.height, equals(100.0));
});
testWidgets('AnimatedContainer sets transformAlignment', (WidgetTester tester) async {
final Key target = UniqueKey();
await tester.pumpWidget(
Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
transform: Matrix4.diagonal3Values(0.5, 0.5, 1),
transformAlignment: Alignment.topLeft,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopLeft(find.byKey(target)), const Offset(350.0, 200.0));
await tester.pumpWidget(
Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
transform: Matrix4.diagonal3Values(0.5, 0.5, 1),
transformAlignment: Alignment.bottomRight,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopLeft(find.byKey(target)), const Offset(350.0, 200.0));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopLeft(find.byKey(target)), const Offset(375.0, 250.0));
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopLeft(find.byKey(target)), const Offset(400.0, 300.0));
});
testWidgets('AnimatedContainer sets clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(
AnimatedContainer(
decoration: const BoxDecoration(
color: Color(0xFFED1D7F),
),
duration: const Duration(milliseconds: 200),
),
);
expect(tester.firstWidget<Container>(find.byType(Container)).clipBehavior, Clip.none);
await tester.pumpWidget(
AnimatedContainer(
decoration: const BoxDecoration(
color: Color(0xFFED1D7F),
),
duration: const Duration(milliseconds: 200),
clipBehavior: Clip.antiAlias,
),
);
expect(tester.firstWidget<Container>(find.byType(Container)).clipBehavior, Clip.antiAlias);
});
}
| flutter/packages/flutter/test/widgets/animated_container_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/animated_container_test.dart",
"repo_id": "flutter",
"token_count": 5238
} | 294 |
// Copyright 2014 The Flutter Authors. 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';
Future<Size> _getSize(WidgetTester tester, BoxConstraints constraints, double aspectRatio) async {
final Key childKey = UniqueKey();
await tester.pumpWidget(
Center(
child: ConstrainedBox(
constraints: constraints,
child: AspectRatio(
aspectRatio: aspectRatio,
child: Container(
key: childKey,
),
),
),
),
);
final RenderBox box = tester.renderObject(find.byKey(childKey));
return box.size;
}
void main() {
testWidgets('Aspect ratio control test', (WidgetTester tester) async {
expect(await _getSize(tester, BoxConstraints.loose(const Size(500.0, 500.0)), 2.0), equals(const Size(500.0, 250.0)));
expect(await _getSize(tester, BoxConstraints.loose(const Size(500.0, 500.0)), 0.5), equals(const Size(250.0, 500.0)));
});
testWidgets('Aspect ratio infinite width', (WidgetTester tester) async {
final Key childKey = UniqueKey();
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: AspectRatio(
aspectRatio: 2.0,
child: Container(
key: childKey,
),
),
),
),
));
final RenderBox box = tester.renderObject(find.byKey(childKey));
expect(box.size, equals(const Size(1200.0, 600.0)));
});
}
| flutter/packages/flutter/test/widgets/aspect_ratio_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/aspect_ratio_test.dart",
"repo_id": "flutter",
"token_count": 698
} | 295 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
// This file is for tests for WidgetsBinding that require a `LiveTestWidgetsFlutterBinding`.
void main() {
LiveTestWidgetsFlutterBinding();
testWidgets('ReportTiming callback records the sendFramesToEngine when it was scheduled', (WidgetTester tester) async {
// Addresses https://github.com/flutter/flutter/issues/144261
// This test needs LiveTestWidgetsFlutterBinding for multiple reasons.
//
// First, this was the environment that this bug was discovered.
//
// Second, unlike `AutomatedTestWidgetsFlutterBinding`, which overrides
// `scheduleWarmUpFrame` to execute the handlers synchronously,
// `LiveTestWidgetsFlutterBinding` still calls them asynchronously. This
// allows `runApp`, which also schedules a warm-up frame, to bind a widget
// without rendering a frame, which is needed to for `deferFirstFrame` to
// take effect.
// Before `testWidgets` executes the test body, it pumps a frame with a
// fixed dummy widget, then calls `resetFirstFrameSent`. The pumped frame
// schedules a reportTiming call that has yet to arrive.
//
// This puts the test in an inconsistent state: a reportTiming callback is
// supposed to happen only after a frame is rendered, but due to
// `resetFirstFrameSent`, the framework thinks no frames have been rendered.
expect(tester.binding.sendFramesToEngine, true);
// Push the widget with `runApp` instead of `tester.pump`, avoiding
// rendering a frame, which is needed for `deferFirstFrame` later to work.
runApp(const DummyWidget());
// Verify that no widget tree is built and nothing is rendered.
expect(find.text('First frame'), findsNothing);
// Defer the first frame, making `sendFramesToEngine` false, so that widget
// tree will be built but not sent to the engine.
tester.binding.deferFirstFrame();
expect(tester.binding.sendFramesToEngine, false);
// Pump a frame, letting the reportTiming callback to run. If the
// reportTiming callback were to assume that `sendFramesToEngine` is true,
// the callback would crash.
await tester.pump(const Duration(milliseconds: 1));
await tester.binding.waitUntilFirstFrameRasterized;
expect(find.text('First frame'), findsOne);
}, skip: kIsWeb); // [intended] Web doesn't use LiveTestWidgetsFlutterBinding
}
class DummyWidget extends StatelessWidget {
const DummyWidget({super.key});
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Text('First frame'),
),
);
}
}
| flutter/packages/flutter/test/widgets/binding_live_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/binding_live_test.dart",
"repo_id": "flutter",
"token_count": 896
} | 296 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'clipboard_utils.dart';
import 'editable_text_utils.dart';
void main() {
final MockClipboard mockClipboard = MockClipboard();
TestWidgetsFlutterBinding.ensureInitialized()
.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
setUp(() async {
// Fill the clipboard so that the Paste option is available in the text
// selection menu.
await Clipboard.setData(const ClipboardData(text: 'Clipboard data'));
});
testWidgets('Hides and shows only a single menu', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey();
final GlobalKey key2 = GlobalKey();
late final BuildContext context;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext localContext) {
context = localContext;
return const SizedBox.shrink();
},
),
),
),
);
expect(find.byKey(key1), findsNothing);
expect(find.byKey(key2), findsNothing);
final ContextMenuController controller1 = ContextMenuController();
await tester.pump();
expect(find.byKey(key1), findsNothing);
expect(find.byKey(key2), findsNothing);
controller1.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key1);
},
);
await tester.pump();
expect(find.byKey(key1), findsOneWidget);
expect(find.byKey(key2), findsNothing);
// Showing the same thing again does nothing and is not an error.
controller1.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key1);
},
);
await tester.pump();
expect(tester.takeException(), null);
expect(find.byKey(key1), findsOneWidget);
expect(find.byKey(key2), findsNothing);
// Showing a new menu hides the first.
final ContextMenuController controller2 = ContextMenuController();
controller2.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key2);
},
);
await tester.pump();
expect(find.byKey(key1), findsNothing);
expect(find.byKey(key2), findsOneWidget);
controller2.remove();
await tester.pump();
expect(find.byKey(key1), findsNothing);
expect(find.byKey(key2), findsNothing);
});
testWidgets('A menu can be hidden and then reshown', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey();
late final BuildContext context;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext localContext) {
context = localContext;
return const SizedBox.shrink();
},
),
),
),
);
expect(find.byKey(key1), findsNothing);
final ContextMenuController controller = ContextMenuController();
addTearDown(controller.remove);
// Instantiating the controller does not shown it.
await tester.pump();
expect(find.byKey(key1), findsNothing);
controller.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key1);
},
);
await tester.pump();
expect(find.byKey(key1), findsOneWidget);
controller.remove();
await tester.pump();
expect(find.byKey(key1), findsNothing);
controller.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key1);
},
);
await tester.pump();
expect(find.byKey(key1), findsOneWidget);
});
testWidgets('markNeedsBuild causes the builder to update', (WidgetTester tester) async {
int buildCount = 0;
late final BuildContext context;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext localContext) {
context = localContext;
return const SizedBox.shrink();
},
),
),
),
);
final ContextMenuController controller = ContextMenuController();
controller.show(
context: context,
contextMenuBuilder: (BuildContext context) {
buildCount++;
return const Placeholder();
},
);
expect(buildCount, 0);
await tester.pump();
expect(buildCount, 1);
controller.markNeedsBuild();
expect(buildCount, 1);
await tester.pump();
expect(buildCount, 2);
controller.remove();
});
testWidgets('Calling show when a built-in widget is already showing its context menu hides the built-in menu', (WidgetTester tester) async {
final GlobalKey builtInKey = GlobalKey();
final GlobalKey directKey = GlobalKey();
late final BuildContext context;
final TextEditingController textEditingController = TextEditingController();
addTearDown(textEditingController.dispose);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext localContext) {
context = localContext;
return EditableText(
controller: textEditingController,
backgroundCursorColor: Colors.grey,
focusNode: focusNode,
style: const TextStyle(),
cursorColor: Colors.red,
selectionControls: materialTextSelectionHandleControls,
contextMenuBuilder: (
BuildContext context,
EditableTextState editableTextState,
) {
return Placeholder(key: builtInKey);
},
);
},
),
),
),
);
expect(find.byKey(builtInKey), findsNothing);
expect(find.byKey(directKey), findsNothing);
final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText));
await tester.tapAt(textOffsetToPosition(tester, 0));
await tester.pump();
expect(state.showToolbar(), true);
await tester.pump();
expect(find.byKey(builtInKey), findsOneWidget);
expect(find.byKey(directKey), findsNothing);
final ContextMenuController controller = ContextMenuController();
controller.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: directKey);
},
);
await tester.pump();
expect(find.byKey(builtInKey), findsNothing);
expect(find.byKey(directKey), findsOneWidget);
expect(controller.isShown, isTrue);
// And showing the built-in menu hides the directly shown menu.
expect(state.showToolbar(), isTrue);
await tester.pump();
expect(find.byKey(builtInKey), findsOneWidget);
expect(find.byKey(directKey), findsNothing);
expect(controller.isShown, isFalse);
// Calling remove on the hidden ContextMenuController does not hide the
// built-in menu.
controller.remove();
await tester.pump();
expect(find.byKey(builtInKey), findsOneWidget);
expect(find.byKey(directKey), findsNothing);
expect(controller.isShown, isFalse);
state.hideToolbar();
await tester.pump();
expect(find.byKey(builtInKey), findsNothing);
expect(find.byKey(directKey), findsNothing);
expect(controller.isShown, isFalse);
},
skip: isContextMenuProvidedByPlatform, // [intended] no Flutter-drawn text selection toolbar on web.
);
}
| flutter/packages/flutter/test/widgets/context_menu_controller_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/context_menu_controller_test.dart",
"repo_id": "flutter",
"token_count": 3076
} | 297 |
// Copyright 2014 The Flutter Authors. 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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('DisplayFeatureSubScreen', () {
testWidgets('without Directionality or anchor', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
child: SizedBox.expand(
key: childKey,
),
),
),
);
// With no Directionality or anchorpoint, the widget throws
final String message = tester.takeException().toString();
expect(message, contains('Directionality'));
});
testWidgets('with anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset(600, 300),
child: SizedBox.expand(
key: childKey,
),
),
),
);
// anchorPoint is in the middle of the right screen
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(390.0));
expect(renderBox.size.height, equals(600.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410,0)));
});
testWidgets('with infinity anchorpoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset.infinite,
child: SizedBox.expand(
key: childKey,
),
),
),
);
// anchorPoint is infinite, so the bottom-most & right-most screen is chosen
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(390.0));
expect(renderBox.size.height, equals(600.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410,0)));
});
testWidgets('with horizontal hinge and anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(0, 290, 800, 310),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset(1000, 1000),
child: SizedBox.expand(
key: childKey,
),
),
),
);
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(800.0));
expect(renderBox.size.height, equals(290.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(0,310)));
});
testWidgets('with multiple display features and anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(0, 290, 800, 310),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
const DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset(1000, 1000),
child: SizedBox.expand(
key: childKey,
),
),
),
);
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(390.0));
expect(renderBox.size.height, equals(290.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410,310)));
});
testWidgets('with non-splitting display features and anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
// Top notch
const DisplayFeature(
bounds: Rect.fromLTRB(100, 0, 700, 100),
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
// Bottom notch
const DisplayFeature(
bounds: Rect.fromLTRB(100, 500, 700, 600),
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
const DisplayFeature(
bounds: Rect.fromLTRB(0, 300, 800, 300),
type: DisplayFeatureType.fold,
state: DisplayFeatureState.postureFlat,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const Directionality(
textDirection: TextDirection.ltr,
child: DisplayFeatureSubScreen(
child: SizedBox.expand(
key: childKey,
),
),
),
),
);
// The display features provided are not wide enough to produce sub-screens
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(800.0));
expect(renderBox.size.height, equals(600.0));
expect(renderBox.localToGlobal(Offset.zero), equals(Offset.zero));
});
testWidgets('with size 0 display feature in half-opened posture and anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(0, 300, 800, 300),
type: DisplayFeatureType.fold,
state: DisplayFeatureState.postureHalfOpened,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset(1000, 1000),
child: SizedBox.expand(
key: childKey,
),
),
),
);
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(800.0));
expect(renderBox.size.height, equals(300.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(0,300)));
});
});
}
| flutter/packages/flutter/test/widgets/display_feature_sub_screen_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/display_feature_sub_screen_test.dart",
"repo_id": "flutter",
"token_count": 3792
} | 298 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('FadeTransition', (WidgetTester tester) async {
final DebugPrintCallback oldPrint = debugPrint;
final List<String> log = <String>[];
debugPrint = (String? message, { int? wrapWidth }) {
log.add(message!);
};
debugPrintBuildScope = true;
final AnimationController controller = AnimationController(
vsync: const TestVSync(),
duration: const Duration(seconds: 2),
);
addTearDown(controller.dispose);
await tester.pumpWidget(FadeTransition(
opacity: controller,
child: const Placeholder(),
));
expect(log, hasLength(2));
expect(log.last, 'buildScope finished');
await tester.pump();
expect(log, hasLength(2));
controller.forward();
await tester.pumpAndSettle();
expect(log, hasLength(2));
debugPrint = oldPrint;
debugPrintBuildScope = false;
});
}
| flutter/packages/flutter/test/widgets/fade_transition_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/fade_transition_test.dart",
"repo_id": "flutter",
"token_count": 408
} | 299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.