1
0
mirror of https://github.com/flutter/samples.git synced 2026-05-21 14:37:57 +00:00

[Gallery] Fix directory structure (#312)

This commit is contained in:
Pierre-Louis
2020-02-05 20:11:54 +01:00
committed by GitHub
parent 082592e9a9
commit cee267cf88
762 changed files with 12 additions and 12 deletions

View File

@@ -0,0 +1,147 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:gallery/data/gallery_options.dart';
import 'package:gallery/l10n/gallery_localizations.dart';
import 'package:gallery/layout/adaptive.dart';
import 'package:gallery/studies/shrine/backdrop.dart';
import 'package:gallery/studies/shrine/category_menu_page.dart';
import 'package:gallery/studies/shrine/expanding_bottom_sheet.dart';
import 'package:gallery/studies/shrine/home.dart';
import 'package:gallery/studies/shrine/login.dart';
import 'package:gallery/studies/shrine/model/app_state_model.dart';
import 'package:gallery/studies/shrine/page_status.dart';
import 'package:gallery/studies/shrine/scrim.dart';
import 'package:gallery/studies/shrine/supplemental/layout_cache.dart';
import 'package:gallery/studies/shrine/theme.dart';
import 'package:scoped_model/scoped_model.dart';
class ShrineApp extends StatefulWidget {
const ShrineApp({Key key, this.navigatorKey}) : super(key: key);
final GlobalKey<NavigatorState> navigatorKey;
@override
_ShrineAppState createState() => _ShrineAppState();
}
class _ShrineAppState extends State<ShrineApp> with TickerProviderStateMixin {
// Controller to coordinate both the opening/closing of backdrop and sliding
// of expanding bottom sheet
AnimationController _controller;
// Animation Controller for expanding/collapsing the cart menu.
AnimationController _expandingController;
AppStateModel _model;
Map<String, List<List<int>>> _layouts = {};
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 450),
value: 1,
);
_expandingController = AnimationController(
duration: const Duration(milliseconds: 500),
vsync: this,
);
_model = AppStateModel()..loadProducts();
}
@override
void dispose() {
_controller.dispose();
_expandingController.dispose();
super.dispose();
}
Widget mobileBackdrop() {
return Backdrop(
frontLayer: const ProductPage(),
backLayer: CategoryMenuPage(onCategoryTap: () => _controller.forward()),
frontTitle: const Text('SHRINE'),
backTitle: Text(GalleryLocalizations.of(context).shrineMenuCaption),
controller: _controller,
);
}
Widget desktopBackdrop() {
return DesktopBackdrop(
frontLayer: ProductPage(),
backLayer: CategoryMenuPage(),
);
}
// Closes the bottom sheet if it is open.
Future<bool> _onWillPop() async {
final status = _expandingController.status;
if (status == AnimationStatus.completed ||
status == AnimationStatus.forward) {
_expandingController.reverse();
return false;
}
return true;
}
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
final Widget backdrop = isDesktop ? desktopBackdrop() : mobileBackdrop();
return ScopedModel<AppStateModel>(
model: _model,
child: WillPopScope(
onWillPop: _onWillPop,
child: MaterialApp(
navigatorKey: widget.navigatorKey,
title: 'Shrine',
debugShowCheckedModeBanner: false,
home: LayoutCache(
layouts: _layouts,
child: PageStatus(
menuController: _controller,
cartController: _expandingController,
child: HomePage(
backdrop: backdrop,
scrim: Scrim(controller: _expandingController),
expandingBottomSheet: ExpandingBottomSheet(
hideController: _controller,
expandingController: _expandingController,
),
),
),
),
initialRoute: '/login',
onGenerateRoute: _getRoute,
theme: shrineTheme.copyWith(
platform: GalleryOptions.of(context).platform,
),
// L10n settings.
localizationsDelegates: GalleryLocalizations.localizationsDelegates,
supportedLocales: GalleryLocalizations.supportedLocales,
locale: GalleryOptions.of(context).locale,
),
),
);
}
}
Route<dynamic> _getRoute(RouteSettings settings) {
if (settings.name != '/login') {
return null;
}
return MaterialPageRoute<void>(
settings: settings,
builder: (context) => LoginPage(),
fullscreenDialog: true,
);
}

View File

@@ -0,0 +1,400 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:gallery/studies/shrine/page_status.dart';
import 'package:meta/meta.dart';
import 'package:gallery/l10n/gallery_localizations.dart';
import 'package:gallery/studies/shrine/category_menu_page.dart';
const Cubic _accelerateCurve = Cubic(0.548, 0, 0.757, 0.464);
const Cubic _decelerateCurve = Cubic(0.23, 0.94, 0.41, 1);
const _peakVelocityTime = 0.248210;
const _peakVelocityProgress = 0.379146;
class _FrontLayer extends StatelessWidget {
const _FrontLayer({
Key key,
this.onTap,
this.child,
}) : super(key: key);
final VoidCallback onTap;
final Widget child;
@override
Widget build(BuildContext context) {
// An area at the top of the product page.
// When the menu page is shown, tapping this area will close the menu
// page and reveal the product page.
final Widget pageTopArea = Container(
height: 40,
alignment: AlignmentDirectional.centerStart,
);
return Material(
elevation: 16,
shape: const BeveledRectangleBorder(
borderRadius:
BorderRadiusDirectional.only(topStart: Radius.circular(46)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
onTap != null
? GestureDetector(
behavior: HitTestBehavior.opaque,
excludeFromSemantics:
true, // Because there is already a "Close Menu" button on screen.
onTap: onTap,
child: pageTopArea,
)
: pageTopArea,
Expanded(
child: child,
),
],
),
);
}
}
class _BackdropTitle extends AnimatedWidget {
const _BackdropTitle({
Key key,
this.listenable,
this.onPress,
@required this.frontTitle,
@required this.backTitle,
}) : assert(frontTitle != null),
assert(backTitle != null),
super(key: key, listenable: listenable);
final Animation<double> listenable;
final void Function() onPress;
final Widget frontTitle;
final Widget backTitle;
@override
Widget build(BuildContext context) {
final Animation<double> animation = CurvedAnimation(
parent: listenable,
curve: const Interval(0, 0.78),
);
final double textDirectionScalar =
Directionality.of(context) == TextDirection.ltr ? 1 : -1;
final slantedMenuIcon =
ImageIcon(AssetImage('packages/shrine_images/slanted_menu.png'));
final directionalSlantedMenuIcon =
Directionality.of(context) == TextDirection.ltr
? slantedMenuIcon
: Transform(
alignment: Alignment.center,
transform: Matrix4.rotationY(pi),
child: slantedMenuIcon,
);
final String menuButtonTooltip = animation.isCompleted
? GalleryLocalizations.of(context).shrineTooltipOpenMenu
: animation.isDismissed
? GalleryLocalizations.of(context).shrineTooltipCloseMenu
: null;
return DefaultTextStyle(
style: Theme.of(context).primaryTextTheme.title,
softWrap: false,
overflow: TextOverflow.ellipsis,
child: Row(children: [
// branded icon
SizedBox(
width: 72,
child: Semantics(
container: true,
child: IconButton(
padding: const EdgeInsetsDirectional.only(end: 8),
onPressed: onPress,
tooltip: menuButtonTooltip,
icon: Stack(children: [
Opacity(
opacity: animation.value,
child: directionalSlantedMenuIcon,
),
FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: Offset(1 * textDirectionScalar, 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: [
Opacity(
opacity: CurvedAnimation(
parent: ReverseAnimation(animation),
curve: const Interval(0.5, 1),
).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: Offset(0.5 * textDirectionScalar, 0),
).evaluate(animation),
child: backTitle,
),
),
Opacity(
opacity: CurvedAnimation(
parent: animation,
curve: const Interval(0.5, 1),
).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: Offset(-0.25 * textDirectionScalar, 0),
end: Offset.zero,
).evaluate(animation),
child: frontTitle,
),
),
],
),
]),
);
}
}
/// Builds a Backdrop.
///
/// A Backdrop widget has two layers, front and back. The front layer is shown
/// by default, and slides down to show the back layer, from which a user
/// can make a selection. The user can also configure the titles for when the
/// front or back layer is showing.
class Backdrop extends StatefulWidget {
const Backdrop({
@required this.frontLayer,
@required this.backLayer,
@required this.frontTitle,
@required this.backTitle,
@required this.controller,
}) : assert(frontLayer != null),
assert(backLayer != null),
assert(frontTitle != null),
assert(backTitle != null),
assert(controller != null);
final Widget frontLayer;
final Widget backLayer;
final Widget frontTitle;
final Widget backTitle;
final AnimationController controller;
@override
_BackdropState createState() => _BackdropState();
}
class _BackdropState extends State<Backdrop>
with SingleTickerProviderStateMixin {
final GlobalKey _backdropKey = GlobalKey(debugLabel: 'Backdrop');
AnimationController _controller;
Animation<RelativeRect> _layerAnimation;
@override
void initState() {
super.initState();
_controller = widget.controller;
}
bool get _frontLayerVisible {
final AnimationStatus status = _controller.status;
return status == AnimationStatus.completed ||
status == AnimationStatus.forward;
}
void _toggleBackdropLayerVisibility() {
// Call setState here to update layerAnimation if that's necessary
setState(() {
_frontLayerVisible ? _controller.reverse() : _controller.forward();
});
}
// _layerAnimation animates the front layer between open and close.
// _getLayerAnimation adjusts the values in the TweenSequence so the
// curve and timing are correct in both directions.
Animation<RelativeRect> _getLayerAnimation(Size layerSize, double layerTop) {
Curve firstCurve; // Curve for first TweenSequenceItem
Curve secondCurve; // Curve for second TweenSequenceItem
double firstWeight; // Weight of first TweenSequenceItem
double secondWeight; // Weight of second TweenSequenceItem
Animation<double> animation; // Animation on which TweenSequence runs
if (_frontLayerVisible) {
firstCurve = _accelerateCurve;
secondCurve = _decelerateCurve;
firstWeight = _peakVelocityTime;
secondWeight = 1 - _peakVelocityTime;
animation = CurvedAnimation(
parent: _controller.view,
curve: const Interval(0, 0.78),
);
} else {
// These values are only used when the controller runs from t=1.0 to t=0.0
firstCurve = _decelerateCurve.flipped;
secondCurve = _accelerateCurve.flipped;
firstWeight = 1 - _peakVelocityTime;
secondWeight = _peakVelocityTime;
animation = _controller.view;
}
return TweenSequence<RelativeRect>(
[
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(
0,
layerTop,
0,
layerTop - layerSize.height,
),
end: RelativeRect.fromLTRB(
0,
layerTop * _peakVelocityProgress,
0,
(layerTop - layerSize.height) * _peakVelocityProgress,
),
).chain(CurveTween(curve: firstCurve)),
weight: firstWeight,
),
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(
0,
layerTop * _peakVelocityProgress,
0,
(layerTop - layerSize.height) * _peakVelocityProgress,
),
end: RelativeRect.fill,
).chain(CurveTween(curve: secondCurve)),
weight: secondWeight,
),
],
).animate(animation);
}
Widget _buildStack(BuildContext context, BoxConstraints constraints) {
const double layerTitleHeight = 48;
final Size layerSize = constraints.biggest;
final double layerTop = layerSize.height - layerTitleHeight;
_layerAnimation = _getLayerAnimation(layerSize, layerTop);
return Stack(
key: _backdropKey,
children: [
ExcludeSemantics(
excluding: _frontLayerVisible,
child: widget.backLayer,
),
PositionedTransition(
rect: _layerAnimation,
child: ExcludeSemantics(
excluding: !_frontLayerVisible,
child: AnimatedBuilder(
animation: PageStatus.of(context).cartController,
builder: (context, child) => AnimatedBuilder(
animation: PageStatus.of(context).menuController,
builder: (context, child) => _FrontLayer(
onTap: menuPageIsVisible(context)
? _toggleBackdropLayerVisibility
: null,
child: widget.frontLayer,
),
),
),
),
),
],
);
}
@override
Widget build(BuildContext context) {
final AppBar appBar = AppBar(
brightness: Brightness.light,
elevation: 0,
titleSpacing: 0,
title: _BackdropTitle(
listenable: _controller.view,
onPress: _toggleBackdropLayerVisibility,
frontTitle: widget.frontTitle,
backTitle: widget.backTitle,
),
actions: [
IconButton(
icon: const Icon(Icons.search),
tooltip: GalleryLocalizations.of(context).shrineTooltipSearch,
onPressed: () {},
),
IconButton(
icon: const Icon(Icons.tune),
tooltip: GalleryLocalizations.of(context).shrineTooltipSettings,
onPressed: () {},
),
],
);
return AnimatedBuilder(
animation: PageStatus.of(context).cartController,
builder: (context, child) => ExcludeSemantics(
excluding: cartPageIsVisible(context),
child: Scaffold(
appBar: appBar,
body: LayoutBuilder(
builder: _buildStack,
),
),
),
);
}
}
class DesktopBackdrop extends StatelessWidget {
const DesktopBackdrop({
@required this.frontLayer,
@required this.backLayer,
});
final Widget frontLayer;
final Widget backLayer;
@override
Widget build(BuildContext context) {
return Stack(
children: [
backLayer,
Padding(
padding: EdgeInsetsDirectional.only(
start: desktopCategoryMenuPageWidth(context: context),
),
child: Material(
elevation: 16,
color: Colors.white,
child: frontLayer,
),
)
],
);
}
}

