Auto-format Framework (#160545)

This auto-formats all *.dart files in the repository outside of the
`engine` subdirectory and enforces that these files stay formatted with
a presubmit check.

**Reviewers:** Please carefully review all the commits except for the
one titled "formatted". The "formatted" commit was auto-generated by
running `dev/tools/format.sh -a -f`. The other commits were hand-crafted
to prepare the repo for the formatting change. I recommend reviewing the
commits one-by-one via the "Commits" tab and avoiding Github's "Files
changed" tab as it will likely slow down your browser because of the
size of this PR.

---------

Co-authored-by: Kate Lovett <katelovett@google.com>
Co-authored-by: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com>
This commit is contained in:
Michael Goderbauer
2024-12-19 12:06:21 -08:00
committed by GitHub
parent 8e0993eda8
commit 5491c8c146
4411 changed files with 455108 additions and 415991 deletions

View File

@@ -32,6 +32,7 @@ Future<void> setClipboard(String message) async {
});
completer.complete();
}
if (SchedulerBinding.instance.hasScheduledFrame) {
SchedulerBinding.instance.addPostFrameCallback(completeSetClipboard);
} else {
@@ -44,11 +45,13 @@ Future<AndroidSemanticsNode> getSemantics(Finder finder, WidgetTester tester) as
final int id = tester.getSemantics(finder).id;
final Completer<String> completer = Completer<String>();
Future<void> completeSemantics([Object? _]) async {
final dynamic result = await kSemanticsChannel.invokeMethod<dynamic>('getSemanticsNode', <String, dynamic>{
'id': id,
});
final dynamic result = await kSemanticsChannel.invokeMethod<dynamic>(
'getSemanticsNode',
<String, dynamic>{'id': id},
);
completer.complete(json.encode(result));
}
if (SchedulerBinding.instance.hasScheduledFrame) {
SchedulerBinding.instance.addPostFrameCallback(completeSemantics);
} else {
@@ -94,9 +97,7 @@ Future<void> main() async {
isFocusable: true,
isFocused: false,
isPassword: false,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
// We can't predict the a11y focus when the screen changes.
ignoredActions: ignoredAccessibilityFocusActions,
),
@@ -163,9 +164,7 @@ Future<void> main() async {
isFocusable: true,
isFocused: false,
isPassword: true,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
// We can't predict the a11y focus when the screen changes.
ignoredActions: ignoredAccessibilityFocusActions,
),
@@ -229,7 +228,9 @@ Future<void> main() async {
testWidgets('Checkbox has correct Android semantics', (WidgetTester tester) async {
final Finder checkbox = find.byKey(const ValueKey<String>(checkboxKeyValue));
final Finder disabledCheckbox = find.byKey(const ValueKey<String>(disabledCheckboxKeyValue));
final Finder disabledCheckbox = find.byKey(
const ValueKey<String>(disabledCheckboxKeyValue),
);
await prepareSelectionControls(tester);
expect(
@@ -241,9 +242,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
@@ -259,9 +258,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
expect(
@@ -289,9 +286,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
@@ -307,9 +302,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
}, timeout: Timeout.none);
@@ -327,9 +320,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
@@ -345,9 +336,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
}, timeout: Timeout.none);
@@ -367,9 +356,7 @@ Future<void> main() async {
isFocusable: true,
contentDescription: switchLabel,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
}, timeout: Timeout.none);
@@ -396,9 +383,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
@@ -416,9 +401,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
reason: "Popup $item doesn't have the right semantics",
);
@@ -441,9 +424,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
reason: "Popup $item doesn't have the right semantics the second time",
);
@@ -466,9 +447,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
@@ -494,9 +473,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
reason: "Dropdown $item doesn't have the right semantics",
);
@@ -532,9 +509,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
reason: "Dropdown $item doesn't have the right semantics the second time.",
);
@@ -562,9 +537,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
);
@@ -581,9 +554,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
reason: "Alert OK button doesn't have the right semantics",
);
@@ -621,9 +592,7 @@ Future<void> main() async {
isEnabled: true,
isFocusable: true,
ignoredActions: ignoredAccessibilityFocusActions,
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.click,
],
actions: <AndroidSemanticsAction>[AndroidSemanticsAction.click],
),
reason: "Alert OK button doesn't have the right semantics",
);
@@ -657,7 +626,9 @@ Future<void> main() async {
await tester.pumpAndSettle();
}
testWidgets('AppBar title has correct Android heading semantics', (WidgetTester tester) async {
testWidgets('AppBar title has correct Android heading semantics', (
WidgetTester tester,
) async {
await prepareHeading(tester);
expect(
await getSemantics(find.byKey(const ValueKey<String>(appBarTitleKeyValue)), tester),

View File

@@ -14,9 +14,9 @@ void main() {
}
Map<String, WidgetBuilder> routes = <String, WidgetBuilder>{
selectionControlsRoute : (BuildContext context) => const SelectionControlsPage(),
popupControlsRoute : (BuildContext context) => const PopupControlsPage(),
textFieldRoute : (BuildContext context) => const TextFieldPage(),
selectionControlsRoute: (BuildContext context) => const SelectionControlsPage(),
popupControlsRoute: (BuildContext context) => const PopupControlsPage(),
textFieldRoute: (BuildContext context) => const TextFieldPage(),
headingsRoute: (BuildContext context) => const HeadingsPage(),
};
@@ -31,17 +31,18 @@ class TestApp extends StatelessWidget {
builder: (BuildContext context) {
return Scaffold(
body: ListView(
children: routes.keys.map<Widget>((String value) {
return MaterialButton(
child: Text(value),
onPressed: () {
Navigator.of(context).pushNamed(value);
},
);
}).toList(),
children:
routes.keys.map<Widget>((String value) {
return MaterialButton(
child: Text(value),
onPressed: () {
Navigator.of(context).pushNamed(value);
},
);
}).toList(),
),
);
}
},
),
);
}

View File

@@ -156,8 +156,7 @@ class AndroidSemanticsNode {
}
return <AndroidSemanticsAction>[
for (final int id in actions)
if (AndroidSemanticsAction.deserialize(id) case final AndroidSemanticsAction action)
action,
if (AndroidSemanticsAction.deserialize(id) case final AndroidSemanticsAction action) action,
];
}
@@ -167,7 +166,6 @@ class AndroidSemanticsNode {
}
}
/// A Dart VM implementation of a rectangle.
///
/// Created to mirror the implementation of [ui.Rect].
@@ -198,11 +196,11 @@ class Rect {
if (other.runtimeType != runtimeType) {
return false;
}
return other is Rect
&& other.top == top
&& other.left == left
&& other.right == right
&& other.bottom == bottom;
return other is Rect &&
other.top == top &&
other.left == left &&
other.right == right &&
other.bottom == bottom;
}
@override
@@ -231,9 +229,7 @@ class Size {
if (other.runtimeType != runtimeType) {
return false;
}
return other is Size
&& other.width == width
&& other.height == height;
return other is Size && other.width == width && other.height == height;
}
@override

View File

@@ -29,7 +29,6 @@ class AndroidClassName {
/// Action constants which correspond to `AccessibilityAction` in Android.
enum AndroidSemanticsAction {
/// Matches `AccessibilityAction.ACTION_FOCUS`.
focus(_kFocusIndex),

View File

@@ -77,7 +77,10 @@ class _AndroidSemanticsMatcher extends Matcher {
this.isHeading,
this.isPassword,
this.isLongClickable,
}) : assert(ignoredActions == null || actions != null, 'actions must not be null if ignoredActions is not null'),
}) : assert(
ignoredActions == null || actions != null,
'actions must not be null if ignoredActions is not null',
),
assert(ignoredActions == null || !actions!.any(ignoredActions.contains));
final String? text;
@@ -105,7 +108,7 @@ class _AndroidSemanticsMatcher extends Matcher {
description.add(' with text: $text');
}
if (contentDescription != null) {
description.add( 'with contentDescription $contentDescription');
description.add('with contentDescription $contentDescription');
}
if (className != null) {
description.add(' with className: $className');
@@ -178,14 +181,25 @@ class _AndroidSemanticsMatcher extends Matcher {
itemActions.removeWhere(ignoredActions!.contains);
}
if (!unorderedEquals(actions!).matches(itemActions, matchState)) {
final List<String> actionsString = actions!.map<String>((AndroidSemanticsAction action) => action.toString()).toList()..sort();
final List<String> itemActionsString = itemActions.map<String>((AndroidSemanticsAction action) => action.toString()).toList()..sort();
final Set<String> unexpectedInString = itemActionsString.toSet().difference(actionsString.toSet());
final Set<String> missingInString = actionsString.toSet().difference(itemActionsString.toSet());
final List<String> actionsString =
actions!.map<String>((AndroidSemanticsAction action) => action.toString()).toList()
..sort();
final List<String> itemActionsString =
itemActions.map<String>((AndroidSemanticsAction action) => action.toString()).toList()
..sort();
final Set<String> unexpectedInString = itemActionsString.toSet().difference(
actionsString.toSet(),
);
final Set<String> missingInString = actionsString.toSet().difference(
itemActionsString.toSet(),
);
if (missingInString.isEmpty && unexpectedInString.isEmpty) {
return true;
}
return _failWithMessage('Expected actions: $actionsString\nActual actions: $itemActionsString\nUnexpected: $unexpectedInString\nMissing: $missingInString', matchState);
return _failWithMessage(
'Expected actions: $actionsString\nActual actions: $itemActionsString\nUnexpected: $unexpectedInString\nMissing: $missingInString',
matchState,
);
}
}
if (isChecked != null && isChecked != item.isChecked) {
@@ -220,10 +234,16 @@ class _AndroidSemanticsMatcher extends Matcher {
}
@override
Description describeMismatch(dynamic item, Description mismatchDescription,
Map<dynamic, dynamic> matchState, bool verbose) {
Description describeMismatch(
dynamic item,
Description mismatchDescription,
Map<dynamic, dynamic> matchState,
bool verbose,
) {
final String? failure = matchState['failure'] as String?;
return mismatchDescription.add(failure ?? 'hasAndroidSemantics matcher does not complete successfully');
return mismatchDescription.add(
failure ?? 'hasAndroidSemantics matcher does not complete successfully',
);
}
bool _failWithMessage(String value, Map<dynamic, dynamic> matchState) {

View File

@@ -57,47 +57,39 @@ class _SelectionControlsPageState extends State<SelectionControlsPage> {
return Scaffold(
appBar: AppBar(leading: const BackButton(key: ValueKey<String>('back'))),
body: Material(
child: Column(children: <Widget>[
Row(
children: <Widget>[
Checkbox(
key: checkbox1Key,
value: _isChecked,
onChanged: _updateCheckbox,
),
const Checkbox(
key: checkbox2Key,
value: false,
onChanged: null,
),
],
),
const Spacer(),
Row(children: <Widget>[
Radio<int>(key: radio1Key, value: 0, groupValue: _radio, onChanged: _updateRadio),
Radio<int>(key: radio2Key, value: 1, groupValue: _radio, onChanged: _updateRadio),
Radio<int>(key: radio3Key, value: 2, groupValue: _radio, onChanged: _updateRadio),
]),
const Spacer(),
Switch(
key: switchKey,
value: _isOn,
onChanged: _updateSwitch,
),
const Spacer(),
MergeSemantics(
child: Row(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
const Text(switchLabel),
Switch(
key: labeledSwitchKey,
value: _isLabeledOn,
onChanged: _updateLabeledSwitch,
),
Checkbox(key: checkbox1Key, value: _isChecked, onChanged: _updateCheckbox),
const Checkbox(key: checkbox2Key, value: false, onChanged: null),
],
),
),
]),
const Spacer(),
Row(
children: <Widget>[
Radio<int>(key: radio1Key, value: 0, groupValue: _radio, onChanged: _updateRadio),
Radio<int>(key: radio2Key, value: 1, groupValue: _radio, onChanged: _updateRadio),
Radio<int>(key: radio3Key, value: 2, groupValue: _radio, onChanged: _updateRadio),
],
),
const Spacer(),
Switch(key: switchKey, value: _isOn, onChanged: _updateSwitch),
const Spacer(),
MergeSemantics(
child: Row(
children: <Widget>[
const Text(switchLabel),
Switch(
key: labeledSwitchKey,
value: _isLabeledOn,
onChanged: _updateLabeledSwitch,
),
],
),
),
],
),
),
);
}

View File

@@ -21,9 +21,7 @@ class HeadingsPage extends StatelessWidget {
leading: const BackButton(key: ValueKey<String>('back')),
title: const Text('Heading', key: _appBarTitleKey),
),
body: const Center(
child: Text('Body text', key: _bodyTextKey),
),
body: const Center(child: Text('Body text', key: _bodyTextKey)),
);
}
}

View File

@@ -53,13 +53,14 @@ class _PopupControlsPageState extends State<PopupControlsPage> {
DropdownButton<String>(
key: const ValueKey<String>(dropdownButtonKeyValue),
value: dropdownValue,
items: popupItems.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>('$dropdownKeyValue.$item'),
value: item,
child: Text(item),
);
}).toList(),
items:
popupItems.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>('$dropdownKeyValue.$item'),
value: item,
child: Text(item),
);
}).toList(),
onChanged: (String? value) {
setState(() {
dropdownValue = value!;
@@ -76,12 +77,21 @@ class _PopupControlsPageState extends State<PopupControlsPage> {
builder: (BuildContext context) {
return AlertDialog(
key: const ValueKey<String>(alertKeyValue),
title: const Text('Title text', key: ValueKey<String>('$alertKeyValue.Title')),
title: const Text(
'Title text',
key: ValueKey<String>('$alertKeyValue.Title'),
),
content: const SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('Body text line 1.', key: ValueKey<String>('$alertKeyValue.Body1')),
Text('Body text line 2.', key: ValueKey<String>('$alertKeyValue.Body2')),
Text(
'Body text line 1.',
key: ValueKey<String>('$alertKeyValue.Body1'),
),
Text(
'Body text line 2.',
key: ValueKey<String>('$alertKeyValue.Body2'),
),
],
),
),

View File

@@ -28,19 +28,18 @@ class _TextFieldPageState extends State<TextFieldPage> {
return Scaffold(
appBar: AppBar(leading: BackButton(key: backButtonKey)),
body: Material(
child: Column(children: <Widget>[
TextField(
key: normalTextFieldKey,
controller: _normalController,
),
const Spacer(),
TextField(
key: passwordTextFieldKey,
controller: _passwordController,
obscureText: true,
),
],
child: Column(
children: <Widget>[
TextField(key: normalTextFieldKey, controller: _normalController),
const Spacer(),
TextField(
key: passwordTextFieldKey,
controller: _passwordController,
obscureText: true,
),
],
),
),
));
);
}
}

View File

@@ -71,26 +71,29 @@ void main() {
test('matches all android semantics properties', () {
final AndroidSemanticsNode node = AndroidSemanticsNode.deserialize(source);
expect(node, hasAndroidSemantics(
isChecked: false,
isCheckable: false,
isEditable: false,
isFocusable: false,
isFocused: false,
isPassword: false,
isLongClickable: false,
text: 'hello',
contentDescription: 'other hello',
className: 'android.view.View',
id: 23,
rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.focus,
AndroidSemanticsAction.clearFocus,
AndroidSemanticsAction.select,
],
size: const Size(10.0, 10.0),
));
expect(
node,
hasAndroidSemantics(
isChecked: false,
isCheckable: false,
isEditable: false,
isFocusable: false,
isFocused: false,
isPassword: false,
isLongClickable: false,
text: 'hello',
contentDescription: 'other hello',
className: 'android.view.View',
id: 23,
rect: const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0),
actions: <AndroidSemanticsAction>[
AndroidSemanticsAction.focus,
AndroidSemanticsAction.clearFocus,
AndroidSemanticsAction.select,
],
size: const Size(10.0, 10.0),
),
);
});
});
}

View File

@@ -7,7 +7,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_driver/driver_extension.dart';
class FutureDataHandler {
final Completer<DataHandler> handlerCompleter = Completer<DataHandler>();
@@ -16,30 +15,31 @@ class FutureDataHandler {
return handler(message);
}
}
FutureDataHandler driverDataHandler = FutureDataHandler();
MethodChannel channel = const MethodChannel('verified_input_test');
Future<dynamic> onMethodChannelCall(MethodCall call) {
switch (call.method) {
// Android side is notifying us of the result of verifying the input
// event.
case 'notify_verified_input':
final bool result = call.arguments as bool;
// FlutterDriver handler, note that this captures the notification
// value delivered via the method channel.
Future<String> handler(String? message) async {
switch (message) {
case 'input_was_verified':
return '$result';
}
return 'unknown message: "$message"';
switch (call.method) {
// Android side is notifying us of the result of verifying the input
// event.
case 'notify_verified_input':
final bool result = call.arguments as bool;
// FlutterDriver handler, note that this captures the notification
// value delivered via the method channel.
Future<String> handler(String? message) async {
switch (message) {
case 'input_was_verified':
return '$result';
}
// Install the handler now.
driverDataHandler.handlerCompleter.complete(handler);
}
return Future<dynamic>.value();
return 'unknown message: "$message"';
}
// Install the handler now.
driverDataHandler.handlerCompleter.complete(handler);
}
return Future<dynamic>.value();
}
void main() {
enableFlutterDriverExtension(handler: driverDataHandler.handleMessage);
@@ -57,12 +57,10 @@ class _Home extends StatelessWidget {
backgroundColor: Colors.black45,
),
body: Container(
padding: const EdgeInsets.all(30.0),
color: Colors.black26,
child: const AndroidView(
key: Key('PlatformView'),
viewType: 'verified-input-view',
)
));
padding: const EdgeInsets.all(30.0),
color: Colors.black26,
child: const AndroidView(key: Key('PlatformView'), viewType: 'verified-input-view'),
),
);
}
}

View File

@@ -7,7 +7,6 @@ import 'dart:io';
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
Future<void> main() async {
late FlutterDriver driver;
@@ -35,8 +34,13 @@ Future<void> main() async {
inputEventWasVerified.whenComplete(() => stop = true);
while (!stop) {
// We must use the Android input tool to get verified input events.
final ProcessResult result =
await Process.run('adb', <String>['shell', 'input', 'tap', '${offset.dx}', '${offset.dy}']);
final ProcessResult result = await Process.run('adb', <String>[
'shell',
'input',
'tap',
'${offset.dx}',
'${offset.dy}',
]);
expect(result.exitCode, equals(0));
}
// Input

View File

@@ -26,7 +26,7 @@ class Home extends StatelessWidget {
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: _allPages.map((PageWidget p) => _buildPageListTile(context, p)).toList(),
children: _allPages.map((PageWidget p) => _buildPageListTile(context, p)).toList(),
),
);
}
@@ -35,14 +35,13 @@ class Home extends StatelessWidget {
return ListTile(
title: Text(page.title),
key: page.tileKey,
onTap: () { _pushPage(context, page); },
onTap: () {
_pushPage(context, page);
},
);
}
void _pushPage(BuildContext context, PageWidget page) {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (_) => Scaffold(
body: page,
)));
Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => Scaffold(body: page)));
}
}

View File

@@ -15,20 +15,22 @@ const List<int> kPointerActions = <int>[
const double kDoubleErrorMargin = 1e-4;
String diffMotionEvents(
Map<String, dynamic> originalEvent,
Map<String, dynamic> synthesizedEvent,
) {
String diffMotionEvents(Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) {
final StringBuffer diff = StringBuffer();
diffMaps(originalEvent, synthesizedEvent, diff, excludeKeys: const <String>[
'pointerProperties', // Compared separately.
'pointerCoords', // Compared separately.
'source', // Unused by Flutter.
'deviceId', // Android documentation says that's an arbitrary number that shouldn't be depended on.
'action', // Compared separately.
'motionEventId', // TODO(kaushikiska): add support for motion event diffing, https://github.com/flutter/flutter/issues/61022.
]);
diffMaps(
originalEvent,
synthesizedEvent,
diff,
excludeKeys: const <String>[
'pointerProperties', // Compared separately.
'pointerCoords', // Compared separately.
'source', // Unused by Flutter.
'deviceId', // Android documentation says that's an arbitrary number that shouldn't be depended on.
'action', // Compared separately.
'motionEventId', // TODO(kaushikiska): add support for motion event diffing, https://github.com/flutter/flutter/issues/61022.
],
);
diffActions(diff, originalEvent, synthesizedEvent);
diffPointerProperties(diff, originalEvent, synthesizedEvent);
@@ -37,19 +39,24 @@ String diffMotionEvents(
return diff.toString();
}
void diffActions(StringBuffer diffBuffer, Map<String, dynamic> originalEvent,
Map<String, dynamic> synthesizedEvent) {
final int synthesizedActionMasked =
getActionMasked(synthesizedEvent['action'] as int);
void diffActions(
StringBuffer diffBuffer,
Map<String, dynamic> originalEvent,
Map<String, dynamic> synthesizedEvent,
) {
final int synthesizedActionMasked = getActionMasked(synthesizedEvent['action'] as int);
final int originalActionMasked = getActionMasked(originalEvent['action'] as int);
final String synthesizedActionName =
getActionName(synthesizedActionMasked, synthesizedEvent['action'] as int);
final String originalActionName =
getActionName(originalActionMasked, originalEvent['action'] as int);
final String synthesizedActionName = getActionName(
synthesizedActionMasked,
synthesizedEvent['action'] as int,
);
final String originalActionName = getActionName(
originalActionMasked,
originalEvent['action'] as int,
);
if (synthesizedActionMasked != originalActionMasked) {
diffBuffer.write(
'action (expected: $originalActionName actual: $synthesizedActionName) ');
diffBuffer.write('action (expected: $originalActionName actual: $synthesizedActionName) ');
}
if (kPointerActions.contains(originalActionMasked) &&
@@ -58,13 +65,17 @@ void diffActions(StringBuffer diffBuffer, Map<String, dynamic> originalEvent,
final int synthesizedPointer = getPointerIdx(synthesizedEvent['action'] as int);
if (originalPointer != synthesizedPointer) {
diffBuffer.write(
'pointerIdx (expected: $originalPointer actual: $synthesizedPointer action: $originalActionName ');
'pointerIdx (expected: $originalPointer actual: $synthesizedPointer action: $originalActionName ',
);
}
}
}
void diffPointerProperties(StringBuffer diffBuffer,
Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) {
void diffPointerProperties(
StringBuffer diffBuffer,
Map<String, dynamic> originalEvent,
Map<String, dynamic> synthesizedEvent,
) {
final List<Map<dynamic, dynamic>> expectedList =
(originalEvent['pointerProperties'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
final List<Map<dynamic, dynamic>> actualList =
@@ -72,21 +83,23 @@ void diffPointerProperties(StringBuffer diffBuffer,
if (expectedList.length != actualList.length) {
diffBuffer.write(
'pointerProperties (actual length: ${actualList.length}, expected length: ${expectedList.length} ');
'pointerProperties (actual length: ${actualList.length}, expected length: ${expectedList.length} ',
);
return;
}
for (int i = 0; i < expectedList.length; i++) {
final Map<String, dynamic> expected =
expectedList[i].cast<String, dynamic>();
final Map<String, dynamic> expected = expectedList[i].cast<String, dynamic>();
final Map<String, dynamic> actual = actualList[i].cast<String, dynamic>();
diffMaps(expected, actual, diffBuffer,
messagePrefix: '[pointerProperty $i] ');
diffMaps(expected, actual, diffBuffer, messagePrefix: '[pointerProperty $i] ');
}
}
void diffPointerCoordsList(StringBuffer diffBuffer,
Map<String, dynamic> originalEvent, Map<String, dynamic> synthesizedEvent) {
void diffPointerCoordsList(
StringBuffer diffBuffer,
Map<String, dynamic> originalEvent,
Map<String, dynamic> synthesizedEvent,
) {
final List<Map<dynamic, dynamic>> expectedList =
(originalEvent['pointerCoords'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
final List<Map<dynamic, dynamic>> actualList =
@@ -94,20 +107,24 @@ void diffPointerCoordsList(StringBuffer diffBuffer,
if (expectedList.length != actualList.length) {
diffBuffer.write(
'pointerCoords (actual length: ${actualList.length}, expected length: ${expectedList.length} ');
'pointerCoords (actual length: ${actualList.length}, expected length: ${expectedList.length} ',
);
return;
}
for (int i = 0; i < expectedList.length; i++) {
final Map<String, dynamic> expected =
expectedList[i].cast<String, dynamic>();
final Map<String, dynamic> expected = expectedList[i].cast<String, dynamic>();
final Map<String, dynamic> actual = actualList[i].cast<String, dynamic>();
diffPointerCoords(expected, actual, i, diffBuffer);
}
}
void diffPointerCoords(Map<String, dynamic> expected,
Map<String, dynamic> actual, int pointerIdx, StringBuffer diffBuffer) {
void diffPointerCoords(
Map<String, dynamic> expected,
Map<String, dynamic> actual,
int pointerIdx,
StringBuffer diffBuffer,
) {
diffMaps(expected, actual, diffBuffer, messagePrefix: '[pointerCoord $pointerIdx] ');
}
@@ -120,8 +137,7 @@ void diffMaps(
}) {
const IterableEquality<String> eq = IterableEquality<String>();
if (!eq.equals(expected.keys, actual.keys)) {
diffBuffer.write(
'${messagePrefix}keys (expected: ${expected.keys} actual: ${actual.keys} ');
diffBuffer.write('${messagePrefix}keys (expected: ${expected.keys} actual: ${actual.keys} ');
return;
}
for (final String key in expected.keys) {
@@ -133,8 +149,7 @@ void diffMaps(
}
if (expected[key] != actual[key]) {
diffBuffer.write(
'$messagePrefix$key (expected: ${expected[key]} actual: ${actual[key]}) ');
diffBuffer.write('$messagePrefix$key (expected: ${expected[key]} actual: ${actual[key]}) ');
}
}
}

View File

@@ -19,7 +19,7 @@ const String kEventsFileName = 'touchEvents';
class MotionEventsPage extends PageWidget {
const MotionEventsPage({Key? key})
: super('Motion Event Tests', const ValueKey<String>('MotionEventsListTile'), key: key);
: super('Motion Event Tests', const ValueKey<String>('MotionEventsListTile'), key: key);
@override
Widget build(BuildContext context) {
@@ -68,15 +68,13 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
SizedBox(
height: 300.0,
child: AndroidView(
key: const ValueKey<String>('PlatformView'),
viewType: 'simple_view',
onPlatformViewCreated: onPlatformViewCreated),
key: const ValueKey<String>('PlatformView'),
viewType: 'simple_view',
onPlatformViewCreated: onPlatformViewCreated,
),
),
Expanded(
child: ListView.builder(
itemBuilder: buildEventTile,
itemCount: flutterViewEvents.length,
),
child: ListView.builder(itemBuilder: buildEventTile, itemCount: flutterViewEvents.length),
),
Row(
children: <Widget>[
@@ -102,8 +100,7 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
child: const Text('SAVE'),
onPressed: () {
const StandardMessageCodec codec = StandardMessageCodec();
saveRecordedEvents(
codec.encodeMessage(flutterViewEvents)!, context);
saveRecordedEvents(codec.encodeMessage(flutterViewEvents)!, context);
},
),
),
@@ -111,14 +108,18 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
child: ElevatedButton(
key: const ValueKey<String>('play'),
child: const Text('PLAY FILE'),
onPressed: () { playEventsFile(); },
onPressed: () {
playEventsFile();
},
),
),
Expanded(
child: ElevatedButton(
key: const ValueKey<String>('back'),
child: const Text('BACK'),
onPressed: () { Navigator.pop(context); },
onPressed: () {
Navigator.pop(context);
},
),
),
],
@@ -130,12 +131,15 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
Future<String> playEventsFile() async {
const StandardMessageCodec codec = StandardMessageCodec();
try {
final ByteData data = await rootBundle.load('packages/assets_for_android_views/assets/touchEvents');
final ByteData data = await rootBundle.load(
'packages/assets_for_android_views/assets/touchEvents',
);
final List<dynamic> unTypedRecordedEvents = codec.decodeMessage(data) as List<dynamic>;
final List<Map<String, dynamic>> recordedEvents = unTypedRecordedEvents
.cast<Map<dynamic, dynamic>>()
.map<Map<String, dynamic>>((Map<dynamic, dynamic> e) =>e.cast<String, dynamic>())
.toList();
final List<Map<String, dynamic>> recordedEvents =
unTypedRecordedEvents
.cast<Map<dynamic, dynamic>>()
.map<Map<String, dynamic>>((Map<dynamic, dynamic> e) => e.cast<String, dynamic>())
.toList();
await channel.invokeMethod<void>('pipeFlutterViewEvents');
await viewChannel?.invokeMethod<void>('pipeTouchEvents');
print('replaying ${recordedEvents.length} motion events');
@@ -198,10 +202,9 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
}
void showMessage(BuildContext context, String message) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(message),
duration: const Duration(seconds: 3),
));
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(message), duration: const Duration(seconds: 3)));
}
void onPlatformViewCreated(int id) {
@@ -255,11 +258,9 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
Widget buildEventTile(BuildContext context, int index) {
if (embeddedViewEvents.length > index) {
return TouchEventDiff(
flutterViewEvents[index], embeddedViewEvents[index]);
return TouchEventDiff(flutterViewEvents[index], embeddedViewEvents[index]);
}
return Text(
'Unmatched event, action: ${flutterViewEvents[index]['action']}');
return Text('Unmatched event, action: ${flutterViewEvents[index]['action']}');
}
}
@@ -271,7 +272,6 @@ class TouchEventDiff extends StatelessWidget {
@override
Widget build(BuildContext context) {
Color color;
final String diff = diffMotionEvents(originalEvent, synthesizedEvent);
String msg;
@@ -291,11 +291,7 @@ class TouchEventDiff extends StatelessWidget {
print('\nactual:');
prettyPrintEvent(synthesizedEvent);
},
child: Container(
color: color,
margin: const EdgeInsets.only(bottom: 2.0),
child: Text(msg),
),
child: Container(color: color, margin: const EdgeInsets.only(bottom: 2.0), child: Text(msg)),
);
}
@@ -307,12 +303,15 @@ class TouchEventDiff extends StatelessWidget {
buffer.write('$actionName ');
if (maskedAction == 5 || maskedAction == 6) {
buffer.write('pointer: ${getPointerIdx(action)} ');
buffer.write('pointer: ${getPointerIdx(action)} ');
}
final List<Map<dynamic, dynamic>> coords = (event['pointerCoords'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
final List<Map<dynamic, dynamic>> coords =
(event['pointerCoords'] as List<dynamic>).cast<Map<dynamic, dynamic>>();
for (int i = 0; i < coords.length; i++) {
buffer.write('p$i x: ${coords[i]['x']} y: ${coords[i]['y']}, pressure: ${coords[i]['pressure']} ');
buffer.write(
'p$i x: ${coords[i]['x']} y: ${coords[i]['y']}, pressure: ${coords[i]['pressure']} ',
);
}
print(buffer);
}

View File

@@ -11,7 +11,11 @@ import 'page.dart';
class WindowManagerIntegrationsPage extends PageWidget {
const WindowManagerIntegrationsPage({Key? key})
: super('Window Manager Integrations Tests', const ValueKey<String>('WmIntegrationsListTile'), key: key);
: super(
'Window Manager Integrations Tests',
const ValueKey<String>('WmIntegrationsListTile'),
key: key,
);
@override
Widget build(BuildContext context) => const WindowManagerBody();
@@ -24,14 +28,9 @@ class WindowManagerBody extends StatefulWidget {
State<WindowManagerBody> createState() => WindowManagerBodyState();
}
enum _LastTestStatus {
pending,
success,
error
}
enum _LastTestStatus { pending, success, error }
class WindowManagerBodyState extends State<WindowManagerBody> {
MethodChannel? viewChannel;
_LastTestStatus _lastTestStatus = _LastTestStatus.pending;
String? lastError;
@@ -41,9 +40,7 @@ class WindowManagerBodyState extends State<WindowManagerBody> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Window Manager Integrations'),
),
appBar: AppBar(title: const Text('Window Manager Integrations')),
body: Column(
children: <Widget>[
SizedBox(
@@ -54,7 +51,7 @@ class WindowManagerBodyState extends State<WindowManagerBody> {
),
),
if (_lastTestStatus != _LastTestStatus.pending) _statusWidget(),
if (viewChannel != null) ... <Widget>[
if (viewChannel != null) ...<Widget>[
ElevatedButton(
key: const ValueKey<String>('ShowAlertDialog'),
onPressed: onShowAlertDialogPressed,
@@ -74,8 +71,8 @@ class WindowManagerBodyState extends State<WindowManagerBody> {
),
if (windowClickCount > 0)
Text(
'Click count: $windowClickCount',
key: const ValueKey<String>('WindowClickCount'),
'Click count: $windowClickCount',
key: const ValueKey<String>('WindowClickCount'),
),
],
),
@@ -93,9 +90,7 @@ class WindowManagerBodyState extends State<WindowManagerBody> {
child: Text(
message!,
key: const ValueKey<String>('Status'),
style: TextStyle(
color: _lastTestStatus == _LastTestStatus.error ? Colors.yellow : null,
),
style: TextStyle(color: _lastTestStatus == _LastTestStatus.error ? Colors.yellow : null),
),
);
}
@@ -152,5 +147,4 @@ class WindowManagerBodyState extends State<WindowManagerBody> {
viewChannel = MethodChannel('simple_view/$id');
});
}
}

View File

@@ -19,8 +19,7 @@ Future<void> main() async {
// Each test below must return back to the home page after finishing.
test('MotionEvent recomposition', () async {
final SerializableFinder motionEventsListTile =
find.byValueKey('MotionEventsListTile');
final SerializableFinder motionEventsListTile = find.byValueKey('MotionEventsListTile');
await driver?.tap(motionEventsListTile);
await driver?.runUnsynchronized(() async {
driver?.waitFor(find.byValueKey('PlatformView'));
@@ -31,11 +30,9 @@ Future<void> main() async {
await driver?.tap(backButton);
}, timeout: Timeout.none);
group('WindowManager', ()
{
group('WindowManager', () {
setUpAll(() async {
final SerializableFinder wmListTile =
find.byValueKey('WmIntegrationsListTile');
final SerializableFinder wmListTile = find.byValueKey('WmIntegrationsListTile');
await driver?.tap(wmListTile);
});
@@ -45,24 +42,28 @@ Future<void> main() async {
});
test('AlertDialog from platform view context', () async {
final SerializableFinder showAlertDialog = find.byValueKey(
'ShowAlertDialog');
final SerializableFinder showAlertDialog = find.byValueKey('ShowAlertDialog');
await driver?.waitFor(showAlertDialog);
await driver?.tap(showAlertDialog);
final String status = (await driver?.getText(find.byValueKey('Status')))!;
expect(status, 'Success');
}, timeout: Timeout.none);
test('Child windows can handle touches', () async {
final SerializableFinder addWindow = find.byValueKey('AddWindow');
await driver?.waitFor(addWindow);
await driver?.tap(addWindow);
final SerializableFinder tapWindow = find.byValueKey('TapWindow');
await driver?.tap(tapWindow);
final String windowClickCount = (await driver?.getText(
find.byValueKey('WindowClickCount'),
))!;
expect(windowClickCount, 'Click count: 1');
}, timeout: Timeout.none, skip: true); // TODO(garyq): Skipped, see https://github.com/flutter/flutter/issues/88479
test(
'Child windows can handle touches',
() async {
final SerializableFinder addWindow = find.byValueKey('AddWindow');
await driver?.waitFor(addWindow);
await driver?.tap(addWindow);
final SerializableFinder tapWindow = find.byValueKey('TapWindow');
await driver?.tap(tapWindow);
final String windowClickCount =
(await driver?.getText(find.byValueKey('WindowClickCount')))!;
expect(windowClickCount, 'Click count: 1');
},
timeout: Timeout.none,
// TODO(garyq): Skipped, see https://github.com/flutter/flutter/issues/88479
skip: true,
);
});
}

View File

@@ -44,17 +44,8 @@ class _TestAppState extends State<TestApp> {
<String, dynamic>{'key': 42},
],
};
static final Uint8List someUint8s = Uint8List.fromList(<int>[
0xBA,
0x5E,
0xBA,
0x11,
]);
static final Int32List someInt32s = Int32List.fromList(<int>[
-0x7fffffff - 1,
0,
0x7fffffff,
]);
static final Uint8List someUint8s = Uint8List.fromList(<int>[0xBA, 0x5E, 0xBA, 0x11]);
static final Int32List someInt32s = Int32List.fromList(<int>[-0x7fffffff - 1, 0, 0x7fffffff]);
static final Int64List someInt64s = Int64List.fromList(<int>[
-0x7fffffffffffffff - 1,
0,
@@ -71,8 +62,7 @@ class _TestAppState extends State<TestApp> {
double.maxFinite,
double.infinity,
]);
static final Float64List someFloat64s =
Float64List.fromList(<double>[
static final Float64List someFloat64s = Float64List.fromList(<double>[
double.nan,
double.negativeInfinity,
-double.maxFinite,
@@ -187,10 +177,7 @@ class _TestAppState extends State<TestApp> {
});
}
Widget _buildTestResultWidget(
BuildContext context,
AsyncSnapshot<TestStepResult> snapshot,
) {
Widget _buildTestResultWidget(BuildContext context, AsyncSnapshot<TestStepResult> snapshot) {
return TestStepResult.fromSnapshot(snapshot).asWidget(context);
}
@@ -199,15 +186,10 @@ class _TestAppState extends State<TestApp> {
return MaterialApp(
title: 'Channels Test',
home: Scaffold(
appBar: AppBar(
title: const Text('Channels Test'),
),
appBar: AppBar(title: const Text('Channels Test')),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: FutureBuilder<TestStepResult>(
future: _result,
builder: _buildTestResultWidget,
),
child: FutureBuilder<TestStepResult>(future: _result, builder: _buildTestResultWidget),
),
floatingActionButton: FloatingActionButton(
key: const ValueKey<String>('step'),

View File

@@ -41,13 +41,11 @@ class ExtendedStandardMessageCodec extends StandardMessageCodec {
}
Future<TestStepResult> basicBinaryHandshake(ByteData? message) async {
const BasicMessageChannel<ByteData?> channel =
BasicMessageChannel<ByteData?>(
const BasicMessageChannel<ByteData?> channel = BasicMessageChannel<ByteData?>(
'binary-msg',
BinaryCodec(),
);
return _basicMessageHandshake<ByteData?>(
'Binary >${toString(message)}<', channel, message);
return _basicMessageHandshake<ByteData?>('Binary >${toString(message)}<', channel, message);
}
Future<TestStepResult> basicStringHandshake(String? message) async {
@@ -59,8 +57,7 @@ Future<TestStepResult> basicStringHandshake(String? message) async {
}
Future<TestStepResult> basicJsonHandshake(dynamic message) async {
const BasicMessageChannel<dynamic> channel =
BasicMessageChannel<dynamic>(
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'json-msg',
JSONMessageCodec(),
);
@@ -68,37 +65,31 @@ Future<TestStepResult> basicJsonHandshake(dynamic message) async {
}
Future<TestStepResult> basicStandardHandshake(dynamic message) async {
const BasicMessageChannel<dynamic> channel =
BasicMessageChannel<dynamic>(
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'std-msg',
ExtendedStandardMessageCodec(),
);
return _basicMessageHandshake<dynamic>(
'Standard >${toString(message)}<', channel, message);
return _basicMessageHandshake<dynamic>('Standard >${toString(message)}<', channel, message);
}
Future<void> _basicBackgroundStandardEchoMain(List<Object> args) async {
final SendPort sendPort = args[2] as SendPort;
final Object message = args[1];
final String name = 'Background Echo >${toString(message)}<';
const String description =
'Uses a platform channel from a background isolate.';
const String description = 'Uses a platform channel from a background isolate.';
try {
BackgroundIsolateBinaryMessenger.ensureInitialized(
args[0] as RootIsolateToken);
BackgroundIsolateBinaryMessenger.ensureInitialized(args[0] as RootIsolateToken);
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'std-echo',
ExtendedStandardMessageCodec(),
);
final Object response = await channel.send(message) as Object;
final TestStatus testStatus = TestStepResult.deepEquals(message, response)
? TestStatus.ok
: TestStatus.failed;
final TestStatus testStatus =
TestStepResult.deepEquals(message, response) ? TestStatus.ok : TestStatus.failed;
sendPort.send(TestStepResult(name, description, testStatus));
} catch (ex) {
sendPort.send(TestStepResult(name, description, TestStatus.failed,
error: ex.toString()));
sendPort.send(TestStepResult(name, description, TestStatus.failed, error: ex.toString()));
}
}
@@ -113,8 +104,7 @@ Future<TestStepResult> basicBackgroundStandardEcho(Object message) async {
}
Future<TestStepResult> basicBinaryMessageToUnknownChannel() async {
const BasicMessageChannel<ByteData?> channel =
BasicMessageChannel<ByteData?>(
const BasicMessageChannel<ByteData?> channel = BasicMessageChannel<ByteData?>(
'binary-unknown',
BinaryCodec(),
);
@@ -130,8 +120,7 @@ Future<TestStepResult> basicStringMessageToUnknownChannel() async {
}
Future<TestStepResult> basicJsonMessageToUnknownChannel() async {
const BasicMessageChannel<dynamic> channel =
BasicMessageChannel<dynamic>(
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'json-unknown',
JSONMessageCodec(),
);
@@ -139,8 +128,7 @@ Future<TestStepResult> basicJsonMessageToUnknownChannel() async {
}
Future<TestStepResult> basicStandardMessageToUnknownChannel() async {
const BasicMessageChannel<dynamic> channel =
BasicMessageChannel<dynamic>(
const BasicMessageChannel<dynamic> channel = BasicMessageChannel<dynamic>(
'std-unknown',
ExtendedStandardMessageCodec(),
);
@@ -204,9 +192,7 @@ Future<TestStepResult> _basicMessageToUnknownChannel<T>(
String toString(dynamic message) {
if (message is ByteData) {
return message.buffer
.asUint8List(message.offsetInBytes, message.lengthInBytes)
.toString();
return message.buffer.asUint8List(message.offsetInBytes, message.lengthInBytes).toString();
} else {
return '$message';
}

View File

@@ -8,25 +8,21 @@ import 'basic_messaging.dart';
import 'test_step.dart';
Future<TestStepResult> methodCallJsonSuccessHandshake(dynamic payload) async {
const MethodChannel channel =
MethodChannel('json-method', JSONMethodCodec());
const MethodChannel channel = MethodChannel('json-method', JSONMethodCodec());
return _methodCallSuccessHandshake('JSON success($payload)', channel, payload);
}
Future<TestStepResult> methodCallJsonErrorHandshake(dynamic payload) async {
const MethodChannel channel =
MethodChannel('json-method', JSONMethodCodec());
const MethodChannel channel = MethodChannel('json-method', JSONMethodCodec());
return _methodCallErrorHandshake('JSON error($payload)', channel, payload);
}
Future<TestStepResult> methodCallJsonNotImplementedHandshake() async {
const MethodChannel channel =
MethodChannel('json-method', JSONMethodCodec());
const MethodChannel channel = MethodChannel('json-method', JSONMethodCodec());
return _methodCallNotImplementedHandshake('JSON notImplemented()', channel);
}
Future<TestStepResult> methodCallStandardSuccessHandshake(
dynamic payload) async {
Future<TestStepResult> methodCallStandardSuccessHandshake(dynamic payload) async {
const MethodChannel channel = MethodChannel(
'std-method',
StandardMethodCodec(ExtendedStandardMessageCodec()),

View File

@@ -38,10 +38,10 @@ class TestStepResult {
factory TestStepResult.fromSnapshot(AsyncSnapshot<TestStepResult> snapshot) {
return switch (snapshot.connectionState) {
ConnectionState.none => const TestStepResult('Not started', nothing, TestStatus.ok),
ConnectionState.none => const TestStepResult('Not started', nothing, TestStatus.ok),
ConnectionState.waiting => const TestStepResult('Executing', nothing, TestStatus.pending),
ConnectionState.done => snapshot.data ?? snapshot.error! as TestStepResult,
ConnectionState.active => throw 'Unsupported state: ConnectionState.active',
ConnectionState.done => snapshot.data ?? snapshot.error! as TestStepResult,
ConnectionState.active => throw 'Unsupported state: ConnectionState.active',
};
}
@@ -75,8 +75,7 @@ class TestStepResult {
const Text(' '),
Text(
status.name,
key: ValueKey<String>(
status == TestStatus.pending ? 'nostatus' : 'status'),
key: ValueKey<String>(status == TestStatus.pending ? 'nostatus' : 'status'),
style: bold,
),
],
@@ -128,9 +127,7 @@ Future<TestStepResult> resultOfHandshake(
String _toString(dynamic message) {
if (message is ByteData) {
return message.buffer
.asUint8List(message.offsetInBytes, message.lengthInBytes)
.toString();
return message.buffer.asUint8List(message.offsetInBytes, message.lengthInBytes).toString();
} else {
return '$message';
}

View File

@@ -4,7 +4,6 @@
import 'package:flutter/material.dart';
class LogoScreen extends StatelessWidget {
const LogoScreen({super.key});

View File

@@ -40,10 +40,7 @@ class MyHomePage extends StatefulWidget {
class MyHomePageState extends State<MyHomePage> {
Future<void>? libraryFuture;
Widget postLoadDisplayWidget = const Text(
'placeholder',
key: Key('PlaceholderText'),
);
Widget postLoadDisplayWidget = const Text('placeholder', key: Key('PlaceholderText'));
@override
void initState() {
@@ -72,26 +69,24 @@ class MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final Widget testWidget = libraryFuture == null ? const Text('preload', key: Key('PreloadText')) :
FutureBuilder<void>(
future: libraryFuture,
builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return postLoadDisplayWidget;
}
return postLoadDisplayWidget;
},
);
final Widget testWidget =
libraryFuture == null
? const Text('preload', key: Key('PreloadText'))
: FutureBuilder<void>(
future: libraryFuture,
builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return postLoadDisplayWidget;
}
return postLoadDisplayWidget;
},
);
return Scaffold(
appBar: AppBar(
title: const Text('Deferred components test'),
),
body: Center(
child: testWidget,
),
appBar: AppBar(title: const Text('Deferred components test')),
body: Center(child: testWidget),
floatingActionButton: FloatingActionButton(
key: const Key('FloatingActionButton'),
onPressed: _pressHandler,

View File

@@ -22,8 +22,7 @@ Future<void> main() async {
final String preloadText = await driver.getText(find.byValueKey('PreloadText'));
expect(preloadText, 'preload');
final SerializableFinder fab =
find.byValueKey('FloatingActionButton');
final SerializableFinder fab = find.byValueKey('FloatingActionButton');
await driver.tap(fab);
final String placeholderText = await driver.getText(find.byValueKey('PlaceholderText'));

View File

@@ -96,7 +96,8 @@ Widget builds: $_widgetBuilds''';
Ticker? ticker;
ticker = createTicker((Duration time) {
tickCount += 1;
if (tickCount == calibrationTickCount) { // about 10 seconds
if (tickCount == calibrationTickCount) {
// about 10 seconds
final Duration elapsed = DateTime.now().difference(startTime);
ticker?.stop();
ticker?.dispose();
@@ -132,30 +133,24 @@ Press play to produce texture frames.''';
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const SizedBox(
width: 300.0,
height: 200.0,
child: Texture(textureId: 0),
),
const SizedBox(width: 300.0, height: 200.0, child: Texture(textureId: 0)),
Container(
width: 300.0,
height: 60.0,
color: Colors.grey,
child: Center(
child: Text(
_summary,
key: const ValueKey<String>('summary'),
),
),
child: Center(child: Text(_summary, key: const ValueKey<String>('summary'))),
),
],
),
),
floatingActionButton: _icon == null ? null : FloatingActionButton(
key: const ValueKey<String>('fab'),
onPressed: _nextState,
child: Icon(_icon),
),
floatingActionButton:
_icon == null
? null
: FloatingActionButton(
key: const ValueKey<String>('fab'),
onPressed: _nextState,
child: Icon(_icon),
),
),
);
}

View File

@@ -39,9 +39,10 @@ class _FlavorState extends State<Flavor> {
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: _flavor == null
? const Text('Awaiting flavor...')
: Text(_flavor!, key: const ValueKey<String>('flavor')),
child:
_flavor == null
? const Text('Awaiting flavor...')
: Text(_flavor!, key: const ValueKey<String>('flavor')),
);
}
}

View File

@@ -31,13 +31,11 @@ const double _kAppBarMidHeight = 256.0;
// the primary scrollable scrolls upwards.
// TODO(hansmuller): it would be worth adding something like this to the framework.
class _RenderStatusBarPaddingSliver extends RenderSliver {
_RenderStatusBarPaddingSliver({
required double maxHeight,
required double scrollFactor,
}) : assert(maxHeight >= 0.0),
assert(scrollFactor >= 1.0),
_maxHeight = maxHeight,
_scrollFactor = scrollFactor;
_RenderStatusBarPaddingSliver({required double maxHeight, required double scrollFactor})
: assert(maxHeight >= 0.0),
assert(scrollFactor >= 1.0),
_maxHeight = maxHeight,
_scrollFactor = scrollFactor;
// The height of the status bar
double get maxHeight => _maxHeight;
@@ -66,7 +64,10 @@ class _RenderStatusBarPaddingSliver extends RenderSliver {
@override
void performLayout() {
final double height = (maxHeight - constraints.scrollOffset / scrollFactor).clamp(0.0, maxHeight);
final double height = (maxHeight - constraints.scrollOffset / scrollFactor).clamp(
0.0,
maxHeight,
);
geometry = SliverGeometry(
paintExtent: math.min(height, constraints.remainingPaintExtent),
scrollExtent: maxHeight,
@@ -76,21 +77,16 @@ class _RenderStatusBarPaddingSliver extends RenderSliver {
}
class _StatusBarPaddingSliver extends SingleChildRenderObjectWidget {
const _StatusBarPaddingSliver({
required this.maxHeight,
this.scrollFactor = 5.0,
}) : assert(maxHeight >= 0.0),
assert(scrollFactor >= 1.0);
const _StatusBarPaddingSliver({required this.maxHeight, this.scrollFactor = 5.0})
: assert(maxHeight >= 0.0),
assert(scrollFactor >= 1.0);
final double maxHeight;
final double scrollFactor;
@override
_RenderStatusBarPaddingSliver createRenderObject(BuildContext context) {
return _RenderStatusBarPaddingSliver(
maxHeight: maxHeight,
scrollFactor: scrollFactor,
);
return _RenderStatusBarPaddingSliver(maxHeight: maxHeight, scrollFactor: scrollFactor);
}
@override
@@ -109,11 +105,7 @@ class _StatusBarPaddingSliver extends SingleChildRenderObjectWidget {
}
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
_SliverAppBarDelegate({
required this.minHeight,
required this.maxHeight,
required this.child,
});
_SliverAppBarDelegate({required this.minHeight, required this.maxHeight, required this.child});
final double minHeight;
final double maxHeight;
@@ -131,9 +123,9 @@ class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
@override
bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
return maxHeight != oldDelegate.maxHeight
|| minHeight != oldDelegate.minHeight
|| child != oldDelegate.child;
return maxHeight != oldDelegate.maxHeight ||
minHeight != oldDelegate.minHeight ||
child != oldDelegate.child;
}
@override
@@ -202,17 +194,23 @@ class _AllSectionsLayout extends MultiChildLayoutDelegate {
// When tCollapsed > 0, the indicators move closer together
//final double rowIndicatorWidth = 48.0 + (1.0 - tCollapsed) * (rowTitleWidth - 48.0);
const double paddedSectionIndicatorWidth = kSectionIndicatorWidth + 8.0;
final double rowIndicatorWidth = paddedSectionIndicatorWidth +
(1.0 - tCollapsed!) * (rowTitleWidth - paddedSectionIndicatorWidth);
double rowIndicatorX = (size.width - rowIndicatorWidth) / 2.0 - selectedIndex! * rowIndicatorWidth;
final double rowIndicatorWidth =
paddedSectionIndicatorWidth +
(1.0 - tCollapsed!) * (rowTitleWidth - paddedSectionIndicatorWidth);
double rowIndicatorX =
(size.width - rowIndicatorWidth) / 2.0 - selectedIndex! * rowIndicatorWidth;
// Compute the size and origin of each card, title, and indicator for the maxHeight
// "column" layout, and the midHeight "row" layout. The actual layout is just the
// interpolated value between the column and row layouts for t.
for (int index = 0; index < cardCount!; index++) {
// Layout the card for index.
final Rect columnCardRect = Rect.fromLTWH(columnCardX, columnCardY, columnCardWidth, columnCardHeight);
final Rect columnCardRect = Rect.fromLTWH(
columnCardX,
columnCardY,
columnCardWidth,
columnCardHeight,
);
final Rect rowCardRect = Rect.fromLTWH(rowCardX, 0.0, rowCardWidth, size.height);
final Rect cardRect = _interpolateRect(columnCardRect, rowCardRect)!.shift(offset);
final String cardId = 'card$index';
@@ -232,12 +230,16 @@ class _AllSectionsLayout extends MultiChildLayoutDelegate {
positionChild('title$index', titleOrigin + offset);
// Layout the selection indicator for index.
final Size indicatorSize = layoutChild('indicator$index', BoxConstraints.loose(cardRect.size));
final Size indicatorSize = layoutChild(
'indicator$index',
BoxConstraints.loose(cardRect.size),
);
final double columnIndicatorX = cardRect.centerRight.dx - indicatorSize.width - 16.0;
final double columnIndicatorY = cardRect.bottomRight.dy - indicatorSize.height - 16.0;
final Offset columnIndicatorOrigin = Offset(columnIndicatorX, columnIndicatorY);
final Rect titleRect = Rect.fromPoints(titleOrigin, titleSize.bottomRight(titleOrigin));
final double centeredRowIndicatorX = rowIndicatorX + (rowIndicatorWidth - indicatorSize.width) / 2.0;
final double centeredRowIndicatorX =
rowIndicatorX + (rowIndicatorWidth - indicatorSize.width) / 2.0;
final double rowIndicatorY = titleRect.bottomCenter.dy + 16.0;
final Offset rowIndicatorOrigin = Offset(centeredRowIndicatorX, rowIndicatorY);
final Offset indicatorOrigin = _interpolatePoint(columnIndicatorOrigin, rowIndicatorOrigin)!;
@@ -252,9 +254,9 @@ class _AllSectionsLayout extends MultiChildLayoutDelegate {
@override
bool shouldRelayout(_AllSectionsLayout oldDelegate) {
return tColumnToRow != oldDelegate.tColumnToRow
|| cardCount != oldDelegate.cardCount
|| selectedIndex != oldDelegate.selectedIndex;
return tColumnToRow != oldDelegate.tColumnToRow ||
cardCount != oldDelegate.cardCount ||
selectedIndex != oldDelegate.selectedIndex;
}
}
@@ -291,16 +293,13 @@ class _AllSectionsView extends AnimatedWidget {
// 0.0 when size.height equals the maxHeight, 1.0 when the size.height
// equals the midHeight.
final double tColumnToRow =
1.0 - ((size.height - midHeight!) /
(maxHeight! - midHeight!)).clamp(0.0, 1.0);
1.0 - ((size.height - midHeight!) / (maxHeight! - midHeight!)).clamp(0.0, 1.0);
// The layout's progress from the midHeight row layout to
// a minHeight row layout. Its value is 0.0 when size.height equals
// midHeight and 1.0 when size.height equals minHeight.
final double tCollapsed =
1.0 - ((size.height - minHeight!) /
(midHeight! - minHeight!)).clamp(0.0, 1.0);
1.0 - ((size.height - minHeight!) / (midHeight! - minHeight!)).clamp(0.0, 1.0);
double indicatorOpacity(int index) {
return 1.0 - _selectedIndexDelta(index) * 0.5;
@@ -318,23 +317,22 @@ class _AllSectionsView extends AnimatedWidget {
for (int index = 0; index < sections.length; index++) {
final Section section = sections[index];
children.add(LayoutId(
id: 'title$index',
child: SectionTitle(
section: section,
scale: titleScale(index),
opacity: titleOpacity(index),
children.add(
LayoutId(
id: 'title$index',
child: SectionTitle(
section: section,
scale: titleScale(index),
opacity: titleOpacity(index),
),
),
));
);
}
for (int index = 0; index < sections.length; index++) {
children.add(LayoutId(
id: 'indicator$index',
child: SectionIndicator(
opacity: indicatorOpacity(index),
),
));
children.add(
LayoutId(id: 'indicator$index', child: SectionIndicator(opacity: indicatorOpacity(index))),
);
}
return CustomMultiChildLayout(
@@ -359,10 +357,7 @@ class _AllSectionsView extends AnimatedWidget {
// app bar's height is _kAppBarMidHeight and only one section heading is
// visible.
class _SnappingScrollPhysics extends ClampingScrollPhysics {
const _SnappingScrollPhysics({
super.parent,
required this.midScrollOffset,
});
const _SnappingScrollPhysics({super.parent, required this.midScrollOffset});
final double midScrollOffset;
@@ -371,12 +366,26 @@ class _SnappingScrollPhysics extends ClampingScrollPhysics {
return _SnappingScrollPhysics(parent: buildParent(ancestor), midScrollOffset: midScrollOffset);
}
Simulation _toMidScrollOffsetSimulation(double offset, double dragVelocity, ScrollMetrics metrics) {
Simulation _toMidScrollOffsetSimulation(
double offset,
double dragVelocity,
ScrollMetrics metrics,
) {
final double velocity = math.max(dragVelocity, minFlingVelocity);
return ScrollSpringSimulation(spring, offset, midScrollOffset, velocity, tolerance: toleranceFor(metrics));
return ScrollSpringSimulation(
spring,
offset,
midScrollOffset,
velocity,
tolerance: toleranceFor(metrics),
);
}
Simulation _toZeroScrollOffsetSimulation(double offset, double dragVelocity, ScrollMetrics metrics) {
Simulation _toZeroScrollOffsetSimulation(
double offset,
double dragVelocity,
ScrollMetrics metrics,
) {
final double velocity = math.max(dragVelocity, minFlingVelocity);
return ScrollSpringSimulation(spring, offset, 0.0, velocity, tolerance: toleranceFor(metrics));
}
@@ -419,7 +428,7 @@ class _SnappingScrollPhysics extends ClampingScrollPhysics {
}
class AnimationDemoHome extends StatefulWidget {
const AnimationDemoHome({ super.key });
const AnimationDemoHome({super.key});
static const String routeName = '/animation';
@@ -457,9 +466,10 @@ class _AnimationDemoHomeState extends State<AnimationDemoHome> {
// Paging is enabled/disabled by setting the heading's PageView scroll physics.
bool _handleScrollNotification(ScrollNotification notification, double midScrollOffset) {
if (notification.depth == 0 && notification is ScrollUpdateNotification) {
final ScrollPhysics physics = _scrollController.position.pixels >= midScrollOffset
? const PageScrollPhysics()
: const NeverScrollableScrollPhysics();
final ScrollPhysics physics =
_scrollController.position.pixels >= midScrollOffset
? const PageScrollPhysics()
: const NeverScrollableScrollPhysics();
if (physics != _headingScrollPhysics) {
setState(() {
_headingScrollPhysics = physics;
@@ -473,17 +483,33 @@ class _AnimationDemoHomeState extends State<AnimationDemoHome> {
if (_scrollController.offset < midScrollOffset) {
// Scroll the overall list to the point where only one section card shows.
// At the same time scroll the PageViews to the page at pageIndex.
_headingPageController.animateToPage(pageIndex, curve: _kScrollCurve, duration: _kScrollDuration);
_scrollController.animateTo(midScrollOffset, curve: _kScrollCurve, duration: _kScrollDuration);
_headingPageController.animateToPage(
pageIndex,
curve: _kScrollCurve,
duration: _kScrollDuration,
);
_scrollController.animateTo(
midScrollOffset,
curve: _kScrollCurve,
duration: _kScrollDuration,
);
} else {
// One one section card is showing: scroll one page forward or back.
final double centerX = _headingPageController.position.viewportDimension / 2.0;
final int newPageIndex = xOffset > centerX ? pageIndex + 1 : pageIndex - 1;
_headingPageController.animateToPage(newPageIndex, curve: _kScrollCurve, duration: _kScrollDuration);
_headingPageController.animateToPage(
newPageIndex,
curve: _kScrollCurve,
duration: _kScrollDuration,
);
}
}
bool _handlePageNotification(ScrollNotification notification, PageController leader, PageController follower) {
bool _handlePageNotification(
ScrollNotification notification,
PageController leader,
PageController follower,
) {
if (notification.depth == 0 && notification is ScrollUpdateNotification) {
selectedIndex.value = leader.page;
if (follower.page != leader.page) {
@@ -503,24 +529,27 @@ class _AnimationDemoHomeState extends State<AnimationDemoHome> {
List<Widget> _allHeadingItems(double maxHeight, double midScrollOffset) {
final List<Widget> sectionCards = <Widget>[];
for (int index = 0; index < allSections.length; index++) {
sectionCards.add(LayoutId(
id: 'card$index',
child: GestureDetector(
behavior: HitTestBehavior.opaque,
child: SectionCard(section: allSections[index]),
onTapUp: (TapUpDetails details) {
final double xOffset = details.globalPosition.dx;
setState(() {
_maybeScroll(midScrollOffset, index, xOffset);
});
},
sectionCards.add(
LayoutId(
id: 'card$index',
child: GestureDetector(
behavior: HitTestBehavior.opaque,
child: SectionCard(section: allSections[index]),
onTapUp: (TapUpDetails details) {
final double xOffset = details.globalPosition.dx;
setState(() {
_maybeScroll(midScrollOffset, index, xOffset);
});
},
),
),
));
);
}
final List<Widget> headings = <Widget>[];
for (int index = 0; index < allSections.length; index++) {
headings.add(ColoredBox(
headings.add(
ColoredBox(
color: _kAppBackgroundColor,
child: ClipRect(
child: _AllSectionsView(
@@ -533,7 +562,7 @@ class _AnimationDemoHomeState extends State<AnimationDemoHome> {
sectionCards: sectionCards,
),
),
)
),
);
}
return headings;
@@ -560,10 +589,7 @@ class _AnimationDemoHomeState extends State<AnimationDemoHome> {
physics: _SnappingScrollPhysics(midScrollOffset: appBarMidScrollOffset),
slivers: <Widget>[
// Start out below the status bar, gradually move to the top of the screen.
_StatusBarPaddingSliver(
maxHeight: statusBarHeight,
scrollFactor: 7.0,
),
_StatusBarPaddingSliver(maxHeight: statusBarHeight, scrollFactor: 7.0),
// Section Headings
SliverPersistentHeader(
pinned: true,
@@ -572,7 +598,11 @@ class _AnimationDemoHomeState extends State<AnimationDemoHome> {
maxHeight: appBarMaxHeight,
child: NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
return _handlePageNotification(notification, _headingPageController, _detailsPageController);
return _handlePageNotification(
notification,
_headingPageController,
_detailsPageController,
);
},
child: PageView(
physics: _headingScrollPhysics,
@@ -588,16 +618,21 @@ class _AnimationDemoHomeState extends State<AnimationDemoHome> {
height: 610.0,
child: NotificationListener<ScrollNotification>(
onNotification: (ScrollNotification notification) {
return _handlePageNotification(notification, _detailsPageController, _headingPageController);
return _handlePageNotification(
notification,
_detailsPageController,
_headingPageController,
);
},
child: PageView(
controller: _detailsPageController,
children: allSections.map<Widget>((Section section) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: _detailItemsFor(section).toList(),
);
}).toList(),
children:
allSections.map<Widget>((Section section) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: _detailItemsFor(section).toList(),
);
}).toList(),
),
),
),

View File

@@ -14,12 +14,7 @@ const Color _mySin = Color(0xFFF3A646);
const String _kGalleryAssetsPackage = 'flutter_gallery_assets';
class SectionDetail {
const SectionDetail({
this.title,
this.subtitle,
this.imageAsset,
this.imageAssetPackage,
});
const SectionDetail({this.title, this.subtitle, this.imageAsset, this.imageAssetPackage});
final String? title;
final String? subtitle;
final String? imageAsset;
@@ -44,9 +39,8 @@ class Section {
final List<SectionDetail>? details;
@override
bool operator==(Object other) {
return other is Section
&& other.title == title;
bool operator ==(Object other) {
return other is Section && other.title == title;
}
@override

View File

@@ -10,7 +10,7 @@ const double kSectionIndicatorWidth = 32.0;
// The card for a single section. Displays the section's gradient and background image.
class SectionCard extends StatelessWidget {
const SectionCard({ super.key, required this.section });
const SectionCard({super.key, required this.section});
final Section section;
@@ -21,12 +21,7 @@ class SectionCard extends StatelessWidget {
button: true,
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: <Color>[
section.leftColor!,
section.rightColor!,
],
),
gradient: LinearGradient(colors: <Color>[section.leftColor!, section.rightColor!]),
),
child: Image.asset(
section.backgroundAsset!,
@@ -43,12 +38,8 @@ class SectionCard extends StatelessWidget {
// The title is rendered with two overlapping text widgets that are vertically
// offset a little. It's supposed to look sort-of 3D.
class SectionTitle extends StatelessWidget {
const SectionTitle({
super.key,
required this.section,
required this.scale,
required this.opacity,
}) : assert(opacity >= 0.0 && opacity <= 1.0);
const SectionTitle({super.key, required this.section, required this.scale, required this.opacity})
: assert(opacity >= 0.0 && opacity <= 1.0);
final Section section;
final double scale;
@@ -77,10 +68,7 @@ class SectionTitle extends StatelessWidget {
alignment: Alignment.center,
child: Stack(
children: <Widget>[
Positioned(
top: 4.0,
child: Text(section.title!, style: sectionTitleShadowStyle),
),
Positioned(top: 4.0, child: Text(section.title!, style: sectionTitleShadowStyle)),
Text(section.title!, style: sectionTitleStyle),
],
),
@@ -92,7 +80,7 @@ class SectionTitle extends StatelessWidget {
// Small horizontal bar that indicates the selected section.
class SectionIndicator extends StatelessWidget {
const SectionIndicator({ super.key, this.opacity = 1.0 });
const SectionIndicator({super.key, this.opacity = 1.0});
final double opacity;
@@ -110,7 +98,7 @@ class SectionIndicator extends StatelessWidget {
// Display a single SectionDetail.
class SectionDetailView extends StatelessWidget {
SectionDetailView({ super.key, required this.detail })
SectionDetailView({super.key, required this.detail})
: assert(detail.imageAsset != null),
assert((detail.imageAsset ?? detail.title) != null);
@@ -122,10 +110,7 @@ class SectionDetailView extends StatelessWidget {
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6.0),
image: DecorationImage(
image: AssetImage(
detail.imageAsset!,
package: detail.imageAssetPackage,
),
image: AssetImage(detail.imageAsset!, package: detail.imageAssetPackage),
fit: BoxFit.cover,
),
),
@@ -136,11 +121,7 @@ class SectionDetailView extends StatelessWidget {
item = Container(
height: 240.0,
padding: const EdgeInsets.all(16.0),
child: SafeArea(
top: false,
bottom: false,
child: image,
),
child: SafeArea(top: false, bottom: false, child: image),
);
} else {
item = ListTile(
@@ -150,9 +131,6 @@ class SectionDetailView extends StatelessWidget {
);
}
return DecoratedBox(
decoration: BoxDecoration(color: Colors.grey.shade200),
child: item,
);
return DecoratedBox(decoration: BoxDecoration(color: Colors.grey.shade200), child: item);
}
}

View File

@@ -114,23 +114,14 @@ class CalculatorState extends State<Calculator> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).canvasColor,
elevation: 0.0,
),
appBar: AppBar(backgroundColor: Theme.of(context).canvasColor, elevation: 0.0),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
// Give the key-pad 3/5 of the vertical space and the display 2/5.
Expanded(
flex: 2,
child: CalcDisplay(content: _expression.toString()),
),
Expanded(flex: 2, child: CalcDisplay(content: _expression.toString())),
const Divider(height: 1.0),
Expanded(
flex: 3,
child: KeyPad(calcState: this),
),
Expanded(flex: 3, child: KeyPad(calcState: this)),
],
),
);
@@ -138,23 +129,18 @@ class CalculatorState extends State<Calculator> {
}
class CalcDisplay extends StatelessWidget {
const CalcDisplay({ super.key, this.content});
const CalcDisplay({super.key, this.content});
final String? content;
@override
Widget build(BuildContext context) {
return Center(
child: Text(
content!,
style: const TextStyle(fontSize: 24.0),
),
);
return Center(child: Text(content!, style: const TextStyle(fontSize: 24.0)));
}
}
class KeyPad extends StatelessWidget {
const KeyPad({ super.key, this.calcState });
const KeyPad({super.key, this.calcState});
final CalculatorState? calcState;
@@ -228,12 +214,7 @@ class KeyRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Expanded(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: keys,
),
);
return Expanded(child: Row(mainAxisAlignment: MainAxisAlignment.center, children: keys));
}
}
@@ -255,7 +236,7 @@ class CalcKey extends StatelessWidget {
style: TextStyle(
// This line is used as a sentinel in the hot reload tests: hot_mode_test.dart
// in the devicelab.
fontSize: (orientation == Orientation.portrait) ? 32.0 : 24.0
fontSize: (orientation == Orientation.portrait) ? 32.0 : 24.0,
),
),
),

View File

@@ -69,17 +69,16 @@ enum Operation { Addition, Subtraction, Multiplication, Division }
/// A token that represents an arithmetic operation symbol.
class OperationToken extends ExpressionToken {
OperationToken(this.operation)
: super(opString(operation));
OperationToken(this.operation) : super(opString(operation));
Operation operation;
static String? opString(Operation operation) {
return switch (operation) {
Operation.Addition => ' + ',
Operation.Subtraction => ' - ',
Operation.Addition => ' + ',
Operation.Subtraction => ' - ',
Operation.Multiplication => ' \u00D7 ',
Operation.Division => ' \u00F7 ',
Operation.Division => ' \u00F7 ',
};
}
}
@@ -117,8 +116,7 @@ enum ExpressionState {
class CalcExpression {
CalcExpression(this._list, this.state);
CalcExpression.empty()
: this(<ExpressionToken>[], ExpressionState.Start);
CalcExpression.empty() : this(<ExpressionToken>[], ExpressionState.Start);
CalcExpression.result(FloatToken result)
: _list = <ExpressionToken?>[result],
@@ -126,6 +124,7 @@ class CalcExpression {
/// The tokens comprising the expression.
final List<ExpressionToken?> _list;
/// The state of the expression.
final ExpressionState state;
@@ -288,9 +287,7 @@ class CalcExpression {
assert(false);
}
}
final List<ExpressionToken> outList = <ExpressionToken>[
ResultToken(currentTermValue),
];
final List<ExpressionToken> outList = <ExpressionToken>[ResultToken(currentTermValue)];
return CalcExpression(outList, ExpressionState.Result);
}

View File

@@ -7,7 +7,7 @@ import 'package:flutter/material.dart';
const double kColorItemHeight = 48.0;
class Palette {
Palette({ this.name, this.primary, this.accent, this.threshold = 900});
Palette({this.name, this.primary, this.accent, this.threshold = 900});
final String? name;
final MaterialColor? primary;
@@ -21,32 +21,46 @@ final List<Palette> allPalettes = <Palette>[
Palette(name: 'RED', primary: Colors.red, accent: Colors.redAccent, threshold: 300),
Palette(name: 'PINK', primary: Colors.pink, accent: Colors.pinkAccent, threshold: 200),
Palette(name: 'PURPLE', primary: Colors.purple, accent: Colors.purpleAccent, threshold: 200),
Palette(name: 'DEEP PURPLE', primary: Colors.deepPurple, accent: Colors.deepPurpleAccent, threshold: 200),
Palette(
name: 'DEEP PURPLE',
primary: Colors.deepPurple,
accent: Colors.deepPurpleAccent,
threshold: 200,
),
Palette(name: 'INDIGO', primary: Colors.indigo, accent: Colors.indigoAccent, threshold: 200),
Palette(name: 'BLUE', primary: Colors.blue, accent: Colors.blueAccent, threshold: 400),
Palette(name: 'LIGHT BLUE', primary: Colors.lightBlue, accent: Colors.lightBlueAccent, threshold: 500),
Palette(
name: 'LIGHT BLUE',
primary: Colors.lightBlue,
accent: Colors.lightBlueAccent,
threshold: 500,
),
Palette(name: 'CYAN', primary: Colors.cyan, accent: Colors.cyanAccent, threshold: 600),
Palette(name: 'TEAL', primary: Colors.teal, accent: Colors.tealAccent, threshold: 400),
Palette(name: 'GREEN', primary: Colors.green, accent: Colors.greenAccent, threshold: 500),
Palette(name: 'LIGHT GREEN', primary: Colors.lightGreen, accent: Colors.lightGreenAccent, threshold: 600),
Palette(
name: 'LIGHT GREEN',
primary: Colors.lightGreen,
accent: Colors.lightGreenAccent,
threshold: 600,
),
Palette(name: 'LIME', primary: Colors.lime, accent: Colors.limeAccent, threshold: 800),
Palette(name: 'YELLOW', primary: Colors.yellow, accent: Colors.yellowAccent),
Palette(name: 'AMBER', primary: Colors.amber, accent: Colors.amberAccent),
Palette(name: 'ORANGE', primary: Colors.orange, accent: Colors.orangeAccent, threshold: 700),
Palette(name: 'DEEP ORANGE', primary: Colors.deepOrange, accent: Colors.deepOrangeAccent, threshold: 400),
Palette(
name: 'DEEP ORANGE',
primary: Colors.deepOrange,
accent: Colors.deepOrangeAccent,
threshold: 400,
),
Palette(name: 'BROWN', primary: Colors.brown, threshold: 200),
Palette(name: 'GREY', primary: Colors.grey, threshold: 500),
Palette(name: 'BLUE GREY', primary: Colors.blueGrey, threshold: 500),
];
class ColorItem extends StatelessWidget {
const ColorItem({
super.key,
required this.index,
required this.color,
this.prefix = '',
});
const ColorItem({super.key, required this.index, required this.color, this.prefix = ''});
final int index;
final Color color;
@@ -67,10 +81,7 @@ class ColorItem extends StatelessWidget {
bottom: false,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text('$prefix$index'),
Text(colorString()),
],
children: <Widget>[Text('$prefix$index'), Text(colorString())],
),
),
),
@@ -79,10 +90,7 @@ class ColorItem extends StatelessWidget {
}
class PaletteTabView extends StatelessWidget {
PaletteTabView({
super.key,
required this.colors,
}) : assert(colors.isValid);
PaletteTabView({super.key, required this.colors}) : assert(colors.isValid);
final Palette colors;
@@ -137,9 +145,10 @@ class ColorsDemo extends StatelessWidget {
),
),
body: TabBarView(
children: allPalettes.map<Widget>((Palette colors) {
return PaletteTabView(colors: colors);
}).toList(),
children:
allPalettes.map<Widget>((Palette colors) {
return PaletteTabView(colors: colors);
}).toList(),
),
),
);

View File

@@ -6,7 +6,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
class _ContactCategory extends StatelessWidget {
const _ContactCategory({ this.icon, this.children });
const _ContactCategory({this.icon, this.children});
final IconData? icon;
final List<Widget>? children;
@@ -16,9 +16,7 @@ class _ContactCategory extends StatelessWidget {
final ThemeData themeData = Theme.of(context);
return Container(
padding: const EdgeInsets.symmetric(vertical: 16.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: themeData.dividerColor))
),
decoration: BoxDecoration(border: Border(bottom: BorderSide(color: themeData.dividerColor))),
child: DefaultTextStyle(
style: Theme.of(context).textTheme.titleMedium!,
child: SafeArea(
@@ -42,7 +40,7 @@ class _ContactCategory extends StatelessWidget {
}
class _ContactItem extends StatelessWidget {
const _ContactItem({ this.icon, required this.lines, this.tooltip, this.onPressed })
const _ContactItem({this.icon, required this.lines, this.tooltip, this.onPressed})
: assert(lines.length > 1);
final IconData? icon;
@@ -115,16 +113,18 @@ class ContactsDemoState extends State<ContactsDemo> {
SliverAppBar(
expandedHeight: _appBarHeight,
pinned: _appBarBehavior == AppBarBehavior.pinned,
floating: _appBarBehavior == AppBarBehavior.floating || _appBarBehavior == AppBarBehavior.snapping,
floating:
_appBarBehavior == AppBarBehavior.floating ||
_appBarBehavior == AppBarBehavior.snapping,
snap: _appBarBehavior == AppBarBehavior.snapping,
actions: <Widget>[
IconButton(
icon: const Icon(Icons.create),
tooltip: 'Edit',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Editing isn't supported in this screen."),
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text("Editing isn't supported in this screen.")),
);
},
),
PopupMenuButton<AppBarBehavior>(
@@ -133,24 +133,25 @@ class ContactsDemoState extends State<ContactsDemo> {
_appBarBehavior = value;
});
},
itemBuilder: (BuildContext context) => <PopupMenuItem<AppBarBehavior>>[
const PopupMenuItem<AppBarBehavior>(
value: AppBarBehavior.normal,
child: Text('App bar scrolls away'),
),
const PopupMenuItem<AppBarBehavior>(
value: AppBarBehavior.pinned,
child: Text('App bar stays put'),
),
const PopupMenuItem<AppBarBehavior>(
value: AppBarBehavior.floating,
child: Text('App bar floats'),
),
const PopupMenuItem<AppBarBehavior>(
value: AppBarBehavior.snapping,
child: Text('App bar snaps'),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuItem<AppBarBehavior>>[
const PopupMenuItem<AppBarBehavior>(
value: AppBarBehavior.normal,
child: Text('App bar scrolls away'),
),
const PopupMenuItem<AppBarBehavior>(
value: AppBarBehavior.pinned,
child: Text('App bar stays put'),
),
const PopupMenuItem<AppBarBehavior>(
value: AppBarBehavior.floating,
child: Text('App bar floats'),
),
const PopupMenuItem<AppBarBehavior>(
value: AppBarBehavior.snapping,
child: Text('App bar snaps'),
),
],
),
],
flexibleSpace: FlexibleSpaceBar(
@@ -190,40 +191,35 @@ class ContactsDemoState extends State<ContactsDemo> {
icon: Icons.message,
tooltip: 'Send message',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Pretend that this opened your SMS application.'),
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Pretend that this opened your SMS application.'),
),
);
},
lines: const <String>[
'(650) 555-1234',
'Mobile',
],
lines: const <String>['(650) 555-1234', 'Mobile'],
),
_ContactItem(
icon: Icons.message,
tooltip: 'Send message',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('A messaging app appears.'),
));
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('A messaging app appears.')));
},
lines: const <String>[
'(323) 555-6789',
'Work',
],
lines: const <String>['(323) 555-6789', 'Work'],
),
_ContactItem(
icon: Icons.message,
tooltip: 'Send message',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Imagine if you will, a messaging application.'),
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Imagine if you will, a messaging application.'),
),
);
},
lines: const <String>[
'(650) 555-6789',
'Home',
],
lines: const <String>['(650) 555-6789', 'Home'],
),
],
),
@@ -235,27 +231,25 @@ class ContactsDemoState extends State<ContactsDemo> {
icon: Icons.email,
tooltip: 'Send personal e-mail',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Here, your e-mail application would open.'),
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Here, your e-mail application would open.'),
),
);
},
lines: const <String>[
'ali_connors@example.com',
'Personal',
],
lines: const <String>['ali_connors@example.com', 'Personal'],
),
_ContactItem(
icon: Icons.email,
tooltip: 'Send work e-mail',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Summon your favorite e-mail application here.'),
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Summon your favorite e-mail application here.'),
),
);
},
lines: const <String>[
'aliconnors@example.com',
'Work',
],
lines: const <String>['aliconnors@example.com', 'Work'],
),
],
),
@@ -266,23 +260,19 @@ class ContactsDemoState extends State<ContactsDemo> {
icon: Icons.map,
tooltip: 'Open map',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('This would show a map of San Francisco.'),
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('This would show a map of San Francisco.')),
);
},
lines: const <String>[
'2000 Main Street',
'San Francisco, CA',
'Home',
],
lines: const <String>['2000 Main Street', 'San Francisco, CA', 'Home'],
),
_ContactItem(
icon: Icons.map,
tooltip: 'Open map',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('This would show a map of Mountain View.'),
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('This would show a map of Mountain View.')),
);
},
lines: const <String>[
'1600 Amphitheater Parkway',
@@ -294,45 +284,25 @@ class ContactsDemoState extends State<ContactsDemo> {
icon: Icons.map,
tooltip: 'Open map',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('This would also show a map, if this was not a demo.'),
));
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('This would also show a map, if this was not a demo.'),
),
);
},
lines: const <String>[
'126 Severyns Ave',
'Mountain View, CA',
'Jet Travel',
],
lines: const <String>['126 Severyns Ave', 'Mountain View, CA', 'Jet Travel'],
),
],
),
_ContactCategory(
icon: Icons.today,
children: <Widget>[
_ContactItem(lines: const <String>['Birthday', 'January 9th, 1989']),
_ContactItem(lines: const <String>['Wedding anniversary', 'June 21st, 2014']),
_ContactItem(
lines: const <String>[
'Birthday',
'January 9th, 1989',
],
),
_ContactItem(
lines: const <String>[
'Wedding anniversary',
'June 21st, 2014',
],
),
_ContactItem(
lines: const <String>[
'First day in office',
'January 20th, 2015',
],
),
_ContactItem(
lines: const <String>[
'Last day in office',
'August 9th, 2018',
],
lines: const <String>['First day in office', 'January 20th, 2015'],
),
_ContactItem(lines: const <String>['Last day in office', 'August 9th, 2018']),
],
),
]),

View File

@@ -22,9 +22,7 @@ class CupertinoProgressIndicatorDemo extends StatelessWidget {
middle: const Text('Activity Indicator'),
trailing: CupertinoDemoDocumentationButton(routeName),
),
child: const Center(
child: CupertinoActivityIndicator(),
),
child: const Center(child: CupertinoActivityIndicator()),
);
}
}

View File

@@ -19,12 +19,13 @@ class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> {
String? lastSelectedValue;
void showDemoDialog({required BuildContext context, Widget? child}) {
showCupertinoDialog<String>(
context: context,
builder: (BuildContext context) => child!,
).then((String? value) {
showCupertinoDialog<String>(context: context, builder: (BuildContext context) => child!).then((
String? value,
) {
if (value != null) {
setState(() { lastSelectedValue = value; });
setState(() {
lastSelectedValue = value;
});
}
});
}
@@ -35,7 +36,9 @@ class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> {
builder: (BuildContext context) => child!,
).then((String? value) {
if (value != null) {
setState(() { lastSelectedValue = value; });
setState(() {
lastSelectedValue = value;
});
}
});
}
@@ -62,8 +65,9 @@ class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> {
child: ListView(
primary: true,
// Add more padding to the normal safe area.
padding: const EdgeInsets.symmetric(vertical: 24.0, horizontal: 72.0)
+ MediaQuery.of(context).padding,
padding:
const EdgeInsets.symmetric(vertical: 24.0, horizontal: 72.0) +
MediaQuery.of(context).padding,
children: <Widget>[
CupertinoButton.filled(
child: const Text('Alert'),
@@ -86,10 +90,7 @@ class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> {
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 36.0),
child: const Text('Alert Buttons Only'),
onPressed: () {
showDemoDialog(
context: context,
child: const CupertinoDessertDialog(),
);
showDemoDialog(context: context, child: const CupertinoDessertDialog());
},
),
const Padding(padding: EdgeInsets.all(8.0)),
@@ -102,10 +103,7 @@ class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> {
),
),
if (lastSelectedValue != null)
Positioned(
bottom: 32.0,
child: Text('You selected: $lastSelectedValue'),
),
Positioned(bottom: 32.0, child: Text('You selected: $lastSelectedValue')),
],
);
},
@@ -140,8 +138,10 @@ class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> {
context: context,
child: CupertinoAlertDialog(
title: const Text('Allow "Maps" to access your location while you are using the app?'),
content: const Text('Your current location will be displayed on the map and used '
'for directions, nearby search results, and estimated travel times.'),
content: const Text(
'Your current location will be displayed on the map and used '
'for directions, nearby search results, and estimated travel times.',
),
actions: <Widget>[
CupertinoDialogAction(
child: const Text("Don't Allow"),
@@ -161,14 +161,16 @@ class _CupertinoAlertDemoState extends State<CupertinoAlertDemo> {
context: context,
child: const CupertinoDessertDialog(
title: Text('Select Favorite Dessert'),
content: Text('Please select your favorite type of dessert from the '
content: Text(
'Please select your favorite type of dessert from the '
'list below. Your selection will be used to customize the suggested '
'list of eateries in your area.'),
'list of eateries in your area.',
),
),
);
}
void _onActionSheetPress(BuildContext context) {
void _onActionSheetPress(BuildContext context) {
showDemoActionSheet(
context: context,
child: CupertinoActionSheet(

View File

@@ -38,16 +38,18 @@ class _CupertinoButtonDemoState extends State<CupertinoButtonsDemo> {
padding: EdgeInsets.all(16.0),
child: Text(
'iOS themed buttons are flat. They can have borders or backgrounds but '
'only when necessary.'
'only when necessary.',
),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget> [
Text(_pressedCount > 0
? 'Button pressed $_pressedCount time${_pressedCount == 1 ? "" : "s"}'
: ' '),
children: <Widget>[
Text(
_pressedCount > 0
? 'Button pressed $_pressedCount time${_pressedCount == 1 ? "" : "s"}'
: ' ',
),
const Padding(padding: EdgeInsets.all(12.0)),
Align(
alignment: const Alignment(0.0, -0.2),
@@ -57,13 +59,12 @@ class _CupertinoButtonDemoState extends State<CupertinoButtonsDemo> {
CupertinoButton(
child: const Text('Cupertino Button'),
onPressed: () {
setState(() { _pressedCount += 1; });
setState(() {
_pressedCount += 1;
});
},
),
const CupertinoButton(
onPressed: null,
child: Text('Disabled'),
),
const CupertinoButton(onPressed: null, child: Text('Disabled')),
],
),
),
@@ -71,14 +72,13 @@ class _CupertinoButtonDemoState extends State<CupertinoButtonsDemo> {
CupertinoButton.filled(
child: const Text('With Background'),
onPressed: () {
setState(() { _pressedCount += 1; });
setState(() {
_pressedCount += 1;
});
},
),
const Padding(padding: EdgeInsets.all(12.0)),
const CupertinoButton.filled(
onPressed: null,
child: Text('Disabled'),
),
const CupertinoButton.filled(onPressed: null, child: Text('Disabled')),
],
),
),

View File

@@ -23,22 +23,41 @@ const List<Color> coolColors = <Color>[
];
const List<String> coolColorNames = <String>[
'Sarcoline', 'Coquelicot', 'Smaragdine', 'Mikado', 'Glaucous', 'Wenge',
'Fulvous', 'Xanadu', 'Falu', 'Eburnean', 'Amaranth', 'Australien',
'Banan', 'Falu', 'Gingerline', 'Incarnadine', 'Labrador', 'Nattier',
'Pervenche', 'Sinoper', 'Verditer', 'Watchet', 'Zaffre',
'Sarcoline',
'Coquelicot',
'Smaragdine',
'Mikado',
'Glaucous',
'Wenge',
'Fulvous',
'Xanadu',
'Falu',
'Eburnean',
'Amaranth',
'Australien',
'Banan',
'Falu',
'Gingerline',
'Incarnadine',
'Labrador',
'Nattier',
'Pervenche',
'Sinoper',
'Verditer',
'Watchet',
'Zaffre',
];
const int _kChildCount = 50;
class CupertinoNavigationDemo extends StatelessWidget {
CupertinoNavigationDemo({ super.key, this.randomSeed })
: colorItems = List<Color>.generate(_kChildCount, (int index) {
return coolColors[math.Random(randomSeed).nextInt(coolColors.length)];
}) ,
colorNameItems = List<String>.generate(_kChildCount, (int index) {
return coolColorNames[math.Random(randomSeed).nextInt(coolColorNames.length)];
});
CupertinoNavigationDemo({super.key, this.randomSeed})
: colorItems = List<Color>.generate(_kChildCount, (int index) {
return coolColors[math.Random(randomSeed).nextInt(coolColors.length)];
}),
colorNameItems = List<String>.generate(_kChildCount, (int index) {
return coolColorNames[math.Random(randomSeed).nextInt(coolColorNames.length)];
});
static const String routeName = '/cupertino/navigation';
@@ -56,10 +75,7 @@ class CupertinoNavigationDemo extends StatelessWidget {
child: CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.house, size: 27),
label: 'Home',
),
BottomNavigationBarItem(icon: Icon(CupertinoIcons.house, size: 27), label: 'Home'),
BottomNavigationBarItem(
icon: Icon(CupertinoIcons.chat_bubble, size: 27),
label: 'Support',
@@ -110,11 +126,7 @@ class ExitButton extends StatelessWidget {
Widget build(BuildContext context) {
return CupertinoButton(
padding: EdgeInsets.zero,
child: const Tooltip(
message: 'Back',
excludeFromSemantics: true,
child: Text('Exit'),
),
child: const Tooltip(message: 'Back', excludeFromSemantics: true, child: Text('Exit')),
onPressed: () {
// The demo is on the root navigator.
Navigator.of(context, rootNavigator: true).pop();
@@ -133,12 +145,7 @@ final Widget trailingButtons = Row(
);
class CupertinoDemoTab1 extends StatelessWidget {
const CupertinoDemoTab1({
super.key,
this.colorItems,
this.colorNameItems,
this.randomSeed,
});
const CupertinoDemoTab1({super.key, this.colorItems, this.colorNameItems, this.randomSeed});
final List<Color>? colorItems;
final List<String>? colorNameItems;
@@ -151,30 +158,24 @@ class CupertinoDemoTab1 extends StatelessWidget {
child: CustomScrollView(
semanticChildCount: _kChildCount,
slivers: <Widget>[
CupertinoSliverNavigationBar(
trailing: trailingButtons,
),
CupertinoSliverNavigationBar(trailing: trailingButtons),
SliverPadding(
// Top media padding consumed by CupertinoSliverNavigationBar.
// Left/Right media padding consumed by Tab1RowItem.
padding: MediaQuery.of(context).removePadding(
removeTop: true,
removeLeft: true,
removeRight: true,
).padding,
padding:
MediaQuery.of(
context,
).removePadding(removeTop: true, removeLeft: true, removeRight: true).padding,
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Tab1RowItem(
index: index,
lastItem: index == _kChildCount - 1,
color: colorItems![index],
colorName: colorNameItems![index],
randomSeed: randomSeed,
);
},
childCount: _kChildCount,
),
delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
return Tab1RowItem(
index: index,
lastItem: index == _kChildCount - 1,
color: colorItems![index],
colorName: colorNameItems![index],
randomSeed: randomSeed,
);
}, childCount: _kChildCount),
),
),
],
@@ -204,15 +205,18 @@ class Tab1RowItem extends StatelessWidget {
final Widget row = GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navigator.of(context).push(CupertinoPageRoute<void>(
title: colorName,
builder: (BuildContext context) => Tab1ItemPage(
color: color,
colorName: colorName,
index: index,
randomSeed: randomSeed,
Navigator.of(context).push(
CupertinoPageRoute<void>(
title: colorName,
builder:
(BuildContext context) => Tab1ItemPage(
color: color,
colorName: colorName,
index: index,
randomSeed: randomSeed,
),
),
));
);
},
child: ColoredBox(
color: CupertinoDynamicColor.resolve(CupertinoColors.systemBackground, context),
@@ -226,10 +230,7 @@ class Tab1RowItem extends StatelessWidget {
Container(
height: 60.0,
width: 60.0,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8.0),
),
decoration: BoxDecoration(color: color, borderRadius: BorderRadius.circular(8.0)),
),
Expanded(
child: Padding(
@@ -242,7 +243,10 @@ class Tab1RowItem extends StatelessWidget {
Text(
'Buy this cool color',
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.secondaryLabel, context),
color: CupertinoDynamicColor.resolve(
CupertinoColors.secondaryLabel,
context,
),
fontSize: 13.0,
fontWeight: FontWeight.w300,
),
@@ -253,17 +257,13 @@ class Tab1RowItem extends StatelessWidget {
),
CupertinoButton(
padding: EdgeInsets.zero,
child: const Icon(CupertinoIcons.plus_circled,
semanticLabel: 'Add',
),
onPressed: () { },
child: const Icon(CupertinoIcons.plus_circled, semanticLabel: 'Add'),
onPressed: () {},
),
CupertinoButton(
padding: EdgeInsets.zero,
child: const Icon(CupertinoIcons.share,
semanticLabel: 'Share',
),
onPressed: () { },
child: const Icon(CupertinoIcons.share, semanticLabel: 'Share'),
onPressed: () {},
),
],
),
@@ -314,9 +314,7 @@ class Tab1ItemPageState extends State<Tab1ItemPage> {
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(
trailing: ExitButton(),
),
navigationBar: const CupertinoNavigationBar(trailing: ExitButton()),
child: SafeArea(
top: false,
bottom: false,
@@ -349,7 +347,10 @@ class Tab1ItemPageState extends State<Tab1ItemPage> {
Text(
'Item number ${widget.index}',
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.secondaryLabel, context),
color: CupertinoDynamicColor.resolve(
CupertinoColors.secondaryLabel,
context,
),
fontSize: 16.0,
fontWeight: FontWeight.w100,
),
@@ -370,14 +371,14 @@ class Tab1ItemPageState extends State<Tab1ItemPage> {
letterSpacing: -0.28,
),
),
onPressed: () { },
onPressed: () {},
),
CupertinoButton.filled(
minSize: 30.0,
padding: EdgeInsets.zero,
borderRadius: BorderRadius.circular(32.0),
child: const Icon(CupertinoIcons.ellipsis),
onPressed: () { },
onPressed: () {},
),
],
),
@@ -420,7 +421,7 @@ class Tab1ItemPageState extends State<Tab1ItemPage> {
color: CupertinoColors.white,
size: 36.0,
),
onPressed: () { },
onPressed: () {},
),
),
),
@@ -441,9 +442,7 @@ class CupertinoDemoTab2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
trailing: trailingButtons,
),
navigationBar: CupertinoNavigationBar(trailing: trailingButtons),
child: CupertinoScrollbar(
child: ListView(
primary: true,
@@ -487,7 +486,10 @@ class Tab2Header extends StatelessWidget {
Text(
'SUPPORT TICKET',
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.secondaryLabel, context),
color: CupertinoDynamicColor.resolve(
CupertinoColors.secondaryLabel,
context,
),
letterSpacing: -0.9,
fontSize: 14.0,
fontWeight: FontWeight.w500,
@@ -496,7 +498,10 @@ class Tab2Header extends StatelessWidget {
Text(
'Show More',
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.secondaryLabel, context),
color: CupertinoDynamicColor.resolve(
CupertinoColors.secondaryLabel,
context,
),
letterSpacing: -0.6,
fontSize: 12.0,
fontWeight: FontWeight.w500,
@@ -508,7 +513,10 @@ class Tab2Header extends StatelessWidget {
),
Container(
decoration: BoxDecoration(
color: CupertinoDynamicColor.resolve(CupertinoColors.quaternarySystemFill, context),
color: CupertinoDynamicColor.resolve(
CupertinoColors.quaternarySystemFill,
context,
),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 18.0, vertical: 12.0),
@@ -583,10 +591,7 @@ class Tab2Header extends StatelessWidget {
}
}
enum Tab2ConversationBubbleColor {
blue,
gray,
}
enum Tab2ConversationBubbleColor { blue, gray }
class Tab2ConversationBubble extends StatelessWidget {
const Tab2ConversationBubble({super.key, this.text, this.color});
@@ -652,7 +657,7 @@ class Tab2ConversationAvatar extends StatelessWidget {
(color!.green - 60).clamp(0, 255),
(color!.blue - 60).clamp(0, 255),
),
]
],
),
),
margin: const EdgeInsets.only(left: 8.0, bottom: 8.0),
@@ -684,15 +689,12 @@ class Tab2ConversationRow extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: isSelf ? CrossAxisAlignment.center : CrossAxisAlignment.end,
children: <Widget>[
if (avatar != null)
avatar!,
if (avatar != null) avatar!,
CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Tab2ConversationBubble(
text: text,
color: isSelf
? Tab2ConversationBubbleColor.blue
: Tab2ConversationBubbleColor.gray,
color: isSelf ? Tab2ConversationBubbleColor.blue : Tab2ConversationBubbleColor.gray,
),
),
],
@@ -703,39 +705,22 @@ class Tab2ConversationRow extends StatelessWidget {
List<Widget> buildTab2Conversation() {
return <Widget>[
const Tab2ConversationRow(text: "My Xanadu doesn't look right"),
const Tab2ConversationRow(
text: "My Xanadu doesn't look right",
),
const Tab2ConversationRow(
avatar: Tab2ConversationAvatar(
text: 'KL',
color: Color(0xFFFD5015),
),
avatar: Tab2ConversationAvatar(text: 'KL', color: Color(0xFFFD5015)),
text: "We'll rush you a new one.\nIt's gonna be incredible",
),
const Tab2ConversationRow(text: 'Awesome thanks!'),
const Tab2ConversationRow(
text: 'Awesome thanks!',
),
const Tab2ConversationRow(
avatar: Tab2ConversationAvatar(
text: 'SJ',
color: Color(0xFF34CAD6),
),
avatar: Tab2ConversationAvatar(text: 'SJ', color: Color(0xFF34CAD6)),
text: "We'll send you our\nnewest Labrador too!",
),
const Tab2ConversationRow(text: 'Yay'),
const Tab2ConversationRow(
text: 'Yay',
),
const Tab2ConversationRow(
avatar: Tab2ConversationAvatar(
text: 'KL',
color: Color(0xFFFD5015),
),
avatar: Tab2ConversationAvatar(text: 'KL', color: Color(0xFFFD5015)),
text: "Actually there's one more thing...",
),
const Tab2ConversationRow(
text: "What's that?",
),
const Tab2ConversationRow(text: "What's that?"),
];
}
@@ -745,8 +730,8 @@ class CupertinoDemoTab3 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(trailing: trailingButtons),
backgroundColor: CupertinoColors.systemBackground,
navigationBar: CupertinoNavigationBar(trailing: trailingButtons),
backgroundColor: CupertinoColors.systemBackground,
child: ListView(
children: <Widget>[
const Padding(padding: EdgeInsets.only(top: 32.0)),
@@ -810,11 +795,7 @@ class Tab3Dialog extends StatelessWidget {
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Icon(
CupertinoIcons.profile_circled,
size: 160.0,
color: Color(0xFF646464),
),
const Icon(CupertinoIcons.profile_circled, size: 160.0, color: Color(0xFF646464)),
const Padding(padding: EdgeInsets.only(top: 18.0)),
CupertinoButton.filled(
child: const Text('Sign in'),

View File

@@ -21,9 +21,7 @@ class CupertinoPickerDemo extends StatefulWidget {
}
class _BottomPicker extends StatelessWidget {
const _BottomPicker({
required this.child,
});
const _BottomPicker({required this.child});
final Widget child;
@@ -34,17 +32,11 @@ class _BottomPicker extends StatelessWidget {
padding: const EdgeInsets.only(top: 6.0),
color: CupertinoColors.systemBackground.resolveFrom(context),
child: DefaultTextStyle(
style: TextStyle(
color: CupertinoColors.label.resolveFrom(context),
fontSize: 22.0,
),
style: TextStyle(color: CupertinoColors.label.resolveFrom(context), fontSize: 22.0),
child: GestureDetector(
// Blocks taps from propagating to the modal sheet and popping.
onTap: () { },
child: SafeArea(
top: false,
child: child,
),
onTap: () {},
child: SafeArea(top: false, child: child),
),
),
);
@@ -52,9 +44,7 @@ class _BottomPicker extends StatelessWidget {
}
class _Menu extends StatelessWidget {
const _Menu({
required this.children,
});
const _Menu({required this.children});
final List<Widget> children;
@@ -74,10 +64,7 @@ class _Menu extends StatelessWidget {
child: SafeArea(
top: false,
bottom: false,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: children,
),
child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: children),
),
),
);
@@ -99,8 +86,9 @@ class _CupertinoPickerDemoState extends State<CupertinoPickerDemo> {
DateTime dateTime = DateTime.now();
Widget _buildColorPicker(BuildContext context) {
final FixedExtentScrollController scrollController =
FixedExtentScrollController(initialItem: _selectedColorIndex);
final FixedExtentScrollController scrollController = FixedExtentScrollController(
initialItem: _selectedColorIndex,
);
return GestureDetector(
onTap: () async {
@@ -117,9 +105,7 @@ class _CupertinoPickerDemoState extends State<CupertinoPickerDemo> {
setState(() => _selectedColorIndex = index);
},
children: List<Widget>.generate(coolColorNames.length, (int index) {
return Center(
child: Text(coolColorNames[index]),
);
return Center(child: Text(coolColorNames[index]));
}),
),
);
@@ -131,7 +117,9 @@ class _CupertinoPickerDemoState extends State<CupertinoPickerDemo> {
const Text('Favorite Color'),
Text(
coolColorNames[_selectedColorIndex],
style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)),
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context),
),
),
],
),
@@ -162,9 +150,11 @@ class _CupertinoPickerDemoState extends State<CupertinoPickerDemo> {
const Text('Countdown Timer'),
Text(
'${timer.inHours}:'
'${(timer.inMinutes % 60).toString().padLeft(2,'0')}:'
'${(timer.inSeconds % 60).toString().padLeft(2,'0')}',
style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)),
'${(timer.inMinutes % 60).toString().padLeft(2, '0')}:'
'${(timer.inSeconds % 60).toString().padLeft(2, '0')}',
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context),
),
),
],
),
@@ -196,9 +186,11 @@ class _CupertinoPickerDemoState extends State<CupertinoPickerDemo> {
const Text('Date'),
Text(
DateFormat.yMMMMd().format(date),
style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)),
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context),
),
),
]
],
),
);
}
@@ -228,7 +220,9 @@ class _CupertinoPickerDemoState extends State<CupertinoPickerDemo> {
const Text('Time'),
Text(
DateFormat.jm().format(time),
style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)),
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context),
),
),
],
),
@@ -259,7 +253,9 @@ class _CupertinoPickerDemoState extends State<CupertinoPickerDemo> {
const Text('Date and Time'),
Text(
DateFormat.yMMMd().add_jm().format(dateTime),
style: TextStyle(color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context)),
style: TextStyle(
color: CupertinoDynamicColor.resolve(CupertinoColors.inactiveGray, context),
),
),
],
),

View File

@@ -28,14 +28,11 @@ class _CupertinoRefreshControlDemoState extends State<CupertinoRefreshControlDem
void repopulateList() {
final Random random = Random();
randomizedContacts = List<List<String>>.generate(
100,
(int index) {
return contacts[random.nextInt(contacts.length)]
// Randomly adds a telephone icon next to the contact or not.
..add(random.nextBool().toString());
},
);
randomizedContacts = List<List<String>>.generate(100, (int index) {
return contacts[random.nextInt(contacts.length)]
// Randomly adds a telephone icon next to the contact or not.
..add(random.nextBool().toString());
});
}
@override
@@ -65,28 +62,24 @@ class _CupertinoRefreshControlDemoState extends State<CupertinoRefreshControlDem
),
CupertinoSliverRefreshControl(
onRefresh: () {
return Future<void>.delayed(const Duration(seconds: 2))
..then((_) {
if (mounted) {
setState(() => repopulateList());
}
return Future<void>.delayed(const Duration(seconds: 2))..then((_) {
if (mounted) {
setState(() => repopulateList());
}
});
},
),
SliverSafeArea(
top: false, // Top safe area is consumed by the navigation bar.
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return _ListItem(
name: randomizedContacts[index][0],
place: randomizedContacts[index][1],
date: randomizedContacts[index][2],
called: randomizedContacts[index][3] == 'true',
);
},
childCount: 20,
),
delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
return _ListItem(
name: randomizedContacts[index][0],
place: randomizedContacts[index][1],
date: randomizedContacts[index][2],
called: randomizedContacts[index][3] == 'true',
);
}, childCount: 20),
),
),
],
@@ -144,12 +137,7 @@ List<List<String>> contacts = <List<String>>[
];
class _ListItem extends StatelessWidget {
const _ListItem({
this.name,
this.place,
this.date,
this.called,
});
const _ListItem({this.name, this.place, this.date, this.called});
final String? name;
final String? place;
@@ -166,23 +154,22 @@ class _ListItem extends StatelessWidget {
children: <Widget>[
SizedBox(
width: 38.0,
child: called!
? Align(
alignment: Alignment.topCenter,
child: Icon(
CupertinoIcons.phone_solid,
color: CupertinoColors.inactiveGray.resolveFrom(context),
size: 18.0,
),
)
: null,
child:
called!
? Align(
alignment: Alignment.topCenter,
child: Icon(
CupertinoIcons.phone_solid,
color: CupertinoColors.inactiveGray.resolveFrom(context),
size: 18.0,
),
)
: null,
),
Expanded(
child: Container(
Expanded(
child: Container(
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(color: Color(0xFFBCBBC1), width: 0.0),
),
border: Border(bottom: BorderSide(color: Color(0xFFBCBBC1), width: 0.0)),
),
padding: const EdgeInsets.only(left: 1.0, bottom: 9.0, right: 10.0),
child: Row(
@@ -196,10 +183,7 @@ class _ListItem extends StatelessWidget {
name!,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontWeight: FontWeight.w600,
letterSpacing: -0.18,
),
style: const TextStyle(fontWeight: FontWeight.w600, letterSpacing: -0.18),
),
Text(
place!,

View File

@@ -27,21 +27,9 @@ class _CupertinoSegmentedControlDemoState extends State<CupertinoSegmentedContro
};
final Map<int, Widget> icons = const <int, Widget>{
0: Center(
child: FlutterLogo(
size: 100.0,
),
),
1: Center(
child: FlutterLogo(
size: 200.0,
),
),
2: Center(
child: FlutterLogo(
size: 300.0,
),
),
0: Center(child: FlutterLogo(size: 100.0)),
1: Center(child: FlutterLogo(size: 200.0)),
2: Center(child: FlutterLogo(size: 300.0)),
};
int? currentSegment = 0;
@@ -90,19 +78,13 @@ class _CupertinoSegmentedControlDemoState extends State<CupertinoSegmentedContro
),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 32.0,
horizontal: 16.0,
),
padding: const EdgeInsets.symmetric(vertical: 32.0, horizontal: 16.0),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Builder(
builder: (BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(
vertical: 64.0,
horizontal: 16.0,
),
padding: const EdgeInsets.symmetric(vertical: 64.0, horizontal: 16.0),
decoration: BoxDecoration(
color: CupertinoTheme.of(context).scaffoldBackgroundColor,
borderRadius: BorderRadius.circular(3.0),

View File

@@ -39,7 +39,7 @@ class _CupertinoSliderDemoState extends State<CupertinoSliderDemo> {
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget> [
children: <Widget>[
CupertinoSlider(
value: _value,
max: 100.0,
@@ -54,7 +54,7 @@ class _CupertinoSliderDemoState extends State<CupertinoSliderDemo> {
),
Column(
mainAxisSize: MainAxisSize.min,
children: <Widget> [
children: <Widget>[
CupertinoSlider(
value: _discreteValue,
max: 100.0,

View File

@@ -16,7 +16,6 @@ class CupertinoSwitchDemo extends StatefulWidget {
}
class _CupertinoSwitchDemoState extends State<CupertinoSwitchDemo> {
bool _switchValue = false;
@override
@@ -49,9 +48,7 @@ class _CupertinoSwitchDemoState extends State<CupertinoSwitchDemo> {
});
},
),
Text(
"Enabled - ${_switchValue ? "On" : "Off"}"
),
Text("Enabled - ${_switchValue ? "On" : "Off"}"),
],
),
),
@@ -59,13 +56,8 @@ class _CupertinoSwitchDemoState extends State<CupertinoSwitchDemo> {
container: true,
child: const Column(
children: <Widget>[
CupertinoSwitch(
value: true,
onChanged: null,
),
Text(
'Disabled - On'
),
CupertinoSwitch(value: true, onChanged: null),
Text('Disabled - On'),
],
),
),
@@ -73,13 +65,8 @@ class _CupertinoSwitchDemoState extends State<CupertinoSwitchDemo> {
container: true,
child: const Column(
children: <Widget>[
CupertinoSwitch(
value: false,
onChanged: null,
),
Text(
'Disabled - Off'
),
CupertinoSwitch(value: false, onChanged: null),
Text('Disabled - Off'),
],
),
),

View File

@@ -32,10 +32,7 @@ class _CupertinoTextFieldDemoState extends State<CupertinoTextFieldDemo> {
textCapitalization: TextCapitalization.sentences,
placeholder: 'Text Message',
decoration: BoxDecoration(
border: Border.all(
width: 0.0,
color: CupertinoColors.inactiveGray,
),
border: Border.all(width: 0.0, color: CupertinoColors.inactiveGray),
borderRadius: BorderRadius.circular(15.0),
),
maxLines: null,
@@ -56,7 +53,7 @@ class _CupertinoTextFieldDemoState extends State<CupertinoTextFieldDemo> {
),
autofocus: true,
suffixMode: OverlayVisibilityMode.editing,
onSubmitted: (String text)=> setState(()=> _chatTextController!.clear()),
onSubmitted: (String text) => setState(() => _chatTextController!.clear()),
);
}

View File

@@ -33,7 +33,7 @@ class FortnightlyDemo extends StatelessWidget {
}
class ShortAppBar extends StatelessWidget {
const ShortAppBar({ super.key, this.onBackPressed });
const ShortAppBar({super.key, this.onBackPressed});
final VoidCallback? onBackPressed;
@@ -115,19 +115,13 @@ over water meant for the whole central valley of California? The story will shoc
children: <Widget>[
Row(
children: <Widget>[
Text(
'US',
style: textTheme.labelSmall,
),
Text('US', style: textTheme.labelSmall),
Text(
' ¬ ',
// TODO(larche): Replace textTheme.headline2.color with a ColorScheme value when known.
style: textTheme.labelSmall!.apply(color: textTheme.displayMedium!.color),
),
Text(
'CULTURE',
style: textTheme.labelSmall,
),
Text('CULTURE', style: textTheme.labelSmall),
],
),
const SizedBox(height: 10),
@@ -138,7 +132,7 @@ over water meant for the whole central valley of California? The story will shoc
const SizedBox(height: 10),
Text(
'How these crazy fruits sweetened our hearts, relationships, '
'and puffed pastries',
'and puffed pastries',
style: textTheme.bodyMedium,
),
Padding(
@@ -153,10 +147,7 @@ over water meant for the whole central valley of California? The story will shoc
radius: 20,
),
const SizedBox(width: 12),
Text(
'by',
style: textTheme.displayMedium,
),
Text('by', style: textTheme.displayMedium),
const SizedBox(width: 4),
const Text(
'Connor Eghan',
@@ -170,10 +161,7 @@ over water meant for the whole central valley of California? The story will shoc
],
),
),
Text(
'$paragraph1\n\n$paragraph2',
style: textTheme.bodyLarge,
),
Text('$paragraph1\n\n$paragraph2', style: textTheme.bodyLarge),
],
),
),

View File

@@ -11,7 +11,7 @@ import 'package:flutter/material.dart';
// (CategoryView) on top of the backdrop.
class Category {
const Category({ this.title, this.assets });
const Category({this.title, this.assets});
final String? title;
final List<String>? assets;
@override
@@ -95,7 +95,7 @@ const List<Category> allCategories = <Category>[
];
class CategoryView extends StatelessWidget {
const CategoryView({ super.key, this.category });
const CategoryView({super.key, this.category});
final Category? category;
@@ -106,41 +106,36 @@ class CategoryView extends StatelessWidget {
child: ListView(
primary: true,
key: PageStorageKey<Category?>(category),
padding: const EdgeInsets.symmetric(
vertical: 16.0,
horizontal: 64.0,
),
children: category!.assets!.map<Widget>((String asset) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Card(
child: Container(
width: 144.0,
alignment: Alignment.center,
child: Column(
children: <Widget>[
Image.asset(
asset,
package: 'flutter_gallery_assets',
fit: BoxFit.contain,
padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 64.0),
children:
category!.assets!.map<Widget>((String asset) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Card(
child: Container(
width: 144.0,
alignment: Alignment.center,
child: Column(
children: <Widget>[
Image.asset(
asset,
package: 'flutter_gallery_assets',
fit: BoxFit.contain,
),
Container(
padding: const EdgeInsets.only(bottom: 16.0),
alignment: AlignmentDirectional.center,
child: Text(asset, style: theme.textTheme.bodySmall),
),
],
),
Container(
padding: const EdgeInsets.only(bottom: 16.0),
alignment: AlignmentDirectional.center,
child: Text(
asset,
style: theme.textTheme.bodySmall,
),
),
],
),
),
),
),
const SizedBox(height: 24.0),
],
);
}).toList(),
const SizedBox(height: 24.0),
],
);
}).toList(),
),
);
}
@@ -187,10 +182,7 @@ class BackdropPanel extends StatelessWidget {
alignment: AlignmentDirectional.centerStart,
child: DefaultTextStyle(
style: theme.textTheme.titleMedium!,
child: Tooltip(
message: 'Tap to dismiss',
child: title,
),
child: Tooltip(message: 'Tap to dismiss', child: title),
),
),
),
@@ -204,10 +196,7 @@ class BackdropPanel extends StatelessWidget {
// Cross fades between 'Select a Category' and 'Asset Viewer'.
class BackdropTitle extends AnimatedWidget {
const BackdropTitle({
super.key,
required Animation<double> super.listenable,
});
const BackdropTitle({super.key, required Animation<double> super.listenable});
@override
Widget build(BuildContext context) {
@@ -219,17 +208,15 @@ class BackdropTitle extends AnimatedWidget {
child: Stack(
children: <Widget>[
Opacity(
opacity: CurvedAnimation(
parent: ReverseAnimation(animation),
curve: const Interval(0.5, 1.0),
).value,
opacity:
CurvedAnimation(
parent: ReverseAnimation(animation),
curve: const Interval(0.5, 1.0),
).value,
child: const Text('Select a Category'),
),
Opacity(
opacity: CurvedAnimation(
parent: animation,
curve: const Interval(0.5, 1.0),
).value,
opacity: CurvedAnimation(parent: animation, curve: const Interval(0.5, 1.0)).value,
child: const Text('Asset Viewer'),
),
],
@@ -302,11 +289,13 @@ class _BackdropDemoState extends State<BackdropDemo> with SingleTickerProviderSt
}
final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight;
_controller.fling(velocity: switch (flingVelocity) {
< 0.0 => math.max(2.0, -flingVelocity),
> 0.0 => math.min(-2.0, -flingVelocity),
_ => _controller.value < 0.5 ? -2.0 : 2.0,
});
_controller.fling(
velocity: switch (flingVelocity) {
< 0.0 => math.max(2.0, -flingVelocity),
> 0.0 => math.min(-2.0, -flingVelocity),
_ => _controller.value < 0.5 ? -2.0 : 2.0,
},
);
}
// Stacks a BackdropPanel, which displays the selected category, on top
@@ -332,24 +321,23 @@ class _BackdropDemoState extends State<BackdropDemo> with SingleTickerProviderSt
);
final ThemeData theme = Theme.of(context);
final List<Widget> backdropItems = allCategories.map<Widget>((Category category) {
final bool selected = category == _category;
return Material(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
color: selected
? Colors.white.withOpacity(0.25)
: Colors.transparent,
child: ListTile(
title: Text(category.title!),
selected: selected,
onTap: () {
_changeCategory(category);
},
),
);
}).toList();
final List<Widget> backdropItems =
allCategories.map<Widget>((Category category) {
final bool selected = category == _category;
return Material(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
),
color: selected ? Colors.white.withOpacity(0.25) : Colors.transparent,
child: ListTile(
title: Text(category.title!),
selected: selected,
onTap: () {
_changeCategory(category);
},
),
);
}).toList();
return ColoredBox(
key: _backdropKey,
@@ -388,9 +376,7 @@ class _BackdropDemoState extends State<BackdropDemo> with SingleTickerProviderSt
return Scaffold(
appBar: AppBar(
elevation: 0.0,
title: BackdropTitle(
listenable: _controller.view,
),
title: BackdropTitle(listenable: _controller.view),
actions: <Widget>[
IconButton(
onPressed: _toggleBackdropPanelVisibility,
@@ -402,9 +388,7 @@ class _BackdropDemoState extends State<BackdropDemo> with SingleTickerProviderSt
),
],
),
body: LayoutBuilder(
builder: _buildStack,
),
body: LayoutBuilder(builder: _buildStack),
);
}
}

View File

@@ -6,14 +6,10 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
enum BannerDemoAction {
reset,
showMultipleActions,
showLeading,
}
enum BannerDemoAction { reset, showMultipleActions, showLeading }
class BannerDemo extends StatefulWidget {
const BannerDemo({ super.key });
const BannerDemo({super.key});
static const String routeName = '/material/banner';
@@ -75,32 +71,36 @@ class _BannerDemoState extends State<BannerDemo> {
MaterialDemoDocumentationButton(BannerDemo.routeName),
PopupMenuButton<BannerDemoAction>(
onSelected: handleDemoAction,
itemBuilder: (BuildContext context) => <PopupMenuEntry<BannerDemoAction>>[
const PopupMenuItem<BannerDemoAction>(
value: BannerDemoAction.reset,
child: Text('Reset the banner'),
),
const PopupMenuDivider(),
CheckedPopupMenuItem<BannerDemoAction>(
value: BannerDemoAction.showMultipleActions,
checked: _showMultipleActions,
child: const Text('Multiple actions'),
),
CheckedPopupMenuItem<BannerDemoAction>(
value: BannerDemoAction.showLeading,
checked: _showLeading,
child: const Text('Leading icon'),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuEntry<BannerDemoAction>>[
const PopupMenuItem<BannerDemoAction>(
value: BannerDemoAction.reset,
child: Text('Reset the banner'),
),
const PopupMenuDivider(),
CheckedPopupMenuItem<BannerDemoAction>(
value: BannerDemoAction.showMultipleActions,
checked: _showMultipleActions,
child: const Text('Multiple actions'),
),
CheckedPopupMenuItem<BannerDemoAction>(
value: BannerDemoAction.showLeading,
checked: _showLeading,
child: const Text('Leading icon'),
),
],
),
],
),
body: ListView.builder(itemCount: _displayBanner ? _numItems + 1 : _numItems, itemBuilder: (BuildContext context, int index) {
if (index == 0 && _displayBanner) {
return banner;
}
return ListTile(title: Text('Item ${_displayBanner ? index : index + 1}'),);
}),
body: ListView.builder(
itemCount: _displayBanner ? _numItems + 1 : _numItems,
itemBuilder: (BuildContext context, int index) {
if (index == 0 && _displayBanner) {
return banner;
}
return ListTile(title: Text('Item ${_displayBanner ? index : index + 1}'));
},
),
);
}
}

View File

@@ -20,7 +20,8 @@ class BottomAppBarDemo extends StatefulWidget {
// for bottom application bar.
class _BottomAppBarDemoState extends State<BottomAppBarDemo> {
static final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey = GlobalKey<ScaffoldMessengerState>();
static final GlobalKey<ScaffoldMessengerState> _scaffoldMessengerKey =
GlobalKey<ScaffoldMessengerState>();
// FAB shape
@@ -42,10 +43,7 @@ class _BottomAppBarDemoState extends State<BottomAppBarDemo> {
static const _ChoiceValue<Widget> kDiamondFab = _ChoiceValue<Widget>(
title: 'Diamond',
label: 'diamond shape floating action button',
value: _DiamondFab(
onPressed: _showSnackbar,
child: Icon(Icons.add, semanticLabel: 'Action'),
),
value: _DiamondFab(onPressed: _showSnackbar, child: Icon(Icons.add, semanticLabel: 'Action')),
);
// Notch
@@ -64,38 +62,40 @@ class _BottomAppBarDemoState extends State<BottomAppBarDemo> {
// FAB Position
static const _ChoiceValue<FloatingActionButtonLocation> kFabEndDocked = _ChoiceValue<FloatingActionButtonLocation>(
title: 'Attached - End',
label: 'floating action button is docked at the end of the bottom app bar',
value: FloatingActionButtonLocation.endDocked,
);
static const _ChoiceValue<FloatingActionButtonLocation> kFabEndDocked =
_ChoiceValue<FloatingActionButtonLocation>(
title: 'Attached - End',
label: 'floating action button is docked at the end of the bottom app bar',
value: FloatingActionButtonLocation.endDocked,
);
static const _ChoiceValue<FloatingActionButtonLocation> kFabCenterDocked = _ChoiceValue<FloatingActionButtonLocation>(
title: 'Attached - Center',
label: 'floating action button is docked at the center of the bottom app bar',
value: FloatingActionButtonLocation.centerDocked,
);
static const _ChoiceValue<FloatingActionButtonLocation> kFabCenterDocked =
_ChoiceValue<FloatingActionButtonLocation>(
title: 'Attached - Center',
label: 'floating action button is docked at the center of the bottom app bar',
value: FloatingActionButtonLocation.centerDocked,
);
static const _ChoiceValue<FloatingActionButtonLocation> kFabEndFloat= _ChoiceValue<FloatingActionButtonLocation>(
title: 'Free - End',
label: 'floating action button floats above the end of the bottom app bar',
value: FloatingActionButtonLocation.endFloat,
);
static const _ChoiceValue<FloatingActionButtonLocation> kFabEndFloat =
_ChoiceValue<FloatingActionButtonLocation>(
title: 'Free - End',
label: 'floating action button floats above the end of the bottom app bar',
value: FloatingActionButtonLocation.endFloat,
);
static const _ChoiceValue<FloatingActionButtonLocation> kFabCenterFloat = _ChoiceValue<FloatingActionButtonLocation>(
title: 'Free - Center',
label: 'floating action button is floats above the center of the bottom app bar',
value: FloatingActionButtonLocation.centerFloat,
);
static const _ChoiceValue<FloatingActionButtonLocation> kFabCenterFloat =
_ChoiceValue<FloatingActionButtonLocation>(
title: 'Free - Center',
label: 'floating action button is floats above the center of the bottom app bar',
value: FloatingActionButtonLocation.centerFloat,
);
static void _showSnackbar() {
const String text =
"When the Scaffold's floating action button location changes, "
'the floating action button animates to its new position. '
'The BottomAppBar adapts its shape appropriately.';
_scaffoldMessengerKey.currentState!.showSnackBar(
const SnackBar(content: Text(text)),
);
"When the Scaffold's floating action button location changes, "
'the floating action button animates to its new position. '
'The BottomAppBar adapts its shape appropriately.';
_scaffoldMessengerKey.currentState!.showSnackBar(const SnackBar(content: Text(text)));
}
// App bar color
@@ -143,62 +143,79 @@ class _BottomAppBarDemoState extends State<BottomAppBarDemo> {
return ScaffoldMessenger(
key: _scaffoldMessengerKey,
child: Builder(
builder: (BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Bottom app bar'),
elevation: 0.0,
actions: <Widget>[
MaterialDemoDocumentationButton(BottomAppBarDemo.routeName),
IconButton(
icon: const Icon(Icons.sentiment_very_satisfied, semanticLabel: 'Update shape'),
onPressed: () {
setState(() {
_fabShape = _fabShape == kCircularFab ? kDiamondFab : kCircularFab;
});
},
builder:
(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Bottom app bar'),
elevation: 0.0,
actions: <Widget>[
MaterialDemoDocumentationButton(BottomAppBarDemo.routeName),
IconButton(
icon: const Icon(Icons.sentiment_very_satisfied, semanticLabel: 'Update shape'),
onPressed: () {
setState(() {
_fabShape = _fabShape == kCircularFab ? kDiamondFab : kCircularFab;
});
},
),
],
),
],
),
body: Scrollbar(
child: ListView(
primary: true,
padding: const EdgeInsets.only(bottom: 88.0),
children: <Widget>[
const _Heading('FAB Shape'),
body: Scrollbar(
child: ListView(
primary: true,
padding: const EdgeInsets.only(bottom: 88.0),
children: <Widget>[
const _Heading('FAB Shape'),
_RadioItem<Widget>(kCircularFab, _fabShape, _onFabShapeChanged),
_RadioItem<Widget>(kDiamondFab, _fabShape, _onFabShapeChanged),
_RadioItem<Widget>(kNoFab, _fabShape, _onFabShapeChanged),
_RadioItem<Widget>(kCircularFab, _fabShape, _onFabShapeChanged),
_RadioItem<Widget>(kDiamondFab, _fabShape, _onFabShapeChanged),
_RadioItem<Widget>(kNoFab, _fabShape, _onFabShapeChanged),
const Divider(),
const _Heading('Notch'),
const Divider(),
const _Heading('Notch'),
_RadioItem<bool>(kShowNotchTrue, _showNotch, _onShowNotchChanged),
_RadioItem<bool>(kShowNotchFalse, _showNotch, _onShowNotchChanged),
_RadioItem<bool>(kShowNotchTrue, _showNotch, _onShowNotchChanged),
_RadioItem<bool>(kShowNotchFalse, _showNotch, _onShowNotchChanged),
const Divider(),
const _Heading('FAB Position'),
const Divider(),
const _Heading('FAB Position'),
_RadioItem<FloatingActionButtonLocation>(kFabEndDocked, _fabLocation, _onFabLocationChanged),
_RadioItem<FloatingActionButtonLocation>(kFabCenterDocked, _fabLocation, _onFabLocationChanged),
_RadioItem<FloatingActionButtonLocation>(kFabEndFloat, _fabLocation, _onFabLocationChanged),
_RadioItem<FloatingActionButtonLocation>(kFabCenterFloat, _fabLocation, _onFabLocationChanged),
_RadioItem<FloatingActionButtonLocation>(
kFabEndDocked,
_fabLocation,
_onFabLocationChanged,
),
_RadioItem<FloatingActionButtonLocation>(
kFabCenterDocked,
_fabLocation,
_onFabLocationChanged,
),
_RadioItem<FloatingActionButtonLocation>(
kFabEndFloat,
_fabLocation,
_onFabLocationChanged,
),
_RadioItem<FloatingActionButtonLocation>(
kFabCenterFloat,
_fabLocation,
_onFabLocationChanged,
),
const Divider(),
const _Heading('App bar color'),
const Divider(),
const _Heading('App bar color'),
_ColorsItem(kBabColors, _babColor, _onBabColorChanged),
],
_ColorsItem(kBabColors, _babColor, _onBabColorChanged),
],
),
),
floatingActionButton: _fabShape.value,
floatingActionButtonLocation: _fabLocation.value,
bottomNavigationBar: _DemoBottomAppBar(
color: _babColor,
fabLocation: _fabLocation.value,
shape: _selectNotch(),
),
),
),
floatingActionButton: _fabShape.value,
floatingActionButtonLocation: _fabLocation.value,
bottomNavigationBar: _DemoBottomAppBar(
color: _babColor,
fabLocation: _fabLocation.value,
shape: _selectNotch(),
),
),
),
);
}
@@ -218,7 +235,7 @@ class _BottomAppBarDemoState extends State<BottomAppBarDemo> {
}
class _ChoiceValue<T> {
const _ChoiceValue({ this.value, this.title, this.label });
const _ChoiceValue({this.value, this.title, this.label});
final T? value;
final String? title;
@@ -245,11 +262,7 @@ class _RadioItem<T> extends StatelessWidget {
child: MergeSemantics(
child: Row(
children: <Widget>[
Radio<_ChoiceValue<T>>(
value: value,
groupValue: groupValue,
onChanged: onChanged,
),
Radio<_ChoiceValue<T>>(value: value, groupValue: groupValue, onChanged: onChanged),
Expanded(
child: Semantics(
container: true,
@@ -260,10 +273,7 @@ class _RadioItem<T> extends StatelessWidget {
onTap: () {
onChanged(value);
},
child: Text(
value.title!,
style: theme.textTheme.titleMedium,
),
child: Text(value.title!, style: theme.textTheme.titleMedium),
),
),
),
@@ -292,28 +302,23 @@ class _ColorsItem extends StatelessWidget {
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: colors.map<Widget>((_NamedColor namedColor) {
return RawMaterialButton(
onPressed: () {
onChanged(namedColor.color);
},
constraints: const BoxConstraints.tightFor(
width: 32.0,
height: 32.0,
),
fillColor: namedColor.color,
shape: CircleBorder(
side: BorderSide(
color: namedColor.color == selectedColor ? Colors.black : const Color(0xFFD5D7DA),
width: 2.0,
),
),
child: Semantics(
value: namedColor.name,
selected: namedColor.color == selectedColor,
),
);
}).toList(),
children:
colors.map<Widget>((_NamedColor namedColor) {
return RawMaterialButton(
onPressed: () {
onChanged(namedColor.color);
},
constraints: const BoxConstraints.tightFor(width: 32.0, height: 32.0),
fillColor: namedColor.color,
shape: CircleBorder(
side: BorderSide(
color: namedColor.color == selectedColor ? Colors.black : const Color(0xFFD5D7DA),
width: 2.0,
),
),
child: Semantics(value: namedColor.name, selected: namedColor.color == selectedColor),
);
}).toList(),
);
}
}
@@ -330,20 +335,13 @@ class _Heading extends StatelessWidget {
height: 48.0,
padding: const EdgeInsetsDirectional.only(start: 56.0),
alignment: AlignmentDirectional.centerStart,
child: Text(
text,
style: theme.textTheme.bodyLarge,
),
child: Text(text, style: theme.textTheme.bodyLarge),
);
}
}
class _DemoBottomAppBar extends StatelessWidget {
const _DemoBottomAppBar({
this.color,
this.fabLocation,
this.shape,
});
const _DemoBottomAppBar({this.color, this.fabLocation, this.shape});
final Color? color;
final FloatingActionButtonLocation? fabLocation;
@@ -359,39 +357,39 @@ class _DemoBottomAppBar extends StatelessWidget {
return BottomAppBar(
color: color,
shape: shape,
child: Row(children: <Widget>[
IconButton(
icon: const Icon(Icons.menu, semanticLabel: 'Show bottom sheet'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) => const _DemoDrawer(),
);
},
),
if (kCenterLocations.contains(fabLocation)) const Expanded(child: SizedBox()),
IconButton(
icon: const Icon(Icons.search, semanticLabel: 'show search action',),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('This is a dummy search action.')),
);
},
),
IconButton(
icon: Icon(
Theme.of(context).platform == TargetPlatform.iOS
? Icons.more_horiz
: Icons.more_vert,
semanticLabel: 'Show menu actions',
child: Row(
children: <Widget>[
IconButton(
icon: const Icon(Icons.menu, semanticLabel: 'Show bottom sheet'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) => const _DemoDrawer(),
);
},
),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('This is a dummy menu action.')),
);
},
),
]),
if (kCenterLocations.contains(fabLocation)) const Expanded(child: SizedBox()),
IconButton(
icon: const Icon(Icons.search, semanticLabel: 'show search action'),
onPressed: () {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('This is a dummy search action.')));
},
),
IconButton(
icon: Icon(
Theme.of(context).platform == TargetPlatform.iOS ? Icons.more_horiz : Icons.more_vert,
semanticLabel: 'Show menu actions',
),
onPressed: () {
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('This is a dummy menu action.')));
},
),
],
),
);
}
}
@@ -405,14 +403,8 @@ class _DemoDrawer extends StatelessWidget {
return const Drawer(
child: Column(
children: <Widget>[
ListTile(
leading: Icon(Icons.search),
title: Text('Search'),
),
ListTile(
leading: Icon(Icons.threed_rotation),
title: Text('3D'),
),
ListTile(leading: Icon(Icons.search), title: Text('Search')),
ListTile(leading: Icon(Icons.threed_rotation), title: Text('3D')),
],
),
);
@@ -421,10 +413,7 @@ class _DemoDrawer extends StatelessWidget {
// A diamond-shaped floating action button.
class _DiamondFab extends StatelessWidget {
const _DiamondFab({
this.child,
this.onPressed,
});
const _DiamondFab({this.child, this.onPressed});
final Widget? child;
final VoidCallback? onPressed;
@@ -473,9 +462,7 @@ class _DiamondNotchedRectangle implements NotchedShape {
// notchToCenter is the horizontal distance between the guest's center and
// the host's top edge where the notch starts (marked with "*").
// We compute notchToCenter by similar triangles:
final double notchToCenter =
intersection.height * (guest.height / 2.0)
/ (guest.width / 2.0);
final double notchToCenter = intersection.height * (guest.height / 2.0) / (guest.width / 2.0);
return Path()
..moveTo(host.left, host.top)
@@ -498,22 +485,22 @@ class _DiamondBorder extends ShapeBorder {
}
@override
Path getInnerPath(Rect rect, { TextDirection? textDirection }) {
Path getInnerPath(Rect rect, {TextDirection? textDirection}) {
return getOuterPath(rect, textDirection: textDirection);
}
@override
Path getOuterPath(Rect rect, { TextDirection? textDirection }) {
Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
return Path()
..moveTo(rect.left + rect.width / 2.0, rect.top)
..lineTo(rect.right, rect.top + rect.height / 2.0)
..lineTo(rect.left + rect.width / 2.0, rect.bottom)
..lineTo(rect.left + rect.width / 2.0, rect.bottom)
..lineTo(rect.left, rect.top + rect.height / 2.0)
..close();
}
@override
void paint(Canvas canvas, Rect rect, { TextDirection? textDirection }) { }
void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {}
// This border doesn't support scaling.
@override

View File

@@ -22,13 +22,10 @@ class NavigationIconView {
label: title,
backgroundColor: color,
),
controller = AnimationController(
duration: kThemeAnimationDuration,
vsync: vsync,
) {
_animation = controller.drive(CurveTween(
curve: const Interval(0.5, 1.0, curve: Curves.fastOutSlowIn),
));
controller = AnimationController(duration: kThemeAnimationDuration, vsync: vsync) {
_animation = controller.drive(
CurveTween(curve: const Interval(0.5, 1.0, curve: Curves.fastOutSlowIn)),
);
}
final Widget _icon;
@@ -47,7 +44,7 @@ class NavigationIconView {
final ThemeData theme = Theme.of(context);
iconColor = switch (theme.brightness) {
Brightness.light => theme.colorScheme.primary,
Brightness.dark => theme.colorScheme.secondary,
Brightness.dark => theme.colorScheme.secondary,
};
}
@@ -61,14 +58,8 @@ class NavigationIconView {
),
),
child: IconTheme(
data: IconThemeData(
color: iconColor,
size: 120.0,
),
child: Semantics(
label: 'Placeholder for $_title tab',
child: _icon,
),
data: IconThemeData(color: iconColor, size: 120.0),
child: Semantics(label: 'Placeholder for $_title tab', child: _icon),
),
),
);
@@ -100,9 +91,7 @@ class CustomInactiveIcon extends StatelessWidget {
margin: const EdgeInsets.all(4.0),
width: iconTheme.size! - 8.0,
height: iconTheme.size! - 8.0,
decoration: BoxDecoration(
border: Border.all(color: iconTheme.color!, width: 2.0),
),
decoration: BoxDecoration(border: Border.all(color: iconTheme.color!, width: 2.0)),
);
}
}
@@ -116,8 +105,7 @@ class BottomNavigationDemo extends StatefulWidget {
State<BottomNavigationDemo> createState() => _BottomNavigationDemoState();
}
class _BottomNavigationDemoState extends State<BottomNavigationDemo>
with TickerProviderStateMixin {
class _BottomNavigationDemoState extends State<BottomNavigationDemo> with TickerProviderStateMixin {
int _currentIndex = 0;
BottomNavigationBarType _type = BottomNavigationBarType.shifting;
late List<NavigationIconView> _navigationViews;
@@ -192,9 +180,12 @@ class _BottomNavigationDemoState extends State<BottomNavigationDemo>
@override
Widget build(BuildContext context) {
final BottomNavigationBar botNavBar = BottomNavigationBar(
items: _navigationViews
.map<BottomNavigationBarItem>((NavigationIconView navigationView) => navigationView.item)
.toList(),
items:
_navigationViews
.map<BottomNavigationBarItem>(
(NavigationIconView navigationView) => navigationView.item,
)
.toList(),
currentIndex: _currentIndex,
type: _type,
onTap: (int index) {
@@ -217,22 +208,21 @@ class _BottomNavigationDemoState extends State<BottomNavigationDemo>
_type = value;
});
},
itemBuilder: (BuildContext context) => <PopupMenuItem<BottomNavigationBarType>>[
const PopupMenuItem<BottomNavigationBarType>(
value: BottomNavigationBarType.fixed,
child: Text('Fixed'),
),
const PopupMenuItem<BottomNavigationBarType>(
value: BottomNavigationBarType.shifting,
child: Text('Shifting'),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuItem<BottomNavigationBarType>>[
const PopupMenuItem<BottomNavigationBarType>(
value: BottomNavigationBarType.fixed,
child: Text('Fixed'),
),
const PopupMenuItem<BottomNavigationBarType>(
value: BottomNavigationBarType.shifting,
child: Text('Shifting'),
),
],
),
],
),
body: Center(
child: _buildTransitionsStack(),
),
body: Center(child: _buildTransitionsStack()),
bottomNavigationBar: botNavBar,
);
}

View File

@@ -12,7 +12,8 @@ const String _elevatedText =
const String _elevatedCode = 'buttons_elevated';
const String _textText = 'A text button displays an ink splash on press '
const String _textText =
'A text button displays an ink splash on press '
'but does not lift. Use text buttons on toolbars, in dialogs and '
'inline with padding';
@@ -100,7 +101,8 @@ class _ButtonsDemoState extends State<ButtonsDemo> {
description: _actionText,
demoWidget: buildActionButton(),
exampleCodeTag: _actionCode,
documentationUrl: 'https://api.flutter.dev/flutter/material/FloatingActionButton-class.html',
documentationUrl:
'https://api.flutter.dev/flutter/material/FloatingActionButton-class.html',
),
];
@@ -189,7 +191,7 @@ class _ButtonsDemoState extends State<ButtonsDemo> {
),
const TextButton(
onPressed: null,
child: Text('DISABLED', semanticsLabel: 'DISABLED BUTTON 3',),
child: Text('DISABLED', semanticsLabel: 'DISABLED BUTTON 3'),
),
],
),
@@ -285,17 +287,15 @@ class _ButtonsDemoState extends State<ButtonsDemo> {
dropdown1Value = newValue;
});
},
items: <String>['One', 'Two', 'Free', 'Four'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
items:
<String>['One', 'Two', 'Free', 'Four'].map<DropdownMenuItem<String>>((
String value,
) {
return DropdownMenuItem<String>(value: value, child: Text(value));
}).toList(),
),
),
const SizedBox(
height: 24.0,
),
const SizedBox(height: 24.0),
ListTile(
title: const Text('Dropdown with a hint:'),
trailing: DropdownButton<String>(
@@ -306,17 +306,15 @@ class _ButtonsDemoState extends State<ButtonsDemo> {
dropdown2Value = newValue;
});
},
items: <String>['One', 'Two', 'Free', 'Four'].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
items:
<String>['One', 'Two', 'Free', 'Four'].map<DropdownMenuItem<String>>((
String value,
) {
return DropdownMenuItem<String>(value: value, child: Text(value));
}).toList(),
),
),
const SizedBox(
height: 24.0,
),
const SizedBox(height: 24.0),
ListTile(
title: const Text('Scrollable dropdown:'),
trailing: DropdownButton<String>(
@@ -326,18 +324,29 @@ class _ButtonsDemoState extends State<ButtonsDemo> {
dropdown3Value = newValue;
});
},
items: <String>[
'One', 'Two', 'Free', 'Four', 'Can', 'I', 'Have', 'A', 'Little',
'Bit', 'More', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten',
]
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
})
.toList(),
),
items:
<String>[
'One',
'Two',
'Free',
'Four',
'Can',
'I',
'Have',
'A',
'Little',
'Bit',
'More',
'Five',
'Six',
'Seven',
'Eight',
'Nine',
'Ten',
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(value: value, child: Text(value));
}).toList(),
),
),
],
),
@@ -351,27 +360,22 @@ class _ButtonsDemoState extends State<ButtonsDemo> {
alignment: const Alignment(0.0, -0.2),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
IconButton(
icon: const Icon(
Icons.thumb_up,
semanticLabel: 'Thumbs up',
),
onPressed: () {
setState(() => iconButtonToggle = !iconButtonToggle);
},
color: iconButtonToggle ? Theme.of(context).primaryColor : null,
),
const IconButton(
icon: Icon(
Icons.thumb_up,
semanticLabel: 'Thumbs not up',
),
onPressed: null,
),
]
.map<Widget>((Widget button) => SizedBox(width: 64.0, height: 64.0, child: button))
.toList(),
children:
<Widget>[
IconButton(
icon: const Icon(Icons.thumb_up, semanticLabel: 'Thumbs up'),
onPressed: () {
setState(() => iconButtonToggle = !iconButtonToggle);
},
color: iconButtonToggle ? Theme.of(context).primaryColor : null,
),
const IconButton(
icon: Icon(Icons.thumb_up, semanticLabel: 'Thumbs not up'),
onPressed: null,
),
]
.map<Widget>((Widget button) => SizedBox(width: 64.0, height: 64.0, child: button))
.toList(),
),
);
}

View File

@@ -8,11 +8,7 @@ import '../../gallery/demo.dart';
const String _kGalleryAssetsPackage = 'flutter_gallery_assets';
enum CardDemoType {
standard,
tappable,
selectable,
}
enum CardDemoType { standard, tappable, selectable }
class TravelDestination {
const TravelDestination({
@@ -64,7 +60,7 @@ const List<TravelDestination> destinations = <TravelDestination>[
];
class TravelDestinationItem extends StatelessWidget {
const TravelDestinationItem({ super.key, required this.destination, this.shape });
const TravelDestinationItem({super.key, required this.destination, this.shape});
// This height will allow for all the Card's content to fit comfortably within the card.
static const double height = 338.0;
@@ -98,7 +94,7 @@ class TravelDestinationItem extends StatelessWidget {
}
class TappableTravelDestinationItem extends StatelessWidget {
const TappableTravelDestinationItem({ super.key, required this.destination, this.shape });
const TappableTravelDestinationItem({super.key, required this.destination, this.shape});
// This height will allow for all the Card's content to fit comfortably within the card.
static const double height = 298.0;
@@ -141,7 +137,7 @@ class TappableTravelDestinationItem extends StatelessWidget {
}
class SelectableTravelDestinationItem extends StatefulWidget {
const SelectableTravelDestinationItem({ super.key, required this.destination, this.shape });
const SelectableTravelDestinationItem({super.key, required this.destination, this.shape});
final TravelDestination destination;
final ShapeBorder? shape;
@@ -151,7 +147,6 @@ class SelectableTravelDestinationItem extends StatefulWidget {
}
class _SelectableTravelDestinationItemState extends State<SelectableTravelDestinationItem> {
// This height will allow for all the Card's content to fit comfortably within the card.
static const double height = 298.0;
bool _isSelected = false;
@@ -188,11 +183,12 @@ class _SelectableTravelDestinationItemState extends State<SelectableTravelDestin
child: Stack(
children: <Widget>[
Container(
color: _isSelected
// Generally, material cards use primary with 8% opacity for the selected state.
// See: https://material.io/design/interaction/states.html#anatomy
? colorScheme.primary.withOpacity(0.08)
: Colors.transparent,
color:
_isSelected
// Generally, material cards use primary with 8% opacity for the selected state.
// See: https://material.io/design/interaction/states.html#anatomy
? colorScheme.primary.withOpacity(0.08)
: Colors.transparent,
),
TravelDestinationContent(destination: widget.destination),
Align(
@@ -218,10 +214,7 @@ class _SelectableTravelDestinationItemState extends State<SelectableTravelDestin
}
class SectionTitle extends StatelessWidget {
const SectionTitle({
super.key,
this.title,
});
const SectionTitle({super.key, this.title});
final String? title;
@@ -238,7 +231,7 @@ class SectionTitle extends StatelessWidget {
}
class TravelDestinationContent extends StatelessWidget {
const TravelDestinationContent({ super.key, required this.destination });
const TravelDestinationContent({super.key, required this.destination});
final TravelDestination destination;
@@ -247,7 +240,9 @@ class TravelDestinationContent extends StatelessWidget {
final ThemeData theme = Theme.of(context);
final TextStyle titleStyle = theme.textTheme.headlineSmall!.copyWith(color: Colors.white);
final TextStyle descriptionStyle = theme.textTheme.titleMedium!;
final ButtonStyle textButtonStyle = TextButton.styleFrom(foregroundColor: Colors.amber.shade500);
final ButtonStyle textButtonStyle = TextButton.styleFrom(
foregroundColor: Colors.amber.shade500,
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -275,10 +270,7 @@ class TravelDestinationContent extends StatelessWidget {
child: FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(
destination.title,
style: titleStyle,
),
child: Text(destination.title, style: titleStyle),
),
),
],
@@ -318,12 +310,16 @@ class TravelDestinationContent extends StatelessWidget {
children: <Widget>[
TextButton(
style: textButtonStyle,
onPressed: () { print('pressed'); },
onPressed: () {
print('pressed');
},
child: Text('SHARE', semanticsLabel: 'Share ${destination.title}'),
),
TextButton(
style: textButtonStyle,
onPressed: () { print('pressed'); },
onPressed: () {
print('pressed');
},
child: Text('EXPLORE', semanticsLabel: 'Explore ${destination.title}'),
),
],
@@ -354,20 +350,20 @@ class _CardsDemoState extends State<CardsDemo> {
actions: <Widget>[
MaterialDemoDocumentationButton(CardsDemo.routeName),
IconButton(
icon: const Icon(
Icons.sentiment_very_satisfied,
semanticLabel: 'update shape',
),
icon: const Icon(Icons.sentiment_very_satisfied, semanticLabel: 'update shape'),
onPressed: () {
setState(() {
_shape = _shape != null ? null : const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16.0),
topRight: Radius.circular(16.0),
bottomLeft: Radius.circular(2.0),
bottomRight: Radius.circular(2.0),
),
);
_shape =
_shape != null
? null
: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16.0),
topRight: Radius.circular(16.0),
bottomLeft: Radius.circular(2.0),
bottomRight: Radius.circular(2.0),
),
);
});
},
),
@@ -382,9 +378,18 @@ class _CardsDemoState extends State<CardsDemo> {
Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: switch (destination.type) {
CardDemoType.standard => TravelDestinationItem(destination: destination, shape: _shape),
CardDemoType.tappable => TappableTravelDestinationItem(destination: destination, shape: _shape),
CardDemoType.selectable => SelectableTravelDestinationItem(destination: destination, shape: _shape),
CardDemoType.standard => TravelDestinationItem(
destination: destination,
shape: _shape,
),
CardDemoType.tappable => TappableTravelDestinationItem(
destination: destination,
shape: _shape,
),
CardDemoType.selectable => SelectableTravelDestinationItem(
destination: destination,
shape: _shape,
),
},
),
],

View File

@@ -6,21 +6,9 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
const List<String> _defaultMaterialsA = <String>[
'poker',
'tortilla',
'fish and',
'micro',
'wood',
];
const List<String> _defaultMaterialsA = <String>['poker', 'tortilla', 'fish and', 'micro', 'wood'];
const List<String> _defaultMaterialsB = <String>[
'apple',
'orange',
'tomato',
'grape',
'lettuce',
];
const List<String> _defaultMaterialsB = <String>['apple', 'orange', 'tomato', 'grape', 'lettuce'];
const List<String> _defaultActions = <String>[
'flake',
@@ -46,21 +34,9 @@ const Map<String, String> _results = <String, String>{
'eat': 'eating',
};
const List<String> _defaultToolsA = <String>[
'hammer',
'chisel',
'fryer',
'fabricator',
'customer',
];
const List<String> _defaultToolsA = <String>['hammer', 'chisel', 'fryer', 'fabricator', 'customer'];
const List<String> _defaultToolsB = <String>[
'keyboard',
'mouse',
'monitor',
'printer',
'cable',
];
const List<String> _defaultToolsB = <String>['keyboard', 'mouse', 'monitor', 'printer', 'cable'];
const Map<String, String> _avatars = <String, String>{
'hammer': 'people/square/ali.png',
@@ -87,10 +63,7 @@ const Map<String, Set<String>> _materialActions = <String, Set<String>>{
};
class _ChipsTile extends StatelessWidget {
const _ChipsTile({
this.label,
this.children,
});
const _ChipsTile({this.label, this.children});
final String? label;
final List<Widget>? children;
@@ -110,12 +83,10 @@ class _ChipsTile extends StatelessWidget {
),
if (children!.isNotEmpty)
Wrap(
children: children!.map<Widget>((Widget chip) {
return Padding(
padding: const EdgeInsets.all(2.0),
child: chip,
);
}).toList(),
children:
children!.map<Widget>((Widget chip) {
return Padding(padding: const EdgeInsets.all(2.0), child: chip);
}).toList(),
)
else
Semantics(
@@ -124,7 +95,12 @@ class _ChipsTile extends StatelessWidget {
alignment: Alignment.center,
constraints: const BoxConstraints(minWidth: 48.0, minHeight: 48.0),
padding: const EdgeInsets.all(8.0),
child: Text('None', style: Theme.of(context).textTheme.bodySmall!.copyWith(fontStyle: FontStyle.italic)),
child: Text(
'None',
style: Theme.of(
context,
).textTheme.bodySmall!.copyWith(fontStyle: FontStyle.italic),
),
),
),
],
@@ -209,10 +185,7 @@ class _ChipDemoState extends State<ChipDemo> {
AssetImage _nameToAvatar(String name) {
assert(_avatars.containsKey(name));
return AssetImage(
_avatars[name]!,
package: 'flutter_gallery_assets',
);
return AssetImage(_avatars[name]!, package: 'flutter_gallery_assets');
}
String _createResult() {
@@ -226,65 +199,69 @@ class _ChipDemoState extends State<ChipDemo> {
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final List<Widget> chips = _materialsA.map<Widget>((String name) {
return Chip(
key: ValueKey<String>(name),
backgroundColor: _nameToColor(name, theme),
label: Text(_capitalize(name)),
onDeleted: () {
setState(() {
_removeMaterial(name);
});
},
);
}).toList();
final List<Widget> chips =
_materialsA.map<Widget>((String name) {
return Chip(
key: ValueKey<String>(name),
backgroundColor: _nameToColor(name, theme),
label: Text(_capitalize(name)),
onDeleted: () {
setState(() {
_removeMaterial(name);
});
},
);
}).toList();
final List<Widget> inputChips = _toolsA.map<Widget>((String name) {
return InputChip(
key: ValueKey<String>(name),
avatar: CircleAvatar(
backgroundImage: _nameToAvatar(name),
),
label: Text(_capitalize(name)),
onDeleted: () {
setState(() {
_removeTool(name);
});
});
}).toList();
final List<Widget> inputChips =
_toolsA.map<Widget>((String name) {
return InputChip(
key: ValueKey<String>(name),
avatar: CircleAvatar(backgroundImage: _nameToAvatar(name)),
label: Text(_capitalize(name)),
onDeleted: () {
setState(() {
_removeTool(name);
});
},
);
}).toList();
final List<Widget> choiceChips = _materialsB.map<Widget>((String name) {
return ChoiceChip(
key: ValueKey<String>(name),
backgroundColor: _nameToColor(name, theme),
label: Text(_capitalize(name)),
selected: _selectedMaterial == name,
onSelected: (bool value) {
setState(() {
_selectedMaterial = value ? name : '';
});
},
);
}).toList();
final List<Widget> choiceChips =
_materialsB.map<Widget>((String name) {
return ChoiceChip(
key: ValueKey<String>(name),
backgroundColor: _nameToColor(name, theme),
label: Text(_capitalize(name)),
selected: _selectedMaterial == name,
onSelected: (bool value) {
setState(() {
_selectedMaterial = value ? name : '';
});
},
);
}).toList();
final List<Widget> filterChips = _toolsB.map<Widget>((String name) {
return FilterChip(
key: ValueKey<String>(name),
label: Text(_capitalize(name)),
selected: _toolsB.contains(name) && _selectedTools.contains(name),
onSelected: !_toolsB.contains(name)
? null
: (bool value) {
setState(() {
if (!value) {
_selectedTools.remove(name);
} else {
_selectedTools.add(name);
}
});
},
);
}).toList();
final List<Widget> filterChips =
_toolsB.map<Widget>((String name) {
return FilterChip(
key: ValueKey<String>(name),
label: Text(_capitalize(name)),
selected: _toolsB.contains(name) && _selectedTools.contains(name),
onSelected:
!_toolsB.contains(name)
? null
: (bool value) {
setState(() {
if (!value) {
_selectedTools.remove(name);
} else {
_selectedTools.add(name);
}
});
},
);
}).toList();
Set<String> allowedActions = <String>{};
if (_selectedMaterial.isNotEmpty) {
@@ -294,16 +271,17 @@ class _ChipDemoState extends State<ChipDemo> {
allowedActions = allowedActions.intersection(_materialActions[_selectedMaterial]!);
}
final List<Widget> actionChips = allowedActions.map<Widget>((String name) {
return ActionChip(
label: Text(_capitalize(name)),
onPressed: () {
setState(() {
_selectedAction = name;
});
},
);
}).toList();
final List<Widget> actionChips =
allowedActions.map<Widget>((String name) {
return ActionChip(
label: Text(_capitalize(name)),
onPressed: () {
setState(() {
_selectedAction = name;
});
},
);
}).toList();
final List<Widget> tiles = <Widget>[
const SizedBox(height: 8.0, width: 0.0),
@@ -315,12 +293,7 @@ class _ChipDemoState extends State<ChipDemo> {
const Divider(),
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Text(
_createResult(),
style: theme.textTheme.titleLarge,
),
),
child: Center(child: Text(_createResult(), style: theme.textTheme.titleLarge)),
),
];
@@ -340,19 +313,16 @@ class _ChipDemoState extends State<ChipDemo> {
],
),
body: ChipTheme(
data: _showShapeBorder
? theme.chipTheme.copyWith(
shape: BeveledRectangleBorder(
side: const BorderSide(width: 0.66, color: Colors.grey),
borderRadius: BorderRadius.circular(10.0),
))
: theme.chipTheme,
child: Scrollbar(
child: ListView(
primary: true,
children: tiles,
)
),
data:
_showShapeBorder
? theme.chipTheme.copyWith(
shape: BeveledRectangleBorder(
side: const BorderSide(width: 0.66, color: Colors.grey),
borderRadius: BorderRadius.circular(10.0),
),
)
: theme.chipTheme,
child: Scrollbar(child: ListView(primary: true, children: tiles)),
),
floatingActionButton: FloatingActionButton(
onPressed: () => setState(_reset),

View File

@@ -7,7 +7,16 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
class Dessert {
Dessert(this.name, this.calories, this.fat, this.carbs, this.protein, this.sodium, this.calcium, this.iron);
Dessert(
this.name,
this.calories,
this.fat,
this.carbs,
this.protein,
this.sodium,
this.calcium,
this.iron,
);
final String name;
final int calories;
final double fat;
@@ -22,60 +31,60 @@ class Dessert {
class DessertDataSource extends DataTableSource {
final List<Dessert> _desserts = <Dessert>[
Dessert('Frozen yogurt', 159, 6.0, 24, 4.0, 87, 14, 1),
Dessert('Ice cream sandwich', 237, 9.0, 37, 4.3, 129, 8, 1),
Dessert('Eclair', 262, 16.0, 24, 6.0, 337, 6, 7),
Dessert('Cupcake', 305, 3.7, 67, 4.3, 413, 3, 8),
Dessert('Gingerbread', 356, 15.0, 49, 3.9, 327, 7, 16),
Dessert('Jelly bean', 375, 0.0, 94, 0.0, 50, 0, 0),
Dessert('Lollipop', 392, 0.2, 98, 0.0, 38, 0, 2),
Dessert('Honeycomb', 408, 3.2, 87, 6.5, 562, 0, 45),
Dessert('Donut', 452, 25.0, 51, 4.9, 326, 2, 22),
Dessert('KitKat', 518, 26.0, 65, 7.0, 54, 12, 6),
Dessert('Frozen yogurt', 159, 6.0, 24, 4.0, 87, 14, 1),
Dessert('Ice cream sandwich', 237, 9.0, 37, 4.3, 129, 8, 1),
Dessert('Eclair', 262, 16.0, 24, 6.0, 337, 6, 7),
Dessert('Cupcake', 305, 3.7, 67, 4.3, 413, 3, 8),
Dessert('Gingerbread', 356, 15.0, 49, 3.9, 327, 7, 16),
Dessert('Jelly bean', 375, 0.0, 94, 0.0, 50, 0, 0),
Dessert('Lollipop', 392, 0.2, 98, 0.0, 38, 0, 2),
Dessert('Honeycomb', 408, 3.2, 87, 6.5, 562, 0, 45),
Dessert('Donut', 452, 25.0, 51, 4.9, 326, 2, 22),
Dessert('KitKat', 518, 26.0, 65, 7.0, 54, 12, 6),
Dessert('Frozen yogurt with sugar', 168, 6.0, 26, 4.0, 87, 14, 1),
Dessert('Ice cream sandwich with sugar', 246, 9.0, 39, 4.3, 129, 8, 1),
Dessert('Eclair with sugar', 271, 14.0, 26, 6.0, 337, 6, 7),
Dessert('Cupcake with sugar', 314, 3.7, 69, 4.3, 413, 3, 8),
Dessert('Gingerbread with sugar', 345, 13.0, 51, 3.9, 327, 7, 16),
Dessert('Jelly bean with sugar', 364, 0.0, 96, 0.0, 50, 0, 0),
Dessert('Lollipop with sugar', 401, 0.2, 100, 0.0, 38, 0, 2),
Dessert('Honeycomb with sugar', 417, 3.2, 89, 6.5, 562, 0, 45),
Dessert('Donut with sugar', 461, 25.0, 53, 4.9, 326, 2, 22),
Dessert('KitKat with sugar', 527, 26.0, 67, 7.0, 54, 12, 6),
Dessert('Frozen yogurt with sugar', 168, 6.0, 26, 4.0, 87, 14, 1),
Dessert('Ice cream sandwich with sugar', 246, 9.0, 39, 4.3, 129, 8, 1),
Dessert('Eclair with sugar', 271, 14.0, 26, 6.0, 337, 6, 7),
Dessert('Cupcake with sugar', 314, 3.7, 69, 4.3, 413, 3, 8),
Dessert('Gingerbread with sugar', 345, 13.0, 51, 3.9, 327, 7, 16),
Dessert('Jelly bean with sugar', 364, 0.0, 96, 0.0, 50, 0, 0),
Dessert('Lollipop with sugar', 401, 0.2, 100, 0.0, 38, 0, 2),
Dessert('Honeycomb with sugar', 417, 3.2, 89, 6.5, 562, 0, 45),
Dessert('Donut with sugar', 461, 25.0, 53, 4.9, 326, 2, 22),
Dessert('KitKat with sugar', 527, 26.0, 67, 7.0, 54, 12, 6),
Dessert('Frozen yogurt with honey', 223, 6.0, 36, 4.0, 87, 14, 1),
Dessert('Ice cream sandwich with honey', 301, 9.0, 49, 4.3, 129, 8, 1),
Dessert('Eclair with honey', 326, 12.0, 36, 6.0, 337, 6, 7),
Dessert('Cupcake with honey', 369, 3.7, 79, 4.3, 413, 3, 8),
Dessert('Gingerbread with honey', 420, 11.0, 61, 3.9, 327, 7, 16),
Dessert('Jelly bean with honey', 439, 0.0, 106, 0.0, 50, 0, 0),
Dessert('Lollipop with honey', 456, 0.2, 110, 0.0, 38, 0, 2),
Dessert('Honeycomb with honey', 472, 3.2, 99, 6.5, 562, 0, 45),
Dessert('Donut with honey', 516, 25.0, 63, 4.9, 326, 2, 22),
Dessert('KitKat with honey', 582, 26.0, 77, 7.0, 54, 12, 6),
Dessert('Frozen yogurt with honey', 223, 6.0, 36, 4.0, 87, 14, 1),
Dessert('Ice cream sandwich with honey', 301, 9.0, 49, 4.3, 129, 8, 1),
Dessert('Eclair with honey', 326, 12.0, 36, 6.0, 337, 6, 7),
Dessert('Cupcake with honey', 369, 3.7, 79, 4.3, 413, 3, 8),
Dessert('Gingerbread with honey', 420, 11.0, 61, 3.9, 327, 7, 16),
Dessert('Jelly bean with honey', 439, 0.0, 106, 0.0, 50, 0, 0),
Dessert('Lollipop with honey', 456, 0.2, 110, 0.0, 38, 0, 2),
Dessert('Honeycomb with honey', 472, 3.2, 99, 6.5, 562, 0, 45),
Dessert('Donut with honey', 516, 25.0, 63, 4.9, 326, 2, 22),
Dessert('KitKat with honey', 582, 26.0, 77, 7.0, 54, 12, 6),
Dessert('Frozen yogurt with milk', 262, 8.4, 36, 12.0, 194, 44, 1),
Dessert('Ice cream sandwich with milk', 339, 11.4, 49, 12.3, 236, 38, 1),
Dessert('Eclair with milk', 365, 18.4, 36, 14.0, 444, 36, 7),
Dessert('Cupcake with milk', 408, 6.1, 79, 12.3, 520, 33, 8),
Dessert('Gingerbread with milk', 459, 18.4, 61, 11.9, 434, 37, 16),
Dessert('Jelly bean with milk', 478, 2.4, 106, 8.0, 157, 30, 0),
Dessert('Lollipop with milk', 495, 2.6, 110, 8.0, 145, 30, 2),
Dessert('Honeycomb with milk', 511, 5.6, 99, 14.5, 669, 30, 45),
Dessert('Donut with milk', 555, 27.4, 63, 12.9, 433, 32, 22),
Dessert('KitKat with milk', 621, 28.4, 77, 15.0, 161, 42, 6),
Dessert('Frozen yogurt with milk', 262, 8.4, 36, 12.0, 194, 44, 1),
Dessert('Ice cream sandwich with milk', 339, 11.4, 49, 12.3, 236, 38, 1),
Dessert('Eclair with milk', 365, 18.4, 36, 14.0, 444, 36, 7),
Dessert('Cupcake with milk', 408, 6.1, 79, 12.3, 520, 33, 8),
Dessert('Gingerbread with milk', 459, 18.4, 61, 11.9, 434, 37, 16),
Dessert('Jelly bean with milk', 478, 2.4, 106, 8.0, 157, 30, 0),
Dessert('Lollipop with milk', 495, 2.6, 110, 8.0, 145, 30, 2),
Dessert('Honeycomb with milk', 511, 5.6, 99, 14.5, 669, 30, 45),
Dessert('Donut with milk', 555, 27.4, 63, 12.9, 433, 32, 22),
Dessert('KitKat with milk', 621, 28.4, 77, 15.0, 161, 42, 6),
Dessert('Coconut slice and frozen yogurt', 318, 21.0, 31, 5.5, 96, 14, 7),
Dessert('Coconut slice and ice cream sandwich', 396, 24.0, 44, 5.8, 138, 8, 7),
Dessert('Coconut slice and eclair', 421, 31.0, 31, 7.5, 346, 6, 13),
Dessert('Coconut slice and cupcake', 464, 18.7, 74, 5.8, 422, 3, 14),
Dessert('Coconut slice and gingerbread', 515, 31.0, 56, 5.4, 316, 7, 22),
Dessert('Coconut slice and jelly bean', 534, 15.0, 101, 1.5, 59, 0, 6),
Dessert('Coconut slice and lollipop', 551, 15.2, 105, 1.5, 47, 0, 8),
Dessert('Coconut slice and honeycomb', 567, 18.2, 94, 8.0, 571, 0, 51),
Dessert('Coconut slice and donut', 611, 40.0, 58, 6.4, 335, 2, 28),
Dessert('Coconut slice and KitKat', 677, 41.0, 72, 8.5, 63, 12, 12),
Dessert('Coconut slice and frozen yogurt', 318, 21.0, 31, 5.5, 96, 14, 7),
Dessert('Coconut slice and ice cream sandwich', 396, 24.0, 44, 5.8, 138, 8, 7),
Dessert('Coconut slice and eclair', 421, 31.0, 31, 7.5, 346, 6, 13),
Dessert('Coconut slice and cupcake', 464, 18.7, 74, 5.8, 422, 3, 14),
Dessert('Coconut slice and gingerbread', 515, 31.0, 56, 5.4, 316, 7, 22),
Dessert('Coconut slice and jelly bean', 534, 15.0, 101, 1.5, 59, 0, 6),
Dessert('Coconut slice and lollipop', 551, 15.2, 105, 1.5, 47, 0, 8),
Dessert('Coconut slice and honeycomb', 567, 18.2, 94, 8.0, 571, 0, 51),
Dessert('Coconut slice and donut', 611, 40.0, 58, 6.4, 335, 2, 28),
Dessert('Coconut slice and KitKat', 677, 41.0, 72, 8.5, 63, 12, 12),
];
void _sort<T>(Comparable<T> Function(Dessert d) getField, bool ascending) {
@@ -171,9 +180,7 @@ class _DataTableDemoState extends State<DataTableDemo> {
return Scaffold(
appBar: AppBar(
title: const Text('Data tables'),
actions: <Widget>[
MaterialDemoDocumentationButton(DataTableDemo.routeName),
],
actions: <Widget>[MaterialDemoDocumentationButton(DataTableDemo.routeName)],
),
body: Scrollbar(
child: ListView(
@@ -183,51 +190,71 @@ class _DataTableDemoState extends State<DataTableDemo> {
PaginatedDataTable(
header: const Text('Nutrition'),
rowsPerPage: _rowsPerPage!,
onRowsPerPageChanged: (int? value) { setState(() { _rowsPerPage = value; }); },
onRowsPerPageChanged: (int? value) {
setState(() {
_rowsPerPage = value;
});
},
sortColumnIndex: _sortColumnIndex,
sortAscending: _sortAscending,
onSelectAll: _dessertsDataSource._selectAll,
columns: <DataColumn>[
DataColumn(
label: const Text('Dessert (100g serving)'),
onSort: (int columnIndex, bool ascending) => _sort<String>((Dessert d) => d.name, columnIndex, ascending),
onSort:
(int columnIndex, bool ascending) =>
_sort<String>((Dessert d) => d.name, columnIndex, ascending),
),
DataColumn(
label: const Text('Calories'),
tooltip: 'The total amount of food energy in the given serving size.',
numeric: true,
onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.calories, columnIndex, ascending),
onSort:
(int columnIndex, bool ascending) =>
_sort<num>((Dessert d) => d.calories, columnIndex, ascending),
),
DataColumn(
label: const Text('Fat (g)'),
numeric: true,
onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.fat, columnIndex, ascending),
onSort:
(int columnIndex, bool ascending) =>
_sort<num>((Dessert d) => d.fat, columnIndex, ascending),
),
DataColumn(
label: const Text('Carbs (g)'),
numeric: true,
onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.carbs, columnIndex, ascending),
onSort:
(int columnIndex, bool ascending) =>
_sort<num>((Dessert d) => d.carbs, columnIndex, ascending),
),
DataColumn(
label: const Text('Protein (g)'),
numeric: true,
onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.protein, columnIndex, ascending),
onSort:
(int columnIndex, bool ascending) =>
_sort<num>((Dessert d) => d.protein, columnIndex, ascending),
),
DataColumn(
label: const Text('Sodium (mg)'),
numeric: true,
onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.sodium, columnIndex, ascending),
onSort:
(int columnIndex, bool ascending) =>
_sort<num>((Dessert d) => d.sodium, columnIndex, ascending),
),
DataColumn(
label: const Text('Calcium (%)'),
tooltip: 'The amount of calcium as a percentage of the recommended daily amount.',
numeric: true,
onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.calcium, columnIndex, ascending),
onSort:
(int columnIndex, bool ascending) =>
_sort<num>((Dessert d) => d.calcium, columnIndex, ascending),
),
DataColumn(
label: const Text('Iron (%)'),
numeric: true,
onSort: (int columnIndex, bool ascending) => _sort<num>((Dessert d) => d.iron, columnIndex, ascending),
onSort:
(int columnIndex, bool ascending) =>
_sort<num>((Dessert d) => d.iron, columnIndex, ascending),
),
],
source: _dessertsDataSource,

View File

@@ -8,12 +8,7 @@ import 'package:intl/intl.dart';
import '../../gallery/demo.dart';
class _InputDropdown extends StatelessWidget {
const _InputDropdown({
this.labelText,
this.valueText,
this.valueStyle,
this.onPressed,
});
const _InputDropdown({this.labelText, this.valueText, this.valueStyle, this.onPressed});
final String? labelText;
final String? valueText;
@@ -25,17 +20,19 @@ class _InputDropdown extends StatelessWidget {
return InkWell(
onTap: onPressed,
child: InputDecorator(
decoration: InputDecoration(
labelText: labelText,
),
decoration: InputDecoration(labelText: labelText),
baseStyle: valueStyle,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(valueText!, style: valueStyle),
Icon(Icons.arrow_drop_down,
color: Theme.of(context).brightness == Brightness.light ? Colors.grey.shade700 : Colors.white70,
Icon(
Icons.arrow_drop_down,
color:
Theme.of(context).brightness == Brightness.light
? Colors.grey.shade700
: Colors.white70,
),
],
),
@@ -72,10 +69,7 @@ class _DateTimePicker extends StatelessWidget {
}
Future<void> _selectTime(BuildContext context) async {
final TimeOfDay? picked = await showTimePicker(
context: context,
initialTime: selectedTime!,
);
final TimeOfDay? picked = await showTimePicker(context: context, initialTime: selectedTime!);
if (picked != null && picked != selectedTime) {
selectTime!(picked);
}
@@ -93,7 +87,9 @@ class _DateTimePicker extends StatelessWidget {
labelText: labelText,
valueText: DateFormat.yMMMd().format(selectedDate!),
valueStyle: valueStyle,
onPressed: () { _selectDate(context); },
onPressed: () {
_selectDate(context);
},
),
),
const SizedBox(width: 12.0),
@@ -102,7 +98,9 @@ class _DateTimePicker extends StatelessWidget {
child: _InputDropdown(
valueText: selectedTime!.format(context),
valueStyle: valueStyle,
onPressed: () { _selectTime(context); },
onPressed: () {
_selectTime(context);
},
),
),
],
@@ -150,9 +148,7 @@ class _DateAndTimePickerDemoState extends State<DateAndTimePickerDemo> {
style: Theme.of(context).textTheme.headlineMedium,
),
TextField(
decoration: const InputDecoration(
labelText: 'Location',
),
decoration: const InputDecoration(labelText: 'Location'),
style: Theme.of(context).textTheme.headlineMedium!.copyWith(fontSize: 20.0),
),
_DateTimePicker(
@@ -200,12 +196,10 @@ class _DateAndTimePickerDemoState extends State<DateAndTimePickerDemo> {
_activity = newValue;
});
},
items: _allActivities.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
items:
_allActivities.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(value: value, child: Text(value));
}).toList(),
),
),
],

View File

@@ -7,21 +7,16 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
import 'full_screen_dialog_demo.dart';
enum DialogDemoAction {
cancel,
discard,
disagree,
agree,
}
enum DialogDemoAction { cancel, discard, disagree, agree }
const String _alertWithoutTitleText = 'Discard draft?';
const String _alertWithTitleText =
'Let Google help apps determine location. This means sending anonymous location '
'data to Google, even when no apps are running.';
'Let Google help apps determine location. This means sending anonymous location '
'data to Google, even when no apps are running.';
class DialogDemoItem extends StatelessWidget {
const DialogDemoItem({ super.key, this.icon, this.color, this.text, this.onPressed });
const DialogDemoItem({super.key, this.icon, this.color, this.text, this.onPressed});
final IconData? icon;
final Color? color;
@@ -35,10 +30,7 @@ class DialogDemoItem extends StatelessWidget {
child: Row(
children: <Widget>[
Icon(icon, size: 36.0, color: color),
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Text(text!),
),
Padding(padding: const EdgeInsets.only(left: 16.0), child: Text(text!)),
],
),
);
@@ -55,7 +47,6 @@ class DialogDemo extends StatefulWidget {
}
class DialogDemoState extends State<DialogDemo> {
TimeOfDay? _selectedTime;
@override
@@ -65,16 +56,11 @@ class DialogDemoState extends State<DialogDemo> {
_selectedTime = TimeOfDay(hour: now.hour, minute: now.minute);
}
void showDemoDialog<T>({ required BuildContext context, Widget? child }) {
showDialog<T>(
context: context,
builder: (BuildContext context) => child!,
)
.then((T? value) { // The value passed to Navigator.pop() or null.
void showDemoDialog<T>({required BuildContext context, Widget? child}) {
showDialog<T>(context: context, builder: (BuildContext context) => child!).then((T? value) {
// The value passed to Navigator.pop() or null.
if (context.mounted && value != null) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('You selected: $value'),
));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('You selected: $value')));
}
});
}
@@ -82,7 +68,9 @@ class DialogDemoState extends State<DialogDemo> {
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final TextStyle dialogTextStyle = theme.textTheme.titleMedium!.copyWith(color: theme.textTheme.bodySmall!.color);
final TextStyle dialogTextStyle = theme.textTheme.titleMedium!.copyWith(
color: theme.textTheme.bodySmall!.color,
);
return Scaffold(
appBar: AppBar(
@@ -91,124 +79,128 @@ class DialogDemoState extends State<DialogDemo> {
),
body: ListView(
padding: const EdgeInsets.symmetric(vertical: 24.0, horizontal: 72.0),
children: <Widget>[
ElevatedButton(
child: const Text('ALERT'),
onPressed: () {
showDemoDialog<DialogDemoAction>(
context: context,
child: AlertDialog(
content: Text(
_alertWithoutTitleText,
style: dialogTextStyle,
),
actions: <Widget>[
TextButton(
child: const Text('CANCEL'),
onPressed: () { Navigator.pop(context, DialogDemoAction.cancel); },
children:
<Widget>[
ElevatedButton(
child: const Text('ALERT'),
onPressed: () {
showDemoDialog<DialogDemoAction>(
context: context,
child: AlertDialog(
content: Text(_alertWithoutTitleText, style: dialogTextStyle),
actions: <Widget>[
TextButton(
child: const Text('CANCEL'),
onPressed: () {
Navigator.pop(context, DialogDemoAction.cancel);
},
),
TextButton(
child: const Text('DISCARD'),
onPressed: () {
Navigator.pop(context, DialogDemoAction.discard);
},
),
],
),
TextButton(
child: const Text('DISCARD'),
onPressed: () { Navigator.pop(context, DialogDemoAction.discard); },
);
},
),
ElevatedButton(
child: const Text('ALERT WITH TITLE'),
onPressed: () {
showDemoDialog<DialogDemoAction>(
context: context,
child: AlertDialog(
title: const Text("Use Google's location service?"),
content: Text(_alertWithTitleText, style: dialogTextStyle),
actions: <Widget>[
TextButton(
child: const Text('DISAGREE'),
onPressed: () {
Navigator.pop(context, DialogDemoAction.disagree);
},
),
TextButton(
child: const Text('AGREE'),
onPressed: () {
Navigator.pop(context, DialogDemoAction.agree);
},
),
],
),
],
),
);
},
),
ElevatedButton(
child: const Text('ALERT WITH TITLE'),
onPressed: () {
showDemoDialog<DialogDemoAction>(
context: context,
child: AlertDialog(
title: const Text("Use Google's location service?"),
content: Text(
_alertWithTitleText,
style: dialogTextStyle,
),
actions: <Widget>[
TextButton(
child: const Text('DISAGREE'),
onPressed: () { Navigator.pop(context, DialogDemoAction.disagree); },
);
},
),
ElevatedButton(
child: const Text('SIMPLE'),
onPressed: () {
showDemoDialog<String>(
context: context,
child: SimpleDialog(
title: const Text('Set backup account'),
children: <Widget>[
DialogDemoItem(
icon: Icons.account_circle,
color: theme.primaryColor,
text: 'username@gmail.com',
onPressed: () {
Navigator.pop(context, 'username@gmail.com');
},
),
DialogDemoItem(
icon: Icons.account_circle,
color: theme.primaryColor,
text: 'user02@gmail.com',
onPressed: () {
Navigator.pop(context, 'user02@gmail.com');
},
),
DialogDemoItem(
icon: Icons.add_circle,
text: 'add account',
color: theme.disabledColor,
),
],
),
TextButton(
child: const Text('AGREE'),
onPressed: () { Navigator.pop(context, DialogDemoAction.agree); },
);
},
),
ElevatedButton(
child: const Text('CONFIRMATION'),
onPressed: () {
showTimePicker(context: context, initialTime: _selectedTime!).then((
TimeOfDay? value,
) {
if (!context.mounted) {
return;
}
if (value != null && value != _selectedTime) {
_selectedTime = value;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('You selected: ${value.format(context)}')),
);
}
});
},
),
ElevatedButton(
child: const Text('FULLSCREEN'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute<DismissDialogAction>(
builder: (BuildContext context) => const FullScreenDialogDemo(),
fullscreenDialog: true,
),
],
),
);
},
),
ElevatedButton(
child: const Text('SIMPLE'),
onPressed: () {
showDemoDialog<String>(
context: context,
child: SimpleDialog(
title: const Text('Set backup account'),
children: <Widget>[
DialogDemoItem(
icon: Icons.account_circle,
color: theme.primaryColor,
text: 'username@gmail.com',
onPressed: () { Navigator.pop(context, 'username@gmail.com'); },
),
DialogDemoItem(
icon: Icons.account_circle,
color: theme.primaryColor,
text: 'user02@gmail.com',
onPressed: () { Navigator.pop(context, 'user02@gmail.com'); },
),
DialogDemoItem(
icon: Icons.add_circle,
text: 'add account',
color: theme.disabledColor,
),
],
),
);
},
),
ElevatedButton(
child: const Text('CONFIRMATION'),
onPressed: () {
showTimePicker(
context: context,
initialTime: _selectedTime!,
)
.then((TimeOfDay? value) {
if (!context.mounted) {
return;
}
if (value != null && value != _selectedTime) {
_selectedTime = value;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('You selected: ${value.format(context)}'),
));
}
});
},
),
ElevatedButton(
child: const Text('FULLSCREEN'),
onPressed: () {
Navigator.push(context, MaterialPageRoute<DismissDialogAction>(
builder: (BuildContext context) => const FullScreenDialogDemo(),
fullscreenDialog: true,
));
},
),
]
// Add a little space between the buttons
.map<Widget>((Widget button) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: button,
);
})
.toList(),
);
},
),
]
// Add a little space between the buttons
.map<Widget>((Widget button) {
return Container(padding: const EdgeInsets.symmetric(vertical: 8.0), child: button);
}).toList(),
),
);
}

View File

@@ -24,16 +24,12 @@ class DrawerDemo extends StatefulWidget {
class _DrawerDemoState extends State<DrawerDemo> with TickerProviderStateMixin {
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
static const List<String> _drawerContents = <String>[
'A', 'B', 'C', 'D', 'E',
];
static const List<String> _drawerContents = <String>['A', 'B', 'C', 'D', 'E'];
static final Animatable<Offset> _drawerDetailsTween = Tween<Offset>(
begin: const Offset(0.0, -1.0),
end: Offset.zero,
).chain(CurveTween(
curve: Curves.fastOutSlowIn,
));
).chain(CurveTween(curve: Curves.fastOutSlowIn));
late AnimationController _controller;
late Animation<double> _drawerContentsOpacity;
@@ -43,10 +39,7 @@ class _DrawerDemoState extends State<DrawerDemo> with TickerProviderStateMixin {
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 200),
);
_controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 200));
_drawerContentsOpacity = CurvedAnimation(
parent: ReverseAnimation(_controller),
curve: Curves.fastOutSlowIn,
@@ -75,9 +68,9 @@ class _DrawerDemoState extends State<DrawerDemo> with TickerProviderStateMixin {
void _showNotImplementedMessage() {
Navigator.pop(context); // Dismiss the drawer.
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("The drawer's items don't do anything"),
));
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text("The drawer's items don't do anything")));
}
@override
@@ -104,10 +97,7 @@ class _DrawerDemoState extends State<DrawerDemo> with TickerProviderStateMixin {
accountName: const Text('Trevor Widget'),
accountEmail: const Text('trevor.widget@example.com'),
currentAccountPicture: const CircleAvatar(
backgroundImage: AssetImage(
_kAsset0,
package: _kGalleryAssetsPackage,
),
backgroundImage: AssetImage(_kAsset0, package: _kGalleryAssetsPackage),
),
otherAccountsPictures: <Widget>[
GestureDetector(
@@ -118,10 +108,7 @@ class _DrawerDemoState extends State<DrawerDemo> with TickerProviderStateMixin {
child: Semantics(
label: 'Switch to Account B',
child: const CircleAvatar(
backgroundImage: AssetImage(
_kAsset1,
package: _kGalleryAssetsPackage,
),
backgroundImage: AssetImage(_kAsset1, package: _kGalleryAssetsPackage),
),
),
),
@@ -133,10 +120,7 @@ class _DrawerDemoState extends State<DrawerDemo> with TickerProviderStateMixin {
child: Semantics(
label: 'Switch to Account C',
child: const CircleAvatar(
backgroundImage: AssetImage(
_kAsset2,
package: _kGalleryAssetsPackage,
),
backgroundImage: AssetImage(_kAsset2, package: _kGalleryAssetsPackage),
),
),
),
@@ -168,13 +152,14 @@ class _DrawerDemoState extends State<DrawerDemo> with TickerProviderStateMixin {
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: _drawerContents.map<Widget>((String id) {
return ListTile(
leading: CircleAvatar(child: Text(id)),
title: Text('Drawer item $id'),
onTap: _showNotImplementedMessage,
);
}).toList(),
children:
_drawerContents.map<Widget>((String id) {
return ListTile(
leading: CircleAvatar(child: Text(id)),
title: Text('Drawer item $id'),
onTap: _showNotImplementedMessage,
);
}).toList(),
),
),
// The drawer's "details" view.
@@ -227,16 +212,14 @@ class _DrawerDemoState extends State<DrawerDemo> with TickerProviderStateMixin {
decoration: const BoxDecoration(
shape: BoxShape.circle,
image: DecorationImage(
image: AssetImage(
_kAsset0,
package: _kGalleryAssetsPackage,
),
image: AssetImage(_kAsset0, package: _kGalleryAssetsPackage),
),
),
),
Padding(
padding: const EdgeInsets.only(top: 8.0),
child: Text('Tap here to open the drawer',
child: Text(
'Tap here to open the drawer',
style: Theme.of(context).textTheme.titleMedium,
),
),

View File

@@ -19,17 +19,7 @@ class _ElevationDemoState extends State<ElevationDemo> {
bool _showElevation = true;
List<Widget> buildCards() {
const List<double> elevations = <double>[
0.0,
1.0,
2.0,
3.0,
4.0,
5.0,
8.0,
16.0,
24.0,
];
const List<double> elevations = <double>[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 8.0, 16.0, 24.0];
return elevations.map<Widget>((double elevation) {
return Center(
@@ -39,9 +29,7 @@ class _ElevationDemoState extends State<ElevationDemo> {
child: SizedBox(
height: 100.0,
width: 100.0,
child: Center(
child: Text('${elevation.toStringAsFixed(0)} pt'),
),
child: Center(child: Text('${elevation.toStringAsFixed(0)} pt')),
),
),
);
@@ -64,12 +52,7 @@ class _ElevationDemoState extends State<ElevationDemo> {
),
],
),
body: Scrollbar(
child: ListView(
primary: true,
children: buildCards(),
),
),
body: Scrollbar(child: ListView(primary: true, children: buildCards())),
);
}
}

View File

@@ -7,23 +7,13 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
@visibleForTesting
enum Location {
Barbados,
Bahamas,
Bermuda
}
enum Location { Barbados, Bahamas, Bermuda }
typedef DemoItemBodyBuilder<T> = Widget Function(DemoItem<T> item);
typedef ValueToString<T> = String? Function(T value);
class DualHeaderWithHint extends StatelessWidget {
const DualHeaderWithHint({
super.key,
this.name,
this.value,
this.hint,
this.showHint,
});
const DualHeaderWithHint({super.key, this.name, this.value, this.hint, this.showHint});
final String? name;
final String? value;
@@ -56,10 +46,7 @@ class DualHeaderWithHint extends StatelessWidget {
child: FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(
name!,
style: textTheme.bodyMedium!.copyWith(fontSize: 15.0),
),
child: Text(name!, style: textTheme.bodyMedium!.copyWith(fontSize: 15.0)),
),
),
),
@@ -101,11 +88,7 @@ class CollapsibleBody extends StatelessWidget {
return Column(
children: <Widget>[
Container(
margin: const EdgeInsets.only(
left: 24.0,
right: 24.0,
bottom: 24.0,
) - margin,
margin: const EdgeInsets.only(left: 24.0, right: 24.0, bottom: 24.0) - margin,
child: Center(
child: DefaultTextStyle(
style: textTheme.bodySmall!.copyWith(fontSize: 15.0),
@@ -123,19 +106,19 @@ class CollapsibleBody extends StatelessWidget {
margin: const EdgeInsets.only(right: 8.0),
child: TextButton(
onPressed: onCancel,
child: const Text('CANCEL', style: TextStyle(
color: Colors.black54,
fontSize: 15.0,
fontWeight: FontWeight.w500,
)),
child: const Text(
'CANCEL',
style: TextStyle(
color: Colors.black54,
fontSize: 15.0,
fontWeight: FontWeight.w500,
),
),
),
),
Container(
margin: const EdgeInsets.only(right: 8.0),
child: TextButton(
onPressed: onSave,
child: const Text('SAVE'),
),
child: TextButton(onPressed: onSave, child: const Text('SAVE')),
),
],
),
@@ -146,13 +129,8 @@ class CollapsibleBody extends StatelessWidget {
}
class DemoItem<T> {
DemoItem({
this.name,
this.value,
this.hint,
this.builder,
required this.valueToString,
}) : textController = TextEditingController(text: valueToString(value));
DemoItem({this.name, this.value, this.hint, this.builder, required this.valueToString})
: textController = TextEditingController(text: valueToString(value));
final String? name;
final String? hint;
@@ -210,17 +188,22 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
builder: (BuildContext context) {
return CollapsibleBody(
margin: const EdgeInsets.symmetric(horizontal: 16.0),
onSave: () { Form.of(context).save(); close(); },
onCancel: () { Form.of(context).reset(); close(); },
onSave: () {
Form.of(context).save();
close();
},
onCancel: () {
Form.of(context).reset();
close();
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: TextFormField(
controller: item.textController,
decoration: InputDecoration(
hintText: item.hint,
labelText: item.name,
),
onSaved: (String? value) { item.value = value; },
decoration: InputDecoration(hintText: item.hint, labelText: item.name),
onSaved: (String? value) {
item.value = value;
},
),
),
);
@@ -240,15 +223,24 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
item.isExpanded = false;
});
}
return Form(
child: Builder(
builder: (BuildContext context) {
return CollapsibleBody(
onSave: () { Form.of(context).save(); close(); },
onCancel: () { Form.of(context).reset(); close(); },
onSave: () {
Form.of(context).save();
close();
},
onCancel: () {
Form.of(context).reset();
close();
},
child: FormField<Location>(
initialValue: item.value,
onSaved: (Location? result) { item.value = result; },
onSaved: (Location? result) {
item.value = result;
},
builder: (FormFieldState<Location> field) {
return Column(
mainAxisSize: MainAxisSize.min,
@@ -277,7 +269,7 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
},
),
);
}
},
),
);
},
@@ -298,11 +290,19 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
child: Builder(
builder: (BuildContext context) {
return CollapsibleBody(
onSave: () { Form.of(context).save(); close(); },
onCancel: () { Form.of(context).reset(); close(); },
onSave: () {
Form.of(context).save();
close();
},
onCancel: () {
Form.of(context).reset();
close();
},
child: FormField<double>(
initialValue: item.value,
onSaved: (double? value) { item.value = value; },
onSaved: (double? value) {
item.value = value;
},
builder: (FormFieldState<double> field) {
return Container(
// Allow room for the value indicator.
@@ -319,7 +319,7 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
},
),
);
}
},
),
);
},
@@ -332,9 +332,7 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
return Scaffold(
appBar: AppBar(
title: const Text('Expansion panels'),
actions: <Widget>[
MaterialDemoDocumentationButton(ExpansionPanelsDemo.routeName),
],
actions: <Widget>[MaterialDemoDocumentationButton(ExpansionPanelsDemo.routeName)],
),
body: SingleChildScrollView(
child: SafeArea(
@@ -348,13 +346,14 @@ class _ExpansionPanelsDemoState extends State<ExpansionPanelsDemo> {
_demoItems[index].isExpanded = isExpanded;
});
},
children: _demoItems.map<ExpansionPanel>((DemoItem<dynamic> item) {
return ExpansionPanel(
isExpanded: item.isExpanded,
headerBuilder: item.headerBuilder,
body: item.build(),
);
}).toList(),
children:
_demoItems.map<ExpansionPanel>((DemoItem<dynamic> item) {
return ExpansionPanel(
isExpanded: item.isExpanded,
headerBuilder: item.headerBuilder,
body: item.build(),
);
}).toList(),
),
),
),

View File

@@ -9,14 +9,10 @@ import 'package:intl/intl.dart';
// This demo is based on
// https://material.io/design/components/dialogs.html#full-screen-dialog
enum DismissDialogAction {
cancel,
discard,
save,
}
enum DismissDialogAction { cancel, discard, save }
class DateTimeItem extends StatelessWidget {
DateTimeItem({ super.key, required DateTime dateTime, required this.onChanged })
DateTimeItem({super.key, required DateTime dateTime, required this.onChanged})
: date = DateTime(dateTime.year, dateTime.month, dateTime.day),
time = TimeOfDay(hour: dateTime.hour, minute: dateTime.minute);
@@ -36,7 +32,7 @@ class DateTimeItem extends StatelessWidget {
child: Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: theme.dividerColor))
border: Border(bottom: BorderSide(color: theme.dividerColor)),
),
child: InkWell(
onTap: () {
@@ -45,10 +41,11 @@ class DateTimeItem extends StatelessWidget {
initialDate: date,
firstDate: date.subtract(const Duration(days: 30)),
lastDate: date.add(const Duration(days: 30)),
)
.then((DateTime? value) {
).then((DateTime? value) {
if (value != null) {
onChanged(DateTime(value.year, value.month, value.day, time.hour, time.minute));
onChanged(
DateTime(value.year, value.month, value.day, time.hour, time.minute),
);
}
});
},
@@ -66,15 +63,11 @@ class DateTimeItem extends StatelessWidget {
margin: const EdgeInsets.only(left: 8.0),
padding: const EdgeInsets.symmetric(vertical: 8.0),
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: theme.dividerColor))
border: Border(bottom: BorderSide(color: theme.dividerColor)),
),
child: InkWell(
onTap: () {
showTimePicker(
context: context,
initialTime: time,
)
.then((TimeOfDay? value) {
showTimePicker(context: context, initialTime: time).then((TimeOfDay? value) {
if (value != null) {
onChanged(DateTime(date.year, date.month, date.day, value.hour, value.minute));
}
@@ -116,16 +109,15 @@ class FullScreenDialogDemoState extends State<FullScreenDialogDemo> {
}
final ThemeData theme = Theme.of(context);
final TextStyle dialogTextStyle = theme.textTheme.titleMedium!.copyWith(color: theme.textTheme.bodySmall!.color);
final TextStyle dialogTextStyle = theme.textTheme.titleMedium!.copyWith(
color: theme.textTheme.bodySmall!.color,
);
final bool? shouldDiscard = await showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Text(
'Discard new event?',
style: dialogTextStyle,
),
content: Text('Discard new event?', style: dialogTextStyle),
actions: <Widget>[
TextButton(
child: const Text('CANCEL'),
@@ -164,7 +156,7 @@ class FullScreenDialogDemoState extends State<FullScreenDialogDemo> {
return Scaffold(
appBar: AppBar(
title: Text(_hasName ? _eventName : 'Event Name TBD'),
actions: <Widget> [
actions: <Widget>[
TextButton(
child: Text('SAVE', style: theme.textTheme.bodyMedium!.copyWith(color: Colors.white)),
onPressed: () {
@@ -180,101 +172,97 @@ class FullScreenDialogDemoState extends State<FullScreenDialogDemo> {
child: ListView(
primary: true,
padding: const EdgeInsets.all(16.0),
children: <Widget>[
Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
alignment: Alignment.bottomLeft,
child: TextField(
decoration: const InputDecoration(
labelText: 'Event name',
filled: true,
),
style: theme.textTheme.headlineSmall,
onChanged: (String value) {
setState(() {
_hasName = value.isNotEmpty;
if (_hasName) {
_eventName = value;
}
});
},
),
),
Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
alignment: Alignment.bottomLeft,
child: TextField(
decoration: const InputDecoration(
labelText: 'Location',
hintText: 'Where is the event?',
filled: true,
),
onChanged: (String value) {
setState(() {
_hasLocation = value.isNotEmpty;
});
},
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('From', style: theme.textTheme.bodySmall),
DateTimeItem(
dateTime: _fromDateTime,
onChanged: (DateTime value) {
setState(() {
_fromDateTime = value;
_saveNeeded = true;
});
},
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('To', style: theme.textTheme.bodySmall),
DateTimeItem(
dateTime: _toDateTime,
onChanged: (DateTime value) {
setState(() {
_toDateTime = value;
_saveNeeded = true;
});
},
),
const Text('All-day'),
],
),
Container(
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: theme.dividerColor))
),
child: Row(
children: <Widget> [
Checkbox(
value: _allDayValue,
onChanged: (bool? value) {
children:
<Widget>[
Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
alignment: Alignment.bottomLeft,
child: TextField(
decoration: const InputDecoration(labelText: 'Event name', filled: true),
style: theme.textTheme.headlineSmall,
onChanged: (String value) {
setState(() {
_allDayValue = value;
_saveNeeded = true;
_hasName = value.isNotEmpty;
if (_hasName) {
_eventName = value;
}
});
},
),
const Text('All-day'),
],
),
),
]
.map<Widget>((Widget child) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
height: 96.0,
child: child,
);
})
.toList(),
),
Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
alignment: Alignment.bottomLeft,
child: TextField(
decoration: const InputDecoration(
labelText: 'Location',
hintText: 'Where is the event?',
filled: true,
),
onChanged: (String value) {
setState(() {
_hasLocation = value.isNotEmpty;
});
},
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('From', style: theme.textTheme.bodySmall),
DateTimeItem(
dateTime: _fromDateTime,
onChanged: (DateTime value) {
setState(() {
_fromDateTime = value;
_saveNeeded = true;
});
},
),
],
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('To', style: theme.textTheme.bodySmall),
DateTimeItem(
dateTime: _toDateTime,
onChanged: (DateTime value) {
setState(() {
_toDateTime = value;
_saveNeeded = true;
});
},
),
const Text('All-day'),
],
),
Container(
decoration: BoxDecoration(
border: Border(bottom: BorderSide(color: theme.dividerColor)),
),
child: Row(
children: <Widget>[
Checkbox(
value: _allDayValue,
onChanged: (bool? value) {
setState(() {
_allDayValue = value;
_saveNeeded = true;
});
},
),
const Text('All-day'),
],
),
),
].map<Widget>((Widget child) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 8.0),
height: 96.0,
child: child,
);
}).toList(),
),
),
),

View File

@@ -6,11 +6,7 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
enum GridDemoTileStyle {
imageOnly,
oneLine,
twoLine
}
enum GridDemoTileStyle { imageOnly, oneLine, twoLine }
typedef BannerTapCallback = void Function(Photo photo);
@@ -18,13 +14,7 @@ const double _kMinFlingVelocity = 800.0;
const String _kGalleryAssetsPackage = 'flutter_gallery_assets';
class Photo {
Photo({
this.assetName,
this.assetPackage,
this.title,
this.caption,
this.isFavorite = false,
});
Photo({this.assetName, this.assetPackage, this.title, this.caption, this.isFavorite = false});
final String? assetName;
final String? assetPackage;
@@ -38,7 +28,7 @@ class Photo {
}
class GridPhotoViewer extends StatefulWidget {
const GridPhotoViewer({ super.key, this.photo });
const GridPhotoViewer({super.key, this.photo});
final Photo? photo;
@@ -53,11 +43,7 @@ class _GridTitleText extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FittedBox(
fit: BoxFit.scaleDown,
alignment: Alignment.centerLeft,
child: Text(text!),
);
return FittedBox(fit: BoxFit.scaleDown, alignment: Alignment.centerLeft, child: Text(text!));
}
}
@@ -72,8 +58,7 @@ class _GridPhotoViewerState extends State<GridPhotoViewer> with SingleTickerProv
@override
void initState() {
super.initState();
_controller = AnimationController(vsync: this)
..addListener(_handleFlingAnimation);
_controller = AnimationController(vsync: this)..addListener(_handleFlingAnimation);
}
@override
@@ -87,10 +72,7 @@ class _GridPhotoViewerState extends State<GridPhotoViewer> with SingleTickerProv
Offset _clampOffset(Offset offset) {
final Size size = context.size!;
final Offset minOffset = Offset(size.width, size.height) * (1.0 - _scale);
return Offset(
offset.dx.clamp(minOffset.dx, 0.0),
offset.dy.clamp(minOffset.dy, 0.0),
);
return Offset(offset.dx.clamp(minOffset.dx, 0.0), offset.dy.clamp(minOffset.dy, 0.0));
}
void _handleFlingAnimation() {
@@ -123,10 +105,9 @@ class _GridPhotoViewerState extends State<GridPhotoViewer> with SingleTickerProv
}
final Offset direction = details.velocity.pixelsPerSecond / magnitude;
final double distance = (Offset.zero & context.size!).shortestSide;
_flingAnimation = _controller.drive(Tween<Offset>(
begin: _offset,
end: _clampOffset(_offset + direction * distance),
));
_flingAnimation = _controller.drive(
Tween<Offset>(begin: _offset, end: _clampOffset(_offset + direction * distance)),
);
_controller
..value = 0.0
..fling(velocity: magnitude / 1000.0);
@@ -140,9 +121,10 @@ class _GridPhotoViewerState extends State<GridPhotoViewer> with SingleTickerProv
onScaleEnd: _handleOnScaleEnd,
child: ClipRect(
child: Transform(
transform: Matrix4.identity()
..translate(_offset.dx, _offset.dy)
..scale(_scale),
transform:
Matrix4.identity()
..translate(_offset.dx, _offset.dy)
..scale(_scale),
child: Image.asset(
widget.photo!.assetName!,
package: widget.photo!.assetPackage,
@@ -167,21 +149,19 @@ class GridDemoPhotoItem extends StatelessWidget {
final BannerTapCallback onBannerTap; // User taps on the photo's header or footer.
void showPhoto(BuildContext context) {
Navigator.push(context, MaterialPageRoute<void>(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(photo.title!),
),
body: SizedBox.expand(
child: Hero(
tag: photo.tag!,
child: GridPhotoViewer(photo: photo),
Navigator.push(
context,
MaterialPageRoute<void>(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(photo.title!)),
body: SizedBox.expand(
child: Hero(tag: photo.tag!, child: GridPhotoViewer(photo: photo)),
),
),
);
}
));
);
},
),
);
}
@override
@@ -189,15 +169,13 @@ class GridDemoPhotoItem extends StatelessWidget {
final Widget image = Semantics(
label: '${photo.title} - ${photo.caption}',
child: GestureDetector(
onTap: () { showPhoto(context); },
onTap: () {
showPhoto(context);
},
child: Hero(
key: Key(photo.assetName!),
tag: photo.tag!,
child: Image.asset(
photo.assetName!,
package: photo.assetPackage,
fit: BoxFit.cover,
),
child: Image.asset(photo.assetName!, package: photo.assetPackage, fit: BoxFit.cover),
),
),
);
@@ -211,14 +189,13 @@ class GridDemoPhotoItem extends StatelessWidget {
case GridDemoTileStyle.oneLine:
return GridTile(
header: GestureDetector(
onTap: () { onBannerTap(photo); },
onTap: () {
onBannerTap(photo);
},
child: GridTileBar(
title: _GridTitleText(photo.title),
backgroundColor: Colors.black45,
leading: Icon(
icon,
color: Colors.white,
),
leading: Icon(icon, color: Colors.white),
),
),
child: image,
@@ -227,15 +204,14 @@ class GridDemoPhotoItem extends StatelessWidget {
case GridDemoTileStyle.twoLine:
return GridTile(
footer: GestureDetector(
onTap: () { onBannerTap(photo); },
onTap: () {
onBannerTap(photo);
},
child: GridTileBar(
backgroundColor: Colors.black45,
title: _GridTitleText(photo.title),
subtitle: _GridTitleText(photo.caption),
trailing: Icon(
icon,
color: Colors.white,
),
trailing: Icon(icon, color: Colors.white),
),
),
child: image,
@@ -245,7 +221,7 @@ class GridDemoPhotoItem extends StatelessWidget {
}
class GridListDemo extends StatefulWidget {
const GridListDemo({ super.key });
const GridListDemo({super.key});
static const String routeName = '/material/grid-list';
@@ -347,20 +323,21 @@ class GridListDemoState extends State<GridListDemo> {
MaterialDemoDocumentationButton(GridListDemo.routeName),
PopupMenuButton<GridDemoTileStyle>(
onSelected: changeTileStyle,
itemBuilder: (BuildContext context) => <PopupMenuItem<GridDemoTileStyle>>[
const PopupMenuItem<GridDemoTileStyle>(
value: GridDemoTileStyle.imageOnly,
child: Text('Image only'),
),
const PopupMenuItem<GridDemoTileStyle>(
value: GridDemoTileStyle.oneLine,
child: Text('One line'),
),
const PopupMenuItem<GridDemoTileStyle>(
value: GridDemoTileStyle.twoLine,
child: Text('Two line'),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuItem<GridDemoTileStyle>>[
const PopupMenuItem<GridDemoTileStyle>(
value: GridDemoTileStyle.imageOnly,
child: Text('Image only'),
),
const PopupMenuItem<GridDemoTileStyle>(
value: GridDemoTileStyle.oneLine,
child: Text('One line'),
),
const PopupMenuItem<GridDemoTileStyle>(
value: GridDemoTileStyle.twoLine,
child: Text('Two line'),
),
],
),
],
),
@@ -376,17 +353,18 @@ class GridListDemoState extends State<GridListDemo> {
crossAxisSpacing: 4.0,
padding: const EdgeInsets.all(4.0),
childAspectRatio: (orientation == Orientation.portrait) ? 1.0 : 1.3,
children: photos.map<Widget>((Photo photo) {
return GridDemoPhotoItem(
photo: photo,
tileStyle: _tileStyle,
onBannerTap: (Photo photo) {
setState(() {
photo.isFavorite = !photo.isFavorite;
});
},
);
}).toList(),
children:
photos.map<Widget>((Photo photo) {
return GridDemoPhotoItem(
photo: photo,
tileStyle: _tileStyle,
onBannerTap: (Photo photo) {
setState(() {
photo.isFavorite = !photo.isFavorite;
});
},
);
}).toList(),
),
),
),

View File

@@ -67,7 +67,10 @@ class IconsDemoState extends State<IconsDemo> {
children: <Widget>[
_IconsDemoCard(handleIconButtonPress, Icons.face), // direction-agnostic icon
const SizedBox(height: 24.0),
_IconsDemoCard(handleIconButtonPress, Icons.battery_unknown), // direction-aware icon
_IconsDemoCard(
handleIconButtonPress,
Icons.battery_unknown,
), // direction-aware icon
],
),
),
@@ -92,16 +95,15 @@ class _IconsDemoCard extends StatelessWidget {
);
}
Widget _centeredText(String label) =>
Padding(
// Match the default padding of IconButton.
padding: const EdgeInsets.all(8.0),
child: Text(label, textAlign: TextAlign.center),
);
Widget _centeredText(String label) => Padding(
// Match the default padding of IconButton.
padding: const EdgeInsets.all(8.0),
child: Text(label, textAlign: TextAlign.center),
);
TableRow _buildIconRow(double size) {
return TableRow(
children: <Widget> [
children: <Widget>[
_centeredText('${size.floor()} $icon'),
_buildIconButton(size, icon, true),
_buildIconButton(size, icon, false),
@@ -112,7 +114,9 @@ class _IconsDemoCard extends StatelessWidget {
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final TextStyle textStyle = theme.textTheme.titleMedium!.copyWith(color: theme.textTheme.bodySmall!.color);
final TextStyle textStyle = theme.textTheme.titleMedium!.copyWith(
color: theme.textTheme.bodySmall!.color,
);
return Card(
child: DefaultTextStyle(
style: textStyle,
@@ -120,13 +124,13 @@ class _IconsDemoCard extends StatelessWidget {
explicitChildNodes: true,
child: Table(
defaultVerticalAlignment: TableCellVerticalAlignment.middle,
children: <TableRow> [
children: <TableRow>[
TableRow(
children: <Widget> [
children: <Widget>[
_centeredText('Size $icon'),
_centeredText('Enabled $icon'),
_centeredText('Disabled $icon'),
]
],
),
_buildIconRow(18.0),
_buildIconRow(24.0),

View File

@@ -9,19 +9,16 @@ import 'package:flutter/semantics.dart';
import '../../gallery/demo.dart';
enum LeaveBehindDemoAction {
reset,
horizontalSwipe,
leftSwipe,
rightSwipe,
confirmDismiss,
}
enum LeaveBehindDemoAction { reset, horizontalSwipe, leftSwipe, rightSwipe, confirmDismiss }
class LeaveBehindItem implements Comparable<LeaveBehindItem> {
LeaveBehindItem({ this.index, this.name, this.subject, this.body });
LeaveBehindItem({this.index, this.name, this.subject, this.body});
LeaveBehindItem.from(LeaveBehindItem item)
: index = item.index, name = item.name, subject = item.subject, body = item.body;
: index = item.index,
name = item.name,
subject = item.subject,
body = item.body;
final int? index;
final String? name;
@@ -33,7 +30,7 @@ class LeaveBehindItem implements Comparable<LeaveBehindItem> {
}
class LeaveBehindDemo extends StatefulWidget {
const LeaveBehindDemo({ super.key });
const LeaveBehindDemo({super.key});
static const String routeName = '/material/leave-behind';
@@ -91,26 +88,34 @@ class LeaveBehindDemoState extends State<LeaveBehindDemo> {
setState(() {
leaveBehindItems.remove(item);
});
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('You archived item ${item.index}'),
action: SnackBarAction(
label: 'UNDO',
onPressed: () { handleUndo(item); },
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('You archived item ${item.index}'),
action: SnackBarAction(
label: 'UNDO',
onPressed: () {
handleUndo(item);
},
),
),
));
);
}
void _handleDelete(LeaveBehindItem item) {
setState(() {
leaveBehindItems.remove(item);
});
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('You deleted item ${item.index}'),
action: SnackBarAction(
label: 'UNDO',
onPressed: () { handleUndo(item); },
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('You deleted item ${item.index}'),
action: SnackBarAction(
label: 'UNDO',
onPressed: () {
handleUndo(item);
},
),
),
));
);
}
@override
@@ -127,16 +132,17 @@ class LeaveBehindDemoState extends State<LeaveBehindDemo> {
body = Scrollbar(
child: ListView(
primary: true,
children: leaveBehindItems.map<Widget>((LeaveBehindItem item) {
return _LeaveBehindListItem(
confirmDismiss: _confirmDismiss,
item: item,
onArchive: _handleArchive,
onDelete: _handleDelete,
dismissDirection: _dismissDirection,
);
}).toList(),
),
children:
leaveBehindItems.map<Widget>((LeaveBehindItem item) {
return _LeaveBehindListItem(
confirmDismiss: _confirmDismiss,
item: item,
onArchive: _handleArchive,
onDelete: _handleDelete,
dismissDirection: _dismissDirection,
);
}).toList(),
),
);
}
@@ -147,33 +153,34 @@ class LeaveBehindDemoState extends State<LeaveBehindDemo> {
MaterialDemoDocumentationButton(LeaveBehindDemo.routeName),
PopupMenuButton<LeaveBehindDemoAction>(
onSelected: handleDemoAction,
itemBuilder: (BuildContext context) => <PopupMenuEntry<LeaveBehindDemoAction>>[
const PopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.reset,
child: Text('Reset the list'),
),
const PopupMenuDivider(),
CheckedPopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.horizontalSwipe,
checked: _dismissDirection == DismissDirection.horizontal,
child: const Text('Horizontal swipe'),
),
CheckedPopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.leftSwipe,
checked: _dismissDirection == DismissDirection.endToStart,
child: const Text('Only swipe left'),
),
CheckedPopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.rightSwipe,
checked: _dismissDirection == DismissDirection.startToEnd,
child: const Text('Only swipe right'),
),
CheckedPopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.confirmDismiss,
checked: _confirmDismiss,
child: const Text('Confirm dismiss'),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuEntry<LeaveBehindDemoAction>>[
const PopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.reset,
child: Text('Reset the list'),
),
const PopupMenuDivider(),
CheckedPopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.horizontalSwipe,
checked: _dismissDirection == DismissDirection.horizontal,
child: const Text('Horizontal swipe'),
),
CheckedPopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.leftSwipe,
checked: _dismissDirection == DismissDirection.endToStart,
child: const Text('Only swipe left'),
),
CheckedPopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.rightSwipe,
checked: _dismissDirection == DismissDirection.startToEnd,
child: const Text('Only swipe right'),
),
CheckedPopupMenuItem<LeaveBehindDemoAction>(
value: LeaveBehindDemoAction.confirmDismiss,
checked: _confirmDismiss,
child: const Text('Confirm dismiss'),
),
],
),
],
),
@@ -223,35 +230,34 @@ class _LeaveBehindListItem extends StatelessWidget {
_handleDelete();
}
},
confirmDismiss: !confirmDismiss ? null : (DismissDirection dismissDirection) async {
switch (dismissDirection) {
case DismissDirection.endToStart:
return await _showConfirmationDialog(context, 'archive') ?? false;
case DismissDirection.startToEnd:
return await _showConfirmationDialog(context, 'delete') ?? false;
case DismissDirection.horizontal:
case DismissDirection.vertical:
case DismissDirection.up:
case DismissDirection.down:
case DismissDirection.none:
assert(false);
}
return false;
},
confirmDismiss:
!confirmDismiss
? null
: (DismissDirection dismissDirection) async {
switch (dismissDirection) {
case DismissDirection.endToStart:
return await _showConfirmationDialog(context, 'archive') ?? false;
case DismissDirection.startToEnd:
return await _showConfirmationDialog(context, 'delete') ?? false;
case DismissDirection.horizontal:
case DismissDirection.vertical:
case DismissDirection.up:
case DismissDirection.down:
case DismissDirection.none:
assert(false);
}
return false;
},
background: ColoredBox(
color: theme.primaryColor,
child: const Center(
child: ListTile(
leading: Icon(Icons.delete, color: Colors.white, size: 36.0),
),
child: ListTile(leading: Icon(Icons.delete, color: Colors.white, size: 36.0)),
),
),
secondaryBackground: ColoredBox(
color: theme.primaryColor,
child: const Center(
child: ListTile(
trailing: Icon(Icons.archive, color: Colors.white, size: 36.0),
),
child: ListTile(trailing: Icon(Icons.archive, color: Colors.white, size: 36.0)),
),
),
child: Container(

View File

@@ -21,7 +21,7 @@ enum _MaterialListType {
}
class ListDemo extends StatefulWidget {
const ListDemo({ super.key });
const ListDemo({super.key});
static const String routeName = '/material/list';
@@ -40,22 +40,35 @@ class _ListDemoState extends State<ListDemo> {
bool? _showDividers = false;
bool _reverseSort = false;
List<String> items = <String>[
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
];
void changeItemType(_MaterialListType? type) {
setState(() {
_itemType = type;
});
_bottomSheet?.setState!(() { });
_bottomSheet?.setState!(() {});
}
void _showConfigurationSheet() {
final PersistentBottomSheetController bottomSheet = scaffoldKey.currentState!.showBottomSheet((BuildContext bottomSheetContext) {
final PersistentBottomSheetController bottomSheet = scaffoldKey.currentState!.showBottomSheet((
BuildContext bottomSheetContext,
) {
return Container(
decoration: const BoxDecoration(
border: Border(top: BorderSide(color: Colors.black26)),
),
decoration: const BoxDecoration(border: Border(top: BorderSide(color: Colors.black26))),
child: ListView(
shrinkWrap: true,
primary: false,
@@ -65,7 +78,10 @@ class _ListDemoState extends State<ListDemo> {
dense: true,
title: const Text('One-line'),
trailing: Radio<_MaterialListType>(
value: _showAvatars! ? _MaterialListType.oneLineWithAvatar : _MaterialListType.oneLine,
value:
_showAvatars!
? _MaterialListType.oneLineWithAvatar
: _MaterialListType.oneLine,
groupValue: _itemType,
onChanged: changeItemType,
),
@@ -105,7 +121,7 @@ class _ListDemoState extends State<ListDemo> {
});
final StateSetter? bottomSheetSetState = _bottomSheet?.setState;
if (bottomSheetSetState != null) {
bottomSheetSetState(() { });
bottomSheetSetState(() {});
}
},
),
@@ -123,7 +139,7 @@ class _ListDemoState extends State<ListDemo> {
});
final StateSetter? bottomSheetSetState = _bottomSheet?.setState;
if (bottomSheetSetState != null) {
bottomSheetSetState(() { });
bottomSheetSetState(() {});
}
},
),
@@ -141,7 +157,7 @@ class _ListDemoState extends State<ListDemo> {
});
final StateSetter? bottomSheetSetState = _bottomSheet?.setState;
if (bottomSheetSetState != null) {
bottomSheetSetState(() { });
bottomSheetSetState(() {});
}
},
),
@@ -159,7 +175,7 @@ class _ListDemoState extends State<ListDemo> {
});
final StateSetter? bottomSheetSetState = _bottomSheet?.setState;
if (bottomSheetSetState != null) {
bottomSheetSetState(() { });
bottomSheetSetState(() {});
}
},
),
@@ -186,17 +202,20 @@ class _ListDemoState extends State<ListDemo> {
Widget buildListTile(BuildContext context, String item) {
final String? subtitle = switch (_itemType) {
_MaterialListType.oneLine || _MaterialListType.oneLineWithAvatar || null => null,
_MaterialListType.twoLine => 'Additional item information.',
_MaterialListType.threeLine => 'Even more additional list item information appears on line three.',
_MaterialListType.twoLine => 'Additional item information.',
_MaterialListType.threeLine =>
'Even more additional list item information appears on line three.',
};
return MergeSemantics(
child: ListTile(
isThreeLine: _itemType == _MaterialListType.threeLine,
dense: _dense,
leading: _showAvatars != null ? ExcludeSemantics(child: CircleAvatar(child: Text(item))) : null,
leading:
_showAvatars != null ? ExcludeSemantics(child: CircleAvatar(child: Text(item))) : null,
title: Text('This item represents $item.'),
subtitle: subtitle != null ? Text(subtitle) : null,
trailing: _showIcons != null ? Icon(Icons.info, color: Theme.of(context).disabledColor) : null,
trailing:
_showIcons != null ? Icon(Icons.info, color: Theme.of(context).disabledColor) : null,
),
);
}
@@ -234,9 +253,7 @@ class _ListDemoState extends State<ListDemo> {
),
IconButton(
icon: Icon(
Theme.of(context).platform == TargetPlatform.iOS
? Icons.more_horiz
: Icons.more_vert,
Theme.of(context).platform == TargetPlatform.iOS ? Icons.more_horiz : Icons.more_vert,
),
tooltip: 'Show menu',
onPressed: _bottomSheet == null ? _showConfigurationSheet : null,

View File

@@ -7,7 +7,7 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
class MenuDemo extends StatefulWidget {
const MenuDemo({ super.key });
const MenuDemo({super.key});
static const String routeName = '/material/menu';
@@ -16,7 +16,6 @@ class MenuDemo extends StatefulWidget {
}
class MenuDemoState extends State<MenuDemo> {
final String _simpleValue1 = 'Menu item value one';
final String _simpleValue2 = 'Menu item value two';
final String _simpleValue3 = 'Menu item value three';
@@ -36,9 +35,7 @@ class MenuDemoState extends State<MenuDemo> {
}
void showInSnackBar(String value) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(value),
));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(value)));
}
void showMenuSelection(String value) {
@@ -69,27 +66,18 @@ class MenuDemoState extends State<MenuDemo> {
MaterialDemoDocumentationButton(MenuDemo.routeName),
PopupMenuButton<String>(
onSelected: showMenuSelection,
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
const PopupMenuItem<String>(
value: 'Toolbar menu',
child: Text('Toolbar menu'),
),
const PopupMenuItem<String>(
value: 'Right here',
child: Text('Right here'),
),
const PopupMenuItem<String>(
value: 'Hooray!',
child: Text('Hooray!'),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuItem<String>>[
const PopupMenuItem<String>(value: 'Toolbar menu', child: Text('Toolbar menu')),
const PopupMenuItem<String>(value: 'Right here', child: Text('Right here')),
const PopupMenuItem<String>(value: 'Hooray!', child: Text('Hooray!')),
],
),
],
),
body: ListTileTheme(
iconColor: Theme.of(context).brightness == Brightness.light
? Colors.grey[600]
: Colors.grey[500],
iconColor:
Theme.of(context).brightness == Brightness.light ? Colors.grey[600] : Colors.grey[500],
child: ListView(
padding: kMaterialListPadding,
children: <Widget>[
@@ -101,20 +89,21 @@ class MenuDemoState extends State<MenuDemo> {
trailing: PopupMenuButton<String>(
padding: EdgeInsets.zero,
onSelected: showMenuSelection,
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
PopupMenuItem<String>(
value: _simpleValue1,
child: const Text('Context menu item one'),
),
const PopupMenuItem<String>(
enabled: false,
child: Text('A disabled menu item'),
),
PopupMenuItem<String>(
value: _simpleValue3,
child: const Text('Context menu item three'),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuItem<String>>[
PopupMenuItem<String>(
value: _simpleValue1,
child: const Text('Context menu item one'),
),
const PopupMenuItem<String>(
enabled: false,
child: Text('A disabled menu item'),
),
PopupMenuItem<String>(
value: _simpleValue3,
child: const Text('Context menu item three'),
),
],
),
),
// Pressing the PopupMenuButton on the right of this item shows
@@ -125,37 +114,26 @@ class MenuDemoState extends State<MenuDemo> {
trailing: PopupMenuButton<String>(
padding: EdgeInsets.zero,
onSelected: showMenuSelection,
itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: 'Preview',
child: ListTile(
leading: Icon(Icons.visibility),
title: Text('Preview'),
),
),
const PopupMenuItem<String>(
value: 'Share',
child: ListTile(
leading: Icon(Icons.person_add),
title: Text('Share'),
),
),
const PopupMenuItem<String>(
value: 'Get Link',
child: ListTile(
leading: Icon(Icons.link),
title: Text('Get link'),
),
),
const PopupMenuDivider(),
const PopupMenuItem<String>(
value: 'Remove',
child: ListTile(
leading: Icon(Icons.delete),
title: Text('Remove'),
),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: 'Preview',
child: ListTile(leading: Icon(Icons.visibility), title: Text('Preview')),
),
const PopupMenuItem<String>(
value: 'Share',
child: ListTile(leading: Icon(Icons.person_add), title: Text('Share')),
),
const PopupMenuItem<String>(
value: 'Get Link',
child: ListTile(leading: Icon(Icons.link), title: Text('Get link')),
),
const PopupMenuDivider(),
const PopupMenuItem<String>(
value: 'Remove',
child: ListTile(leading: Icon(Icons.delete), title: Text('Remove')),
),
],
),
),
// This entire list item is a PopupMenuButton. Tapping anywhere shows
@@ -169,20 +147,12 @@ class MenuDemoState extends State<MenuDemo> {
title: const Text('An item with a simple menu'),
subtitle: Text(_simpleValue!),
),
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
PopupMenuItem<String>(
value: _simpleValue1,
child: Text(_simpleValue1),
),
PopupMenuItem<String>(
value: _simpleValue2,
child: Text(_simpleValue2),
),
PopupMenuItem<String>(
value: _simpleValue3,
child: Text(_simpleValue3),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuItem<String>>[
PopupMenuItem<String>(value: _simpleValue1, child: Text(_simpleValue1)),
PopupMenuItem<String>(value: _simpleValue2, child: Text(_simpleValue2)),
PopupMenuItem<String>(value: _simpleValue3, child: Text(_simpleValue3)),
],
),
// Pressing the PopupMenuButton on the right of this item shows a menu
// whose items have checked icons that reflect this app's state.
@@ -191,29 +161,30 @@ class MenuDemoState extends State<MenuDemo> {
trailing: PopupMenuButton<String>(
padding: EdgeInsets.zero,
onSelected: showCheckedMenuSelections,
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
CheckedPopupMenuItem<String>(
value: _checkedValue1,
checked: isChecked(_checkedValue1),
child: Text(_checkedValue1),
),
CheckedPopupMenuItem<String>(
value: _checkedValue2,
enabled: false,
checked: isChecked(_checkedValue2),
child: Text(_checkedValue2),
),
CheckedPopupMenuItem<String>(
value: _checkedValue3,
checked: isChecked(_checkedValue3),
child: Text(_checkedValue3),
),
CheckedPopupMenuItem<String>(
value: _checkedValue4,
checked: isChecked(_checkedValue4),
child: Text(_checkedValue4),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuItem<String>>[
CheckedPopupMenuItem<String>(
value: _checkedValue1,
checked: isChecked(_checkedValue1),
child: Text(_checkedValue1),
),
CheckedPopupMenuItem<String>(
value: _checkedValue2,
enabled: false,
checked: isChecked(_checkedValue2),
child: Text(_checkedValue2),
),
CheckedPopupMenuItem<String>(
value: _checkedValue3,
checked: isChecked(_checkedValue3),
child: Text(_checkedValue3),
),
CheckedPopupMenuItem<String>(
value: _checkedValue4,
checked: isChecked(_checkedValue4),
child: Text(_checkedValue4),
),
],
),
),
],

View File

@@ -22,18 +22,22 @@ class ModalBottomSheetDemo extends StatelessWidget {
child: ElevatedButton(
child: const Text('SHOW BOTTOM SHEET'),
onPressed: () {
showModalBottomSheet<void>(context: context, builder: (BuildContext context) {
return Padding(
padding: const EdgeInsets.all(32.0),
child: Text('This is the modal bottom sheet. Slide down to dismiss.',
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).colorScheme.secondary,
fontSize: 24.0,
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return Padding(
padding: const EdgeInsets.all(32.0),
child: Text(
'This is the modal bottom sheet. Slide down to dismiss.',
textAlign: TextAlign.center,
style: TextStyle(
color: Theme.of(context).colorScheme.secondary,
fontSize: 24.0,
),
),
),
);
});
);
},
);
},
),
),

View File

@@ -11,7 +11,7 @@ import '../../gallery/demo.dart';
enum IndicatorType { overscroll, refresh }
class OverscrollDemo extends StatefulWidget {
const OverscrollDemo({ super.key });
const OverscrollDemo({super.key});
static const String routeName = '/material/overscroll';
@@ -22,7 +22,20 @@ class OverscrollDemo extends StatefulWidget {
class OverscrollDemoState extends State<OverscrollDemo> {
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = GlobalKey<RefreshIndicatorState>();
static final List<String> _items = <String>[
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
];
Future<void> _handleRefresh() {
@@ -32,15 +45,17 @@ class OverscrollDemoState extends State<OverscrollDemo> {
if (!mounted) {
return;
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('Refresh complete'),
action: SnackBarAction(
label: 'RETRY',
onPressed: () {
_refreshIndicatorKey.currentState!.show();
},
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: const Text('Refresh complete'),
action: SnackBarAction(
label: 'RETRY',
onPressed: () {
_refreshIndicatorKey.currentState!.show();
},
),
),
));
);
});
}
@@ -74,7 +89,9 @@ class OverscrollDemoState extends State<OverscrollDemo> {
isThreeLine: true,
leading: CircleAvatar(child: Text(item)),
title: Text('This item represents $item.'),
subtitle: const Text('Even more additional list item information appears on line three.'),
subtitle: const Text(
'Even more additional list item information appears on line three.',
),
);
},
),

View File

@@ -7,7 +7,7 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
class _PageSelector extends StatelessWidget {
const _PageSelector({ this.icons });
const _PageSelector({this.icons});
final List<Icon>? icons;
@@ -35,14 +35,18 @@ class _PageSelector extends StatelessWidget {
IconButton(
icon: const Icon(Icons.chevron_left),
color: color,
onPressed: () { _handleArrowButtonPress(context, -1); },
onPressed: () {
_handleArrowButtonPress(context, -1);
},
tooltip: 'Page back',
),
TabPageSelector(controller: controller),
IconButton(
icon: const Icon(Icons.chevron_right),
color: color,
onPressed: () { _handleArrowButtonPress(context, 1); },
onPressed: () {
_handleArrowButtonPress(context, 1);
},
tooltip: 'Page forward',
),
],
@@ -50,21 +54,15 @@ class _PageSelector extends StatelessWidget {
),
Expanded(
child: IconTheme(
data: IconThemeData(
size: 128.0,
color: color,
),
data: IconThemeData(size: 128.0, color: color),
child: TabBarView(
children: icons!.map<Widget>((Icon icon) {
return Container(
padding: const EdgeInsets.all(12.0),
child: Card(
child: Center(
child: icon,
),
),
);
}).toList(),
children:
icons!.map<Widget>((Icon icon) {
return Container(
padding: const EdgeInsets.all(12.0),
child: Card(child: Center(child: icon)),
);
}).toList(),
),
),
),
@@ -94,10 +92,7 @@ class PageSelectorDemo extends StatelessWidget {
title: const Text('Page selector'),
actions: <Widget>[MaterialDemoDocumentationButton(routeName)],
),
body: DefaultTabController(
length: icons.length,
child: _PageSelector(icons: icons),
),
body: DefaultTabController(length: icons.length, child: _PageSelector(icons: icons)),
);
}
}

View File

@@ -27,34 +27,36 @@ class _PersistentBottomSheetDemoState extends State<PersistentBottomSheetDemo> {
}
void _showBottomSheet() {
setState(() { // disable the button
setState(() {
// disable the button
_showBottomSheetCallback = null;
});
_scaffoldKey.currentState!.showBottomSheet((BuildContext context) {
final ThemeData themeData = Theme.of(context);
return Container(
decoration: BoxDecoration(
border: Border(top: BorderSide(color: themeData.disabledColor))
),
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Text('This is a Material persistent bottom sheet. Drag downwards to dismiss it.',
textAlign: TextAlign.center,
style: TextStyle(
color: themeData.colorScheme.secondary,
fontSize: 24.0,
_scaffoldKey.currentState!
.showBottomSheet((BuildContext context) {
final ThemeData themeData = Theme.of(context);
return Container(
decoration: BoxDecoration(
border: Border(top: BorderSide(color: themeData.disabledColor)),
),
),
),
);
})
.closed.whenComplete(() {
if (mounted) {
setState(() { // re-enable the button
_showBottomSheetCallback = _showBottomSheet;
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Text(
'This is a Material persistent bottom sheet. Drag downwards to dismiss it.',
textAlign: TextAlign.center,
style: TextStyle(color: themeData.colorScheme.secondary, fontSize: 24.0),
),
),
);
})
.closed
.whenComplete(() {
if (mounted) {
setState(() {
// re-enable the button
_showBottomSheetCallback = _showBottomSheet;
});
}
});
}
});
}
void _showMessage() {
@@ -82,17 +84,12 @@ class _PersistentBottomSheetDemoState extends State<PersistentBottomSheetDemo> {
key: _scaffoldKey,
appBar: AppBar(
title: const Text('Persistent bottom sheet'),
actions: <Widget>[
MaterialDemoDocumentationButton(PersistentBottomSheetDemo.routeName),
],
actions: <Widget>[MaterialDemoDocumentationButton(PersistentBottomSheetDemo.routeName)],
),
floatingActionButton: FloatingActionButton(
onPressed: _showMessage,
backgroundColor: Colors.redAccent,
child: const Icon(
Icons.add,
semanticLabel: 'Add',
),
child: const Icon(Icons.add, semanticLabel: 'Add'),
),
body: Center(
child: ElevatedButton(

View File

@@ -15,7 +15,8 @@ class ProgressIndicatorDemo extends StatefulWidget {
State<ProgressIndicatorDemo> createState() => _ProgressIndicatorDemoState();
}
class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo> with SingleTickerProviderStateMixin {
class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<double> _animation;
@@ -67,10 +68,7 @@ class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo> with Sing
Widget _buildIndicators(BuildContext context, Widget? child) {
final List<Widget> indicators = <Widget>[
const SizedBox(
width: 200.0,
child: LinearProgressIndicator(),
),
const SizedBox(width: 200.0, child: LinearProgressIndicator()),
const LinearProgressIndicator(),
const LinearProgressIndicator(),
LinearProgressIndicator(value: _animation.value),
@@ -79,14 +77,15 @@ class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo> with Sing
children: <Widget>[
const CircularProgressIndicator(),
SizedBox(
width: 20.0,
height: 20.0,
child: CircularProgressIndicator(value: _animation.value),
width: 20.0,
height: 20.0,
child: CircularProgressIndicator(value: _animation.value),
),
SizedBox(
width: 100.0,
height: 20.0,
child: Text('${(_animation.value * 100.0).toStringAsFixed(1)}%',
child: Text(
'${(_animation.value * 100.0).toStringAsFixed(1)}%',
textAlign: TextAlign.right,
),
),
@@ -94,12 +93,15 @@ class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo> with Sing
),
];
return Column(
children: indicators
.map<Widget>((Widget c) => Container(
margin: const EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0),
child: c,
))
.toList(),
children:
indicators
.map<Widget>(
(Widget c) => Container(
margin: const EdgeInsets.symmetric(vertical: 15.0, horizontal: 20.0),
child: c,
),
)
.toList(),
);
}
@@ -122,10 +124,7 @@ class _ProgressIndicatorDemoState extends State<ProgressIndicatorDemo> with Sing
bottom: false,
child: Container(
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
child: AnimatedBuilder(
animation: _animation,
builder: _buildIndicators,
),
child: AnimatedBuilder(animation: _animation, builder: _buildIndicators),
),
),
),

View File

@@ -18,7 +18,7 @@ enum _ReorderableListType {
}
class ReorderableListDemo extends StatefulWidget {
const ReorderableListDemo({ super.key });
const ReorderableListDemo({super.key});
static const String routeName = '/material/reorderable-list';
@@ -41,9 +41,23 @@ class _ListDemoState extends State<ReorderableListDemo> {
_ReorderableListType? _itemType = _ReorderableListType.threeLine;
bool? _reverse = false;
bool _reverseSort = false;
final List<_ListItem> _items = <String>[
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
].map<_ListItem>((String item) => _ListItem(item, false)).toList();
final List<_ListItem> _items =
<String>[
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
].map<_ListItem>((String item) => _ListItem(item, false)).toList();
void changeItemType(_ReorderableListType? type) {
setState(() {
@@ -73,9 +87,7 @@ class _ListDemoState extends State<ReorderableListDemo> {
setState(() {
_bottomSheet = scaffoldKey.currentState!.showBottomSheet((BuildContext bottomSheetContext) {
return DecoratedBox(
decoration: const BoxDecoration(
border: Border(top: BorderSide(color: Colors.black26)),
),
decoration: const BoxDecoration(border: Border(top: BorderSide(color: Colors.black26))),
child: ListView(
shrinkWrap: true,
primary: false,
@@ -149,15 +161,10 @@ class _ListDemoState extends State<ReorderableListDemo> {
key: Key(item.value),
height: 100.0,
width: 100.0,
child: CircleAvatar(
backgroundColor: Colors.green,
child: Text(item.value),
),
child: CircleAvatar(backgroundColor: Colors.green, child: Text(item.value)),
);
case null:
listTile = Container(
key: Key(item.value),
);
listTile = Container(key: Key(item.value));
}
return listTile;
@@ -173,7 +180,6 @@ class _ListDemoState extends State<ReorderableListDemo> {
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
@@ -188,15 +194,16 @@ class _ListDemoState extends State<ReorderableListDemo> {
onPressed: () {
setState(() {
_reverseSort = !_reverseSort;
_items.sort((_ListItem a, _ListItem b) => _reverseSort ? b.value.compareTo(a.value) : a.value.compareTo(b.value));
_items.sort(
(_ListItem a, _ListItem b) =>
_reverseSort ? b.value.compareTo(a.value) : a.value.compareTo(b.value),
);
});
},
),
IconButton(
icon: Icon(
Theme.of(context).platform == TargetPlatform.iOS
? Icons.more_horiz
: Icons.more_vert,
Theme.of(context).platform == TargetPlatform.iOS ? Icons.more_horiz : Icons.more_vert,
),
tooltip: 'Show menu',
onPressed: _bottomSheet == null ? _showConfigurationSheet : null,
@@ -206,14 +213,20 @@ class _ListDemoState extends State<ReorderableListDemo> {
body: Scrollbar(
child: ReorderableListView(
primary: true,
header: _itemType != _ReorderableListType.threeLine
? Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Header of the list', style: Theme.of(context).textTheme.headlineSmall))
: null,
header:
_itemType != _ReorderableListType.threeLine
? Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Header of the list',
style: Theme.of(context).textTheme.headlineSmall,
),
)
: null,
onReorder: _onReorder,
reverse: _reverse!,
scrollDirection: _itemType == _ReorderableListType.horizontalAvatar ? Axis.horizontal : Axis.vertical,
scrollDirection:
_itemType == _ReorderableListType.horizontalAvatar ? Axis.horizontal : Axis.vertical,
padding: const EdgeInsets.symmetric(vertical: 8.0),
children: _items.map<Widget>(buildListTile).toList(),
),

View File

@@ -6,14 +6,10 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
enum TabsDemoStyle {
iconsAndText,
iconsOnly,
textOnly
}
enum TabsDemoStyle { iconsAndText, iconsOnly, textOnly }
class _Page {
const _Page({ this.icon, this.text });
const _Page({this.icon, this.text});
final IconData? icon;
final String? text;
}
@@ -44,7 +40,8 @@ class ScrollableTabsDemo extends StatefulWidget {
ScrollableTabsDemoState createState() => ScrollableTabsDemoState();
}
class ScrollableTabsDemoState extends State<ScrollableTabsDemo> with SingleTickerProviderStateMixin {
class ScrollableTabsDemoState extends State<ScrollableTabsDemo>
with SingleTickerProviderStateMixin {
TabController? _controller;
TabsDemoStyle _demoStyle = TabsDemoStyle.iconsAndText;
bool _customIndicator = false;
@@ -75,49 +72,29 @@ class ScrollableTabsDemoState extends State<ScrollableTabsDemo> with SingleTicke
switch (_demoStyle) {
case TabsDemoStyle.iconsAndText:
return ShapeDecoration(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
side: BorderSide(
color: Colors.white24,
width: 2.0,
),
) + const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
side: BorderSide(
color: Colors.transparent,
width: 4.0,
),
),
shape:
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
side: BorderSide(color: Colors.white24, width: 2.0),
) +
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
side: BorderSide(color: Colors.transparent, width: 4.0),
),
);
case TabsDemoStyle.iconsOnly:
return ShapeDecoration(
shape: const CircleBorder(
side: BorderSide(
color: Colors.white24,
width: 4.0,
),
) + const CircleBorder(
side: BorderSide(
color: Colors.transparent,
width: 4.0,
),
),
shape:
const CircleBorder(side: BorderSide(color: Colors.white24, width: 4.0)) +
const CircleBorder(side: BorderSide(color: Colors.transparent, width: 4.0)),
);
case TabsDemoStyle.textOnly:
return ShapeDecoration(
shape: const StadiumBorder(
side: BorderSide(
color: Colors.white24,
width: 2.0,
),
) + const StadiumBorder(
side: BorderSide(
color: Colors.transparent,
width: 4.0,
),
),
shape:
const StadiumBorder(side: BorderSide(color: Colors.white24, width: 2.0)) +
const StadiumBorder(side: BorderSide(color: Colors.transparent, width: 4.0)),
);
}
}
@@ -142,57 +119,60 @@ class ScrollableTabsDemoState extends State<ScrollableTabsDemo> with SingleTicke
PopupMenuButton<TabsDemoStyle>(
tooltip: 'Popup Menu',
onSelected: changeDemoStyle,
itemBuilder: (BuildContext context) => <PopupMenuItem<TabsDemoStyle>>[
const PopupMenuItem<TabsDemoStyle>(
value: TabsDemoStyle.iconsAndText,
child: Text('Icons and text'),
),
const PopupMenuItem<TabsDemoStyle>(
value: TabsDemoStyle.iconsOnly,
child: Text('Icons only'),
),
const PopupMenuItem<TabsDemoStyle>(
value: TabsDemoStyle.textOnly,
child: Text('Text only'),
),
],
itemBuilder:
(BuildContext context) => <PopupMenuItem<TabsDemoStyle>>[
const PopupMenuItem<TabsDemoStyle>(
value: TabsDemoStyle.iconsAndText,
child: Text('Icons and text'),
),
const PopupMenuItem<TabsDemoStyle>(
value: TabsDemoStyle.iconsOnly,
child: Text('Icons only'),
),
const PopupMenuItem<TabsDemoStyle>(
value: TabsDemoStyle.textOnly,
child: Text('Text only'),
),
],
),
],
bottom: TabBar(
controller: _controller,
isScrollable: true,
indicator: getIndicator(),
tabs: _allPages.map<Tab>((_Page page) {
return switch (_demoStyle) {
TabsDemoStyle.iconsAndText => Tab(text: page.text, icon: Icon(page.icon)),
TabsDemoStyle.iconsOnly => Tab(icon: Icon(page.icon)),
TabsDemoStyle.textOnly => Tab(text: page.text),
};
}).toList()
tabs:
_allPages.map<Tab>((_Page page) {
return switch (_demoStyle) {
TabsDemoStyle.iconsAndText => Tab(text: page.text, icon: Icon(page.icon)),
TabsDemoStyle.iconsOnly => Tab(icon: Icon(page.icon)),
TabsDemoStyle.textOnly => Tab(text: page.text),
};
}).toList(),
),
),
body: TabBarView(
controller: _controller,
children: _allPages.map<Widget>((_Page page) {
return SafeArea(
top: false,
bottom: false,
child: Container(
key: ObjectKey(page.icon),
padding: const EdgeInsets.all(12.0),
child: Card(
child: Center(
child: Icon(
page.icon,
color: iconColor,
size: 128.0,
semanticLabel: 'Placeholder for ${page.text} tab',
children:
_allPages.map<Widget>((_Page page) {
return SafeArea(
top: false,
bottom: false,
child: Container(
key: ObjectKey(page.icon),
padding: const EdgeInsets.all(12.0),
child: Card(
child: Center(
child: Icon(
page.icon,
color: iconColor,
size: 128.0,
semanticLabel: 'Placeholder for ${page.text} tab',
),
),
),
),
),
),
);
}).toList(),
);
}).toList(),
),
);
}

View File

@@ -43,10 +43,7 @@ class _SearchDemoState extends State<SearchDemo> {
tooltip: 'Search',
icon: const Icon(Icons.search),
onPressed: () async {
final int? selected = await showSearch<int?>(
context: context,
delegate: _delegate,
);
final int? selected = await showSearch<int?>(context: context, delegate: _delegate);
if (selected != null && selected != _lastIntegerSelected) {
setState(() {
_lastIntegerSelected = selected;
@@ -58,11 +55,9 @@ class _SearchDemoState extends State<SearchDemo> {
IconButton(
tooltip: 'More (not implemented)',
icon: Icon(
Theme.of(context).platform == TargetPlatform.iOS
? Icons.more_horiz
: Icons.more_vert,
Theme.of(context).platform == TargetPlatform.iOS ? Icons.more_horiz : Icons.more_vert,
),
onPressed: () { },
onPressed: () {},
),
],
),
@@ -78,13 +73,7 @@ class _SearchDemoState extends State<SearchDemo> {
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Press the '),
Tooltip(
message: 'search',
child: Icon(
Icons.search,
size: 18.0,
),
),
Tooltip(message: 'search', child: Icon(Icons.search, size: 18.0)),
Text(' icon in the AppBar'),
],
),
@@ -93,7 +82,7 @@ class _SearchDemoState extends State<SearchDemo> {
),
),
const SizedBox(height: 64.0),
Text('Last selected integer: ${_lastIntegerSelected ?? 'NONE' }.'),
Text('Last selected integer: ${_lastIntegerSelected ?? 'NONE'}.'),
],
),
),
@@ -123,10 +112,7 @@ class _SearchDemoState extends State<SearchDemo> {
context: context,
// DrawerHeader consumes top MediaQuery padding.
removeTop: true,
child: const ListTile(
leading: Icon(Icons.payment),
title: Text('Placeholder'),
),
child: const ListTile(leading: Icon(Icons.payment), title: Text('Placeholder')),
),
],
),
@@ -143,10 +129,7 @@ class _SearchDemoSearchDelegate extends SearchDelegate<int?> {
Widget buildLeading(BuildContext context) {
return IconButton(
tooltip: 'Back',
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
icon: AnimatedIcon(icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
onPressed: () {
close(context, null);
},
@@ -155,10 +138,8 @@ class _SearchDemoSearchDelegate extends SearchDelegate<int?> {
@override
Widget buildSuggestions(BuildContext context) {
final Iterable<int> suggestions = query.isEmpty
? _history
: _data.where((int i) => '$i'.startsWith(query));
final Iterable<int> suggestions =
query.isEmpty ? _history : _data.where((int i) => '$i'.startsWith(query));
return _SuggestionList(
query: query,
@@ -184,21 +165,9 @@ class _SearchDemoSearchDelegate extends SearchDelegate<int?> {
return ListView(
children: <Widget>[
_ResultCard(
title: 'This integer',
integer: searched,
searchDelegate: this,
),
_ResultCard(
title: 'Next integer',
integer: searched + 1,
searchDelegate: this,
),
_ResultCard(
title: 'Previous integer',
integer: searched - 1,
searchDelegate: this,
),
_ResultCard(title: 'This integer', integer: searched, searchDelegate: this),
_ResultCard(title: 'Next integer', integer: searched + 1, searchDelegate: this),
_ResultCard(title: 'Previous integer', integer: searched - 1, searchDelegate: this),
],
);
}
@@ -227,10 +196,8 @@ class _SearchDemoSearchDelegate extends SearchDelegate<int?> {
}
@override
PreferredSizeWidget buildBottom(BuildContext context) => const PreferredSize(
preferredSize: Size.fromHeight(56.0),
child: Text('Numbers'),
);
PreferredSizeWidget buildBottom(BuildContext context) =>
const PreferredSize(preferredSize: Size.fromHeight(56.0), child: Text('Numbers'));
}
class _ResultCard extends StatelessWidget {
@@ -253,10 +220,7 @@ class _ResultCard extends StatelessWidget {
child: Column(
children: <Widget>[
Text(title!),
Text(
'$integer',
style: theme.textTheme.headlineSmall!.copyWith(fontSize: 72.0),
),
Text('$integer', style: theme.textTheme.headlineSmall!.copyWith(fontSize: 72.0)),
],
),
),

View File

@@ -7,23 +7,23 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
const String _checkboxText =
'Checkboxes allow the user to select multiple options from a set. '
"A normal checkbox's value is true or false and a tristate checkbox's "
'value can also be null.';
'Checkboxes allow the user to select multiple options from a set. '
"A normal checkbox's value is true or false and a tristate checkbox's "
'value can also be null.';
const String _checkboxCode = 'selectioncontrols_checkbox';
const String _radioText =
'Radio buttons allow the user to select one option from a set. Use radio '
'buttons for exclusive selection if you think that the user needs to see '
'all available options side-by-side.';
'Radio buttons allow the user to select one option from a set. Use radio '
'buttons for exclusive selection if you think that the user needs to see '
'all available options side-by-side.';
const String _radioCode = 'selectioncontrols_radio';
const String _switchText =
'On/off switches toggle the state of a single settings option. The option '
'that the switch controls, as well as the state it’s in, should be made '
'clear from the corresponding inline label.';
'On/off switches toggle the state of a single settings option. The option '
'that the switch controls, as well as the state it’s in, should be made '
'clear from the corresponding inline label.';
const String _switchCode = 'selectioncontrols_switch';
@@ -63,10 +63,7 @@ class _SelectionControlsDemoState extends State<SelectionControlsDemo> {
),
];
return TabbedComponentDemoScaffold(
title: 'Selection controls',
demos: demos,
);
return TabbedComponentDemoScaffold(title: 'Selection controls', demos: demos);
}
bool? checkboxValueA = true;
@@ -149,42 +146,18 @@ class _SelectionControlsDemoState extends State<SelectionControlsDemo> {
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Radio<int>(
value: 0,
groupValue: radioValue,
onChanged: handleRadioValueChanged,
),
Radio<int>(
value: 1,
groupValue: radioValue,
onChanged: handleRadioValueChanged,
),
Radio<int>(
value: 2,
groupValue: radioValue,
onChanged: handleRadioValueChanged,
),
Radio<int>(value: 0, groupValue: radioValue, onChanged: handleRadioValueChanged),
Radio<int>(value: 1, groupValue: radioValue, onChanged: handleRadioValueChanged),
Radio<int>(value: 2, groupValue: radioValue, onChanged: handleRadioValueChanged),
],
),
// Disabled radio buttons
const Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Radio<int>(
value: 0,
groupValue: 0,
onChanged: null,
),
Radio<int>(
value: 1,
groupValue: 0,
onChanged: null,
),
Radio<int>(
value: 2,
groupValue: 0,
onChanged: null,
),
Radio<int>(value: 0, groupValue: 0, onChanged: null),
Radio<int>(value: 1, groupValue: 0, onChanged: null),
Radio<int>(value: 2, groupValue: 0, onChanged: null),
],
),
],

View File

@@ -17,7 +17,7 @@ class SliderDemo extends StatefulWidget {
State<SliderDemo> createState() => _SliderDemoState();
}
Path _downTriangle(double size, Offset thumbCenter, { bool invert = false }) {
Path _downTriangle(double size, Offset thumbCenter, {bool invert = false}) {
final Path thumbPath = Path();
final double height = math.sqrt(3.0) / 2.0;
final double centerHeight = size * height / 3.0;
@@ -30,7 +30,7 @@ Path _downTriangle(double size, Offset thumbCenter, { bool invert = false }) {
return thumbPath;
}
Path _rightTriangle(double size, Offset thumbCenter, { bool invert = false }) {
Path _rightTriangle(double size, Offset thumbCenter, {bool invert = false}) {
final Path thumbPath = Path();
final double halfSize = size / 2.0;
final double sign = invert ? -1.0 : 1.0;
@@ -43,7 +43,8 @@ Path _rightTriangle(double size, Offset thumbCenter, { bool invert = false }) {
Path _upTriangle(double size, Offset thumbCenter) => _downTriangle(size, thumbCenter, invert: true);
Path _leftTriangle(double size, Offset thumbCenter) => _rightTriangle(size, thumbCenter, invert: true);
Path _leftTriangle(double size, Offset thumbCenter) =>
_rightTriangle(size, thumbCenter, invert: true);
class _CustomRangeThumbShape extends RangeSliderThumbShape {
static const double _thumbSize = 4.0;
@@ -51,7 +52,9 @@ class _CustomRangeThumbShape extends RangeSliderThumbShape {
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return isEnabled ? const Size.fromRadius(_thumbSize) : const Size.fromRadius(_disabledThumbSize);
return isEnabled
? const Size.fromRadius(_thumbSize)
: const Size.fromRadius(_disabledThumbSize);
}
static final Animatable<double> sizeTween = Tween<double>(
@@ -82,9 +85,9 @@ class _CustomRangeThumbShape extends RangeSliderThumbShape {
final double size = _thumbSize * sizeTween.evaluate(enableAnimation);
final Path thumbPath = switch ((textDirection!, thumb!)) {
(TextDirection.rtl, Thumb.start) => _rightTriangle(size, center),
(TextDirection.rtl, Thumb.end) => _leftTriangle(size, center),
(TextDirection.rtl, Thumb.end) => _leftTriangle(size, center),
(TextDirection.ltr, Thumb.start) => _leftTriangle(size, center),
(TextDirection.ltr, Thumb.end) => _rightTriangle(size, center),
(TextDirection.ltr, Thumb.end) => _rightTriangle(size, center),
};
canvas.drawPath(thumbPath, Paint()..color = colorTween.evaluate(enableAnimation)!);
}
@@ -96,7 +99,9 @@ class _CustomThumbShape extends SliderComponentShape {
@override
Size getPreferredSize(bool isEnabled, bool isDiscrete) {
return isEnabled ? const Size.fromRadius(_thumbSize) : const Size.fromRadius(_disabledThumbSize);
return isEnabled
? const Size.fromRadius(_thumbSize)
: const Size.fromRadius(_disabledThumbSize);
}
static final Animatable<double> sizeTween = Tween<double>(
@@ -165,26 +170,26 @@ class _CustomValueIndicatorShape extends SliderComponentShape {
begin: sliderTheme.disabledThumbColor,
end: sliderTheme.valueIndicatorColor,
);
final Tween<double> slideUpTween = Tween<double>(
begin: 0.0,
end: _slideUpHeight,
);
final Tween<double> slideUpTween = Tween<double>(begin: 0.0, end: _slideUpHeight);
final double size = _indicatorSize * sizeTween.evaluate(enableAnimation);
final Offset slideUpOffset = Offset(0.0, -slideUpTween.evaluate(activationAnimation));
final Path thumbPath = _upTriangle(size, thumbCenter + slideUpOffset);
final Color paintColor = enableColor.evaluate(enableAnimation)!.withAlpha((255.0 * activationAnimation.value).round());
canvas.drawPath(
thumbPath,
Paint()..color = paintColor,
);
final Color paintColor = enableColor
.evaluate(enableAnimation)!
.withAlpha((255.0 * activationAnimation.value).round());
canvas.drawPath(thumbPath, Paint()..color = paintColor);
canvas.drawLine(
thumbCenter,
thumbCenter + slideUpOffset,
Paint()
..color = paintColor
..style = PaintingStyle.stroke
..strokeWidth = 2.0);
labelPainter.paint(canvas, thumbCenter + slideUpOffset + Offset(-labelPainter.width / 2.0, -labelPainter.height - 4.0));
thumbCenter,
thumbCenter + slideUpOffset,
Paint()
..color = paintColor
..style = PaintingStyle.stroke
..strokeWidth = 2.0,
);
labelPainter.paint(
canvas,
thumbCenter + slideUpOffset + Offset(-labelPainter.width / 2.0, -labelPainter.height - 4.0),
);
}
}
@@ -254,9 +259,7 @@ class _SlidersState extends State<_Sliders> {
}
},
keyboardType: TextInputType.number,
controller: TextEditingController(
text: _continuousValue.toStringAsFixed(0),
),
controller: TextEditingController(text: _continuousValue.toStringAsFixed(0)),
),
),
),
@@ -275,10 +278,7 @@ class _SlidersState extends State<_Sliders> {
),
const Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Slider.adaptive(value: 0.25, onChanged: null),
Text('Disabled'),
],
children: <Widget>[Slider.adaptive(value: 0.25, onChanged: null), Text('Disabled')],
),
Column(
mainAxisSize: MainAxisSize.min,
@@ -311,7 +311,9 @@ class _SlidersState extends State<_Sliders> {
valueIndicatorColor: Colors.deepPurpleAccent,
thumbShape: _CustomThumbShape(),
valueIndicatorShape: _CustomValueIndicatorShape(),
valueIndicatorTextStyle: theme.textTheme.bodyLarge!.copyWith(color: theme.colorScheme.onSurface),
valueIndicatorTextStyle: theme.textTheme.bodyLarge!.copyWith(
color: theme.colorScheme.onSurface,
),
),
child: Slider(
value: _discreteCustomValue,
@@ -383,7 +385,10 @@ class _RangeSlidersState extends State<_RangeSliders> {
values: _discreteValues,
max: 200.0,
divisions: 5,
labels: RangeLabels('${_discreteValues.start.round()}', '${_discreteValues.end.round()}'),
labels: RangeLabels(
'${_discreteValues.start.round()}',
'${_discreteValues.end.round()}',
),
onChanged: (RangeValues values) {
setState(() {
_discreteValues = values;
@@ -411,7 +416,10 @@ class _RangeSlidersState extends State<_RangeSliders> {
values: _discreteCustomValues,
max: 200.0,
divisions: 5,
labels: RangeLabels('${_discreteCustomValues.start.round()}', '${_discreteCustomValues.end.round()}'),
labels: RangeLabels(
'${_discreteCustomValues.start.round()}',
'${_discreteCustomValues.end.round()}',
),
onChanged: (RangeValues values) {
setState(() {
_discreteCustomValues = values;

View File

@@ -7,19 +7,18 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
const String _text1 =
'Snackbars provide lightweight feedback about an operation by '
'showing a brief message at the bottom of the screen. Snackbars '
'can contain an action.';
'Snackbars provide lightweight feedback about an operation by '
'showing a brief message at the bottom of the screen. Snackbars '
'can contain an action.';
const String _text2 =
'Snackbars should contain a single line of text directly related '
'to the operation performed. They cannot contain icons.';
'Snackbars should contain a single line of text directly related '
'to the operation performed. They cannot contain icons.';
const String _text3 =
'By default snackbars automatically disappear after a few seconds ';
const String _text3 = 'By default snackbars automatically disappear after a few seconds ';
class SnackBarDemo extends StatefulWidget {
const SnackBarDemo({ super.key });
const SnackBarDemo({super.key});
static const String routeName = '/material/snack-bar';
@@ -36,37 +35,37 @@ class _SnackBarDemoState extends State<SnackBarDemo> {
bottom: false,
child: ListView(
padding: const EdgeInsets.all(24.0),
children: <Widget>[
const Text(_text1),
const Text(_text2),
Center(
child: ElevatedButton(
child: const Text('SHOW A SNACKBAR'),
onPressed: () {
final int thisSnackBarIndex = _snackBarIndex++;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('This is snackbar #$thisSnackBarIndex.'),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text("You pressed snackbar $thisSnackBarIndex's action."),
));
},
),
));
},
),
),
const Text(_text3),
]
.map<Widget>((Widget child) {
return Container(
margin: const EdgeInsets.symmetric(vertical: 12.0),
child: child,
);
})
.toList(),
children:
<Widget>[
const Text(_text1),
const Text(_text2),
Center(
child: ElevatedButton(
child: const Text('SHOW A SNACKBAR'),
onPressed: () {
final int thisSnackBarIndex = _snackBarIndex++;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('This is snackbar #$thisSnackBarIndex.'),
action: SnackBarAction(
label: 'ACTION',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("You pressed snackbar $thisSnackBarIndex's action."),
),
);
},
),
),
);
},
),
),
const Text(_text3),
].map<Widget>((Widget child) {
return Container(margin: const EdgeInsets.symmetric(vertical: 12.0), child: child);
}).toList(),
),
);
}
@@ -81,7 +80,7 @@ class _SnackBarDemoState extends State<SnackBarDemo> {
body: Builder(
// Create an inner BuildContext so that the snackBar onPressed methods
// can refer to the Scaffold with Scaffold.of().
builder: buildBody
builder: buildBody,
),
floatingActionButton: FloatingActionButton(
tooltip: 'Create',

View File

@@ -12,7 +12,7 @@ import '../../gallery/demo.dart';
const String _kGalleryAssetsPackage = 'flutter_gallery_assets';
class _Page {
_Page({ this.label });
_Page({this.label});
final String? label;
String get id => label!.characters.first;
@override
@@ -20,7 +20,7 @@ class _Page {
}
class _CardData {
const _CardData({ this.title, this.imageAsset, this.imageAssetPackage });
const _CardData({this.title, this.imageAsset, this.imageAssetPackage});
final String? title;
final String? imageAsset;
final String? imageAssetPackage;
@@ -94,7 +94,7 @@ final Map<_Page, List<_CardData>> _allPages = <_Page, List<_CardData>>{
};
class _CardDataItem extends StatelessWidget {
const _CardDataItem({ this.page, this.data });
const _CardDataItem({this.page, this.data});
static const double height = 272.0;
final _Page? page;
@@ -109,9 +109,7 @@ class _CardDataItem extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Align(
alignment: page!.id == 'H'
? Alignment.centerLeft
: Alignment.centerRight,
alignment: page!.id == 'H' ? Alignment.centerLeft : Alignment.centerRight,
child: CircleAvatar(child: Text(page!.id)),
),
SizedBox(
@@ -123,12 +121,7 @@ class _CardDataItem extends StatelessWidget {
fit: BoxFit.contain,
),
),
Center(
child: Text(
data!.title!,
style: Theme.of(context).textTheme.titleLarge,
),
),
Center(child: Text(data!.title!, style: Theme.of(context).textTheme.titleLarge)),
],
),
),
@@ -158,57 +151,49 @@ class TabsDemo extends StatelessWidget {
expandedHeight: 150.0,
forceElevated: innerBoxIsScrolled,
bottom: TabBar(
tabs: _allPages.keys.map<Widget>(
(_Page page) => Tab(text: page.label),
).toList(),
tabs:
_allPages.keys.map<Widget>((_Page page) => Tab(text: page.label)).toList(),
),
),
),
];
},
body: TabBarView(
children: _allPages.keys.map<Widget>((_Page page) {
return SafeArea(
top: false,
bottom: false,
child: Builder(
builder: (BuildContext context) {
return CustomScrollView(
key: PageStorageKey<_Page>(page),
slivers: <Widget>[
SliverOverlapInjector(
handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
),
SliverPadding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 16.0,
),
sliver: SliverFixedExtentList(
itemExtent: _CardDataItem.height,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
final _CardData data = _allPages[page]![index];
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
),
child: _CardDataItem(
page: page,
data: data,
),
);
},
childCount: _allPages[page]!.length,
children:
_allPages.keys.map<Widget>((_Page page) {
return SafeArea(
top: false,
bottom: false,
child: Builder(
builder: (BuildContext context) {
return CustomScrollView(
key: PageStorageKey<_Page>(page),
slivers: <Widget>[
SliverOverlapInjector(
handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
),
),
),
],
);
},
),
);
}).toList(),
SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
sliver: SliverFixedExtentList(
itemExtent: _CardDataItem.height,
delegate: SliverChildBuilderDelegate((
BuildContext context,
int index,
) {
final _CardData data = _allPages[page]![index];
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: _CardDataItem(page: page, data: data),
);
}, childCount: _allPages[page]!.length),
),
),
],
);
},
),
);
}).toList(),
),
),
),

View File

@@ -7,13 +7,13 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
const String _explanatoryText =
"When the Scaffold's floating action button changes, the new button fades and "
'turns into view. In this demo, changing tabs can cause the app to be rebuilt '
'with a FloatingActionButton that the Scaffold distinguishes from the others '
'by its key.';
"When the Scaffold's floating action button changes, the new button fades and "
'turns into view. In this demo, changing tabs can cause the app to be rebuilt '
'with a FloatingActionButton that the Scaffold distinguishes from the others '
'by its key.';
class _Page {
_Page({ this.label, this.colors, this.icon });
_Page({this.label, this.colors, this.icon});
final String? label;
final MaterialColor? colors;
@@ -74,7 +74,7 @@ class _TabsFabDemoState extends State<TabsFabDemo> with SingleTickerProviderStat
_scaffoldKey.currentState!.showBottomSheet((BuildContext context) {
return Container(
decoration: BoxDecoration(
border: Border(top: BorderSide(color: Theme.of(context).dividerColor))
border: Border(top: BorderSide(color: Theme.of(context).dividerColor)),
),
child: Padding(
padding: const EdgeInsets.all(32.0),
@@ -92,17 +92,15 @@ class _TabsFabDemoState extends State<TabsFabDemo> with SingleTickerProviderStat
padding: const EdgeInsets.fromLTRB(48.0, 48.0, 48.0, 96.0),
child: Card(
child: Center(
child: Text(page.label!,
style: TextStyle(
color: page.labelColor,
fontSize: 32.0,
),
child: Text(
page.label!,
style: TextStyle(color: page.labelColor, fontSize: 32.0),
textAlign: TextAlign.center,
),
),
),
);
}
},
);
}
@@ -139,12 +137,16 @@ class _TabsFabDemoState extends State<TabsFabDemo> with SingleTickerProviderStat
title: const Text('FAB per tab'),
bottom: TabBar(
controller: _controller,
tabs: _allPages.map<Widget>((_Page page) => Tab(text: page.label!.toUpperCase())).toList(),
tabs:
_allPages.map<Widget>((_Page page) => Tab(text: page.label!.toUpperCase())).toList(),
),
actions: <Widget>[
MaterialDemoDocumentationButton(TabsFabDemo.routeName),
IconButton(
icon: const Icon(Icons.sentiment_very_satisfied, semanticLabel: 'Toggle extended buttons'),
icon: const Icon(
Icons.sentiment_very_satisfied,
semanticLabel: 'Toggle extended buttons',
),
onPressed: () {
setState(() {
_extendedButtons = !_extendedButtons;

View File

@@ -9,7 +9,7 @@ import 'package:flutter/services.dart';
import '../../gallery/demo.dart';
class TextFormFieldDemo extends StatefulWidget {
const TextFormFieldDemo({ super.key });
const TextFormFieldDemo({super.key});
static const String routeName = '/material/text-form-field';
@@ -84,13 +84,10 @@ class _PasswordFieldState extends State<PasswordField> {
}
class TextFormFieldDemoState extends State<TextFormFieldDemo> {
PersonData person = PersonData();
void showInSnackBar(String value) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(value),
));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(value)));
}
AutovalidateMode _autovalidateMode = AutovalidateMode.disabled;
@@ -154,14 +151,18 @@ class TextFormFieldDemoState extends State<TextFormFieldDemo> {
return AlertDialog(
title: const Text('This form has errors'),
content: const Text('Really leave this form?'),
actions: <Widget> [
actions: <Widget>[
TextButton(
child: const Text('YES'),
onPressed: () { Navigator.of(context).pop(true); },
onPressed: () {
Navigator.of(context).pop(true);
},
),
TextButton(
child: const Text('NO'),
onPressed: () { Navigator.of(context).pop(false); },
onPressed: () {
Navigator.of(context).pop(false);
},
),
],
);
@@ -191,7 +192,8 @@ class TextFormFieldDemoState extends State<TextFormFieldDemo> {
child: Form(
key: _formKey,
autovalidateMode: _autovalidateMode,
canPop: _formKey.currentState == null || !_formWasEdited || _formKey.currentState!.validate(),
canPop:
_formKey.currentState == null || !_formWasEdited || _formKey.currentState!.validate(),
onPopInvokedWithResult: _handlePopInvoked,
child: Scrollbar(
child: SingleChildScrollView(
@@ -211,7 +213,9 @@ class TextFormFieldDemoState extends State<TextFormFieldDemo> {
hintText: 'What do people call you?',
labelText: 'Name *',
),
onSaved: (String? value) { person.name = value; },
onSaved: (String? value) {
person.name = value;
},
validator: _validateName,
),
const SizedBox(height: 24.0),
@@ -225,10 +229,12 @@ class TextFormFieldDemoState extends State<TextFormFieldDemo> {
prefixText: '+1',
),
keyboardType: TextInputType.phone,
onSaved: (String? value) { person.phoneNumber = value; },
onSaved: (String? value) {
person.phoneNumber = value;
},
validator: _validatePhoneNumber,
// TextInputFormatters are applied in sequence.
inputFormatters: <TextInputFormatter> [
inputFormatters: <TextInputFormatter>[
FilteringTextInputFormatter.digitsOnly,
// Fit the validating format.
_phoneNumberFormatter,
@@ -244,13 +250,16 @@ class TextFormFieldDemoState extends State<TextFormFieldDemo> {
labelText: 'E-mail',
),
keyboardType: TextInputType.emailAddress,
onSaved: (String? value) { person.email = value; },
onSaved: (String? value) {
person.email = value;
},
),
const SizedBox(height: 24.0),
TextFormField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: 'Tell us about yourself (e.g., write down what you do or what hobbies you have)',
hintText:
'Tell us about yourself (e.g., write down what you do or what hobbies you have)',
helperText: 'Keep it short, this is just a demo.',
labelText: 'Life story',
),
@@ -292,16 +301,10 @@ class TextFormFieldDemoState extends State<TextFormFieldDemo> {
),
const SizedBox(height: 24.0),
Center(
child: ElevatedButton(
onPressed: _handleSubmitted,
child: const Text('SUBMIT'),
),
child: ElevatedButton(onPressed: _handleSubmitted, child: const Text('SUBMIT')),
),
const SizedBox(height: 24.0),
Text(
'* indicates required field',
style: Theme.of(context).textTheme.bodySmall,
),
Text('* indicates required field', style: Theme.of(context).textTheme.bodySmall),
const SizedBox(height: 24.0),
],
),
@@ -316,10 +319,7 @@ class TextFormFieldDemoState extends State<TextFormFieldDemo> {
/// Format incoming numeric text to fit the format of (###) ###-#### ##...
class _UsNumberTextInputFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
TextEditingValue formatEditUpdate(TextEditingValue oldValue, TextEditingValue newValue) {
final int newTextLength = newValue.text.length;
int selectionIndex = newValue.selection.end;
int usedSubstringIndex = 0;

View File

@@ -7,9 +7,9 @@ import 'package:flutter/material.dart';
import '../../gallery/demo.dart';
const String _introText =
'Tooltips are short identifying messages that briefly appear in response to '
'a long press. Tooltip messages are also used by services that make Flutter '
'apps accessible, like screen readers.';
'Tooltips are short identifying messages that briefly appear in response to '
'a long press. Tooltip messages are also used by services that make Flutter '
'apps accessible, like screen readers.';
class TooltipDemo extends StatelessWidget {
const TooltipDemo({super.key});
@@ -30,46 +30,41 @@ class TooltipDemo extends StatelessWidget {
top: false,
bottom: false,
child: ListView(
children: <Widget>[
Text(_introText, style: theme.textTheme.titleMedium),
Row(
children: <Widget>[
Text('Long press the ', style: theme.textTheme.titleMedium),
Tooltip(
message: 'call icon',
child: Icon(
Icons.call,
size: 18.0,
children:
<Widget>[
Text(_introText, style: theme.textTheme.titleMedium),
Row(
children: <Widget>[
Text('Long press the ', style: theme.textTheme.titleMedium),
Tooltip(
message: 'call icon',
child: Icon(Icons.call, size: 18.0, color: theme.iconTheme.color),
),
Text(' icon.', style: theme.textTheme.titleMedium),
],
),
Center(
child: IconButton(
iconSize: 48.0,
icon: const Icon(Icons.call),
color: theme.iconTheme.color,
tooltip: 'Place a phone call',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('That was an ordinary tap.')),
);
},
),
),
Text(' icon.', style: theme.textTheme.titleMedium),
],
),
Center(
child: IconButton(
iconSize: 48.0,
icon: const Icon(Icons.call),
color: theme.iconTheme.color,
tooltip: 'Place a phone call',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('That was an ordinary tap.'),
));
},
),
),
]
.map<Widget>((Widget widget) {
return Padding(
padding: const EdgeInsets.only(top: 16.0, left: 16.0, right: 16.0),
child: widget,
);
})
.toList(),
].map<Widget>((Widget widget) {
return Padding(
padding: const EdgeInsets.only(top: 16.0, left: 16.0, right: 16.0),
child: widget,
);
}).toList(),
),
);
}
},
),
);
}

View File

@@ -5,7 +5,7 @@
import 'package:flutter/material.dart';
class PestoDemo extends StatelessWidget {
const PestoDemo({ super.key });
const PestoDemo({super.key});
static const String routeName = '/pesto';
@@ -13,7 +13,6 @@ class PestoDemo extends StatelessWidget {
Widget build(BuildContext context) => const PestoHome();
}
const String _kSmallLogoImage = 'logos/pesto/logo_small.png';
const String _kGalleryAssetsPackage = 'flutter_gallery_assets';
const double _kAppBarHeight = 128.0;
@@ -53,16 +52,12 @@ class PestoStyle extends TextStyle {
Color super.color = Colors.black87,
super.letterSpacing,
super.height,
}) : super(
inherit: false,
fontFamily: 'Raleway',
textBaseline: TextBaseline.alphabetic,
);
}) : super(inherit: false, fontFamily: 'Raleway', textBaseline: TextBaseline.alphabetic);
}
// Displays a grid of recipe cards.
class RecipeGridPage extends StatefulWidget {
const RecipeGridPage({ super.key, this.recipes });
const RecipeGridPage({super.key, this.recipes});
final List<Recipe?>? recipes;
@@ -71,7 +66,6 @@ class RecipeGridPage extends StatefulWidget {
}
class _RecipeGridPageState extends State<RecipeGridPage> {
@override
Widget build(BuildContext context) {
final double statusBarHeight = MediaQuery.of(context).padding.top;
@@ -81,9 +75,9 @@ class _RecipeGridPageState extends State<RecipeGridPage> {
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.redAccent,
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Not supported.'),
));
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('Not supported.')));
},
child: const Icon(Icons.edit),
),
@@ -107,9 +101,9 @@ class _RecipeGridPageState extends State<RecipeGridPage> {
icon: const Icon(Icons.search),
tooltip: 'Search',
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('Not supported.'),
));
ScaffoldMessenger.of(
context,
).showSnackBar(const SnackBar(content: Text('Not supported.')));
},
),
],
@@ -125,9 +119,7 @@ class _RecipeGridPageState extends State<RecipeGridPage> {
top: statusBarHeight + 0.5 * extraPadding,
bottom: extraPadding,
),
child: Center(
child: PestoLogo(height: logoHeight, t: t.clamp(0.0, 1.0)),
),
child: Center(child: PestoLogo(height: logoHeight, t: t.clamp(0.0, 1.0))),
);
},
),
@@ -150,37 +142,42 @@ class _RecipeGridPageState extends State<RecipeGridPage> {
crossAxisSpacing: 8.0,
mainAxisSpacing: 8.0,
),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
final Recipe? recipe = widget.recipes![index];
return RecipeCard(
recipe: recipe,
onTap: () { showRecipePage(context, recipe); },
);
},
childCount: widget.recipes!.length,
),
delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
final Recipe? recipe = widget.recipes![index];
return RecipeCard(
recipe: recipe,
onTap: () {
showRecipePage(context, recipe);
},
);
}, childCount: widget.recipes!.length),
),
);
}
void showFavoritesPage(BuildContext context) {
Navigator.push(context, MaterialPageRoute<void>(
settings: const RouteSettings(name: '/pesto/favorites'),
builder: (BuildContext context) => const PestoFavorites(),
));
Navigator.push(
context,
MaterialPageRoute<void>(
settings: const RouteSettings(name: '/pesto/favorites'),
builder: (BuildContext context) => const PestoFavorites(),
),
);
}
void showRecipePage(BuildContext context, Recipe? recipe) {
Navigator.push(context, MaterialPageRoute<void>(
settings: const RouteSettings(name: '/pesto/recipe'),
builder: (BuildContext context) {
return Theme(
data: _kTheme.copyWith(platform: Theme.of(context).platform),
child: RecipePage(recipe: recipe),
);
},
));
Navigator.push(
context,
MaterialPageRoute<void>(
settings: const RouteSettings(name: '/pesto/recipe'),
builder: (BuildContext context) {
return Theme(
data: _kTheme.copyWith(platform: Theme.of(context).platform),
child: RecipePage(recipe: recipe),
);
},
),
);
}
}
@@ -200,7 +197,12 @@ class _PestoLogoState extends State<PestoLogo> {
static const double kLogoWidth = 220.0;
static const double kImageHeight = 108.0;
static const double kTextHeight = 48.0;
final TextStyle titleStyle = const PestoStyle(fontSize: kTextHeight, fontWeight: FontWeight.w900, color: Colors.white, letterSpacing: 3.0);
final TextStyle titleStyle = const PestoStyle(
fontSize: kTextHeight,
fontWeight: FontWeight.w900,
color: Colors.white,
letterSpacing: 3.0,
);
final RectTween _textRectTween = RectTween(
begin: const Rect.fromLTWH(0.0, kLogoHeight, kLogoWidth, kTextHeight),
end: const Rect.fromLTWH(0.0, kImageHeight, kLogoWidth, kTextHeight),
@@ -248,7 +250,7 @@ class _PestoLogoState extends State<PestoLogo> {
// A card with the recipe's image, author, and title.
class RecipeCard extends StatelessWidget {
const RecipeCard({ super.key, this.recipe, this.onTap });
const RecipeCard({super.key, this.recipe, this.onTap});
final Recipe? recipe;
final VoidCallback? onTap;
@@ -293,7 +295,12 @@ class RecipeCard extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(recipe!.name!, style: titleStyle, softWrap: false, overflow: TextOverflow.ellipsis),
Text(
recipe!.name!,
style: titleStyle,
softWrap: false,
overflow: TextOverflow.ellipsis,
),
Text(recipe!.author!, style: authorStyle),
],
),
@@ -310,7 +317,7 @@ class RecipeCard extends StatelessWidget {
// Displays one recipe. Includes the recipe sheet with a background image.
class RecipePage extends StatefulWidget {
const RecipePage({ super.key, this.recipe });
const RecipePage({super.key, this.recipe});
final Recipe? recipe;
@@ -319,7 +326,11 @@ class RecipePage extends StatefulWidget {
}
class _RecipePageState extends State<RecipePage> {
final TextStyle menuItemStyle = const PestoStyle(fontSize: 15.0, color: Colors.black54, height: 24.0/15.0);
final TextStyle menuItemStyle = const PestoStyle(
fontSize: 15.0,
color: Colors.black54,
height: 24.0 / 15.0,
);
double _getAppBarHeight(BuildContext context) => MediaQuery.of(context).size.height * 0.3;
@@ -356,13 +367,14 @@ class _RecipePageState extends State<RecipePage> {
backgroundColor: Colors.transparent,
actions: <Widget>[
PopupMenuButton<String>(
onSelected: (String item) { },
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
_buildMenuItem(Icons.share, 'Tweet recipe'),
_buildMenuItem(Icons.email, 'Email recipe'),
_buildMenuItem(Icons.message, 'Message recipe'),
_buildMenuItem(Icons.people, 'Share on Facebook'),
],
onSelected: (String item) {},
itemBuilder:
(BuildContext context) => <PopupMenuItem<String>>[
_buildMenuItem(Icons.share, 'Tweet recipe'),
_buildMenuItem(Icons.email, 'Email recipe'),
_buildMenuItem(Icons.message, 'Message recipe'),
_buildMenuItem(Icons.people, 'Share on Facebook'),
],
),
],
flexibleSpace: const FlexibleSpaceBar(
@@ -430,13 +442,25 @@ class _RecipePageState extends State<RecipePage> {
/// Displays the recipe's name and instructions.
class RecipeSheet extends StatelessWidget {
RecipeSheet({ super.key, this.recipe });
RecipeSheet({super.key, this.recipe});
final TextStyle titleStyle = const PestoStyle(fontSize: 34.0);
final TextStyle descriptionStyle = const PestoStyle(fontSize: 15.0, color: Colors.black54, height: 24.0/15.0);
final TextStyle itemStyle = const PestoStyle(fontSize: 15.0, height: 24.0/15.0);
final TextStyle itemAmountStyle = PestoStyle(fontSize: 15.0, color: _kTheme.primaryColor, height: 24.0/15.0);
final TextStyle headingStyle = const PestoStyle(fontSize: 16.0, fontWeight: FontWeight.bold, height: 24.0/15.0);
final TextStyle descriptionStyle = const PestoStyle(
fontSize: 15.0,
color: Colors.black54,
height: 24.0 / 15.0,
);
final TextStyle itemStyle = const PestoStyle(fontSize: 15.0, height: 24.0 / 15.0);
final TextStyle itemAmountStyle = PestoStyle(
fontSize: 15.0,
color: _kTheme.primaryColor,
height: 24.0 / 15.0,
);
final TextStyle headingStyle = const PestoStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
height: 24.0 / 15.0,
);
final Recipe? recipe;
@@ -449,9 +473,7 @@ class RecipeSheet extends StatelessWidget {
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 40.0),
child: Table(
columnWidths: const <int, TableColumnWidth>{
0: FixedColumnWidth(64.0),
},
columnWidths: const <int, TableColumnWidth>{0: FixedColumnWidth(64.0)},
children: <TableRow>[
TableRow(
children: <Widget>[
@@ -470,7 +492,7 @@ class RecipeSheet extends StatelessWidget {
verticalAlignment: TableCellVerticalAlignment.middle,
child: Text(recipe!.name!, style: titleStyle),
),
]
],
),
TableRow(
children: <Widget>[
@@ -479,7 +501,7 @@ class RecipeSheet extends StatelessWidget {
padding: const EdgeInsets.only(top: 8.0, bottom: 4.0),
child: Text(recipe!.description!, style: descriptionStyle),
),
]
],
),
TableRow(
children: <Widget>[
@@ -488,7 +510,7 @@ class RecipeSheet extends StatelessWidget {
padding: const EdgeInsets.only(top: 24.0, bottom: 4.0),
child: Text('Ingredients', style: headingStyle),
),
]
],
),
...recipe!.ingredients!.map<TableRow>((RecipeIngredient ingredient) {
return _buildItemRow(ingredient.amount!, ingredient.description!);
@@ -500,7 +522,7 @@ class RecipeSheet extends StatelessWidget {
padding: const EdgeInsets.only(top: 24.0, bottom: 4.0),
child: Text('Steps', style: headingStyle),
),
]
],
),
...recipe!.steps!.map<TableRow>((RecipeStep step) {
return _buildItemRow(step.duration ?? '', step.description!);
@@ -572,7 +594,8 @@ const List<Recipe> kPestoRecipes = <Recipe>[
author: 'Peter Carlsson',
ingredientsImagePath: 'food/icons/main.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: 'The perfect dish to welcome your family and friends with on a crisp autumn night. Pair with roasted veggies to truly impress them.',
description:
'The perfect dish to welcome your family and friends with on a crisp autumn night. Pair with roasted veggies to truly impress them.',
imagePath: 'food/roasted_chicken.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
@@ -592,22 +615,20 @@ const List<Recipe> kPestoRecipes = <Recipe>[
author: 'Trevor Hansen',
ingredientsImagePath: 'food/icons/veggie.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: 'This vegetable has more to offer than just its root. Beet greens can be tossed into a salad to add some variety or sauteed on its own with some oil and garlic.',
description:
'This vegetable has more to offer than just its root. Beet greens can be tossed into a salad to add some variety or sauteed on its own with some oil and garlic.',
imagePath: 'food/chopped_beet_leaves.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
RecipeIngredient(amount: '3 cups', description: 'Beet greens'),
],
steps: <RecipeStep>[
RecipeStep(duration: '5 min', description: 'Chop'),
],
ingredients: <RecipeIngredient>[RecipeIngredient(amount: '3 cups', description: 'Beet greens')],
steps: <RecipeStep>[RecipeStep(duration: '5 min', description: 'Chop')],
),
Recipe(
name: 'Pesto Pasta',
author: 'Ali Connors',
ingredientsImagePath: 'food/icons/main.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: "With this pesto recipe, you can quickly whip up a meal to satisfy your savory needs. And if you're feeling festive, you can add bacon to taste.",
description:
"With this pesto recipe, you can quickly whip up a meal to satisfy your savory needs. And if you're feeling festive, you can add bacon to taste.",
imagePath: 'food/pesto_pasta.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
@@ -622,16 +643,15 @@ const List<Recipe> kPestoRecipes = <Recipe>[
RecipeIngredient(amount: '1/8 tsp', description: 'Pepper'),
RecipeIngredient(amount: '3 lbs', description: 'Bacon'),
],
steps: <RecipeStep>[
RecipeStep(duration: '15 min', description: 'Blend'),
],
steps: <RecipeStep>[RecipeStep(duration: '15 min', description: 'Blend')],
),
Recipe(
name: 'Cherry Pie',
author: 'Sandra Adams',
ingredientsImagePath: 'food/icons/main.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: "Sometimes when you're craving some cheer in your life you can jumpstart your day with some cherry pie. Dessert for breakfast is perfectly acceptable.",
description:
"Sometimes when you're craving some cheer in your life you can jumpstart your day with some cherry pie. Dessert for breakfast is perfectly acceptable.",
imagePath: 'food/cherry_pie.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
@@ -651,23 +671,23 @@ const List<Recipe> kPestoRecipes = <Recipe>[
author: 'Peter Carlsson',
ingredientsImagePath: 'food/icons/spicy.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: "Everyone's favorite leafy green is back. Paired with fresh sliced onion, it's ready to tackle any dish, whether it be a salad or an egg scramble.",
description:
"Everyone's favorite leafy green is back. Paired with fresh sliced onion, it's ready to tackle any dish, whether it be a salad or an egg scramble.",
imagePath: 'food/spinach_onion_salad.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
RecipeIngredient(amount: '4 cups', description: 'Spinach'),
RecipeIngredient(amount: '1 cup', description: 'Sliced onion'),
],
steps: <RecipeStep>[
RecipeStep(duration: '5 min', description: 'Mix'),
],
steps: <RecipeStep>[RecipeStep(duration: '5 min', description: 'Mix')],
),
Recipe(
name: 'Butternut Squash Soup',
author: 'Ali Connors',
ingredientsImagePath: 'food/icons/healthy.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: 'This creamy butternut squash soup will warm you on the chilliest of winter nights and bring a delightful pop of orange to the dinner table.',
description:
'This creamy butternut squash soup will warm you on the chilliest of winter nights and bring a delightful pop of orange to the dinner table.',
imagePath: 'food/butternut_squash_soup.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
@@ -691,7 +711,8 @@ const List<Recipe> kPestoRecipes = <Recipe>[
author: 'Trevor Hansen',
ingredientsImagePath: 'food/icons/quick.png',
ingredientsImagePackage: _kGalleryAssetsPackage,
description: "You 'feta' believe this is a crowd-pleaser! Flaky phyllo pastry surrounds a delicious mixture of spinach and cheeses to create the perfect appetizer.",
description:
"You 'feta' believe this is a crowd-pleaser! Flaky phyllo pastry surrounds a delicious mixture of spinach and cheeses to create the perfect appetizer.",
imagePath: 'food/spanakopita.png',
imagePackage: _kGalleryAssetsPackage,
ingredients: <RecipeIngredient>[
@@ -705,7 +726,10 @@ const List<Recipe> kPestoRecipes = <Recipe>[
steps: <RecipeStep>[
RecipeStep(duration: '5 min', description: 'Sauté vegetables'),
RecipeStep(duration: '3 min', description: 'Stir vegetables and other filling ingredients'),
RecipeStep(duration: '10 min', description: 'Fill phyllo squares half-full with filling and fold.'),
RecipeStep(
duration: '10 min',
description: 'Fill phyllo squares half-full with filling and fold.',
),
RecipeStep(duration: '40 min', description: 'Bake'),
],
),

View File

@@ -97,17 +97,15 @@ ThemeData _buildShrineTheme() {
}
TextTheme _buildShrineTextTheme(TextTheme base) {
return base.copyWith(
headlineSmall: base.headlineSmall!.copyWith(fontWeight: FontWeight.w500),
titleLarge: base.titleLarge!.copyWith(fontSize: 18.0),
bodySmall: base.bodySmall!.copyWith(fontWeight: FontWeight.w400, fontSize: 14.0),
bodyLarge: base.bodyLarge!.copyWith(fontWeight: FontWeight.w500, fontSize: 16.0),
labelLarge: base.labelLarge!.copyWith(fontWeight: FontWeight.w500, fontSize: 14.0),
).apply(
fontFamily: 'Raleway',
displayColor: kShrineBrown900,
bodyColor: kShrineBrown900,
);
return base
.copyWith(
headlineSmall: base.headlineSmall!.copyWith(fontWeight: FontWeight.w500),
titleLarge: base.titleLarge!.copyWith(fontSize: 18.0),
bodySmall: base.bodySmall!.copyWith(fontWeight: FontWeight.w400, fontSize: 14.0),
bodyLarge: base.bodyLarge!.copyWith(fontWeight: FontWeight.w500, fontSize: 16.0),
labelLarge: base.labelLarge!.copyWith(fontWeight: FontWeight.w500, fontSize: 14.0),
)
.apply(fontFamily: 'Raleway', displayColor: kShrineBrown900, bodyColor: kShrineBrown900);
}
const ColorScheme kShrineColorScheme = ColorScheme(

View File

@@ -12,11 +12,7 @@ const double _kPeakVelocityTime = 0.248210;
const double _kPeakVelocityProgress = 0.379146;
class _TappableWhileStatusIs extends StatefulWidget {
const _TappableWhileStatusIs(
this.status, {
this.controller,
this.child,
});
const _TappableWhileStatusIs(this.status, {this.controller, this.child});
final AnimationController? controller;
final AnimationStatus status;
@@ -53,10 +49,7 @@ class _TappableWhileStatusIsState extends State<_TappableWhileStatusIs> {
@override
Widget build(BuildContext context) {
Widget child = AbsorbPointer(
absorbing: !_active!,
child: widget.child,
);
Widget child = AbsorbPointer(absorbing: !_active!, child: widget.child);
if (!_active!) {
child = FocusScope(
@@ -70,10 +63,7 @@ class _TappableWhileStatusIsState extends State<_TappableWhileStatusIs> {
}
class _FrontLayer extends StatelessWidget {
const _FrontLayer({
this.onTap,
this.child,
});
const _FrontLayer({this.onTap, this.child});
final VoidCallback? onTap;
final Widget? child;
@@ -91,14 +81,9 @@ class _FrontLayer extends StatelessWidget {
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Container(
height: 40.0,
alignment: AlignmentDirectional.centerStart,
),
),
Expanded(
child: child!,
child: Container(height: 40.0, alignment: AlignmentDirectional.centerStart),
),
Expanded(child: child!),
],
),
);
@@ -128,61 +113,63 @@ class _BackdropTitle extends AnimatedWidget {
style: Theme.of(context).primaryTextTheme.titleLarge!,
softWrap: false,
overflow: TextOverflow.ellipsis,
child: Row(children: <Widget>[
// branded icon
SizedBox(
width: 72.0,
child: IconButton(
padding: const EdgeInsets.only(right: 8.0),
onPressed: onPress,
icon: Stack(children: <Widget>[
Opacity(
opacity: animation.value,
child: const ImageIcon(AssetImage('packages/shrine_images/slanted_menu.png')),
child: Row(
children: <Widget>[
// branded icon
SizedBox(
width: 72.0,
child: IconButton(
padding: const EdgeInsets.only(right: 8.0),
onPressed: onPress,
icon: Stack(
children: <Widget>[
Opacity(
opacity: animation.value,
child: const ImageIcon(AssetImage('packages/shrine_images/slanted_menu.png')),
),
FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: const Offset(1.0, 0.0),
).evaluate(animation),
child: const ImageIcon(AssetImage('packages/shrine_images/diamond.png')),
),
],
),
FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: const Offset(1.0, 0.0),
).evaluate(animation),
child: const ImageIcon(AssetImage('packages/shrine_images/diamond.png')),
),
]),
),
),
),
// Here, we do a custom cross fade between backTitle and frontTitle.
// This makes a smooth animation between the two texts.
Stack(
children: <Widget>[
Opacity(
opacity: CurvedAnimation(
parent: ReverseAnimation(animation),
curve: const Interval(0.5, 1.0),
).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: const Offset(0.5, 0.0),
).evaluate(animation),
child: backTitle,
// Here, we do a custom cross fade between backTitle and frontTitle.
// This makes a smooth animation between the two texts.
Stack(
children: <Widget>[
Opacity(
opacity:
CurvedAnimation(
parent: ReverseAnimation(animation),
curve: const Interval(0.5, 1.0),
).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: const Offset(0.5, 0.0),
).evaluate(animation),
child: backTitle,
),
),
),
Opacity(
opacity: CurvedAnimation(
parent: animation,
curve: const Interval(0.5, 1.0),
).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: const Offset(-0.25, 0.0),
end: Offset.zero,
).evaluate(animation),
child: frontTitle,
Opacity(
opacity: CurvedAnimation(parent: animation, curve: const Interval(0.5, 1.0)).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: const Offset(-0.25, 0.0),
end: Offset.zero,
).evaluate(animation),
child: frontTitle,
),
),
),
],
),
]),
],
),
],
),
);
}
}
@@ -257,10 +244,7 @@ class _BackdropState extends State<Backdrop> with SingleTickerProviderStateMixin
secondCurve = _kDecelerateCurve;
firstWeight = _kPeakVelocityTime;
secondWeight = 1.0 - _kPeakVelocityTime;
animation = CurvedAnimation(
parent: _controller!.view,
curve: const Interval(0.0, 0.78),
);
animation = CurvedAnimation(parent: _controller!.view, curve: const Interval(0.0, 0.78));
} else {
// These values are only used when the controller runs from t=1.0 to t=0.0
firstCurve = _kDecelerateCurve.flipped;
@@ -270,39 +254,32 @@ class _BackdropState extends State<Backdrop> with SingleTickerProviderStateMixin
animation = _controller!.view;
}
return TweenSequence<RelativeRect>(
<TweenSequenceItem<RelativeRect>>[
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(
0.0,
layerTop,
0.0,
layerTop - layerSize.height,
),
end: RelativeRect.fromLTRB(
0.0,
layerTop * _kPeakVelocityProgress,
0.0,
(layerTop - layerSize.height) * _kPeakVelocityProgress,
),
).chain(CurveTween(curve: firstCurve)),
weight: firstWeight,
),
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(
0.0,
layerTop * _kPeakVelocityProgress,
0.0,
(layerTop - layerSize.height) * _kPeakVelocityProgress,
),
end: RelativeRect.fill,
).chain(CurveTween(curve: secondCurve)),
weight: secondWeight,
),
],
).animate(animation);
return TweenSequence<RelativeRect>(<TweenSequenceItem<RelativeRect>>[
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(0.0, layerTop, 0.0, layerTop - layerSize.height),
end: RelativeRect.fromLTRB(
0.0,
layerTop * _kPeakVelocityProgress,
0.0,
(layerTop - layerSize.height) * _kPeakVelocityProgress,
),
).chain(CurveTween(curve: firstCurve)),
weight: firstWeight,
),
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(
0.0,
layerTop * _kPeakVelocityProgress,
0.0,
(layerTop - layerSize.height) * _kPeakVelocityProgress,
),
end: RelativeRect.fill,
).chain(CurveTween(curve: secondCurve)),
weight: secondWeight,
),
]).animate(animation);
}
Widget _buildStack(BuildContext context, BoxConstraints constraints) {
@@ -367,11 +344,6 @@ class _BackdropState extends State<Backdrop> with SingleTickerProviderStateMixin
),
],
);
return Scaffold(
appBar: appBar,
body: LayoutBuilder(
builder: _buildStack,
),
);
return Scaffold(appBar: appBar, body: LayoutBuilder(builder: _buildStack));
}
}

View File

@@ -10,10 +10,7 @@ import 'model/app_state_model.dart';
import 'model/product.dart';
class CategoryMenuPage extends StatelessWidget {
const CategoryMenuPage({
super.key,
this.onCategoryTap,
});
const CategoryMenuPage({super.key, this.onCategoryTap});
final VoidCallback? onCategoryTap;
@@ -21,39 +18,36 @@ class CategoryMenuPage extends StatelessWidget {
final String categoryString = category.toString().replaceAll('Category.', '').toUpperCase();
final ThemeData theme = Theme.of(context);
return ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) =>
GestureDetector(
builder:
(BuildContext context, Widget? child, AppStateModel model) => GestureDetector(
onTap: () {
model.setCategory(category);
onCategoryTap?.call();
},
child: model.selectedCategory == category
? Column(
children: <Widget>[
const SizedBox(height: 16.0),
Text(
categoryString,
style: theme.textTheme.bodyLarge,
textAlign: TextAlign.center,
child:
model.selectedCategory == category
? Column(
children: <Widget>[
const SizedBox(height: 16.0),
Text(
categoryString,
style: theme.textTheme.bodyLarge,
textAlign: TextAlign.center,
),
const SizedBox(height: 14.0),
Container(width: 70.0, height: 2.0, color: kShrinePink400),
],
)
: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Text(
categoryString,
style: theme.textTheme.bodyLarge!.copyWith(
color: kShrineBrown900.withAlpha(153),
),
textAlign: TextAlign.center,
),
),
const SizedBox(height: 14.0),
Container(
width: 70.0,
height: 2.0,
color: kShrinePink400,
),
],
)
: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Text(
categoryString,
style: theme.textTheme.bodyLarge!.copyWith(
color: kShrineBrown900.withAlpha(153)
),
textAlign: TextAlign.center,
),
),
),
);
}

View File

@@ -32,12 +32,14 @@ class ExpandingBottomSheet extends StatefulWidget {
ExpandingBottomSheetState createState() => ExpandingBottomSheetState();
static ExpandingBottomSheetState? of(BuildContext context, {bool isNullOk = false}) {
final ExpandingBottomSheetState? result = context.findAncestorStateOfType<ExpandingBottomSheetState>();
final ExpandingBottomSheetState? result =
context.findAncestorStateOfType<ExpandingBottomSheetState>();
if (isNullOk || result != null) {
return result;
}
throw FlutterError(
'ExpandingBottomSheet.of() called with a context that does not contain a ExpandingBottomSheet.\n');
'ExpandingBottomSheet.of() called with a context that does not contain a ExpandingBottomSheet.\n',
);
}
}
@@ -70,24 +72,16 @@ Animation<T> _getEmphasizedEasingAnimation<T>({
secondWeight = _kPeakVelocityTime;
}
return TweenSequence<T>(
<TweenSequenceItem<T>>[
TweenSequenceItem<T>(
weight: firstWeight,
tween: Tween<T>(
begin: begin,
end: peak,
).chain(CurveTween(curve: firstCurve)),
),
TweenSequenceItem<T>(
weight: secondWeight,
tween: Tween<T>(
begin: peak,
end: end,
).chain(CurveTween(curve: secondCurve)),
),
],
).animate(parent);
return TweenSequence<T>(<TweenSequenceItem<T>>[
TweenSequenceItem<T>(
weight: firstWeight,
tween: Tween<T>(begin: begin, end: peak).chain(CurveTween(curve: firstCurve)),
),
TweenSequenceItem<T>(
weight: secondWeight,
tween: Tween<T>(begin: peak, end: end).chain(CurveTween(curve: secondCurve)),
),
]).animate(parent);
}
// Calculates the value where two double Animations should be joined. Used by
@@ -118,10 +112,7 @@ class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerP
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 500),
vsync: this,
);
_controller = AnimationController(duration: const Duration(milliseconds: 500), vsync: this);
}
@override
@@ -164,10 +155,7 @@ class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerP
);
} else {
// Closing animation
return Tween<double>(
begin: _kCartHeight,
end: screenHeight,
).animate(
return Tween<double>(begin: _kCartHeight, end: screenHeight).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0.434, 1.0), // not used
@@ -202,9 +190,10 @@ class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerP
return Tween<double>(begin: 1.0, end: 0.0).animate(
CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? const Interval(0.0, 0.3)
: const Interval(0.532, 0.766),
curve:
_controller.status == AnimationStatus.forward
? const Interval(0.0, 0.3)
: const Interval(0.532, 0.766),
),
);
}
@@ -212,9 +201,10 @@ class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerP
Animation<double> _getCartOpacityAnimation() {
return CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? const Interval(0.3, 0.6)
: const Interval(0.766, 1.0),
curve:
_controller.status == AnimationStatus.forward
? const Interval(0.3, 0.6)
: const Interval(0.766, 1.0),
);
}
@@ -252,8 +242,8 @@ class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerP
// products.)
EdgeInsetsDirectional _cartPaddingFor(int numProducts) {
return (numProducts == 0)
? const EdgeInsetsDirectional.only(start: 20.0, end: 8.0)
: const EdgeInsetsDirectional.only(start: 32.0, end: 8.0);
? const EdgeInsetsDirectional.only(start: 20.0, end: 8.0)
: const EdgeInsetsDirectional.only(start: 32.0, end: 8.0);
}
bool get _cartIsVisible => _thumbnailOpacityAnimation.value == 0.0;
@@ -288,10 +278,7 @@ class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerP
}
Widget _buildShoppingCartPage() {
return Opacity(
opacity: _cartOpacityAnimation.value,
child: const ShoppingCartPage(),
);
return Opacity(opacity: _cartOpacityAnimation.value, child: const ShoppingCartPage());
}
Widget _buildCart(BuildContext context, Widget? child) {
@@ -320,15 +307,11 @@ class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerP
child: Material(
animationDuration: Duration.zero,
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(_shapeAnimation.value),
),
borderRadius: BorderRadius.only(topLeft: Radius.circular(_shapeAnimation.value)),
),
elevation: 4.0,
color: kShrinePink50,
child: _cartIsVisible
? _buildShoppingCartPage()
: _buildThumbnails(numProducts),
child: _cartIsVisible ? _buildShoppingCartPage() : _buildThumbnails(numProducts),
),
),
);
@@ -344,10 +327,7 @@ class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerP
parent: widget.hideController,
);
return SlideTransition(
position: _slideAnimation,
child: child,
);
return SlideTransition(position: _slideAnimation, child: child);
}
// Closes the cart if the cart is open, otherwise exits the app (this should
@@ -378,10 +358,7 @@ class ExpandingBottomSheetState extends State<ExpandingBottomSheet> with TickerP
onTap: open,
child: ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) {
return AnimatedBuilder(
builder: _buildCart,
animation: _controller,
);
return AnimatedBuilder(builder: _buildCart, animation: _controller);
},
),
),
@@ -431,10 +408,7 @@ class _ProductThumbnailRowState extends State<ProductThumbnailRow> {
Widget _buildThumbnail(BuildContext context, int index, Animation<double> animation) {
final Animation<double> thumbnailSize = Tween<double>(begin: 0.8, end: 1.0).animate(
CurvedAnimation(
curve: const Interval(0.33, 1.0, curve: Curves.easeIn),
parent: animation,
),
CurvedAnimation(curve: const Interval(0.33, 1.0, curve: Curves.easeIn), parent: animation),
);
final Animation<double> opacity = CurvedAnimation(
@@ -539,7 +513,9 @@ class ExtraProductsNumber extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<AppStateModel>(
builder: (BuildContext builder, Widget? child, AppStateModel model) => _buildOverflow(model, context),
builder:
(BuildContext builder, Widget? child, AppStateModel model) =>
_buildOverflow(model, context),
);
}
}
@@ -579,14 +555,12 @@ class ProductThumbnail extends StatelessWidget {
// _ListModel manipulates an internal list and an AnimatedList
class _ListModel {
_ListModel({
required this.listKey,
required this.removedItemBuilder,
Iterable<int>? initialItems,
}) : _items = initialItems?.toList() ?? <int>[];
_ListModel({required this.listKey, required this.removedItemBuilder, Iterable<int>? initialItems})
: _items = initialItems?.toList() ?? <int>[];
final GlobalKey<AnimatedListState> listKey;
final Widget Function(int item, BuildContext context, Animation<double> animation) removedItemBuilder;
final Widget Function(int item, BuildContext context, Animation<double> animation)
removedItemBuilder;
final List<int> _items;
AnimatedListState? get _animatedList => listKey.currentState;

View File

@@ -21,16 +21,13 @@ class ProductPage extends StatelessWidget {
return ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) {
return AsymmetricView(products: model.getProducts());
});
},
);
}
}
class HomePage extends StatelessWidget {
const HomePage({
this.expandingBottomSheet,
this.backdrop,
super.key,
});
const HomePage({this.expandingBottomSheet, this.backdrop, super.key});
final ExpandingBottomSheet? expandingBottomSheet;
final Backdrop? backdrop;
@@ -39,8 +36,7 @@ class HomePage extends StatelessWidget {
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
if (backdrop != null)
backdrop!,
if (backdrop != null) backdrop!,
Align(alignment: Alignment.bottomRight, child: expandingBottomSheet),
],
);

View File

@@ -16,7 +16,7 @@ class LoginPage extends StatefulWidget {
class _LoginPageState extends State<LoginPage> {
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
static const ShapeDecoration _decoration = ShapeDecoration(
static const ShapeDecoration _decoration = ShapeDecoration(
shape: BeveledRectangleBorder(
side: BorderSide(color: kShrineBrown900, width: 0.5),
borderRadius: BorderRadius.all(Radius.circular(7.0)),
@@ -49,10 +49,7 @@ class _LoginPageState extends State<LoginPage> {
children: <Widget>[
Image.asset('packages/shrine_images/diamond.png'),
const SizedBox(height: 16.0),
Text(
'SHRINE',
style: Theme.of(context).textTheme.headlineSmall,
),
Text('SHRINE', style: Theme.of(context).textTheme.headlineSmall),
],
),
const SizedBox(height: 120.0),
@@ -62,9 +59,7 @@ class _LoginPageState extends State<LoginPage> {
decoration: _decoration,
child: TextField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
),
decoration: const InputDecoration(labelText: 'Username'),
),
),
),
@@ -75,9 +70,7 @@ class _LoginPageState extends State<LoginPage> {
decoration: _decoration,
child: TextField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Password',
),
decoration: const InputDecoration(labelText: 'Password'),
),
),
),
@@ -130,9 +123,6 @@ class PrimaryColorOverride extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Theme(
data: Theme.of(context).copyWith(primaryColor: color),
child: child!,
);
return Theme(data: Theme.of(context).copyWith(primaryColor: color), child: child!);
}
}

View File

@@ -30,8 +30,8 @@ class AppStateModel extends Model {
// Totaled prices of the items in the cart.
double get subtotalCost {
return _productsInCart.keys
.map((int id) => _availableProducts![id].price * _productsInCart[id]!)
.fold(0.0, (double sum, int e) => sum + e);
.map((int id) => _availableProducts![id].price * _productsInCart[id]!)
.fold(0.0, (double sum, int e) => sum + e);
}
// Total shipping cost for the items in the cart.
@@ -54,9 +54,7 @@ class AppStateModel extends Model {
if (_selectedCategory == Category.all) {
return List<Product>.from(_availableProducts!);
} else {
return _availableProducts!
.where((Product p) => p.category == _selectedCategory)
.toList();
return _availableProducts!.where((Product p) => p.category == _selectedCategory).toList();
}
}

View File

@@ -2,12 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
enum Category {
all,
accessories,
clothing,
home,
}
enum Category { all, accessories, clothing, home }
class Product {
const Product({

View File

@@ -55,27 +55,9 @@ List<Product> loadProducts(Category category) {
name: 'Weave keyring',
price: 16,
),
Product(
category: Category.accessories,
id: 7,
isFeatured: true,
name: 'Gatsby hat',
price: 40,
),
Product(
category: Category.accessories,
id: 8,
isFeatured: true,
name: 'Shrug bag',
price: 198,
),
Product(
category: Category.home,
id: 9,
isFeatured: true,
name: 'Gilt desk trio',
price: 58,
),
Product(category: Category.accessories, id: 7, isFeatured: true, name: 'Gatsby hat', price: 40),
Product(category: Category.accessories, id: 8, isFeatured: true, name: 'Shrug bag', price: 198),
Product(category: Category.home, id: 9, isFeatured: true, name: 'Gilt desk trio', price: 58),
Product(
category: Category.home,
id: 10,
@@ -90,34 +72,10 @@ List<Product> loadProducts(Category category) {
name: 'Soothe ceramic set',
price: 28,
),
Product(
category: Category.home,
id: 12,
isFeatured: false,
name: 'Hurrahs tea set',
price: 34,
),
Product(
category: Category.home,
id: 13,
isFeatured: true,
name: 'Blue stone mug',
price: 18,
),
Product(
category: Category.home,
id: 14,
isFeatured: true,
name: 'Rainwater tray',
price: 27,
),
Product(
category: Category.home,
id: 15,
isFeatured: true,
name: 'Chambray napkins',
price: 16,
),
Product(category: Category.home, id: 12, isFeatured: false, name: 'Hurrahs tea set', price: 34),
Product(category: Category.home, id: 13, isFeatured: true, name: 'Blue stone mug', price: 18),
Product(category: Category.home, id: 14, isFeatured: true, name: 'Rainwater tray', price: 27),
Product(category: Category.home, id: 15, isFeatured: true, name: 'Chambray napkins', price: 16),
Product(
category: Category.home,
id: 16,
@@ -125,20 +83,8 @@ List<Product> loadProducts(Category category) {
name: 'Succulent planters',
price: 16,
),
Product(
category: Category.home,
id: 17,
isFeatured: false,
name: 'Quartet table',
price: 175,
),
Product(
category: Category.home,
id: 18,
isFeatured: true,
name: 'Kitchen quattro',
price: 129,
),
Product(category: Category.home, id: 17, isFeatured: false, name: 'Quartet table', price: 175),
Product(category: Category.home, id: 18, isFeatured: true, name: 'Kitchen quattro', price: 129),
Product(
category: Category.clothing,
id: 19,
@@ -146,13 +92,7 @@ List<Product> loadProducts(Category category) {
name: 'Clay sweater',
price: 48,
),
Product(
category: Category.clothing,
id: 20,
isFeatured: false,
name: 'Sea tunic',
price: 45,
),
Product(category: Category.clothing, id: 20, isFeatured: false, name: 'Sea tunic', price: 45),
Product(
category: Category.clothing,
id: 21,
@@ -209,13 +149,7 @@ List<Product> loadProducts(Category category) {
name: 'Surf and perf shirt',
price: 48,
),
Product(
category: Category.clothing,
id: 29,
isFeatured: true,
name: 'Ginger scarf',
price: 98,
),
Product(category: Category.clothing, id: 29, isFeatured: true, name: 'Ginger scarf', price: 98),
Product(
category: Category.clothing,
id: 30,

View File

@@ -23,7 +23,8 @@ class ShoppingCartPage extends StatefulWidget {
class _ShoppingCartPageState extends State<ShoppingCartPage> {
List<Widget> _createShoppingCartRows(AppStateModel model) {
return model.productsInCart.keys
.map((int id) => ShoppingCartRow(
.map(
(int id) => ShoppingCartRow(
product: model.getProductById(id),
quantity: model.productsInCart[id],
onPressed: () {
@@ -58,16 +59,16 @@ class _ShoppingCartPageState extends State<ShoppingCartPage> {
),
Text(
'CART',
style: localTheme.textTheme.titleMedium!.copyWith(fontWeight: FontWeight.w600),
style: localTheme.textTheme.titleMedium!.copyWith(
fontWeight: FontWeight.w600,
),
),
const SizedBox(width: 16.0),
Text('${model.totalCartQuantity} ITEMS'),
],
),
const SizedBox(height: 16.0),
Column(
children: _createShoppingCartRows(model),
),
Column(children: _createShoppingCartRows(model)),
ShoppingCartSummary(model: model),
const SizedBox(height: 100.0),
],
@@ -109,7 +110,9 @@ class ShoppingCartSummary extends StatelessWidget {
@override
Widget build(BuildContext context) {
final TextStyle smallAmountStyle = Theme.of(context).textTheme.bodyMedium!.copyWith(color: kShrineBrown600);
final TextStyle smallAmountStyle = Theme.of(
context,
).textTheme.bodyMedium!.copyWith(color: kShrineBrown600);
final TextStyle? largeAmountStyle = Theme.of(context).textTheme.headlineMedium;
final NumberFormat formatter = NumberFormat.simpleCurrency(
decimalDigits: 2,
@@ -126,49 +129,29 @@ class ShoppingCartSummary extends StatelessWidget {
children: <Widget>[
Row(
children: <Widget>[
const Expanded(
child: Text('TOTAL'),
),
Text(
formatter.format(model!.totalCost),
style: largeAmountStyle,
),
const Expanded(child: Text('TOTAL')),
Text(formatter.format(model!.totalCost), style: largeAmountStyle),
],
),
const SizedBox(height: 16.0),
Row(
children: <Widget>[
const Expanded(
child: Text('Subtotal:'),
),
Text(
formatter.format(model!.subtotalCost),
style: smallAmountStyle,
),
const Expanded(child: Text('Subtotal:')),
Text(formatter.format(model!.subtotalCost), style: smallAmountStyle),
],
),
const SizedBox(height: 4.0),
Row(
children: <Widget>[
const Expanded(
child: Text('Shipping:'),
),
Text(
formatter.format(model!.shippingCost),
style: smallAmountStyle,
),
const Expanded(child: Text('Shipping:')),
Text(formatter.format(model!.shippingCost), style: smallAmountStyle),
],
),
const SizedBox(height: 4.0),
Row(
children: <Widget>[
const Expanded(
child: Text('Tax:'),
),
Text(
formatter.format(model!.tax),
style: smallAmountStyle,
),
const Expanded(child: Text('Tax:')),
Text(formatter.format(model!.tax), style: smallAmountStyle),
],
),
],
@@ -181,12 +164,7 @@ class ShoppingCartSummary extends StatelessWidget {
}
class ShoppingCartRow extends StatelessWidget {
const ShoppingCartRow({
super.key,
required this.product,
required this.quantity,
this.onPressed,
});
const ShoppingCartRow({super.key, required this.product, required this.quantity, this.onPressed});
final Product product;
final int? quantity;
@@ -208,10 +186,7 @@ class ShoppingCartRow extends StatelessWidget {
children: <Widget>[
SizedBox(
width: _leftColumnWidth,
child: IconButton(
icon: const Icon(Icons.remove_circle_outline),
onPressed: onPressed,
),
child: IconButton(icon: const Icon(Icons.remove_circle_outline), onPressed: onPressed),
),
Expanded(
child: Padding(
@@ -235,15 +210,15 @@ class ShoppingCartRow extends StatelessWidget {
children: <Widget>[
Row(
children: <Widget>[
Expanded(
child: Text('Quantity: $quantity'),
),
Expanded(child: Text('Quantity: $quantity')),
Text('x ${formatter.format(product.price)}'),
],
),
Text(
product.name,
style: localTheme.textTheme.titleMedium!.copyWith(fontWeight: FontWeight.w600),
style: localTheme.textTheme.titleMedium!.copyWith(
fontWeight: FontWeight.w600,
),
),
],
),
@@ -251,10 +226,7 @@ class ShoppingCartRow extends StatelessWidget {
],
),
const SizedBox(height: 16.0),
const Divider(
color: kShrineBrown900,
height: 10.0,
),
const Divider(color: kShrineBrown900, height: 10.0),
],
),
),

View File

@@ -33,23 +33,16 @@ class AsymmetricView extends StatelessWidget {
final int bottom = _evenCasesIndex(index);
column = TwoProductCardColumn(
bottom: products![bottom],
top: products!.length - 1 >= bottom + 1
? products![bottom + 1]
: null,
top: products!.length - 1 >= bottom + 1 ? products![bottom + 1] : null,
);
width += 32.0;
} else {
/// Odd cases
column = OneProductCardColumn(
product: products![_oddCasesIndex(index)],
);
column = OneProductCardColumn(product: products![_oddCasesIndex(index)]);
}
return SizedBox(
width: width,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: column,
),
child: Padding(padding: const EdgeInsets.symmetric(horizontal: 16.0), child: column),
);
}).toList();
}
@@ -68,9 +61,7 @@ class AsymmetricView extends StatelessWidget {
}
int _listItemCount(int totalItems) {
return (totalItems % 3 == 0)
? totalItems ~/ 3 * 2
: (totalItems / 3).ceil() * 2 - 1;
return (totalItems % 3 == 0) ? totalItems ~/ 3 * 2 : (totalItems / 3).ceil() * 2 - 1;
}
@override

View File

@@ -64,7 +64,9 @@ class CutCornersBorder extends OutlineInputBorder {
if (start > 0.0 || extent! > 0.0) {
path.relativeMoveTo(extent! + start, center.top);
_notchedSidesAndBottom(center, path);
path..lineTo(center.left + cut, center.top)..lineTo(start, center.top);
path
..lineTo(center.left + cut, center.top)
..lineTo(start, center.top);
} else {
path.moveTo(center.left + cut, center.top);
_notchedSidesAndBottom(center, path);

View File

@@ -10,8 +10,8 @@ import '../model/app_state_model.dart';
import '../model/product.dart';
class ProductCard extends StatelessWidget {
const ProductCard({ super.key, this.imageAspectRatio = 33 / 49, this.product })
: assert(imageAspectRatio > 0);
const ProductCard({super.key, this.imageAspectRatio = 33 / 49, this.product})
: assert(imageAspectRatio > 0);
final double imageAspectRatio;
final Product? product;
@@ -35,7 +35,8 @@ class ProductCard extends StatelessWidget {
// The fontSize to use for computing the heuristic UI scaling factor.
const double defaultFontSize = 14.0;
final double containerScalingFactor = MediaQuery.textScalerOf(context).scale(defaultFontSize) / defaultFontSize;
final double containerScalingFactor =
MediaQuery.textScalerOf(context).scale(defaultFontSize) / defaultFontSize;
return ScopedModelDescendant<AppStateModel>(
builder: (BuildContext context, Widget? child, AppStateModel model) {
@@ -51,10 +52,7 @@ class ProductCard extends StatelessWidget {
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AspectRatio(
aspectRatio: imageAspectRatio,
child: imageWidget,
),
AspectRatio(aspectRatio: imageAspectRatio, child: imageWidget),
SizedBox(
height: kTextBoxHeight * containerScalingFactor,
width: 121.0,
@@ -78,10 +76,7 @@ class ProductCard extends StatelessWidget {
),
],
),
const Padding(
padding: EdgeInsets.all(16.0),
child: Icon(Icons.add_shopping_cart),
),
const Padding(padding: EdgeInsets.all(16.0), child: Icon(Icons.add_shopping_cart)),
],
),
);

View File

@@ -8,52 +8,44 @@ import '../model/product.dart';
import 'product_card.dart';
class TwoProductCardColumn extends StatelessWidget {
const TwoProductCardColumn({
super.key,
required this.bottom,
this.top,
});
const TwoProductCardColumn({super.key, required this.bottom, this.top});
final Product? bottom, top;
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
const double spacerHeight = 44.0;
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
const double spacerHeight = 44.0;
final double heightOfCards = (constraints.biggest.height - spacerHeight) / 2.0;
final double availableHeightForImages = heightOfCards - ProductCard.kTextBoxHeight;
// Ensure the cards take up the available space as long as the screen is
// sufficiently tall, otherwise fallback on a constant aspect ratio.
final double imageAspectRatio = availableHeightForImages >= 0.0
? constraints.biggest.width / availableHeightForImages
: 49.0 / 33.0;
final double heightOfCards = (constraints.biggest.height - spacerHeight) / 2.0;
final double availableHeightForImages = heightOfCards - ProductCard.kTextBoxHeight;
// Ensure the cards take up the available space as long as the screen is
// sufficiently tall, otherwise fallback on a constant aspect ratio.
final double imageAspectRatio =
availableHeightForImages >= 0.0
? constraints.biggest.width / availableHeightForImages
: 49.0 / 33.0;
return ListView(
physics: const ClampingScrollPhysics(),
children: <Widget>[
Padding(
padding: const EdgeInsetsDirectional.only(start: 28.0),
child: top != null
? ProductCard(
imageAspectRatio: imageAspectRatio,
product: top,
)
: SizedBox(
height: heightOfCards > 0 ? heightOfCards : spacerHeight,
),
),
const SizedBox(height: spacerHeight),
Padding(
padding: const EdgeInsetsDirectional.only(end: 28.0),
child: ProductCard(
imageAspectRatio: imageAspectRatio,
product: bottom,
return ListView(
physics: const ClampingScrollPhysics(),
children: <Widget>[
Padding(
padding: const EdgeInsetsDirectional.only(start: 28.0),
child:
top != null
? ProductCard(imageAspectRatio: imageAspectRatio, product: top)
: SizedBox(height: heightOfCards > 0 ? heightOfCards : spacerHeight),
),
),
],
);
});
const SizedBox(height: spacerHeight),
Padding(
padding: const EdgeInsetsDirectional.only(end: 28.0),
child: ProductCard(imageAspectRatio: imageAspectRatio, product: bottom),
),
],
);
},
);
}
}
@@ -67,14 +59,7 @@ class OneProductCardColumn extends StatelessWidget {
return ListView(
physics: const ClampingScrollPhysics(),
reverse: true,
children: <Widget>[
const SizedBox(
height: 40.0,
),
ProductCard(
product: product,
),
],
children: <Widget>[const SizedBox(height: 40.0), ProductCard(product: product)],
);
}
}

View File

@@ -6,7 +6,7 @@ import 'package:flutter/material.dart';
import 'shrine/app.dart';
class ShrineDemo extends StatelessWidget {
const ShrineDemo({ super.key });
const ShrineDemo({super.key});
static const String routeName = '/shrine'; // Used by the Gallery app.

View File

@@ -9,13 +9,14 @@ import 'transformations_demo_edit_board_point.dart';
import 'transformations_demo_gesture_transformable.dart';
class TransformationsDemo extends StatefulWidget {
const TransformationsDemo({ super.key });
const TransformationsDemo({super.key});
static const String routeName = '/transformations';
@override
State<TransformationsDemo> createState() => _TransformationsDemoState();
}
class _TransformationsDemoState extends State<TransformationsDemo> {
// The radius of a hexagon tile in pixels.
static const double _kHexagonRadius = 32.0;
@@ -32,10 +33,8 @@ class _TransformationsDemoState extends State<TransformationsDemo> {
);
@override
Widget build (BuildContext context) {
final BoardPainter painter = BoardPainter(
board: _board,
);
Widget build(BuildContext context) {
final BoardPainter painter = BoardPainter(board: _board);
// The scene is drawn by a CustomPaint, but user interaction is handled by
// the GestureTransformable parent widget.
@@ -80,9 +79,7 @@ class _TransformationsDemoState extends State<TransformationsDemo> {
initialTranslation: Offset(size.width / 2, size.height / 2),
onTapUp: _onTapUp,
size: size,
child: CustomPaint(
painter: painter,
),
child: CustomPaint(painter: painter),
);
},
),
@@ -134,22 +131,25 @@ class _TransformationsDemoState extends State<TransformationsDemo> {
if (_board.selected == null) {
return;
}
showModalBottomSheet<Widget>(context: context, builder: (BuildContext context) {
return Container(
width: double.infinity,
height: 150,
padding: const EdgeInsets.all(12.0),
child: EditBoardPoint(
boardPoint: _board.selected!,
onColorSelection: (Color color) {
setState(() {
_board = _board.copyWithBoardPointColor(_board.selected!, color);
Navigator.pop(context);
});
},
),
);
});
showModalBottomSheet<Widget>(
context: context,
builder: (BuildContext context) {
return Container(
width: double.infinity,
height: 150,
padding: const EdgeInsets.all(12.0),
child: EditBoardPoint(
boardPoint: _board.selected!,
onColorSelection: (Color color) {
setState(() {
_board = _board.copyWithBoardPointColor(_board.selected!, color);
Navigator.pop(context);
});
},
),
);
},
);
},
tooltip: 'Edit Tile',
child: const Icon(Icons.edit),
@@ -168,18 +168,14 @@ class _TransformationsDemoState extends State<TransformationsDemo> {
// CustomPainter is what is passed to CustomPaint and actually draws the scene
// when its `paint` method is called.
class BoardPainter extends CustomPainter {
const BoardPainter({
this.board,
});
const BoardPainter({this.board});
final Board? board;
@override
void paint(Canvas canvas, Size size) {
void drawBoardPoint(BoardPoint? boardPoint) {
final Color color = boardPoint!.color.withOpacity(
board!.selected == boardPoint ? 0.2 : 1.0,
);
final Color color = boardPoint!.color.withOpacity(board!.selected == boardPoint ? 0.2 : 1.0);
final Vertices vertices = board!.getVerticesForBoardPoint(boardPoint, color);
canvas.drawVertices(vertices, BlendMode.color, Paint());
vertices.dispose();

View File

@@ -81,7 +81,7 @@ class Board extends IterableMixin<BoardPoint?> {
// Get the BoardPoint that comes after the given BoardPoint. If given null,
// returns the origin BoardPoint. If given BoardPoint is the last, returns
// null.
BoardPoint? _getNextBoardPoint (BoardPoint? boardPoint) {
BoardPoint? _getNextBoardPoint(BoardPoint? boardPoint) {
// If before the first element.
if (boardPoint == null) {
return BoardPoint(-boardRadius, 0);
@@ -114,8 +114,7 @@ class Board extends IterableMixin<BoardPoint?> {
static int getDistance(BoardPoint a, BoardPoint b) {
final Vector3 a3 = a.cubeCoordinates;
final Vector3 b3 = b.cubeCoordinates;
return
((a3.x - b3.x).abs() + (a3.y - b3.y).abs() + (a3.z - b3.z).abs()) ~/ 2;
return ((a3.x - b3.x).abs() + (a3.y - b3.y).abs() + (a3.z - b3.z).abs()) ~/ 2;
}
// Return the q,r BoardPoint for a point in the scene, where the origin is in
@@ -148,9 +147,10 @@ class Board extends IterableMixin<BoardPoint?> {
Vertices getVerticesForBoardPoint(BoardPoint boardPoint, Color color) {
final Point<double> centerOfHexZeroCenter = boardPointToPoint(boardPoint);
final List<Offset> positions = positionsForHexagonAtOrigin.map((Offset offset) {
return offset.translate(centerOfHexZeroCenter.x, centerOfHexZeroCenter.y);
}).toList();
final List<Offset> positions =
positionsForHexagonAtOrigin.map((Offset offset) {
return offset.translate(centerOfHexZeroCenter.x, centerOfHexZeroCenter.y);
}).toList();
return Vertices(
VertexMode.triangleFan,
@@ -177,8 +177,8 @@ class Board extends IterableMixin<BoardPoint?> {
// Return a new board where boardPoint has the given color.
Board copyWithBoardPointColor(BoardPoint boardPoint, Color color) {
final BoardPoint nextBoardPoint = boardPoint.copyWithColor(color);
final int boardPointIndex = _boardPoints.indexWhere((BoardPoint boardPointI) =>
boardPointI.q == boardPoint.q && boardPointI.r == boardPoint.r
final int boardPointIndex = _boardPoints.indexWhere(
(BoardPoint boardPointI) => boardPointI.q == boardPoint.q && boardPointI.r == boardPoint.r,
);
if (elementAt(boardPointIndex) == boardPoint && boardPoint.color == color) {
@@ -187,9 +187,7 @@ class Board extends IterableMixin<BoardPoint?> {
final List<BoardPoint> nextBoardPoints = List<BoardPoint>.from(_boardPoints);
nextBoardPoints[boardPointIndex] = nextBoardPoint;
final BoardPoint? selectedBoardPoint = boardPoint == selected
? nextBoardPoint
: selected;
final BoardPoint? selectedBoardPoint = boardPoint == selected ? nextBoardPoint : selected;
return Board(
boardRadius: boardRadius,
hexagonRadius: hexagonRadius,
@@ -231,28 +229,20 @@ class _BoardIterator implements Iterator<BoardPoint?> {
// A range of q/r board coordinate values.
@immutable
class _Range {
const _Range(this.min, this.max)
: assert(min <= max);
const _Range(this.min, this.max) : assert(min <= max);
final int min;
final int max;
}
final Set<Color> boardPointColors = <Color>{
Colors.grey,
Colors.black,
Colors.red,
Colors.blue,
};
final Set<Color> boardPointColors = <Color>{Colors.grey, Colors.black, Colors.red, Colors.blue};
// A location on the board in axial coordinates.
// Axial coordinates use two integers, q and r, to locate a hexagon on a grid.
// https://www.redblobgames.com/grids/hexagons/#coordinates-axial
@immutable
class BoardPoint {
const BoardPoint(this.q, this.r, {
this.color = Colors.grey,
});
const BoardPoint(this.q, this.r, {this.color = Colors.grey});
final int q;
final int r;
@@ -269,9 +259,7 @@ class BoardPoint {
if (other.runtimeType != runtimeType) {
return false;
}
return other is BoardPoint
&& other.q == q
&& other.r == r;
return other is BoardPoint && other.q == q && other.r == r;
}
@override
@@ -281,10 +269,6 @@ class BoardPoint {
// Convert from q,r axial coords to x,y,z cube coords.
Vector3 get cubeCoordinates {
return Vector3(
q.toDouble(),
r.toDouble(),
(-q - r).toDouble(),
);
return Vector3(q.toDouble(), r.toDouble(), (-q - r).toDouble());
}
}

View File

@@ -19,18 +19,19 @@ class ColorPicker extends StatelessWidget {
final ValueChanged<Color>? onColorSelection;
@override
Widget build (BuildContext context) {
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: colors.map((Color color) {
return _ColorPickerSwatch(
color: color,
selected: color == selectedColor,
onTap: () {
onColorSelection?.call(color);
},
);
}).toList(),
children:
colors.map((Color color) {
return _ColorPickerSwatch(
color: color,
selected: color == selectedColor,
onTap: () {
onColorSelection?.call(color);
},
);
}).toList(),
);
}
}
@@ -38,18 +39,14 @@ class ColorPicker extends StatelessWidget {
// A single selectable color widget in the ColorPicker.
@immutable
class _ColorPickerSwatch extends StatelessWidget {
const _ColorPickerSwatch({
required this.color,
required this.selected,
this.onTap,
});
const _ColorPickerSwatch({required this.color, required this.selected, this.onTap});
final Color color;
final bool selected;
final VoidCallback? onTap;
@override
Widget build (BuildContext context) {
Widget build(BuildContext context) {
return Container(
width: 60.0,
height: 60.0,
@@ -59,10 +56,7 @@ class _ColorPickerSwatch extends StatelessWidget {
onPressed: () {
onTap?.call();
},
child: !selected ? null : const Icon(
Icons.check,
color: Colors.white,
),
child: !selected ? null : const Icon(Icons.check, color: Colors.white),
),
);
}

View File

@@ -9,17 +9,13 @@ import 'transformations_demo_color_picker.dart';
// The panel for editing a board point.
@immutable
class EditBoardPoint extends StatelessWidget {
const EditBoardPoint({
super.key,
required this.boardPoint,
this.onColorSelection,
});
const EditBoardPoint({super.key, required this.boardPoint, this.onColorSelection});
final BoardPoint boardPoint;
final ValueChanged<Color>? onColorSelection;
@override
Widget build (BuildContext context) {
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[

View File

@@ -72,10 +72,7 @@ class GestureTransformable extends StatefulWidget {
this.onScaleUpdate,
this.onScaleEnd,
}) : assert(minScale > 0),
assert(
!reset || onResetEnd != null,
'Must implement onResetEnd to use reset.',
);
assert(!reset || onResetEnd != null, 'Must implement onResetEnd to use reset.');
final Widget child;
final Size size;
@@ -122,11 +119,7 @@ class GestureTransformable extends StatefulWidget {
// A single user event can only represent one of these gestures. The user can't
// do multiple at the same time, which results in more precise transformations.
enum _GestureType {
translate,
scale,
rotate,
}
enum _GestureType { translate, scale, rotate }
// This is public only for access from a unit test.
class _GestureTransformableState extends State<GestureTransformable> with TickerProviderStateMixin {
@@ -165,17 +158,18 @@ class _GestureTransformableState extends State<GestureTransformable> with Ticker
// On viewportPoint, perform the inverse transformation of the scene to get
// where the point would be in the scene before the transformation.
final Matrix4 inverseMatrix = Matrix4.inverted(transform);
final Vector3 untransformed = inverseMatrix.transform3(Vector3(
viewportPoint.dx,
viewportPoint.dy,
0,
));
final Vector3 untransformed = inverseMatrix.transform3(
Vector3(viewportPoint.dx, viewportPoint.dy, 0),
);
return Offset(untransformed.x, untransformed.y);
}
// Get the offset of the current widget from the global screen coordinates.
static Offset getOffset(BuildContext context) {
assert(context.findRenderObject() != null, 'The given context must have a renderObject, such as after the first build has completed.');
assert(
context.findRenderObject() != null,
'The given context must have a renderObject, such as after the first build has completed.',
);
final RenderBox renderObject = context.findRenderObject()! as RenderBox;
return renderObject.localToGlobal(Offset.zero);
}
@@ -185,12 +179,8 @@ class _GestureTransformableState extends State<GestureTransformable> with Ticker
super.initState();
_boundaryRect = widget.boundaryRect ?? Offset.zero & widget.size;
_transform = _initialTransform;
_controller = AnimationController(
vsync: this,
);
_controllerReset = AnimationController(
vsync: this,
);
_controller = AnimationController(vsync: this);
_controllerReset = AnimationController(vsync: this);
if (widget.reset) {
_animateResetInitialize();
}
@@ -212,71 +202,159 @@ class _GestureTransformableState extends State<GestureTransformable> with Ticker
// its child, which is the CustomPaint.
return GestureDetector(
behavior: HitTestBehavior.opaque, // Necessary when translating off screen
onTapDown: widget.onTapDown == null ? null : (TapDownDetails details) {
widget.onTapDown!(TapDownDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onTapUp: widget.onTapUp == null ? null : (TapUpDetails details) {
widget.onTapUp!(TapUpDetails(
kind: details.kind,
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onTapDown:
widget.onTapDown == null
? null
: (TapDownDetails details) {
widget.onTapDown!(
TapDownDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onTapUp:
widget.onTapUp == null
? null
: (TapUpDetails details) {
widget.onTapUp!(
TapUpDetails(
kind: details.kind,
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onTap: widget.onTap,
onTapCancel: widget.onTapCancel,
onDoubleTap: widget.onDoubleTap,
onLongPress: widget.onLongPress,
onLongPressUp: widget.onLongPressUp,
onVerticalDragDown: widget.onVerticalDragDown == null ? null : (DragDownDetails details) {
widget.onVerticalDragDown!(DragDownDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onVerticalDragStart: widget.onVerticalDragStart == null ? null : (DragStartDetails details) {
widget.onVerticalDragStart!(DragStartDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onVerticalDragUpdate: widget.onVerticalDragUpdate == null ? null : (DragUpdateDetails details) {
widget.onVerticalDragUpdate!(DragUpdateDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onVerticalDragDown:
widget.onVerticalDragDown == null
? null
: (DragDownDetails details) {
widget.onVerticalDragDown!(
DragDownDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onVerticalDragStart:
widget.onVerticalDragStart == null
? null
: (DragStartDetails details) {
widget.onVerticalDragStart!(
DragStartDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onVerticalDragUpdate:
widget.onVerticalDragUpdate == null
? null
: (DragUpdateDetails details) {
widget.onVerticalDragUpdate!(
DragUpdateDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onVerticalDragEnd: widget.onVerticalDragEnd,
onVerticalDragCancel: widget.onVerticalDragCancel,
onHorizontalDragDown: widget.onHorizontalDragDown == null ? null : (DragDownDetails details) {
widget.onHorizontalDragDown!(DragDownDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onHorizontalDragStart: widget.onHorizontalDragStart == null ? null : (DragStartDetails details) {
widget.onHorizontalDragStart!(DragStartDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onHorizontalDragUpdate: widget.onHorizontalDragUpdate == null ? null : (DragUpdateDetails details) {
widget.onHorizontalDragUpdate!(DragUpdateDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onHorizontalDragDown:
widget.onHorizontalDragDown == null
? null
: (DragDownDetails details) {
widget.onHorizontalDragDown!(
DragDownDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onHorizontalDragStart:
widget.onHorizontalDragStart == null
? null
: (DragStartDetails details) {
widget.onHorizontalDragStart!(
DragStartDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onHorizontalDragUpdate:
widget.onHorizontalDragUpdate == null
? null
: (DragUpdateDetails details) {
widget.onHorizontalDragUpdate!(
DragUpdateDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onHorizontalDragEnd: widget.onHorizontalDragEnd,
onHorizontalDragCancel: widget.onHorizontalDragCancel,
onPanDown: widget.onPanDown == null ? null : (DragDownDetails details) {
widget.onPanDown!(DragDownDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onPanStart: widget.onPanStart == null ? null : (DragStartDetails details) {
widget.onPanStart!(DragStartDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onPanUpdate: widget.onPanUpdate == null ? null : (DragUpdateDetails details) {
widget.onPanUpdate!(DragUpdateDetails(
globalPosition: fromViewport(details.globalPosition - getOffset(context), _transform),
));
},
onPanDown:
widget.onPanDown == null
? null
: (DragDownDetails details) {
widget.onPanDown!(
DragDownDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onPanStart:
widget.onPanStart == null
? null
: (DragStartDetails details) {
widget.onPanStart!(
DragStartDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onPanUpdate:
widget.onPanUpdate == null
? null
: (DragUpdateDetails details) {
widget.onPanUpdate!(
DragUpdateDetails(
globalPosition: fromViewport(
details.globalPosition - getOffset(context),
_transform,
),
),
);
},
onPanEnd: widget.onPanEnd,
onPanCancel: widget.onPanCancel,
onScaleEnd: _onScaleEnd,
@@ -320,15 +398,9 @@ class _GestureTransformableState extends State<GestureTransformable> with Ticker
-scale * viewportBoundaries.left,
-scale * viewportBoundaries.top,
);
final Matrix4 nextMatrix = matrix.clone()..translate(
translation!.dx,
translation.dy,
);
final Matrix4 nextMatrix = matrix.clone()..translate(translation!.dx, translation.dy);
final Vector3 nextTranslationVector = nextMatrix.getTranslation();
final Offset nextTranslation = Offset(
nextTranslationVector.x,
nextTranslationVector.y,
);
final Offset nextTranslation = Offset(nextTranslationVector.x, nextTranslationVector.y);
final bool inBoundaries = translationBoundaries.contains(
Offset(nextTranslation.dx, nextTranslation.dy),
);
@@ -351,14 +423,11 @@ class _GestureTransformableState extends State<GestureTransformable> with Ticker
final Offset tl = fromViewport(Offset.zero, _transform);
final Offset tr = fromViewport(Offset(widget.size.width, 0), _transform);
final Offset bl = fromViewport(Offset(0, widget.size.height), _transform);
final Offset br = fromViewport(
Offset(widget.size.width, widget.size.height),
_transform,
);
if (!_boundaryRect.contains(tl)
|| !_boundaryRect.contains(tr)
|| !_boundaryRect.contains(bl)
|| !_boundaryRect.contains(br)) {
final Offset br = fromViewport(Offset(widget.size.width, widget.size.height), _transform);
if (!_boundaryRect.contains(tl) ||
!_boundaryRect.contains(tr) ||
!_boundaryRect.contains(bl) ||
!_boundaryRect.contains(br)) {
return matrix;
}
@@ -366,10 +435,7 @@ class _GestureTransformableState extends State<GestureTransformable> with Ticker
// scale.
final double currentScale = _transform.getMaxScaleOnAxis();
final double totalScale = currentScale * scale!;
final double clampedTotalScale = totalScale.clamp(
widget.minScale,
widget.maxScale,
);
final double clampedTotalScale = totalScale.clamp(widget.minScale, widget.maxScale);
final double clampedScale = clampedTotalScale / currentScale;
return matrix..scale(clampedScale);
}
@@ -413,15 +479,14 @@ class _GestureTransformableState extends State<GestureTransformable> with Ticker
// Handle an update to an ongoing gesture of _GestureType.
void _onScaleUpdate(ScaleUpdateDetails details) {
double scale = _transform.getMaxScaleOnAxis();
widget.onScaleUpdate?.call(ScaleUpdateDetails(
focalPoint: fromViewport(details.focalPoint, _transform),
scale: details.scale,
rotation: details.rotation,
));
final Offset focalPointScene = fromViewport(
details.focalPoint,
_transform,
widget.onScaleUpdate?.call(
ScaleUpdateDetails(
focalPoint: fromViewport(details.focalPoint, _transform),
scale: details.scale,
rotation: details.rotation,
),
);
final Offset focalPointScene = fromViewport(details.focalPoint, _transform);
if (gestureType == null) {
// Decide which type of gesture this is by comparing the amount of scale
// and rotation in the gesture, if any. Scale starts at 1 and rotation
@@ -449,14 +514,15 @@ class _GestureTransformableState extends State<GestureTransformable> with Ticker
// same places in the scene. That means that the focal point of the
// scale should be on the same place in the scene before and after the
// scale.
final Offset focalPointSceneNext = fromViewport(
details.focalPoint,
_transform,
);
final Offset focalPointSceneNext = fromViewport(details.focalPoint, _transform);
_transform = matrixTranslate(_transform, focalPointSceneNext - focalPointScene);
} else if (gestureType == _GestureType.rotate && details.rotation != 0.0) {
final double desiredRotation = _rotationStart! + details.rotation;
_transform = matrixRotate(_transform, _currentRotation - desiredRotation, details.focalPoint);
_transform = matrixRotate(
_transform,
_currentRotation - desiredRotation,
details.focalPoint,
);
_currentRotation = desiredRotation;
} else if (_translateFromScene != null && details.scale == 1.0) {
// Translate so that the same point in the scene is underneath the
@@ -481,8 +547,8 @@ class _GestureTransformableState extends State<GestureTransformable> with Ticker
_controller.reset();
// If the scale ended with velocity, animate inertial movement
final double velocityTotal = details.velocity.pixelsPerSecond.dx.abs()
+ details.velocity.pixelsPerSecond.dy.abs();
final double velocityTotal =
details.velocity.pixelsPerSecond.dx.abs() + details.velocity.pixelsPerSecond.dy.abs();
if (velocityTotal == 0) {
return;
}

View File

@@ -29,14 +29,11 @@ class InertialMotion {
// The acceleration opposing the initial velocity in x and y components.
Vector2 get _acceleration {
final double velocityTotal = _initialVelocity.pixelsPerSecond.dx.abs()
+ _initialVelocity.pixelsPerSecond.dy.abs();
final double velocityTotal =
_initialVelocity.pixelsPerSecond.dx.abs() + _initialVelocity.pixelsPerSecond.dy.abs();
final double vRatioX = _initialVelocity.pixelsPerSecond.dx / velocityTotal;
final double vRatioY = _initialVelocity.pixelsPerSecond.dy / velocityTotal;
return Vector2(
_kFrictionalAcceleration * vRatioX,
_kFrictionalAcceleration * vRatioY,
);
return Vector2(_kFrictionalAcceleration * vRatioX, _kFrictionalAcceleration * vRatioY);
}
// The position at a given time.

Some files were not shown because too many files have changed in this diff Show More