View File

@@ -0,0 +1,211 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:gallery/data/gallery_options.dart';
import 'package:gallery/l10n/gallery_localizations.dart';
import 'package:gallery/layout/adaptive.dart';
import 'package:gallery/layout/text_scale.dart';
import 'package:gallery/studies/shrine/colors.dart';
import 'package:gallery/studies/shrine/login.dart';
import 'package:gallery/studies/shrine/model/app_state_model.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/page_status.dart';
import 'package:gallery/studies/shrine/triangle_category_indicator.dart';
double desktopCategoryMenuPageWidth({
BuildContext context,
}) {
return 232 * reducedTextScale(context);
}
class CategoryMenuPage extends StatelessWidget {
const CategoryMenuPage({
Key key,
this.onCategoryTap,
}) : super(key: key);
final VoidCallback onCategoryTap;
Widget _buttonText(String caption, TextStyle style) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16),
child: Text(
caption,
style: style,
textAlign: TextAlign.center,
),
);
}
Widget _divider({BuildContext context}) {
return Container(
width: 56 * GalleryOptions.of(context).textScaleFactor(context),
height: 1,
color: Color(0xFF8F716D),
);
}
Widget _buildCategory(Category category, BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
final String categoryString = category.name(context);
final TextStyle selectedCategoryTextStyle = Theme.of(context)
.textTheme
.body2
.copyWith(fontSize: isDesktop ? 17 : 19);
final TextStyle unselectedCategoryTextStyle = selectedCategoryTextStyle
.copyWith(color: shrineBrown900.withOpacity(0.6));
final double indicatorHeight = (isDesktop ? 28 : 30) *
GalleryOptions.of(context).textScaleFactor(context);
final double indicatorWidth = indicatorHeight * 34 / 28;
return ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) => Semantics(
selected: model.selectedCategory == category,
button: true,
child: GestureDetector(
onTap: () {
model.setCategory(category);
if (onCategoryTap != null) {
onCategoryTap();
}
},
child: model.selectedCategory == category
? CustomPaint(
painter: TriangleCategoryIndicator(
indicatorWidth,
indicatorHeight,
),
child: _buttonText(categoryString, selectedCategoryTextStyle),
)
: _buttonText(categoryString, unselectedCategoryTextStyle),
),
),
);
}
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
final TextStyle logoutTextStyle =
Theme.of(context).textTheme.body2.copyWith(
fontSize: isDesktop ? 17 : 19,
color: shrineBrown900.withOpacity(0.6),
);
if (isDesktop) {
return AnimatedBuilder(
animation: PageStatus.of(context).cartController,
builder: (context, child) => ExcludeSemantics(
excluding: !menuPageIsVisible(context),
child: Material(
child: Container(
color: shrinePink100,
width: desktopCategoryMenuPageWidth(context: context),
child: Column(
children: [
const SizedBox(height: 64),
Image.asset(
'packages/shrine_images/diamond.png',
excludeFromSemantics: true,
),
const SizedBox(height: 16),
Semantics(
container: true,
child: Text(
'SHRINE',
style: Theme.of(context).textTheme.headline,
),
),
const Spacer(),
for (final category in categories)
_buildCategory(category, context),
_divider(context: context),
Semantics(
button: true,
child: GestureDetector(
onTap: () {
Navigator.push<void>(
context,
MaterialPageRoute<void>(
builder: (context) => LoginPage(),
),
);
},
child: _buttonText(
GalleryLocalizations.of(context)
.shrineLogoutButtonCaption,
logoutTextStyle,
),
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.search),
tooltip:
GalleryLocalizations.of(context).shrineTooltipSearch,
onPressed: () {},
),
const SizedBox(height: 72),
],
),
),
),
),
);
} else {
return AnimatedBuilder(
animation: PageStatus.of(context).cartController,
builder: (context, child) => AnimatedBuilder(
animation: PageStatus.of(context).menuController,
builder: (context, child) => ExcludeSemantics(
excluding: !menuPageIsVisible(context),
child: Center(
child: Container(
padding: const EdgeInsets.only(top: 40),
color: shrinePink100,
child: ListView(
children: [
for (final category in categories)
_buildCategory(category, context),
Center(
child: _divider(context: context),
),
Semantics(
button: true,
child: GestureDetector(
onTap: () {
if (onCategoryTap != null) {
onCategoryTap();
}
Navigator.push<void>(
context,
MaterialPageRoute<void>(
builder: (context) => LoginPage()),
);
},
child: _buttonText(
GalleryLocalizations.of(context)
.shrineLogoutButtonCaption,
logoutTextStyle,
),
),
),
],
),
),
),
),
),
);
}
}
}

View File

@@ -0,0 +1,18 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
const Color shrinePink50 = Color(0xFFFEEAE6);
const Color shrinePink100 = Color(0xFFFEDBD0);
const Color shrinePink300 = Color(0xFFFBB8AC);
const Color shrinePink400 = Color(0xFFEAA4A4);
const Color shrineBrown900 = Color(0xFF442B2D);
const Color shrineBrown600 = Color(0xFF7D4F52);
const Color shrineErrorRed = Color(0xFFC5032B);
const Color shrineSurfaceWhite = Color(0xFFFFFBFA);
const Color shrineBackgroundWhite = Colors.white;

View File

@@ -0,0 +1,820 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:gallery/layout/adaptive.dart';
import 'package:gallery/layout/text_scale.dart';
import 'package:gallery/l10n/gallery_localizations.dart';
import 'package:gallery/studies/shrine/colors.dart';
import 'package:gallery/studies/shrine/model/app_state_model.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/page_status.dart';
import 'package:gallery/studies/shrine/shopping_cart.dart';
// These curves define the emphasized easing curve.
const Cubic _accelerateCurve = Cubic(0.548, 0, 0.757, 0.464);
const Cubic _decelerateCurve = Cubic(0.23, 0.94, 0.41, 1);
// The time at which the accelerate and decelerate curves switch off
const _peakVelocityTime = 0.248210;
// Percent (as a decimal) of animation that should be completed at _peakVelocityTime
const _peakVelocityProgress = 0.379146;
// Radius of the shape on the top start of the sheet for mobile layouts.
const _mobileCornerRadius = 24.0;
// Radius of the shape on the top start and bottom start of the sheet for mobile layouts.
const _desktopCornerRadius = 12.0;
// Width for just the cart icon and no thumbnails.
const _cartIconWidth = 64.0;
// Height for just the cart icon and no thumbnails.
const _cartIconHeight = 56.0;
// Height of a thumbnail.
const _defaultThumbnailHeight = 40.0;
// Gap between thumbnails.
const _thumbnailGap = 16.0;
// Maximum number of thumbnails shown in the cart.
const _maxThumbnailCount = 3;
double _thumbnailHeight(BuildContext context) {
return _defaultThumbnailHeight * reducedTextScale(context);
}
double _paddedThumbnailHeight(BuildContext context) {
return _thumbnailHeight(context) + _thumbnailGap;
}
class ExpandingBottomSheet extends StatefulWidget {
const ExpandingBottomSheet({
Key key,
@required this.hideController,
@required this.expandingController,
}) : assert(hideController != null),
assert(expandingController != null),
super(key: key);
final AnimationController hideController;
final AnimationController expandingController;
@override
_ExpandingBottomSheetState createState() => _ExpandingBottomSheetState();
static _ExpandingBottomSheetState of(BuildContext context,
{bool isNullOk = false}) {
assert(isNullOk != null);
assert(context != null);
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');
}
}
// Emphasized Easing is a motion curve that has an organic, exciting feeling.
// It's very fast to begin with and then very slow to finish. Unlike standard
// curves, like [Curves.fastOutSlowIn], it can't be expressed in a cubic bezier
// curve formula. It's quintic, not cubic. But it _can_ be expressed as one
// curve followed by another, which we do here.
Animation<T> _getEmphasizedEasingAnimation<T>({
@required T begin,
@required T peak,
@required T end,
@required bool isForward,
@required Animation<double> parent,
}) {
Curve firstCurve;
Curve secondCurve;
double firstWeight;
double secondWeight;
if (isForward) {
firstCurve = _accelerateCurve;
secondCurve = _decelerateCurve;
firstWeight = _peakVelocityTime;
secondWeight = 1 - _peakVelocityTime;
} else {
firstCurve = _decelerateCurve.flipped;
secondCurve = _accelerateCurve.flipped;
firstWeight = 1 - _peakVelocityTime;
secondWeight = _peakVelocityTime;
}
return TweenSequence<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
// callers of _getEmphasisedEasing<double>().
double _getPeakPoint({double begin, double end}) {
return begin + (end - begin) * _peakVelocityProgress;
}
class _ExpandingBottomSheetState extends State<ExpandingBottomSheet>
with TickerProviderStateMixin {
final GlobalKey _expandingBottomSheetKey =
GlobalKey(debugLabel: 'Expanding bottom sheet');
// The width of the Material, calculated by _widthFor() & based on the number
// of products in the cart. 64.0 is the width when there are 0 products
// (_kWidthForZeroProducts)
double _width = _cartIconWidth;
double _height = _cartIconHeight;
// Controller for the opening and closing of the ExpandingBottomSheet
AnimationController get _controller => widget.expandingController;
// Animations for the opening and closing of the ExpandingBottomSheet
Animation<double> _widthAnimation;
Animation<double> _heightAnimation;
Animation<double> _thumbnailOpacityAnimation;
Animation<double> _cartOpacityAnimation;
Animation<double> _topStartShapeAnimation;
Animation<double> _bottomStartShapeAnimation;
Animation<Offset> _slideAnimation;
Animation<double> _gapAnimation;
Animation<double> _getWidthAnimation(double screenWidth) {
if (_controller.status == AnimationStatus.forward) {
// Opening animation
return Tween<double>(begin: _width, end: screenWidth).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0, 0.3, curve: Curves.fastOutSlowIn),
),
);
} else {
// Closing animation
return _getEmphasizedEasingAnimation(
begin: _width,
peak: _getPeakPoint(begin: _width, end: screenWidth),
end: screenWidth,
isForward: false,
parent: CurvedAnimation(
parent: _controller.view, curve: const Interval(0, 0.87)),
);
}
}
Animation<double> _getHeightAnimation(double screenHeight) {
if (_controller.status == AnimationStatus.forward) {
// Opening animation
return _getEmphasizedEasingAnimation(
begin: _height,
peak: _getPeakPoint(begin: _height, end: screenHeight),
end: screenHeight,
isForward: true,
parent: _controller.view,
);
} else {
// Closing animation
return Tween<double>(
begin: _height,
end: screenHeight,
).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0.434, 1, curve: Curves.linear), // not used
// only the reverseCurve will be used
reverseCurve: Interval(0.434, 1, curve: Curves.fastOutSlowIn.flipped),
),
);
}
}
Animation<double> _getDesktopGapAnimation(double gapHeight) {
final double _collapsedGapHeight = gapHeight;
final double _expandedGapHeight = 0;
if (_controller.status == AnimationStatus.forward) {
// Opening animation
return _getEmphasizedEasingAnimation(
begin: _collapsedGapHeight,
peak: _collapsedGapHeight +
(_expandedGapHeight - _collapsedGapHeight) * _peakVelocityProgress,
end: _expandedGapHeight,
isForward: true,
parent: _controller.view,
);
} else {
// Closing animation
return Tween<double>(
begin: _collapsedGapHeight,
end: _expandedGapHeight,
).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0.434, 1), // not used
// only the reverseCurve will be used
reverseCurve: Interval(0.434, 1, curve: Curves.fastOutSlowIn.flipped),
),
);
}
}
// Animation of the top-start cut corner. It's cut when closed and not cut when open.
Animation<double> _getShapeTopStartAnimation(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
final double cornerRadius =
isDesktop ? _desktopCornerRadius : _mobileCornerRadius;
if (_controller.status == AnimationStatus.forward) {
return Tween<double>(begin: cornerRadius, end: 0).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0, 0.3, curve: Curves.fastOutSlowIn),
),
);
} else {
return _getEmphasizedEasingAnimation(
begin: cornerRadius,
peak: _getPeakPoint(begin: cornerRadius, end: 0),
end: 0,
isForward: false,
parent: _controller.view,
);
}
}
// Animation of the bottom-start cut corner. It's cut when closed and not cut when open.
Animation<double> _getShapeBottomStartAnimation(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
final double cornerRadius = isDesktop ? _desktopCornerRadius : 0;
if (_controller.status == AnimationStatus.forward) {
return Tween<double>(begin: cornerRadius, end: 0).animate(
CurvedAnimation(
parent: _controller.view,
curve: const Interval(0, 0.3, curve: Curves.fastOutSlowIn),
),
);
} else {
return _getEmphasizedEasingAnimation(
begin: cornerRadius,
peak: _getPeakPoint(begin: cornerRadius, end: 0),
end: 0,
isForward: false,
parent: _controller.view,
);
}
}
Animation<double> _getThumbnailOpacityAnimation() {
return Tween<double>(begin: 1, end: 0).animate(
CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? const Interval(0, 0.3)
: const Interval(0.532, 0.766),
),
);
}
Animation<double> _getCartOpacityAnimation() {
return CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? const Interval(0.3, 0.6)
: const Interval(0.766, 1),
);
}
// Returns the correct width of the ExpandingBottomSheet based on the number of
// products and the text scaling options in the cart in the mobile layout.
double _mobileWidthFor(int numProducts, BuildContext context) {
final double cartThumbnailGap = numProducts > 0 ? 16 : 0;
final double thumbnailsWidth =
min(numProducts, _maxThumbnailCount) * _paddedThumbnailHeight(context);
final double overflowNumberWidth =
numProducts > _maxThumbnailCount ? 30 * cappedTextScale(context) : 0;
return _cartIconWidth +
cartThumbnailGap +
thumbnailsWidth +
overflowNumberWidth;
}
// Returns the correct height of the ExpandingBottomSheet based on the text scaling
// options in the mobile layout.
double _mobileHeightFor(BuildContext context) {
return _paddedThumbnailHeight(context);
}
// Returns the correct width of the ExpandingBottomSheet based on the text scaling
// options in the desktop layout.
double _desktopWidthFor(BuildContext context) {
return _paddedThumbnailHeight(context) + 8;
}
// Returns the correct height of the ExpandingBottomSheet based on the number of
// products and the text scaling options in the cart in the desktop layout.
double _desktopHeightFor(int numProducts, BuildContext context) {
final double cartThumbnailGap = numProducts > 0 ? 8 : 0;
final double thumbnailsHeight =
min(numProducts, _maxThumbnailCount) * _paddedThumbnailHeight(context);
final double overflowNumberHeight =
numProducts > _maxThumbnailCount ? 28 * reducedTextScale(context) : 0;
return _cartIconHeight +
cartThumbnailGap +
thumbnailsHeight +
overflowNumberHeight;
}
// Returns true if the cart is open or opening and false otherwise.
bool get _isOpen {
final AnimationStatus status = _controller.status;
return status == AnimationStatus.completed ||
status == AnimationStatus.forward;
}
// Opens the ExpandingBottomSheet if it's closed, otherwise does nothing.
void open() {
if (!_isOpen) {
_controller.forward();
}
}
// Closes the ExpandingBottomSheet if it's open or opening, otherwise does nothing.
void close() {
if (_isOpen) {
_controller.reverse();
}
}
// Changes the padding between the start edge of the Material and the cart icon
// based on the number of products in the cart (padding increases when > 0
// products.)
EdgeInsetsDirectional _horizontalCartPaddingFor(int numProducts) {
return (numProducts == 0)
? const EdgeInsetsDirectional.only(start: 20, end: 8)
: const EdgeInsetsDirectional.only(start: 32, end: 8);
}
// Changes the padding above and below the cart icon
// based on the number of products in the cart (padding increases when > 0
// products.)
EdgeInsets _verticalCartPaddingFor(int numProducts) {
return (numProducts == 0)
? const EdgeInsets.only(top: 16, bottom: 16)
: const EdgeInsets.only(top: 16, bottom: 24);
}
bool get _cartIsVisible => _thumbnailOpacityAnimation.value == 0;
// We take 16 pts off of the bottom padding to ensure the collapsed shopping
// cart is not too tall.
double get _bottomSafeArea {
return max(MediaQuery.of(context).viewPadding.bottom - 16, 0);
}
Widget _buildThumbnails(BuildContext context, int numProducts) {
final bool isDesktop = isDisplayDesktop(context);
Widget thumbnails;
if (isDesktop) {
thumbnails = Column(
children: [
AnimatedPadding(
padding: _verticalCartPaddingFor(numProducts),
child: const Icon(Icons.shopping_cart),
duration: const Duration(milliseconds: 225),
),
Container(
width: _width,
height: min(numProducts, _maxThumbnailCount) *
_paddedThumbnailHeight(context),
child: ProductThumbnailRow(),
),
ExtraProductsNumber(),
],
);
} else {
thumbnails = Column(
children: [
Row(
children: [
AnimatedPadding(
padding: _horizontalCartPaddingFor(numProducts),
child: const Icon(Icons.shopping_cart),
duration: const Duration(milliseconds: 225),
),
Container(
// Accounts for the overflow number
width: min(numProducts, _maxThumbnailCount) *
_paddedThumbnailHeight(context) +
(numProducts > 0 ? _thumbnailGap : 0),
height: _height - _bottomSafeArea,
padding: const EdgeInsets.symmetric(vertical: 8),
child: ProductThumbnailRow(),
),
ExtraProductsNumber(),
],
),
],
);
}
return ExcludeSemantics(
child: Opacity(
opacity: _thumbnailOpacityAnimation.value,
child: thumbnails,
),
);
}
Widget _buildShoppingCartPage() {
return Opacity(
opacity: _cartOpacityAnimation.value,
child: ShoppingCartPage(),
);
}
Widget _buildCart(BuildContext context) {
// numProducts is the number of different products in the cart (does not
// include multiples of the same product).
final bool isDesktop = isDisplayDesktop(context);
final AppStateModel model = ScopedModel.of<AppStateModel>(context);
final int numProducts = model.productsInCart.keys.length;
final int totalCartQuantity = model.totalCartQuantity;
final Size screenSize = MediaQuery.of(context).size;
final double screenWidth = screenSize.width;
final double screenHeight = screenSize.height;
final double expandedCartWidth = isDesktop
? (360 * cappedTextScale(context)).clamp(360, screenWidth).toDouble()
: screenWidth;
_width = isDesktop
? _desktopWidthFor(context)
: _mobileWidthFor(numProducts, context);
_widthAnimation = _getWidthAnimation(expandedCartWidth);
_height = isDesktop
? _desktopHeightFor(numProducts, context)
: _mobileHeightFor(context) + _bottomSafeArea;
_heightAnimation = _getHeightAnimation(screenHeight);
_topStartShapeAnimation = _getShapeTopStartAnimation(context);
_bottomStartShapeAnimation = _getShapeBottomStartAnimation(context);
_thumbnailOpacityAnimation = _getThumbnailOpacityAnimation();
_cartOpacityAnimation = _getCartOpacityAnimation();
_gapAnimation =
isDesktop ? _getDesktopGapAnimation(116) : AlwaysStoppedAnimation(0);
final Widget child = Container(
width: _widthAnimation.value,
height: _heightAnimation.value,
child: Material(
animationDuration: const Duration(milliseconds: 0),
shape: BeveledRectangleBorder(
borderRadius: BorderRadiusDirectional.only(
topStart: Radius.circular(_topStartShapeAnimation.value),
bottomStart: Radius.circular(_bottomStartShapeAnimation.value),
),
),
elevation: 4,
color: shrinePink50,
child: _cartIsVisible
? _buildShoppingCartPage()
: _buildThumbnails(context, numProducts),
),
);
final Widget childWithInteraction = productPageIsVisible(context)
? Semantics(
button: true,
label: GalleryLocalizations.of(context)
.shrineScreenReaderCart(totalCartQuantity),
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: open,
child: child,
),
)
: child;
return Padding(
padding: EdgeInsets.only(top: _gapAnimation.value),
child: childWithInteraction,
);
}
// Builder for the hide and reveal animation when the backdrop opens and closes
Widget _buildSlideAnimation(BuildContext context, Widget child) {
final bool isDesktop = isDisplayDesktop(context);
if (isDesktop) {
return child;
} else {
final double textDirectionScalar =
Directionality.of(context) == TextDirection.ltr ? 1 : -1;
_slideAnimation = _getEmphasizedEasingAnimation(
begin: Offset(1 * textDirectionScalar, 0),
peak: Offset(_peakVelocityProgress * textDirectionScalar, 0),
end: const Offset(0, 0),
isForward: widget.hideController.status == AnimationStatus.forward,
parent: widget.hideController,
);
return SlideTransition(
position: _slideAnimation,
child: child,
);
}
}
@override
Widget build(BuildContext context) {
return AnimatedSize(
key: _expandingBottomSheetKey,
duration: const Duration(milliseconds: 225),
curve: Curves.easeInOut,
vsync: this,
alignment: AlignmentDirectional.topStart,
child: AnimatedBuilder(
animation: widget.hideController,
builder: (context, child) => AnimatedBuilder(
animation: widget.expandingController,
builder: (context, child) => ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) =>
_buildSlideAnimation(context, _buildCart(context)),
),
),
),
);
}
}
class ProductThumbnailRow extends StatefulWidget {
@override
_ProductThumbnailRowState createState() => _ProductThumbnailRowState();
}
class _ProductThumbnailRowState extends State<ProductThumbnailRow> {
final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
// _list represents what's currently on screen. If _internalList updates,
// it will need to be updated to match it.
_ListModel _list;
// _internalList represents the list as it is updated by the AppStateModel.
List<int> _internalList;
@override
void initState() {
super.initState();
_list = _ListModel(
listKey: _listKey,
initialItems:
ScopedModel.of<AppStateModel>(context).productsInCart.keys.toList(),
removedItemBuilder: _buildRemovedThumbnail,
);
_internalList = List<int>.from(_list.list);
}
Product _productWithId(int productId) {
final AppStateModel model = ScopedModel.of<AppStateModel>(context);
final Product product = model.getProductById(productId);
assert(product != null);
return product;
}
Widget _buildRemovedThumbnail(
int item, BuildContext context, Animation<double> animation) {
return ProductThumbnail(animation, animation, _productWithId(item));
}
Widget _buildThumbnail(
BuildContext context, int index, Animation<double> animation) {
final Animation<double> thumbnailSize =
Tween<double>(begin: 0.8, end: 1).animate(
CurvedAnimation(
curve: const Interval(0.33, 1, curve: Curves.easeIn),
parent: animation,
),
);
final Animation<double> opacity = CurvedAnimation(
curve: const Interval(0.33, 1, curve: Curves.linear),
parent: animation,
);
return ProductThumbnail(
thumbnailSize, opacity, _productWithId(_list[index]));
}
// If the lists are the same length, assume nothing has changed.
// If the internalList is shorter than the ListModel, an item has been removed.
// If the internalList is longer, then an item has been added.
void _updateLists() {
// Update _internalList based on the model
_internalList =
ScopedModel.of<AppStateModel>(context).productsInCart.keys.toList();
final Set<int> internalSet = Set<int>.from(_internalList);
final Set<int> listSet = Set<int>.from(_list.list);
final Set<int> difference = internalSet.difference(listSet);
if (difference.isEmpty) {
return;
}
for (int product in difference) {
if (_internalList.length < _list.length) {
_list.remove(product);
} else if (_internalList.length > _list.length) {
_list.add(product);
}
}
while (_internalList.length != _list.length) {
int index = 0;
// Check bounds and that the list elements are the same
while (_internalList.isNotEmpty &&
_list.length > 0 &&
index < _internalList.length &&
index < _list.length &&
_internalList[index] == _list[index]) {
index++;
}
}
}
Widget _buildAnimatedList(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
return AnimatedList(
key: _listKey,
shrinkWrap: true,
itemBuilder: _buildThumbnail,
initialItemCount: _list.length,
scrollDirection: isDesktop ? Axis.vertical : Axis.horizontal,
physics: const NeverScrollableScrollPhysics(), // Cart shouldn't scroll
);
}
@override
Widget build(BuildContext context) {
_updateLists();
return ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) => _buildAnimatedList(context),
);
}
}
class ExtraProductsNumber extends StatelessWidget {
// Calculates the number to be displayed at the end of the row if there are
// more than three products in the cart. This calculates overflow products,
// including their duplicates (but not duplicates of products shown as
// thumbnails).
int _calculateOverflow(AppStateModel model) {
final Map<int, int> productMap = model.productsInCart;
// List created to be able to access products by index instead of ID.
// Order is guaranteed because productsInCart returns a LinkedHashMap.
final List<int> products = productMap.keys.toList();
int overflow = 0;
final int numProducts = products.length;
for (int i = _maxThumbnailCount; i < numProducts; i++) {
overflow += productMap[products[i]];
}
return overflow;
}
Widget _buildOverflow(AppStateModel model, BuildContext context) {
if (model.productsInCart.length <= _maxThumbnailCount) {
return Container();
}
final int numOverflowProducts = _calculateOverflow(model);
// Maximum of 99 so padding doesn't get messy.
final int displayedOverflowProducts =
numOverflowProducts <= 99 ? numOverflowProducts : 99;
return Container(
child: Text(
'+$displayedOverflowProducts',
style: Theme.of(context).primaryTextTheme.button,
),
);
}
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<AppStateModel>(
builder: (builder, child, model) => _buildOverflow(model, context),
);
}
}
class ProductThumbnail extends StatelessWidget {
const ProductThumbnail(this.animation, this.opacityAnimation, this.product);
final Animation<double> animation;
final Animation<double> opacityAnimation;
final Product product;
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
return FadeTransition(
opacity: opacityAnimation,
child: ScaleTransition(
scale: animation,
child: Container(
width: _thumbnailHeight(context),
height: _thumbnailHeight(context),
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage(
product.assetName, // asset name
package: product.assetPackage, // asset package
),
fit: BoxFit.cover,
),
borderRadius: const BorderRadius.all(Radius.circular(10)),
),
margin: isDesktop
? const EdgeInsetsDirectional.only(start: 12, end: 12, bottom: 16)
: const EdgeInsetsDirectional.only(start: 16),
),
),
);
}
}
// _ListModel manipulates an internal list and an AnimatedList
class _ListModel {
_ListModel({
@required this.listKey,
@required this.removedItemBuilder,
Iterable<int> initialItems,
}) : assert(listKey != null),
assert(removedItemBuilder != null),
_items = initialItems?.toList() ?? [];
final GlobalKey<AnimatedListState> listKey;
final Widget Function(int, BuildContext, Animation<double>)
removedItemBuilder;
final List<int> _items;
AnimatedListState get _animatedList => listKey.currentState;
void add(int product) {
_insert(_items.length, product);
}
void _insert(int index, int item) {
_items.insert(index, item);
_animatedList.insertItem(index,
duration: const Duration(milliseconds: 225));
}
void remove(int product) {
final int index = _items.indexOf(product);
if (index >= 0) {
_removeAt(index);
}
}
void _removeAt(int index) {
final int removedItem = _items.removeAt(index);
if (removedItem != null) {
_animatedList.removeItem(index, (context, animation) {
return removedItemBuilder(removedItem, context, animation);
});
}
}
int get length => _items.length;
int operator [](int index) => _items[index];
int indexOf(int item) => _items.indexOf(item);
List<int> get list => _items;
}

View File

@@ -0,0 +1,74 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:gallery/data/gallery_options.dart';
import 'package:gallery/layout/adaptive.dart';
import 'package:gallery/studies/shrine/expanding_bottom_sheet.dart';
import 'package:gallery/studies/shrine/model/app_state_model.dart';
import 'package:gallery/studies/shrine/supplemental/asymmetric_view.dart';
import 'package:scoped_model/scoped_model.dart';
const _ordinalSortKeyName = 'home';
class ProductPage extends StatelessWidget {
const ProductPage();
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
return ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) {
return isDesktop
? DesktopAsymmetricView(products: model.getProducts())
: MobileAsymmetricView(products: model.getProducts());
});
}
}
class HomePage extends StatelessWidget {
const HomePage({
this.expandingBottomSheet,
this.scrim,
this.backdrop,
Key key,
}) : super(key: key);
final ExpandingBottomSheet expandingBottomSheet;
final Widget scrim;
final Widget backdrop;
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
// Use sort keys to make sure the cart button is always on the top.
// This way, a11y users do not have to scroll through the entire list to
// find the cart, and can easily get to the cart from anywhere on the page.
return ApplyTextOptions(
child: Stack(
children: [
Semantics(
container: true,
child: backdrop,
sortKey: OrdinalSortKey(1, name: _ordinalSortKeyName),
),
ExcludeSemantics(child: scrim),
Align(
child: Semantics(
container: true,
child: expandingBottomSheet,
sortKey: OrdinalSortKey(0, name: _ordinalSortKeyName),
),
alignment: isDesktop
? AlignmentDirectional.topEnd
: AlignmentDirectional.bottomEnd,
),
],
),
);
}
}

View File

@@ -0,0 +1,230 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:gallery/data/gallery_options.dart';
import 'package:gallery/layout/adaptive.dart';
import 'package:gallery/layout/text_scale.dart';
import 'package:gallery/l10n/gallery_localizations.dart';
import 'package:gallery/studies/shrine/colors.dart';
import 'package:gallery/studies/shrine/theme.dart';
const _horizontalPadding = 24.0;
double desktopLoginScreenMainAreaWidth({BuildContext context}) {
return min(
360 * reducedTextScale(context),
MediaQuery.of(context).size.width - 2 * _horizontalPadding,
);
}
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
@override
Widget build(BuildContext context) {
final bool isDesktop = isDisplayDesktop(context);
return ApplyTextOptions(
child: isDesktop
? LayoutBuilder(
builder: (context, constraints) => Scaffold(
body: SafeArea(
child: Center(
child: Container(
width: desktopLoginScreenMainAreaWidth(context: context),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
_ShrineLogo(),
SizedBox(height: 40),
_UsernameTextField(),
SizedBox(height: 16),
_PasswordTextField(),
SizedBox(height: 24),
_CancelAndNextButtons(),
SizedBox(height: 62),
],
),
),
),
),
),
)
: Scaffold(
body: SafeArea(
child: ListView(
physics: ClampingScrollPhysics(),
padding: const EdgeInsets.symmetric(
horizontal: _horizontalPadding,
),
children: const [
SizedBox(height: 80),
_ShrineLogo(),
SizedBox(height: 120),
_UsernameTextField(),
SizedBox(height: 12),
_PasswordTextField(),
_CancelAndNextButtons(),
],
),
),
),
);
}
}
class _ShrineLogo extends StatelessWidget {
const _ShrineLogo();
@override
Widget build(BuildContext context) {
return ExcludeSemantics(
child: Column(
children: [
Image.asset('packages/shrine_images/diamond.png'),
const SizedBox(height: 16),
Text(
'SHRINE',
style: Theme.of(context).textTheme.headline,
),
],
),
);
}
}
class _UsernameTextField extends StatelessWidget {
const _UsernameTextField();
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final TextEditingController _usernameController = TextEditingController();
return PrimaryColorOverride(
color: shrineBrown900,
child: Container(
child: TextField(
controller: _usernameController,
cursorColor: colorScheme.onSurface,
decoration: InputDecoration(
labelText:
GalleryLocalizations.of(context).shrineLoginUsernameLabel,
labelStyle: TextStyle(letterSpacing: mediumLetterSpacing),
),
),
),
);
}
}
class _PasswordTextField extends StatelessWidget {
const _PasswordTextField();
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final TextEditingController _passwordController = TextEditingController();
return PrimaryColorOverride(
color: shrineBrown900,
child: Container(
child: TextField(
controller: _passwordController,
cursorColor: colorScheme.onSurface,
obscureText: true,
decoration: InputDecoration(
labelText:
GalleryLocalizations.of(context).shrineLoginPasswordLabel,
labelStyle: TextStyle(letterSpacing: mediumLetterSpacing),
),
),
),
);
}
}
class _CancelAndNextButtons extends StatelessWidget {
const _CancelAndNextButtons();
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final bool isDesktop = isDisplayDesktop(context);
final EdgeInsets buttonTextPadding = isDesktop
? EdgeInsets.symmetric(horizontal: 24, vertical: 16)
: EdgeInsets.zero;
return Wrap(
children: [
ButtonBar(
buttonPadding: isDesktop ? EdgeInsets.zero : null,
children: [
FlatButton(
child: Padding(
padding: buttonTextPadding,
child: Text(
GalleryLocalizations.of(context).shrineCancelButtonCaption,
style: TextStyle(color: colorScheme.onSurface),
),
),
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7)),
),
onPressed: () {
// The login screen is immediately displayed on top of
// the Shrine home screen using onGenerateRoute and so
// rootNavigator must be set to true in order to get out
// of Shrine completely.
Navigator.of(context, rootNavigator: true).pop();
},
),
RaisedButton(
child: Padding(
padding: buttonTextPadding,
child: Text(
GalleryLocalizations.of(context).shrineNextButtonCaption,
style: TextStyle(letterSpacing: largeLetterSpacing),
),
),
elevation: 8,
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7)),
),
onPressed: () {
Navigator.pop(context);
},
),
],
),
],
);
}
}
class PrimaryColorOverride extends StatelessWidget {
const PrimaryColorOverride({Key key, this.color, this.child})
: super(key: key);
final Color color;
final Widget child;
@override
Widget build(BuildContext context) {
return Theme(
child: child,
data: Theme.of(context).copyWith(primaryColor: color),
);
}
}

View File

@@ -0,0 +1,114 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:scoped_model/scoped_model.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/model/products_repository.dart';
double _salesTaxRate = 0.06;
double _shippingCostPerItem = 7;
class AppStateModel extends Model {
// All the available products.
List<Product> _availableProducts;
// The currently selected category of products.
Category _selectedCategory = categoryAll;
// The IDs and quantities of products currently in the cart.
final Map<int, int> _productsInCart = <int, int>{};
Map<int, int> get productsInCart => Map<int, int>.from(_productsInCart);
// Total number of items in the cart.
int get totalCartQuantity => _productsInCart.values.fold(0, (v, e) => v + e);
Category get selectedCategory => _selectedCategory;
// Totaled prices of the items in the cart.
double get subtotalCost {
return _productsInCart.keys
.map((id) => _availableProducts[id].price * _productsInCart[id])
.fold(0.0, (sum, e) => sum + e);
}
// Total shipping cost for the items in the cart.
double get shippingCost {
return _shippingCostPerItem *
_productsInCart.values.fold(0.0, (sum, e) => sum + e);
}
// Sales tax for the items in the cart
double get tax => subtotalCost * _salesTaxRate;
// Total cost to order everything in the cart.
double get totalCost => subtotalCost + shippingCost + tax;
// Returns a copy of the list of available products, filtered by category.
List<Product> getProducts() {
if (_availableProducts == null) {
return [];
}
if (_selectedCategory == categoryAll) {
return List<Product>.from(_availableProducts);
} else {
return _availableProducts
.where((p) => p.category == _selectedCategory)
.toList();
}
}
// Adds a product to the cart.
void addProductToCart(int productId) {
if (!_productsInCart.containsKey(productId)) {
_productsInCart[productId] = 1;
} else {
_productsInCart[productId]++;
}
notifyListeners();
}
// Removes an item from the cart.
void removeItemFromCart(int productId) {
if (_productsInCart.containsKey(productId)) {
if (_productsInCart[productId] == 1) {
_productsInCart.remove(productId);
} else {
_productsInCart[productId]--;
}
}
notifyListeners();
}
// Returns the Product instance matching the provided id.
Product getProductById(int id) {
return _availableProducts.firstWhere((p) => p.id == id);
}
// Removes everything from the cart.
void clearCart() {
_productsInCart.clear();
notifyListeners();
}
// Loads the list of available products from the repo.
void loadProducts() {
_availableProducts = ProductsRepository.loadProducts(categoryAll);
notifyListeners();
}
void setCategory(Category newCategory) {
_selectedCategory = newCategory;
notifyListeners();
}
@override
String toString() {
return 'AppStateModel(totalCost: $totalCost)';
}
}

View File

@@ -0,0 +1,70 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import '../../../l10n/gallery_localizations.dart';
class Category {
const Category({
@required this.name,
}) : assert(name != null);
// A function taking a BuildContext as input and
// returns the internationalized name of the category.
final String Function(BuildContext) name;
}
Category categoryAll = Category(
name: (context) => GalleryLocalizations.of(context).shrineCategoryNameAll,
);
Category categoryAccessories = Category(
name: (context) =>
GalleryLocalizations.of(context).shrineCategoryNameAccessories,
);
Category categoryClothing = Category(
name: (context) =>
GalleryLocalizations.of(context).shrineCategoryNameClothing,
);
Category categoryHome = Category(
name: (context) => GalleryLocalizations.of(context).shrineCategoryNameHome,
);
List<Category> categories = [
categoryAll,
categoryAccessories,
categoryClothing,
categoryHome,
];
class Product {
const Product({
@required this.category,
@required this.id,
@required this.isFeatured,
@required this.name,
@required this.price,
}) : assert(category != null),
assert(id != null),
assert(isFeatured != null),
assert(name != null),
assert(price != null);
final Category category;
final int id;
final bool isFeatured;
// A function taking a BuildContext as input and
// returns the internationalized name of the product.
final String Function(BuildContext) name;
final int price;
String get assetName => '$id-0.jpg';
String get assetPackage => 'shrine_images';
}

View File

@@ -0,0 +1,323 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:gallery/studies/shrine/model/product.dart';
import '../../../l10n/gallery_localizations.dart';
class ProductsRepository {
static List<Product> loadProducts(Category category) {
List<Product> allProducts = [
Product(
category: categoryAccessories,
id: 0,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductVagabondSack,
price: 120,
),
Product(
category: categoryAccessories,
id: 1,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductStellaSunglasses,
price: 58,
),
Product(
category: categoryAccessories,
id: 2,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductWhitneyBelt,
price: 35,
),
Product(
category: categoryAccessories,
id: 3,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductGardenStrand,
price: 98,
),
Product(
category: categoryAccessories,
id: 4,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductStrutEarrings,
price: 34,
),
Product(
category: categoryAccessories,
id: 5,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductVarsitySocks,
price: 12,
),
Product(
category: categoryAccessories,
id: 6,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductWeaveKeyring,
price: 16,
),
Product(
category: categoryAccessories,
id: 7,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductGatsbyHat,
price: 40,
),
Product(
category: categoryAccessories,
id: 8,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductShrugBag,
price: 198,
),
Product(
category: categoryHome,
id: 9,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductGiltDeskTrio,
price: 58,
),
Product(
category: categoryHome,
id: 10,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductCopperWireRack,
price: 18,
),
Product(
category: categoryHome,
id: 11,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductSootheCeramicSet,
price: 28,
),
Product(
category: categoryHome,
id: 12,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductHurrahsTeaSet,
price: 34,
),
Product(
category: categoryHome,
id: 13,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductBlueStoneMug,
price: 18,
),
Product(
category: categoryHome,
id: 14,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductRainwaterTray,
price: 27,
),
Product(
category: categoryHome,
id: 15,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductChambrayNapkins,
price: 16,
),
Product(
category: categoryHome,
id: 16,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductSucculentPlanters,
price: 16,
),
Product(
category: categoryHome,
id: 17,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductQuartetTable,
price: 175,
),
Product(
category: categoryHome,
id: 18,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductKitchenQuattro,
price: 129,
),
Product(
category: categoryClothing,
id: 19,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductClaySweater,
price: 48,
),
Product(
category: categoryClothing,
id: 20,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductSeaTunic,
price: 45,
),
Product(
category: categoryClothing,
id: 21,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductPlasterTunic,
price: 38,
),
Product(
category: categoryClothing,
id: 22,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductWhitePinstripeShirt,
price: 70,
),
Product(
category: categoryClothing,
id: 23,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductChambrayShirt,
price: 70,
),
Product(
category: categoryClothing,
id: 24,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductSeabreezeSweater,
price: 60,
),
Product(
category: categoryClothing,
id: 25,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductGentryJacket,
price: 178,
),
Product(
category: categoryClothing,
id: 26,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductNavyTrousers,
price: 74,
),
Product(
category: categoryClothing,
id: 27,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductWalterHenleyWhite,
price: 38,
),
Product(
category: categoryClothing,
id: 28,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductSurfAndPerfShirt,
price: 48,
),
Product(
category: categoryClothing,
id: 29,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductGingerScarf,
price: 98,
),
Product(
category: categoryClothing,
id: 30,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductRamonaCrossover,
price: 68,
),
Product(
category: categoryClothing,
id: 31,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductChambrayShirt,
price: 38,
),
Product(
category: categoryClothing,
id: 32,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductClassicWhiteCollar,
price: 58,
),
Product(
category: categoryClothing,
id: 33,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductCeriseScallopTee,
price: 42,
),
Product(
category: categoryClothing,
id: 34,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductShoulderRollsTee,
price: 27,
),
Product(
category: categoryClothing,
id: 35,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductGreySlouchTank,
price: 24,
),
Product(
category: categoryClothing,
id: 36,
isFeatured: false,
name: (context) =>
GalleryLocalizations.of(context).shrineProductSunshirtDress,
price: 58,
),
Product(
category: categoryClothing,
id: 37,
isFeatured: true,
name: (context) =>
GalleryLocalizations.of(context).shrineProductFineLinesTee,
price: 58,
),
];
if (category == categoryAll) {
return allProducts;
} else {
return allProducts.where((p) => p.category == category).toList();
}
}
}

View File

@@ -0,0 +1,52 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:gallery/layout/adaptive.dart';
class PageStatus extends InheritedWidget {
const PageStatus({
Key key,
@required this.cartController,
@required this.menuController,
@required Widget child,
}) : assert(cartController != null),
assert(menuController != null),
super(key: key, child: child);
final AnimationController cartController;
final AnimationController menuController;
static PageStatus of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<PageStatus>();
}
@override
bool updateShouldNotify(PageStatus old) =>
old.cartController != cartController ||
old.menuController != menuController;
}
bool productPageIsVisible(BuildContext context) {
return _cartControllerOf(context).isDismissed &&
(_menuControllerOf(context).isCompleted || isDisplayDesktop(context));
}
bool menuPageIsVisible(BuildContext context) {
return _cartControllerOf(context).isDismissed &&
(_menuControllerOf(context).isDismissed || isDisplayDesktop(context));
}
bool cartPageIsVisible(BuildContext context) {
return _cartControllerOf(context).isCompleted;
}
AnimationController _cartControllerOf(BuildContext context) {
return PageStatus.of(context).cartController;
}
AnimationController _menuControllerOf(BuildContext context) {
return PageStatus.of(context).menuController;
}

View File

@@ -0,0 +1,46 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class Scrim extends StatelessWidget {
const Scrim({this.controller});
final AnimationController controller;
@override
Widget build(BuildContext context) {
final Size deviceSize = MediaQuery.of(context).size;
return ExcludeSemantics(
child: AnimatedBuilder(
animation: controller,
builder: (context, child) {
final Color color =
Color(0xFFF0EA).withOpacity(controller.value * 0.87);
final Widget scrimRectangle = Container(
width: deviceSize.width, height: deviceSize.height, color: color);
final bool ignorePointer =
(controller.status == AnimationStatus.dismissed);
final bool tapToRevert =
(controller.status == AnimationStatus.completed);
if (tapToRevert) {
return GestureDetector(
onTap: () {
controller.reverse();
},
child: scrimRectangle,
);
} else if (ignorePointer) {
return IgnorePointer(child: scrimRectangle);
} else {
return scrimRectangle;
}
},
),
);
}
}

View File

@@ -0,0 +1,345 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:intl/intl.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:gallery/studies/shrine/colors.dart';
import 'package:gallery/studies/shrine/expanding_bottom_sheet.dart';
import 'package:gallery/studies/shrine/model/app_state_model.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/theme.dart';
import 'package:gallery/l10n/gallery_localizations.dart';
const _startColumnWidth = 60.0;
const _ordinalSortKeyName = 'shopping_cart';
class ShoppingCartPage extends StatefulWidget {
@override
_ShoppingCartPageState createState() => _ShoppingCartPageState();
}
class _ShoppingCartPageState extends State<ShoppingCartPage> {
List<Widget> _createShoppingCartRows(AppStateModel model) {
return model.productsInCart.keys
.map(
(id) => ShoppingCartRow(
product: model.getProductById(id),
quantity: model.productsInCart[id],
onPressed: () {
model.removeItemFromCart(id);
},
),
)
.toList();
}
@override
Widget build(BuildContext context) {
final ThemeData localTheme = Theme.of(context);
return Scaffold(
backgroundColor: shrinePink50,
body: SafeArea(
child: Container(
child: ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) {
return Stack(
children: [
ListView(
children: [
Semantics(
sortKey: OrdinalSortKey(0, name: _ordinalSortKeyName),
child: Row(
children: [
SizedBox(
width: _startColumnWidth,
child: IconButton(
icon: const Icon(Icons.keyboard_arrow_down),
onPressed: () =>
ExpandingBottomSheet.of(context).close(),
tooltip: GalleryLocalizations.of(context)
.shrineTooltipCloseCart,
),
),
Text(
GalleryLocalizations.of(context)
.shrineCartPageCaption,
style: localTheme.textTheme.subhead
.copyWith(fontWeight: FontWeight.w600),
),
const SizedBox(width: 16),
Text(
GalleryLocalizations.of(context)
.shrineCartItemCount(
model.totalCartQuantity,
),
),
],
),
),
const SizedBox(height: 16),
Semantics(
sortKey: OrdinalSortKey(1, name: _ordinalSortKeyName),
child: Column(
children: _createShoppingCartRows(model),
),
),
Semantics(
sortKey: OrdinalSortKey(2, name: _ordinalSortKeyName),
child: ShoppingCartSummary(model: model),
),
const SizedBox(height: 100),
],
),
PositionedDirectional(
bottom: 16,
start: 16,
end: 16,
child: Semantics(
sortKey: OrdinalSortKey(3, name: _ordinalSortKeyName),
child: RaisedButton(
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7)),
),
color: shrinePink100,
splashColor: shrineBrown600,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 12),
child: Text(
GalleryLocalizations.of(context)
.shrineCartClearButtonCaption,
style: TextStyle(letterSpacing: largeLetterSpacing),
),
),
onPressed: () {
model.clearCart();
ExpandingBottomSheet.of(context).close();
},
),
),
),
],
);
},
),
),
),
);
}
}
class ShoppingCartSummary extends StatelessWidget {
const ShoppingCartSummary({this.model});
final AppStateModel model;
@override
Widget build(BuildContext context) {
final TextStyle smallAmountStyle =
Theme.of(context).textTheme.body1.copyWith(color: shrineBrown600);
final TextStyle largeAmountStyle = Theme.of(context)
.textTheme
.display1
.copyWith(letterSpacing: mediumLetterSpacing);
final NumberFormat formatter = NumberFormat.simpleCurrency(
decimalDigits: 2,
locale: Localizations.localeOf(context).toString(),
);
return Row(
children: [
const SizedBox(width: _startColumnWidth),
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.only(end: 16),
child: Column(
children: [
MergeSemantics(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
GalleryLocalizations.of(context).shrineCartTotalCaption,
),
Expanded(
child: Text(
formatter.format(model.totalCost),
style: largeAmountStyle,
textAlign: TextAlign.end,
),
),
],
),
),
const SizedBox(height: 16),
MergeSemantics(
child: Row(
children: [
Text(
GalleryLocalizations.of(context)
.shrineCartSubtotalCaption,
),
Expanded(
child: Text(
formatter.format(model.subtotalCost),
style: smallAmountStyle,
textAlign: TextAlign.end,
),
),
],
),
),
const SizedBox(height: 4),
MergeSemantics(
child: Row(
children: [
Text(
GalleryLocalizations.of(context)
.shrineCartShippingCaption,
),
Expanded(
child: Text(
formatter.format(model.shippingCost),
style: smallAmountStyle,
textAlign: TextAlign.end,
),
),
],
),
),
const SizedBox(height: 4),
MergeSemantics(
child: Row(
children: [
Text(
GalleryLocalizations.of(context).shrineCartTaxCaption,
),
Expanded(
child: Text(
formatter.format(model.tax),
style: smallAmountStyle,
textAlign: TextAlign.end,
),
),
],
),
),
],
),
),
),
],
);
}
}
class ShoppingCartRow extends StatelessWidget {
const ShoppingCartRow({
@required this.product,
@required this.quantity,
this.onPressed,
});
final Product product;
final int quantity;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final NumberFormat formatter = NumberFormat.simpleCurrency(
decimalDigits: 0,
locale: Localizations.localeOf(context).toString(),
);
final ThemeData localTheme = Theme.of(context);
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Row(
key: ValueKey<int>(product.id),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Semantics(
container: true,
label: GalleryLocalizations.of(context)
.shrineScreenReaderRemoveProductButton(product.name(context)),
button: true,
child: ExcludeSemantics(
child: SizedBox(
width: _startColumnWidth,
child: IconButton(
icon: const Icon(Icons.remove_circle_outline),
onPressed: onPressed,
tooltip:
GalleryLocalizations.of(context).shrineTooltipRemoveItem,
),
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.only(end: 16),
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.asset(
product.assetName,
package: product.assetPackage,
fit: BoxFit.cover,
width: 75,
height: 75,
excludeFromSemantics: true,
),
const SizedBox(width: 16),
Expanded(
child: MergeSemantics(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
MergeSemantics(
child: Row(
children: [
Expanded(
child: Text(
GalleryLocalizations.of(context)
.shrineProductQuantity(quantity),
),
),
Text(
GalleryLocalizations.of(context)
.shrineProductPrice(
formatter.format(product.price),
),
),
],
),
),
Text(
product.name(context),
style: localTheme.textTheme.subhead
.copyWith(fontWeight: FontWeight.w600),
),
],
),
),
),
],
),
const SizedBox(height: 16),
const Divider(
color: shrineBrown900,
height: 10,
),
],
),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,295 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:gallery/data/gallery_options.dart';
import 'package:gallery/layout/text_scale.dart';
import 'package:gallery/studies/shrine/category_menu_page.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/supplemental/balanced_layout.dart';
import 'package:gallery/studies/shrine/page_status.dart';
import 'package:gallery/studies/shrine/supplemental/desktop_product_columns.dart';
import 'package:gallery/studies/shrine/supplemental/product_columns.dart';
import 'package:gallery/studies/shrine/supplemental/product_card.dart';
const _topPadding = 34.0;
const _bottomPadding = 44.0;
const _cardToScreenWidthRatio = 0.59;
class MobileAsymmetricView extends StatelessWidget {
const MobileAsymmetricView({Key key, this.products}) : super(key: key);
final List<Product> products;
List<Container> _buildColumns(
BuildContext context,
BoxConstraints constraints,
) {
if (products == null || products.isEmpty) {
return const [];
}
// Decide whether the page size and text size allow 2-column products.
final double cardHeight = (constraints.biggest.height -
_topPadding -
_bottomPadding -
TwoProductCardColumn.spacerHeight) /
2;
final double imageWidth =
_cardToScreenWidthRatio * constraints.biggest.width -
TwoProductCardColumn.horizontalPadding;
final double imageHeight = cardHeight -
MobileProductCard.defaultTextBoxHeight *
GalleryOptions.of(context).textScaleFactor(context);
final bool shouldUseAlternatingLayout =
imageHeight > 0 && imageWidth / imageHeight < 49 / 33;
if (shouldUseAlternatingLayout) {
// Alternating layout: a layout of alternating 2-product
// and 1-product columns.
//
// This will return a list of columns. It will oscillate between the two
// kinds of columns. Even cases of the index (0, 2, 4, etc) will be
// TwoProductCardColumn and the odd cases will be OneProductCardColumn.
//
// Each pair of columns will advance us 3 products forward (2 + 1). That's
// some kinda awkward math so we use _evenCasesIndex and _oddCasesIndex as
// helpers for creating the index of the product list that will correspond
// to the index of the list of columns.
return List<Container>.generate(_listItemCount(products.length), (index) {
double width =
_cardToScreenWidthRatio * MediaQuery.of(context).size.width;
Widget column;
if (index % 2 == 0) {
/// Even cases
final int bottom = _evenCasesIndex(index);
column = TwoProductCardColumn(
bottom: products[bottom],
top:
products.length - 1 >= bottom + 1 ? products[bottom + 1] : null,
imageAspectRatio: imageWidth / imageHeight,
);
width += 32;
} else {
/// Odd cases
column = OneProductCardColumn(
product: products[_oddCasesIndex(index)],
reverse: true,
);
}
return Container(
width: width,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: column,
),
);
}).toList();
} else {
// Alternating layout: a layout of 1-product columns.
return [
for (final product in products)
Container(
width: _cardToScreenWidthRatio * MediaQuery.of(context).size.width,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: OneProductCardColumn(
product: product,
reverse: false,
),
),
)
];
}
}
int _evenCasesIndex(int input) {
// The operator ~/ is a cool one. It's the truncating division operator. It
// divides the number and if there's a remainder / decimal, it cuts it off.
// This is like dividing and then casting the result to int. Also, it's
// functionally equivalent to floor() in this case.
return input ~/ 2 * 3;
}
int _oddCasesIndex(int input) {
assert(input > 0);
return (input / 2).ceil() * 3 - 1;
}
int _listItemCount(int totalItems) {
return (totalItems % 3 == 0)
? totalItems ~/ 3 * 2
: (totalItems / 3).ceil() * 2 - 1;
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: PageStatus.of(context).cartController,
builder: (context, child) => AnimatedBuilder(
animation: PageStatus.of(context).menuController,
builder: (context, child) => ExcludeSemantics(
excluding: !productPageIsVisible(context),
child: LayoutBuilder(
builder: (context, constraints) {
return ListView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsetsDirectional.fromSTEB(
0,
_topPadding,
16,
_bottomPadding,
),
children: _buildColumns(context, constraints),
physics: const AlwaysScrollableScrollPhysics(),
);
},
),
),
),
);
}
}
class DesktopAsymmetricView extends StatelessWidget {
const DesktopAsymmetricView({Key key, this.products}) : super(key: key);
final List<Product> products;
@override
Widget build(BuildContext context) {
// Determine the scale factor for the desktop asymmetric view.
final double textScaleFactor =
GalleryOptions.of(context).textScaleFactor(context);
// When text is larger, the images becomes wider, but at half the rate.
final double imageScaleFactor = reducedTextScale(context);
// When text is larger, horizontal padding becomes smaller.
final double paddingScaleFactor = textScaleFactor >= 1.5 ? 0.25 : 1;
// Calculate number of columns
final double sidebar = desktopCategoryMenuPageWidth(context: context);
final double minimumBoundaryWidth = 84 * paddingScaleFactor;
final double columnWidth = 186 * imageScaleFactor;
final double columnGapWidth = 24 * imageScaleFactor;
final double windowWidth = MediaQuery.of(context).size.width;
final int idealColumnCount = max(
1,
((windowWidth + columnGapWidth - 2 * minimumBoundaryWidth - sidebar) /
(columnWidth + columnGapWidth))
.floor(),
);
// Limit column width to fit within window when there is only one column.
final double actualColumnWidth = idealColumnCount == 1
? min(
columnWidth,
windowWidth - sidebar - 2 * minimumBoundaryWidth,
)
: columnWidth;
final int columnCount = min(idealColumnCount, max(products.length, 1));
return AnimatedBuilder(
animation: PageStatus.of(context).cartController,
builder: (context, child) => ExcludeSemantics(
excluding: !productPageIsVisible(context),
child: DesktopColumns(
columnCount: columnCount,
products: products,
largeImageWidth: actualColumnWidth,
smallImageWidth: columnCount > 1
? columnWidth - columnGapWidth
: actualColumnWidth,
),
),
);
}
}
class DesktopColumns extends StatelessWidget {
DesktopColumns({
@required this.columnCount,
@required this.products,
@required this.largeImageWidth,
@required this.smallImageWidth,
});
final int columnCount;
final List<Product> products;
final double largeImageWidth;
final double smallImageWidth;
@override
Widget build(BuildContext context) {
final Widget _gap = Container(width: 24);
final List<List<Product>> productCardLists = balancedLayout(
context: context,
columnCount: columnCount,
products: products,
largeImageWidth: largeImageWidth,
smallImageWidth: smallImageWidth,
);
final List<DesktopProductCardColumn> productCardColumns =
List<DesktopProductCardColumn>.generate(
columnCount,
(column) {
final bool alignToEnd =
(column % 2 == 1) || (column == columnCount - 1);
final bool startLarge = (column % 2 == 1);
final bool lowerStart = (column % 2 == 1);
return DesktopProductCardColumn(
alignToEnd: alignToEnd,
startLarge: startLarge,
lowerStart: lowerStart,
products: productCardLists[column],
largeImageWidth: largeImageWidth,
smallImageWidth: smallImageWidth,
);
},
);
return ListView(
scrollDirection: Axis.vertical,
children: [
Container(height: 60),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Spacer(),
...List<Widget>.generate(
2 * columnCount - 1,
(generalizedColumnIndex) {
if (generalizedColumnIndex % 2 == 0) {
return productCardColumns[generalizedColumnIndex ~/ 2];
} else {
return _gap;
}
},
),
Spacer(),
],
),
Container(height: 60),
],
physics: const AlwaysScrollableScrollPhysics(),
);
}
}

View File

@@ -0,0 +1,298 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/supplemental/desktop_product_columns.dart';
import 'package:gallery/studies/shrine/supplemental/layout_cache.dart';
/// A placeholder id for an empty element. See [_iterateUntilBalanced]
/// for more information.
const _emptyElement = -1;
/// To avoid infinite loops, improvements to the layout are only performed
/// when a column's height changes by more than
/// [_deviationImprovementThreshold] pixels.
const _deviationImprovementThreshold = 10;
/// Height of a product image, paired with the product's id.
class _TaggedHeightData {
const _TaggedHeightData({
@required this.index,
@required this.height,
});
/// The id of the corresponding product.
final int index;
/// The height of the product image.
final double height;
}
/// Converts a set of [_TaggedHeightData] elements to a list,
/// and add an empty element.
/// Used for iteration.
List<_TaggedHeightData> toListAndAddEmpty(Set<_TaggedHeightData> set) {
List<_TaggedHeightData> result = List<_TaggedHeightData>.from(set);
result.add(_TaggedHeightData(index: _emptyElement, height: 0));
return result;
}
/// Encode parameters for caching.
String _encodeParameters({
@required int columnCount,
@required List<Product> products,
@required double largeImageWidth,
@required double smallImageWidth,
}) {
final String productString =
[for (final product in products) product.id.toString()].join(',');
return '$columnCount;$productString,$largeImageWidth,$smallImageWidth';
}
/// Given a layout, replace integers by their corresponding products.
List<List<Product>> _generateLayout({
@required List<Product> products,
@required List<List<int>> layout,
}) {
return [
for (final column in layout)
[
for (final index in column) products[index],
]
];
}
/// Returns the size of an [Image] widget.
Size _imageSize(Image imageWidget) {
Size result;
imageWidget.image.resolve(ImageConfiguration()).addListener(
ImageStreamListener(
(info, synchronousCall) {
final finalImage = info.image;
result = Size(
finalImage.width.toDouble(),
finalImage.height.toDouble(),
);
},
),
);
return result;
}
/// Given [columnObjects], list of the set of objects in each column,
/// and [columnHeights], list of heights of each column,
/// [_iterateUntilBalanced] moves and swaps objects between columns
/// until their heights are sufficiently close to each other.
/// This prevents the layout having significant, avoidable gaps at the bottom.
void _iterateUntilBalanced(
List<Set<_TaggedHeightData>> columnObjects,
List<double> columnHeights,
) {
int failedMoves = 0;
final int columnCount = columnObjects.length;
// No need to rearrange a 1-column layout.
if (columnCount == 1) {
return;
}
while (true) {
// Loop through all possible 2-combinations of columns.
for (int source = 0; source < columnCount; ++source) {
for (int target = source + 1; target < columnCount; ++target) {
// Tries to find an object A from source column
// and an object B from target column, such that switching them
// causes the height of the two columns to be closer.
// A or B can be empty; in this case, moving an object from one
// column to the other is the best choice.
bool success = false;
final double bestHeight =
(columnHeights[source] + columnHeights[target]) / 2;
final double scoreLimit = (columnHeights[source] - bestHeight).abs();
final List<_TaggedHeightData> sourceObjects =
toListAndAddEmpty(columnObjects[source]);
final List<_TaggedHeightData> targetObjects =
toListAndAddEmpty(columnObjects[target]);
_TaggedHeightData bestA, bestB;
double bestScore;
for (final a in sourceObjects) {
for (final b in targetObjects) {
if (a.index == _emptyElement && b.index == _emptyElement) {
continue;
} else {
final double score =
(columnHeights[source] - a.height + b.height - bestHeight)
.abs();
if (score < scoreLimit - _deviationImprovementThreshold) {
success = true;
if (bestScore == null || score < bestScore) {
bestScore = score;
bestA = a;
bestB = b;
}
}
}
}
}
if (!success) {
++failedMoves;
} else {
failedMoves = 0;
// Switch A and B.
if (bestA.index != _emptyElement) {
columnObjects[source].remove(bestA);
columnObjects[target].add(bestA);
}
if (bestB.index != _emptyElement) {
columnObjects[target].remove(bestB);
columnObjects[source].add(bestB);
}
columnHeights[source] += bestB.height - bestA.height;
columnHeights[target] += bestA.height - bestB.height;
}
// If no two columns' heights can be made closer by switching
// elements, the layout is sufficiently balanced.
if (failedMoves >= columnCount * (columnCount - 1) ~/ 2) {
return;
}
}
}
}
}
/// Given a list of numbers [data], representing the heights of each image,
/// and a list of numbers [biases], representing the heights of the space
/// above each column, [_balancedDistribution] returns a layout of [data]
/// so that the height of each column is sufficiently close to each other,
/// represented as a list of lists of integers, each integer being an ID
/// for a product.
List<List<int>> _balancedDistribution({
int columnCount,
List<double> data,
List<double> biases,
}) {
assert(biases.length == columnCount);
List<Set<_TaggedHeightData>> columnObjects =
List<Set<_TaggedHeightData>>.generate(columnCount, (column) => Set());
List<double> columnHeights = List<double>.from(biases);
for (var i = 0; i < data.length; ++i) {
final int column = i % columnCount;
columnHeights[column] += data[i];
columnObjects[column].add(_TaggedHeightData(index: i, height: data[i]));
}
_iterateUntilBalanced(columnObjects, columnHeights);
return [
for (final column in columnObjects)
[for (final object in column) object.index]..sort(),
];
}
/// Generates a balanced layout for [columnCount] columns,
/// with products specified by the list [products],
/// where the larger images have width [largeImageWidth]
/// and the smaller images have width [smallImageWidth].
/// The current [context] is also given to allow caching.
List<List<Product>> balancedLayout({
BuildContext context,
int columnCount,
List<Product> products,
double largeImageWidth,
double smallImageWidth,
}) {
final String encodedParameters = _encodeParameters(
columnCount: columnCount,
products: products,
largeImageWidth: largeImageWidth,
smallImageWidth: smallImageWidth,
);
// Check if this layout is cached.
if (LayoutCache.of(context).containsKey(encodedParameters)) {
return _generateLayout(
products: products,
layout: LayoutCache.of(context)[encodedParameters],
);
}
final List<Size> productSizes = [
for (var product in products)
_imageSize(
Image.asset(
product.assetName,
package: product.assetPackage,
),
),
];
bool hasNullSize = false;
for (final productSize in productSizes) {
if (productSize == null) {
hasNullSize = true;
break;
}
}
if (hasNullSize) {
// If some image sizes are not read, return default layout.
// Default layout is not cached.
List<List<Product>> result =
List<List<Product>>.generate(columnCount, (columnIndex) => []);
for (var index = 0; index < products.length; ++index) {
result[index % columnCount].add(products[index]);
}
return result;
}
// All images have sizes. Use tailored layout.
final List<double> productHeights = [
for (final productSize in productSizes)
productSize.height /
productSize.width *
(largeImageWidth + smallImageWidth) /
2 +
productCardAdditionalHeight,
];
final List<List<int>> layout = _balancedDistribution(
columnCount: columnCount,
data: productHeights,
biases: List<double>.generate(
columnCount,
(column) => (column % 2 == 0 ? 0 : columnTopSpace),
),
);
// Add tailored layout to cache.
LayoutCache.of(context)[encodedParameters] = layout;
final List<List<Product>> result = _generateLayout(
products: products,
layout: layout,
);
return result;
}

View File

@@ -0,0 +1,129 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' show lerpDouble;
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
class CutCornersBorder extends OutlineInputBorder {
const CutCornersBorder({
BorderSide borderSide = const BorderSide(),
BorderRadius borderRadius = const BorderRadius.all(Radius.circular(2)),
this.cut = 7,
double gapPadding = 2,
}) : super(
borderSide: borderSide,
borderRadius: borderRadius,
gapPadding: gapPadding,
);
@override
CutCornersBorder copyWith({
BorderSide borderSide,
BorderRadius borderRadius,
double gapPadding,
double cut,
}) {
return CutCornersBorder(
borderSide: borderSide ?? this.borderSide,
borderRadius: borderRadius ?? this.borderRadius,
gapPadding: gapPadding ?? this.gapPadding,
cut: cut ?? this.cut,
);
}
final double cut;
@override
ShapeBorder lerpFrom(ShapeBorder a, double t) {
if (a is CutCornersBorder) {
final CutCornersBorder outline = a;
return CutCornersBorder(
borderRadius: BorderRadius.lerp(outline.borderRadius, borderRadius, t),
borderSide: BorderSide.lerp(outline.borderSide, borderSide, t),
cut: cut,
gapPadding: outline.gapPadding,
);
}
return super.lerpFrom(a, t);
}
@override
ShapeBorder lerpTo(ShapeBorder b, double t) {
if (b is CutCornersBorder) {
final CutCornersBorder outline = b;
return CutCornersBorder(
borderRadius: BorderRadius.lerp(borderRadius, outline.borderRadius, t),
borderSide: BorderSide.lerp(borderSide, outline.borderSide, t),
cut: cut,
gapPadding: outline.gapPadding,
);
}
return super.lerpTo(b, t);
}
Path _notchedCornerPath(Rect center, [double start = 0, double extent = 0]) {
final Path path = Path();
if (start > 0 || extent > 0) {
path.relativeMoveTo(extent + start, center.top);
_notchedSidesAndBottom(center, path);
path..lineTo(center.left + cut, center.top)..lineTo(start, center.top);
} else {
path.moveTo(center.left + cut, center.top);
_notchedSidesAndBottom(center, path);
path.lineTo(center.left + cut, center.top);
}
return path;
}
Path _notchedSidesAndBottom(Rect center, Path path) {
return path
..lineTo(center.right - cut, center.top)
..lineTo(center.right, center.top + cut)
..lineTo(center.right, center.top + center.height - cut)
..lineTo(center.right - cut, center.top + center.height)
..lineTo(center.left + cut, center.top + center.height)
..lineTo(center.left, center.top + center.height - cut)
..lineTo(center.left, center.top + cut);
}
@override
void paint(
Canvas canvas,
Rect rect, {
double gapStart,
double gapExtent = 0,
double gapPercentage = 0,
TextDirection textDirection,
}) {
assert(gapExtent != null);
assert(gapPercentage >= 0 && gapPercentage <= 1);
final Paint paint = borderSide.toPaint();
final RRect outer = borderRadius.toRRect(rect);
if (gapStart == null || gapExtent <= 0 || gapPercentage == 0) {
canvas.drawPath(_notchedCornerPath(outer.middleRect), paint);
} else {
final double extent =
lerpDouble(0.0, gapExtent + gapPadding * 2, gapPercentage);
switch (textDirection) {
case TextDirection.rtl:
{
final Path path = _notchedCornerPath(
outer.middleRect, gapStart + gapPadding - extent, extent);
canvas.drawPath(path, paint);
break;
}
case TextDirection.ltr:
{
final Path path = _notchedCornerPath(
outer.middleRect, gapStart - gapPadding, extent);
canvas.drawPath(path, paint);
break;
}
}
}
}
}

View File

@@ -0,0 +1,82 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/supplemental/product_card.dart';
/// Height of the text below each product card.
const productCardAdditionalHeight = 84.0 * 2;
/// Height of the divider between product cards.
const productCardDividerHeight = 84.0;
/// Height of the space at the top of every other column.
const columnTopSpace = 84.0;
class DesktopProductCardColumn extends StatelessWidget {
const DesktopProductCardColumn({
@required this.alignToEnd,
@required this.startLarge,
@required this.lowerStart,
@required this.products,
@required this.largeImageWidth,
@required this.smallImageWidth,
});
final List<Product> products;
final bool alignToEnd;
final bool startLarge;
final bool lowerStart;
final double largeImageWidth;
final double smallImageWidth;
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
final int currentColumnProductCount = products.length;
final int currentColumnWidgetCount =
max(2 * currentColumnProductCount - 1, 0);
return Container(
width: largeImageWidth,
child: Column(
crossAxisAlignment:
alignToEnd ? CrossAxisAlignment.end : CrossAxisAlignment.start,
children: [
if (lowerStart) Container(height: columnTopSpace),
...List<Widget>.generate(currentColumnWidgetCount, (index) {
Widget card;
if (index % 2 == 0) {
// This is a product.
final int productCardIndex = index ~/ 2;
card = DesktopProductCard(
product: products[productCardIndex],
imageWidth: startLarge
? ((productCardIndex % 2 == 0)
? largeImageWidth
: smallImageWidth)
: ((productCardIndex % 2 == 0)
? smallImageWidth
: largeImageWidth),
);
} else {
// This is just a divider.
card = Container(
height: productCardDividerHeight,
);
}
return RepaintBoundary(child: card);
}),
],
),
);
});
}
}

View File

@@ -0,0 +1,22 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class LayoutCache extends InheritedWidget {
const LayoutCache({
Key key,
@required this.layouts,
@required Widget child,
}) : super(key: key, child: child);
static Map<String, List<List<int>>> of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<LayoutCache>().layouts;
}
final Map<String, List<List<int>>> layouts;
@override
bool updateShouldNotify(LayoutCache old) => true;
}

View File

@@ -0,0 +1,134 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:gallery/l10n/gallery_localizations.dart';
import 'package:intl/intl.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:gallery/studies/shrine/model/app_state_model.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/layout/adaptive.dart';
class MobileProductCard extends StatelessWidget {
const MobileProductCard({this.imageAspectRatio = 33 / 49, this.product})
: assert(imageAspectRatio == null || imageAspectRatio > 0);
final double imageAspectRatio;
final Product product;
static const double defaultTextBoxHeight = 65;
@override
Widget build(BuildContext context) {
return Semantics(
container: true,
button: true,
child: _buildProductCard(
context: context,
product: product,
imageAspectRatio: imageAspectRatio,
),
);
}
}
class DesktopProductCard extends StatelessWidget {
const DesktopProductCard({@required this.product, @required this.imageWidth});
final Product product;
final double imageWidth;
@override
Widget build(BuildContext context) {
return _buildProductCard(
context: context,
product: product,
imageWidth: imageWidth,
);
}
}
Widget _buildProductCard({
BuildContext context,
Product product,
double imageWidth,
double imageAspectRatio,
}) {
final bool isDesktop = isDisplayDesktop(context);
final NumberFormat formatter = NumberFormat.simpleCurrency(
decimalDigits: 0,
locale: Localizations.localeOf(context).toString(),
);
final ThemeData theme = Theme.of(context);
final Image imageWidget = Image.asset(
product.assetName,
package: product.assetPackage,
fit: BoxFit.cover,
width: isDesktop ? imageWidth : null,
excludeFromSemantics: true,
);
return ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) {
return Semantics(
hint:
GalleryLocalizations.of(context).shrineScreenReaderProductAddToCart,
child: GestureDetector(
onTap: () {
model.addProductToCart(product.id);
},
child: child,
),
);
},
child: Stack(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
isDesktop
? imageWidget
: AspectRatio(
aspectRatio: imageAspectRatio,
child: imageWidget,
),
SizedBox(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 23),
Container(
width: imageWidth,
child: Text(
product == null ? '' : product.name(context),
style: theme.textTheme.button,
softWrap: true,
textAlign: TextAlign.center,
),
),
const SizedBox(height: 4),
Text(
product == null ? '' : formatter.format(product.price),
style: theme.textTheme.caption,
),
],
),
),
],
),
const Padding(
padding: EdgeInsets.all(16),
child: Icon(Icons.add_shopping_cart),
),
],
),
);
}

View File

@@ -0,0 +1,80 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:gallery/studies/shrine/model/product.dart';
import 'package:gallery/studies/shrine/supplemental/product_card.dart';
class TwoProductCardColumn extends StatelessWidget {
const TwoProductCardColumn({
@required this.bottom,
this.top,
@required this.imageAspectRatio,
}) : assert(bottom != null);
static const double spacerHeight = 44;
static const double horizontalPadding = 28;
final Product bottom, top;
final double imageAspectRatio;
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
return ListView(
physics: const ClampingScrollPhysics(),
children: [
Padding(
padding: const EdgeInsetsDirectional.only(start: horizontalPadding),
child: top != null
? MobileProductCard(
imageAspectRatio: imageAspectRatio,
product: top,
)
: SizedBox(
height: spacerHeight,
),
),
const SizedBox(height: spacerHeight),
Padding(
padding: const EdgeInsetsDirectional.only(end: horizontalPadding),
child: MobileProductCard(
imageAspectRatio: imageAspectRatio,
product: bottom,
),
),
],
);
});
}
}
class OneProductCardColumn extends StatelessWidget {
const OneProductCardColumn({
this.product,
@required this.reverse,
});
final Product product;
// Whether the product column should align to the bottom.
final bool reverse;
@override
Widget build(BuildContext context) {
return ListView(
physics: const ClampingScrollPhysics(),
reverse: reverse,
children: [
const SizedBox(
height: 40,
),
MobileProductCard(
product: product,
),
],
);
}
}

View File

@@ -0,0 +1,105 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:gallery/studies/shrine/colors.dart';
import 'package:gallery/studies/shrine/supplemental/cut_corners_border.dart';
const defaultLetterSpacing = 0.03;
const mediumLetterSpacing = 0.04;
const largeLetterSpacing = 1.0;
final ThemeData shrineTheme = _buildShrineTheme();
IconThemeData _customIconTheme(IconThemeData original) {
return original.copyWith(color: shrineBrown900);
}
ThemeData _buildShrineTheme() {
final ThemeData base = ThemeData.light();
return base.copyWith(
colorScheme: _shrineColorScheme,
accentColor: shrineBrown900,
primaryColor: shrinePink100,
buttonColor: shrinePink100,
scaffoldBackgroundColor: shrineBackgroundWhite,
cardColor: shrineBackgroundWhite,
textSelectionColor: shrinePink100,
errorColor: shrineErrorRed,
buttonTheme: const ButtonThemeData(
colorScheme: _shrineColorScheme,
textTheme: ButtonTextTheme.normal,
),
primaryIconTheme: _customIconTheme(base.iconTheme),
inputDecorationTheme: const InputDecorationTheme(
border: CutCornersBorder(
borderSide: BorderSide(color: shrineBrown900, width: 0.5),
),
contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 16),
),
textTheme: _buildShrineTextTheme(base.textTheme),
primaryTextTheme: _buildShrineTextTheme(base.primaryTextTheme),
accentTextTheme: _buildShrineTextTheme(base.accentTextTheme),
iconTheme: _customIconTheme(base.iconTheme),
);
}
TextTheme _buildShrineTextTheme(TextTheme base) {
return GoogleFonts.rubikTextTheme(base
.copyWith(
headline: base.headline.copyWith(
fontWeight: FontWeight.w500,
letterSpacing: defaultLetterSpacing,
),
title: base.title.copyWith(
fontSize: 18,
letterSpacing: defaultLetterSpacing,
),
caption: base.caption.copyWith(
fontWeight: FontWeight.w400,
fontSize: 14,
letterSpacing: defaultLetterSpacing,
),
body2: base.body2.copyWith(
fontWeight: FontWeight.w500,
fontSize: 16,
letterSpacing: defaultLetterSpacing,
),
body1: base.body1.copyWith(
letterSpacing: defaultLetterSpacing,
),
subhead: base.subhead.copyWith(
letterSpacing: defaultLetterSpacing,
),
display1: base.display1.copyWith(
letterSpacing: defaultLetterSpacing,
),
button: base.button.copyWith(
fontWeight: FontWeight.w500,
fontSize: 14,
letterSpacing: defaultLetterSpacing,
),
)
.apply(
displayColor: shrineBrown900,
bodyColor: shrineBrown900,
));
}
const ColorScheme _shrineColorScheme = ColorScheme(
primary: shrinePink100,
primaryVariant: shrineBrown900,
secondary: shrinePink50,
secondaryVariant: shrineBrown900,
surface: shrineSurfaceWhite,
background: shrineBackgroundWhite,
error: shrineErrorRed,
onPrimary: shrineBrown900,
onSecondary: shrineBrown900,
onSurface: shrineBrown900,
onBackground: shrineBrown900,
onError: shrineSurfaceWhite,
brightness: Brightness.light,
);

View File

@@ -0,0 +1,50 @@
// Copyright 2019 The Flutter team. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:gallery/studies/shrine/colors.dart';
const List<Offset> _vertices = [
Offset(0, -14),
Offset(-17, 14),
Offset(17, 14),
Offset(0, -14),
Offset(0, -7.37),
Offset(10.855, 10.48),
Offset(-10.855, 10.48),
Offset(0, -7.37),
];
class TriangleCategoryIndicator extends CustomPainter {
const TriangleCategoryIndicator(
this.triangleWidth,
this.triangleHeight,
) : assert(triangleWidth != null),
assert(triangleHeight != null);
final double triangleWidth;
final double triangleHeight;
@override
void paint(Canvas canvas, Size size) {
Path myPath = Path()
..addPolygon(
List.from(_vertices.map<Offset>((vertex) {
return Offset(size.width, size.height) / 2 +
Offset(vertex.dx * triangleWidth / 34,
vertex.dy * triangleHeight / 28);
})),
true,
);
Paint myPaint = Paint()..color = shrinePink400;
canvas.drawPath(myPath, myPaint);
}
@override
bool shouldRepaint(TriangleCategoryIndicator oldDelegate) => false;
@override
bool shouldRebuildSemantics(TriangleCategoryIndicator oldDelegate) => false;
}