1
0
mirror of https://github.com/flutter/samples.git synced 2026-05-06 06:56:34 +00:00

Moving Shrine into a material_studies subdirectory (#128)

This commit is contained in:
Andrew Brogdon
2019-08-14 16:27:59 -07:00
committed by GitHub
parent c68165e8a5
commit cf270c32f3
84 changed files with 25 additions and 5 deletions

View File

@@ -0,0 +1,150 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'backdrop.dart';
import 'category_menu_page.dart';
import 'colors.dart';
import 'home.dart';
import 'login.dart';
import 'expanding_bottom_sheet.dart';
import 'supplemental/cut_corners_border.dart';
class ShrineApp extends StatefulWidget {
@override
_ShrineAppState createState() => _ShrineAppState();
}
class _ShrineAppState extends State<ShrineApp>
with SingleTickerProviderStateMixin {
// Controller to coordinate both the opening/closing of backdrop and sliding
// of expanding bottom sheet.
AnimationController _controller;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: Duration(milliseconds: 450),
value: 1.0,
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Shrine',
home: HomePage(
backdrop: Backdrop(
frontLayer: ProductPage(),
backLayer:
CategoryMenuPage(onCategoryTap: () => _controller.forward()),
frontTitle: Text('SHRINE'),
backTitle: Text('MENU'),
controller: _controller,
),
expandingBottomSheet: ExpandingBottomSheet(hideController: _controller),
),
initialRoute: '/login',
onGenerateRoute: _getRoute,
theme: _kShrineTheme,
);
}
}
Route<dynamic> _getRoute(RouteSettings settings) {
if (settings.name != '/login') {
return null;
}
return MaterialPageRoute<void>(
settings: settings,
builder: (context) => LoginPage(),
fullscreenDialog: true,
);
}
final ThemeData _kShrineTheme = _buildShrineTheme();
IconThemeData _customIconTheme(IconThemeData original) {
return original.copyWith(color: kShrineBrown900);
}
ThemeData _buildShrineTheme() {
final ThemeData base = ThemeData.light();
return base.copyWith(
colorScheme: kShrineColorScheme,
accentColor: kShrineBrown900,
primaryColor: kShrinePink100,
buttonColor: kShrinePink100,
scaffoldBackgroundColor: kShrineBackgroundWhite,
cardColor: kShrineBackgroundWhite,
textSelectionColor: kShrinePink100,
errorColor: kShrineErrorRed,
buttonTheme: const ButtonThemeData(
colorScheme: kShrineColorScheme,
textTheme: ButtonTextTheme.normal,
),
primaryIconTheme: _customIconTheme(base.iconTheme),
inputDecorationTheme:
const InputDecorationTheme(border: CutCornersBorder()),
textTheme: _buildShrineTextTheme(base.textTheme),
primaryTextTheme: _buildShrineTextTheme(base.primaryTextTheme),
accentTextTheme: _buildShrineTextTheme(base.accentTextTheme),
iconTheme: _customIconTheme(base.iconTheme),
);
}
TextTheme _buildShrineTextTheme(TextTheme base) {
return base
.copyWith(
headline: base.headline.copyWith(fontWeight: FontWeight.w500),
title: base.title.copyWith(fontSize: 18.0),
caption: base.caption.copyWith(
fontWeight: FontWeight.w400,
fontSize: 14.0,
),
body2: base.body2.copyWith(
fontWeight: FontWeight.w500,
fontSize: 16.0,
),
button: base.button.copyWith(
fontWeight: FontWeight.w500,
fontSize: 14.0,
),
)
.apply(
fontFamily: 'Rubik',
displayColor: kShrineBrown900,
bodyColor: kShrineBrown900,
);
}
const ColorScheme kShrineColorScheme = ColorScheme(
primary: kShrinePink100,
primaryVariant: kShrineBrown900,
secondary: kShrinePink50,
secondaryVariant: kShrineBrown900,
surface: kShrineSurfaceWhite,
background: kShrineBackgroundWhite,
error: kShrineErrorRed,
onPrimary: kShrineBrown900,
onSecondary: kShrineBrown900,
onSurface: kShrineBrown900,
onBackground: kShrineBrown900,
onError: kShrineSurfaceWhite,
brightness: Brightness.light,
);

View File

@@ -0,0 +1,332 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'package:meta/meta.dart';
import 'login.dart';
const Cubic _kAccelerateCurve = Cubic(0.548, 0.0, 0.757, 0.464);
const Cubic _kDecelerateCurve = Cubic(0.23, 0.94, 0.41, 1.0);
const double _kPeakVelocityTime = 0.248210;
const double _kPeakVelocityProgress = 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) {
return Material(
elevation: 16.0,
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.only(topLeft: Radius.circular(46.0)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Container(
height: 40.0,
alignment: AlignmentDirectional.centerStart,
),
),
Expanded(
child: child,
),
],
),
);
}
}
class _BackdropTitle extends AnimatedWidget {
final VoidCallback onPress;
final Widget frontTitle;
final Widget backTitle;
const _BackdropTitle({
Key key,
Listenable listenable,
this.onPress,
@required this.frontTitle,
@required this.backTitle,
}) : assert(frontTitle != null),
assert(backTitle != null),
super(key: key, listenable: listenable);
@override
Widget build(BuildContext context) {
final Animation<double> animation = CurvedAnimation(
parent: this.listenable as Animation<double>,
curve: Interval(0.0, 0.78),
);
return DefaultTextStyle(
style: Theme.of(context).primaryTextTheme.title,
softWrap: false,
overflow: TextOverflow.ellipsis,
child: Row(children: <Widget>[
// branded icon
SizedBox(
width: 72.0,
child: IconButton(
padding: EdgeInsets.only(right: 8.0),
onPressed: this.onPress,
icon: Stack(children: <Widget>[
Opacity(
opacity: animation.value,
child: ImageIcon(AssetImage('assets/slanted_menu.png')),
),
FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: Offset(1.0, 0.0),
).evaluate(animation),
child: ImageIcon(AssetImage('assets/diamond.png')),
)
]),
),
),
// Here, we do a custom cross fade between backTitle and frontTitle.
// This makes a smooth animation between the two texts.
Stack(
children: <Widget>[
Opacity(
opacity: CurvedAnimation(
parent: ReverseAnimation(animation),
curve: Interval(0.5, 1.0),
).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: Offset.zero,
end: Offset(0.5, 0.0),
).evaluate(animation),
child: backTitle,
),
),
Opacity(
opacity: CurvedAnimation(
parent: animation,
curve: Interval(0.5, 1.0),
).value,
child: FractionalTranslation(
translation: Tween<Offset>(
begin: Offset(-0.25, 0.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 {
final Widget frontLayer;
final Widget backLayer;
final Widget frontTitle;
final Widget backTitle;
final AnimationController controller;
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);
@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;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
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 = _kAccelerateCurve;
secondCurve = _kDecelerateCurve;
firstWeight = _kPeakVelocityTime;
secondWeight = 1.0 - _kPeakVelocityTime;
animation = CurvedAnimation(
parent: _controller.view,
curve: Interval(0.0, 0.78),
);
} else {
// These values are only used when the controller runs from t=1.0 to t=0.0
firstCurve = _kDecelerateCurve.flipped;
secondCurve = _kAccelerateCurve.flipped;
firstWeight = 1.0 - _kPeakVelocityTime;
secondWeight = _kPeakVelocityTime;
animation = _controller.view;
}
return TweenSequence(
<TweenSequenceItem<RelativeRect>>[
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(
0.0,
layerTop,
0.0,
layerTop - layerSize.height,
),
end: RelativeRect.fromLTRB(
0.0,
layerTop * _kPeakVelocityProgress,
0.0,
(layerTop - layerSize.height) * _kPeakVelocityProgress,
),
).chain(CurveTween(curve: firstCurve)),
weight: firstWeight,
),
TweenSequenceItem<RelativeRect>(
tween: RelativeRectTween(
begin: RelativeRect.fromLTRB(
0.0,
layerTop * _kPeakVelocityProgress,
0.0,
(layerTop - layerSize.height) * _kPeakVelocityProgress,
),
end: RelativeRect.fill,
).chain(CurveTween(curve: secondCurve)),
weight: secondWeight,
),
],
).animate(animation);
}
Widget _buildStack(BuildContext context, BoxConstraints constraints) {
const double layerTitleHeight = 48.0;
final Size layerSize = constraints.biggest;
final double layerTop = layerSize.height - layerTitleHeight;
_layerAnimation = _getLayerAnimation(layerSize, layerTop);
return Stack(
key: _backdropKey,
children: <Widget>[
widget.backLayer,
PositionedTransition(
rect: _layerAnimation,
child: _FrontLayer(
onTap: _toggleBackdropLayerVisibility,
child: widget.frontLayer,
),
),
],
);
}
@override
Widget build(BuildContext context) {
var appBar = AppBar(
brightness: Brightness.light,
elevation: 0.0,
titleSpacing: 0.0,
title: _BackdropTitle(
listenable: _controller.view,
onPress: _toggleBackdropLayerVisibility,
frontTitle: widget.frontTitle,
backTitle: widget.backTitle,
),
actions: <Widget>[
IconButton(
icon: const Icon(Icons.search, semanticLabel: 'login'),
onPressed: () {
Navigator.push<void>(
context,
MaterialPageRoute(builder: (context) => LoginPage()),
);
},
),
IconButton(
icon: const Icon(Icons.tune, semanticLabel: 'login'),
onPressed: () {
Navigator.push<void>(
context,
MaterialPageRoute(builder: (context) => LoginPage()),
);
},
),
],
);
return Scaffold(
appBar: appBar,
body: LayoutBuilder(
builder: _buildStack,
),
);
}
}

View File

@@ -0,0 +1,83 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'colors.dart';
import 'model/app_state_model.dart';
import 'model/product.dart';
class CategoryMenuPage extends StatelessWidget {
final List<Category> _categories = Category.values;
final VoidCallback onCategoryTap;
const CategoryMenuPage({
Key key,
this.onCategoryTap,
}) : super(key: key);
Widget _buildCategory(Category category, BuildContext context) {
final categoryString =
category.toString().replaceAll('Category.', '').toUpperCase();
final ThemeData theme = Theme.of(context);
return ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) => GestureDetector(
onTap: () {
model.setCategory(category);
if (onCategoryTap != null) onCategoryTap();
},
child: model.selectedCategory == category
? Column(
children: <Widget>[
SizedBox(height: 16.0),
Text(
categoryString,
style: theme.textTheme.body2,
textAlign: TextAlign.center,
),
SizedBox(height: 14.0),
Container(
width: 70.0,
height: 2.0,
color: kShrinePink400,
),
],
)
: Padding(
padding: EdgeInsets.symmetric(vertical: 16.0),
child: Text(
categoryString,
style: theme.textTheme.body2
.copyWith(color: kShrineBrown900.withAlpha(153)),
textAlign: TextAlign.center,
),
),
),
);
}
@override
Widget build(BuildContext context) {
return Center(
child: Container(
padding: EdgeInsets.only(top: 40.0),
color: kShrinePink100,
child: ListView(
children: _categories.map((c) => _buildCategory(c, context)).toList(),
),
),
);
}
}

View File

@@ -0,0 +1,28 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
const kShrinePink50 = Color(0xFFFEEAE6);
const kShrinePink100 = Color(0xFFFEDBD0);
const kShrinePink300 = Color(0xFFFBB8AC);
const kShrinePink400 = Color(0xFFEAA4A4);
const kShrineBrown900 = Color(0xFF442B2D);
const kShrineBrown600 = Color(0xFF7D4F52);
const kShrineErrorRed = Color(0xFFC5032B);
const kShrineSurfaceWhite = Color(0xFFFFFBFA);
const kShrineBackgroundWhite = Colors.white;

View File

@@ -0,0 +1,671 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meta/meta.dart';
import 'package:scoped_model/scoped_model.dart';
import 'colors.dart';
import 'model/app_state_model.dart';
import 'model/product.dart';
import 'shopping_cart.dart';
// These curves define the emphasized easing curve.
const Cubic _kAccelerateCurve = Cubic(0.548, 0.0, 0.757, 0.464);
const Cubic _kDecelerateCurve = Cubic(0.23, 0.94, 0.41, 1.0);
// The time at which the accelerate and decelerate curves switch off
const double _kPeakVelocityTime = 0.248210;
// Percent (as a decimal) of animation that should be completed at _peakVelocityTime
const double _kPeakVelocityProgress = 0.379146;
const double _kCartHeight = 56.0;
// Radius of the shape on the top left of the sheet.
const double _kCornerRadius = 24.0;
// Width for just the cart icon and no thumbnails.
const double _kWidthForCartIcon = 64.0;
class ExpandingBottomSheet extends StatefulWidget {
const ExpandingBottomSheet({Key key, @required this.hideController})
: assert(hideController != null),
super(key: key);
final AnimationController hideController;
@override
_ExpandingBottomSheetState createState() => _ExpandingBottomSheetState();
static _ExpandingBottomSheetState of(BuildContext context,
{bool isNullOk = false}) {
assert(isNullOk != null);
assert(context != null);
final _ExpandingBottomSheetState result = context.ancestorStateOfType(
const TypeMatcher<_ExpandingBottomSheetState>())
as _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 = _kAccelerateCurve;
secondCurve = _kDecelerateCurve;
firstWeight = _kPeakVelocityTime;
secondWeight = 1.0 - _kPeakVelocityTime;
} else {
firstCurve = _kDecelerateCurve.flipped;
secondCurve = _kAccelerateCurve.flipped;
firstWeight = 1.0 - _kPeakVelocityTime;
secondWeight = _kPeakVelocityTime;
}
return TweenSequence(
<TweenSequenceItem<T>>[
TweenSequenceItem<T>(
weight: firstWeight,
tween: Tween<T>(
begin: begin,
end: peak,
).chain(CurveTween(curve: firstCurve)),
),
TweenSequenceItem<T>(
weight: secondWeight,
tween: Tween<T>(
begin: peak,
end: end,
).chain(CurveTween(curve: secondCurve)),
),
],
).animate(parent);
}
// Calculates the value where two double Animations should be joined. Used by
// callers of _getEmphasisedEasing<double>().
double _getPeakPoint({double begin, double end}) {
return begin + (end - begin) * _kPeakVelocityProgress;
}
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 = _kWidthForCartIcon;
// Controller for the opening and closing of the ExpandingBottomSheet
AnimationController _controller;
// Animations for the opening and closing of the ExpandingBottomSheet
Animation<double> _widthAnimation;
Animation<double> _heightAnimation;
Animation<double> _thumbnailOpacityAnimation;
Animation<double> _cartOpacityAnimation;
Animation<double> _shapeAnimation;
Animation<Offset> _slideAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
duration: const Duration(milliseconds: 500),
vsync: this,
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
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: Interval(0.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: Interval(0.0, 0.87)),
);
}
}
Animation<double> _getHeightAnimation(double screenHeight) {
if (_controller.status == AnimationStatus.forward) {
// Opening animation
return _getEmphasizedEasingAnimation(
begin: _kCartHeight,
peak: _kCartHeight +
(screenHeight - _kCartHeight) * _kPeakVelocityProgress,
end: screenHeight,
isForward: true,
parent: _controller.view,
);
} else {
// Closing animation
return Tween<double>(
begin: _kCartHeight,
end: screenHeight,
).animate(
CurvedAnimation(
parent: _controller.view,
curve: Interval(0.434, 1.0, curve: Curves.linear), // not used
// only the reverseCurve will be used
reverseCurve:
Interval(0.434, 1.0, curve: Curves.fastOutSlowIn.flipped),
),
);
}
}
// Animation of the cut corner. It's cut when closed and not cut when open.
Animation<double> _getShapeAnimation() {
if (_controller.status == AnimationStatus.forward) {
return Tween<double>(begin: _kCornerRadius, end: 0.0).animate(
CurvedAnimation(
parent: _controller.view,
curve: Interval(0.0, 0.3, curve: Curves.fastOutSlowIn),
),
);
} else {
return _getEmphasizedEasingAnimation(
begin: _kCornerRadius,
peak: _getPeakPoint(begin: _kCornerRadius, end: 0.0),
end: 0.0,
isForward: false,
parent: _controller.view,
);
}
}
Animation<double> _getThumbnailOpacityAnimation() {
return Tween<double>(begin: 1.0, end: 0.0).animate(
CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? Interval(0.0, 0.3)
: Interval(0.532, 0.766),
),
);
}
Animation<double> _getCartOpacityAnimation() {
return CurvedAnimation(
parent: _controller.view,
curve: _controller.status == AnimationStatus.forward
? Interval(0.3, 0.6)
: Interval(0.766, 1.0),
);
}
// Returns the correct width of the ExpandingBottomSheet based on the number of
// products in the cart.
double _widthFor(int numProducts) {
switch (numProducts) {
case 0:
return _kWidthForCartIcon;
break;
case 1:
return 136.0;
break;
case 2:
return 192.0;
break;
case 3:
return 248.0;
break;
default:
return 278.0;
}
}
// 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 _cartPaddingFor(int numProducts) {
if (numProducts == 0) {
return EdgeInsetsDirectional.only(start: 20.0, end: 8.0);
} else {
return EdgeInsetsDirectional.only(start: 32.0, end: 8.0);
}
}
bool get _cartIsVisible => _thumbnailOpacityAnimation.value == 0.0;
Widget _buildThumbnails(int numProducts) {
return ExcludeSemantics(
child: Opacity(
opacity: _thumbnailOpacityAnimation.value,
child: Column(children: <Widget>[
Row(children: <Widget>[
AnimatedPadding(
padding: _cartPaddingFor(numProducts),
child: Icon(Icons.shopping_cart),
duration: Duration(milliseconds: 225),
),
Container(
// Accounts for the overflow number
width: numProducts > 3 ? _width - 94.0 : _width - 64.0,
height: _kCartHeight,
padding: EdgeInsets.symmetric(vertical: 8.0),
child: ProductThumbnailRow(),
),
ExtraProductsNumber()
]),
]),
),
);
}
Widget _buildShoppingCartPage() {
return Opacity(
opacity: _cartOpacityAnimation.value,
child: ShoppingCartPage(),
);
}
Widget _buildCart(BuildContext context, Widget child) {
// numProducts is the number of different products in the cart (does not
// include multiples of the same product).
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;
_width = _widthFor(numProducts);
_widthAnimation = _getWidthAnimation(screenWidth);
_heightAnimation = _getHeightAnimation(screenHeight);
_shapeAnimation = _getShapeAnimation();
_thumbnailOpacityAnimation = _getThumbnailOpacityAnimation();
_cartOpacityAnimation = _getCartOpacityAnimation();
return Semantics(
button: true,
value: 'Shopping cart, $totalCartQuantity items',
child: Container(
width: _widthAnimation.value,
height: _heightAnimation.value,
child: Material(
animationDuration: Duration(milliseconds: 0),
shape: BeveledRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(_shapeAnimation.value),
),
),
elevation: 4.0,
color: kShrinePink50,
child: _cartIsVisible
? _buildShoppingCartPage()
: _buildThumbnails(numProducts),
),
),
);
}
// Builder for the hide and reveal animation when the backdrop opens and closes
Widget _buildSlideAnimation(BuildContext context, Widget child) {
_slideAnimation = _getEmphasizedEasingAnimation(
begin: Offset(1.0, 0.0),
peak: Offset(_kPeakVelocityProgress, 0.0),
end: Offset(0.0, 0.0),
isForward: widget.hideController.status == AnimationStatus.forward,
parent: widget.hideController,
);
return SlideTransition(
position: _slideAnimation,
child: child,
);
}
// Closes the cart if the cart is open, otherwise exits the app (this should
// only be relevant for Android).
Future<bool> _onWillPop() async {
if (!_isOpen) {
await SystemNavigator.pop();
return true;
}
close();
return true;
}
@override
Widget build(BuildContext context) {
return AnimatedSize(
key: _expandingBottomSheetKey,
duration: Duration(milliseconds: 225),
curve: Curves.easeInOut,
vsync: this,
alignment: FractionalOffset.topLeft,
child: WillPopScope(
onWillPop: _onWillPop,
child: AnimatedBuilder(
animation: widget.hideController,
builder: _buildSlideAnimation,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: open,
child: ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) {
return AnimatedBuilder(
builder: _buildCart,
animation: _controller,
);
},
),
),
),
),
);
}
}
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) {
Animation<double> thumbnailSize =
Tween<double>(begin: 0.8, end: 1.0).animate(
CurvedAnimation(
curve: Interval(0.33, 1.0, curve: Curves.easeIn),
parent: animation,
),
);
Animation<double> opacity = CurvedAnimation(
curve: Interval(0.33, 1.0, 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();
Set<int> internalSet = Set<int>.from(_internalList);
Set<int> listSet = Set<int>.from(_list.list);
Set<int> difference = internalSet.difference(listSet);
if (difference.isEmpty) {
return;
}
difference.forEach((product) {
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() {
return AnimatedList(
key: _listKey,
shrinkWrap: true,
itemBuilder: _buildThumbnail,
initialItemCount: _list.length,
scrollDirection: Axis.horizontal,
physics: NeverScrollableScrollPhysics(), // Cart shouldn't scroll
);
}
@override
Widget build(BuildContext context) {
_updateLists();
return ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) => _buildAnimatedList(),
);
}
}
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) {
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.
List<int> products = productMap.keys.toList();
int overflow = 0;
int numProducts = products.length;
if (numProducts > 3) {
for (int i = 3; i < numProducts; i++) {
overflow += productMap[products[i]];
}
}
return overflow;
}
Widget _buildOverflow(AppStateModel model, BuildContext context) {
if (model.productsInCart.length > 3) {
int numOverflowProducts = _calculateOverflow(model);
// Maximum of 99 so padding doesn't get messy.
int displayedOverflowProducts =
numOverflowProducts <= 99 ? numOverflowProducts : 99;
return Container(
child: Text(
'+$displayedOverflowProducts',
style: Theme.of(context).primaryTextTheme.button,
),
);
} else {
return Container(); // build() can never return null.
}
}
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<AppStateModel>(
builder: (builder, child, model) => _buildOverflow(model, context),
);
}
}
class ProductThumbnail extends StatelessWidget {
final Animation<double> animation;
final Animation<double> opacityAnimation;
final Product product;
ProductThumbnail(this.animation, this.opacityAnimation, this.product);
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: opacityAnimation,
child: ScaleTransition(
scale: animation,
child: Container(
width: 40.0,
height: 40.0,
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage(
product.assetName, // asset name
package: product.assetPackage, // asset package
),
fit: BoxFit.cover,
),
borderRadius: BorderRadius.all(Radius.circular(10.0)),
),
margin: EdgeInsets.only(left: 16.0),
),
),
);
}
}
typedef RemovedItemBuilder = Widget Function(
int, BuildContext, Animation<double>);
// _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 = List<int>.from(initialItems ?? <int>[]);
final GlobalKey<AnimatedListState> listKey;
final RemovedItemBuilder 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: 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,56 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'backdrop.dart';
import 'expanding_bottom_sheet.dart';
import 'model/app_state_model.dart';
import 'model/product.dart';
import 'supplemental/asymmetric_view.dart';
class ProductPage extends StatelessWidget {
final Category category;
const ProductPage({this.category = Category.all});
@override
Widget build(BuildContext context) {
return ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) {
return AsymmetricView(
products: model.getProducts(),
);
});
}
}
class HomePage extends StatelessWidget {
final ExpandingBottomSheet expandingBottomSheet;
final Backdrop backdrop;
const HomePage({Key key, this.expandingBottomSheet, this.backdrop})
: super(key: key);
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
backdrop,
Align(child: expandingBottomSheet, alignment: Alignment.bottomRight)
],
);
}
}

View File

@@ -0,0 +1,111 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'colors.dart';
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
children: <Widget>[
const SizedBox(height: 80.0),
Column(
children: <Widget>[
Image.asset('assets/diamond.png'),
const SizedBox(height: 16.0),
Text(
'SHRINE',
style: Theme.of(context).textTheme.headline,
),
],
),
const SizedBox(height: 120.0),
PrimaryColorOverride(
color: kShrineBrown900,
child: TextField(
controller: _usernameController,
decoration: const InputDecoration(
labelText: 'Username',
),
),
),
const SizedBox(height: 12.0),
PrimaryColorOverride(
color: kShrineBrown900,
child: TextField(
controller: _passwordController,
decoration: const InputDecoration(
labelText: 'Password',
),
),
),
ButtonBar(
children: <Widget>[
FlatButton(
child: const Text('CANCEL'),
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7.0)),
),
onPressed: () {
_usernameController.clear();
_passwordController.clear();
},
),
RaisedButton(
child: const Text('NEXT'),
elevation: 8.0,
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7.0)),
),
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,35 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:scoped_model/scoped_model.dart';
import 'app.dart';
import 'model/app_state_model.dart';
void main() {
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
AppStateModel model = AppStateModel();
model.loadProducts();
runApp(
ScopedModel<AppStateModel>(
model: model,
child: ShrineApp(),
),
);
}

View File

@@ -0,0 +1,114 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:scoped_model/scoped_model.dart';
import 'product.dart';
import 'products_repository.dart';
double _salesTaxRate = 0.06;
double _shippingCostPerItem = 7.0;
class AppStateModel extends Model {
// All the available products.
List<Product> _availableProducts;
// The currently selected category of products.
Category _selectedCategory = Category.all;
// The IDs and quantities of products currently in the cart.
Map<int, int> _productsInCart = {};
Map<int, int> get productsInCart => Map.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 => _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 =>
_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 List<Product>();
if (_selectedCategory == Category.all) {
return List.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(Category.all);
notifyListeners();
}
void setCategory(Category newCategory) {
_selectedCategory = newCategory;
notifyListeners();
}
}

View File

@@ -0,0 +1,48 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/foundation.dart';
enum Category {
all,
accessories,
clothing,
home,
}
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;
final String name;
final int price;
String get assetName => '$id-0.jpg';
String get assetPackage => 'shrine_images';
@override
String toString() => '$name (id=$id)';
}

View File

@@ -0,0 +1,293 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'product.dart';
class ProductsRepository {
static List<Product> loadProducts(Category category) {
const allProducts = <Product>[
Product(
category: Category.accessories,
id: 0,
isFeatured: true,
name: 'Vagabond sack',
price: 120,
),
Product(
category: Category.accessories,
id: 1,
isFeatured: true,
name: 'Stella sunglasses',
price: 58,
),
Product(
category: Category.accessories,
id: 2,
isFeatured: false,
name: 'Whitney belt',
price: 35,
),
Product(
category: Category.accessories,
id: 3,
isFeatured: true,
name: 'Garden strand',
price: 98,
),
Product(
category: Category.accessories,
id: 4,
isFeatured: false,
name: 'Strut earrings',
price: 34,
),
Product(
category: Category.accessories,
id: 5,
isFeatured: false,
name: 'Varsity socks',
price: 12,
),
Product(
category: Category.accessories,
id: 6,
isFeatured: false,
name: 'Weave keyring',
price: 16,
),
Product(
category: Category.accessories,
id: 7,
isFeatured: true,
name: 'Gatsby hat',
price: 40,
),
Product(
category: Category.accessories,
id: 8,
isFeatured: true,
name: 'Shrug bag',
price: 198,
),
Product(
category: Category.home,
id: 9,
isFeatured: true,
name: 'Gilt desk trio',
price: 58,
),
Product(
category: Category.home,
id: 10,
isFeatured: false,
name: 'Copper wire rack',
price: 18,
),
Product(
category: Category.home,
id: 11,
isFeatured: false,
name: 'Soothe ceramic set',
price: 28,
),
Product(
category: Category.home,
id: 12,
isFeatured: false,
name: 'Hurrahs tea set',
price: 34,
),
Product(
category: Category.home,
id: 13,
isFeatured: true,
name: 'Blue stone mug',
price: 18,
),
Product(
category: Category.home,
id: 14,
isFeatured: true,
name: 'Rainwater tray',
price: 27,
),
Product(
category: Category.home,
id: 15,
isFeatured: true,
name: 'Chambray napkins',
price: 16,
),
Product(
category: Category.home,
id: 16,
isFeatured: true,
name: 'Succulent planters',
price: 16,
),
Product(
category: Category.home,
id: 17,
isFeatured: false,
name: 'Quartet table',
price: 175,
),
Product(
category: Category.home,
id: 18,
isFeatured: true,
name: 'Kitchen quattro',
price: 129,
),
Product(
category: Category.clothing,
id: 19,
isFeatured: false,
name: 'Clay sweater',
price: 48,
),
Product(
category: Category.clothing,
id: 20,
isFeatured: false,
name: 'Sea tunic',
price: 45,
),
Product(
category: Category.clothing,
id: 21,
isFeatured: false,
name: 'Plaster tunic',
price: 38,
),
Product(
category: Category.clothing,
id: 22,
isFeatured: false,
name: 'White pinstripe shirt',
price: 70,
),
Product(
category: Category.clothing,
id: 23,
isFeatured: false,
name: 'Chambray shirt',
price: 70,
),
Product(
category: Category.clothing,
id: 24,
isFeatured: true,
name: 'Seabreeze sweater',
price: 60,
),
Product(
category: Category.clothing,
id: 25,
isFeatured: false,
name: 'Gentry jacket',
price: 178,
),
Product(
category: Category.clothing,
id: 26,
isFeatured: false,
name: 'Navy trousers',
price: 74,
),
Product(
category: Category.clothing,
id: 27,
isFeatured: true,
name: 'Walter henley (white)',
price: 38,
),
Product(
category: Category.clothing,
id: 28,
isFeatured: true,
name: 'Surf and perf shirt',
price: 48,
),
Product(
category: Category.clothing,
id: 29,
isFeatured: true,
name: 'Ginger scarf',
price: 98,
),
Product(
category: Category.clothing,
id: 30,
isFeatured: true,
name: 'Ramona crossover',
price: 68,
),
Product(
category: Category.clothing,
id: 31,
isFeatured: false,
name: 'Chambray shirt',
price: 38,
),
Product(
category: Category.clothing,
id: 32,
isFeatured: false,
name: 'Classic white collar',
price: 58,
),
Product(
category: Category.clothing,
id: 33,
isFeatured: true,
name: 'Cerise scallop tee',
price: 42,
),
Product(
category: Category.clothing,
id: 34,
isFeatured: false,
name: 'Shoulder rolls tee',
price: 27,
),
Product(
category: Category.clothing,
id: 35,
isFeatured: false,
name: 'Grey slouch tank',
price: 24,
),
Product(
category: Category.clothing,
id: 36,
isFeatured: false,
name: 'Sunshirt dress',
price: 58,
),
Product(
category: Category.clothing,
id: 37,
isFeatured: true,
name: 'Fine lines tee',
price: 58,
),
];
if (category == Category.all) {
return allProducts;
} else {
return allProducts.where((p) => p.category == category).toList();
}
}
}

View File

@@ -0,0 +1,272 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:scoped_model/scoped_model.dart';
import 'colors.dart';
import 'expanding_bottom_sheet.dart';
import 'model/app_state_model.dart';
import 'model/product.dart';
const _leftColumnWidth = 60.0;
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 localTheme = Theme.of(context);
return Scaffold(
backgroundColor: kShrinePink50,
body: SafeArea(
child: Container(
child: ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) {
return Stack(
children: [
ListView(
children: [
Row(
children: [
SizedBox(
width: _leftColumnWidth,
child: IconButton(
icon: const Icon(Icons.keyboard_arrow_down),
onPressed: () =>
ExpandingBottomSheet.of(context).close()),
),
Text(
'CART',
style: localTheme.textTheme.subhead
.copyWith(fontWeight: FontWeight.w600),
),
const SizedBox(width: 16.0),
Text('${model.totalCartQuantity} ITEMS'),
],
),
const SizedBox(height: 16.0),
Column(
children: _createShoppingCartRows(model),
),
ShoppingCartSummary(model: model),
const SizedBox(height: 100.0),
],
),
Positioned(
bottom: 16.0,
left: 16.0,
right: 16.0,
child: RaisedButton(
shape: const BeveledRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(7.0)),
),
color: kShrinePink100,
splashColor: kShrineBrown600,
child: const Padding(
padding: EdgeInsets.symmetric(vertical: 12.0),
child: Text('CLEAR CART'),
),
onPressed: () {
model.clearCart();
ExpandingBottomSheet.of(context).close();
},
),
),
],
);
},
),
),
),
);
}
}
class ShoppingCartSummary extends StatelessWidget {
ShoppingCartSummary({this.model});
final AppStateModel model;
@override
Widget build(BuildContext context) {
final smallAmountStyle =
Theme.of(context).textTheme.body1.copyWith(color: kShrineBrown600);
final largeAmountStyle = Theme.of(context).textTheme.display1;
final formatter = NumberFormat.simpleCurrency(
decimalDigits: 2, locale: Localizations.localeOf(context).toString());
return Row(
children: [
SizedBox(width: _leftColumnWidth),
Expanded(
child: Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Expanded(
child: Text('TOTAL'),
),
Text(
formatter.format(model.totalCost),
style: largeAmountStyle,
),
],
),
const SizedBox(height: 16.0),
Row(
children: [
const Expanded(
child: Text('Subtotal:'),
),
Text(
formatter.format(model.subtotalCost),
style: smallAmountStyle,
),
],
),
const SizedBox(height: 4.0),
Row(
children: [
const Expanded(
child: Text('Shipping:'),
),
Text(
formatter.format(model.shippingCost),
style: smallAmountStyle,
),
],
),
const SizedBox(height: 4.0),
Row(
children: [
const Expanded(
child: Text('Tax:'),
),
Text(
formatter.format(model.tax),
style: smallAmountStyle,
),
],
),
],
),
),
),
],
);
}
}
class ShoppingCartRow extends StatelessWidget {
ShoppingCartRow(
{@required this.product, @required this.quantity, this.onPressed});
final Product product;
final int quantity;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final formatter = NumberFormat.simpleCurrency(
decimalDigits: 0, locale: Localizations.localeOf(context).toString());
final localTheme = Theme.of(context);
return Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: Row(
key: ValueKey(product.id),
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: _leftColumnWidth,
child: IconButton(
icon: const Icon(Icons.remove_circle_outline),
onPressed: onPressed,
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(right: 16.0),
child: Column(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Image.asset(
product.assetName,
package: product.assetPackage,
fit: BoxFit.cover,
width: 75.0,
height: 75.0,
),
const SizedBox(width: 16.0),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text('Quantity: $quantity'),
),
Text('x ${formatter.format(product.price)}'),
],
),
Text(
product.name,
style: localTheme.textTheme.subhead
.copyWith(fontWeight: FontWeight.w600),
),
],
),
),
],
),
const SizedBox(height: 16.0),
const Divider(
color: kShrineBrown900,
height: 10.0,
),
],
),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,96 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import '../model/product.dart';
import 'product_columns.dart';
class AsymmetricView extends StatelessWidget {
final List<Product> products;
const AsymmetricView({Key key, this.products});
List<Container> _buildColumns(BuildContext context) {
if (products == null || products.isEmpty) {
return const <Container>[];
}
/// 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.generate(_listItemCount(products.length), (index) {
double width = .59 * MediaQuery.of(context).size.width;
Widget column;
if (index % 2 == 0) {
/// Even cases
int bottom = _evenCasesIndex(index);
column = TwoProductCardColumn(
bottom: products[bottom],
top: products.length - 1 >= bottom + 1
? products[bottom + 1]
: null);
width += 32.0;
} else {
/// Odd cases
column = OneProductCardColumn(
product: products[_oddCasesIndex(index)],
);
}
return Container(
width: width,
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: column,
),
);
}).toList();
}
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) {
if (totalItems % 3 == 0) {
return totalItems ~/ 3 * 2;
} else {
return (totalItems / 3).ceil() * 2 - 1;
}
}
@override
Widget build(BuildContext context) {
return ListView(
scrollDirection: Axis.horizontal,
padding: EdgeInsets.fromLTRB(0.0, 34.0, 16.0, 44.0),
children: _buildColumns(context),
physics: AlwaysScrollableScrollPhysics(),
);
}
}

View File

@@ -0,0 +1,139 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
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.0)),
this.cut = 7.0,
double gapPadding = 2.0,
}) : super(
borderSide: borderSide,
borderRadius: borderRadius,
gapPadding: gapPadding);
@override
CutCornersBorder copyWith({
BorderSide borderSide,
BorderRadius borderRadius,
double gapPadding,
double cut,
}) {
return CutCornersBorder(
borderRadius: borderRadius ?? this.borderRadius,
borderSide: borderSide ?? this.borderSide,
cut: cut ?? this.cut,
gapPadding: gapPadding ?? this.gapPadding,
);
}
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.0, double extent = 0.0]) {
final Path path = Path();
if (start > 0.0 || extent > 0.0) {
path.relativeMoveTo(extent + start, center.top);
_notchedSidesAndBottom(center, path);
path..lineTo(center.left + cut, center.top)..lineTo(start, center.top);
} 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.0,
double gapPercentage = 0.0,
TextDirection textDirection,
}) {
assert(gapExtent != null);
assert(gapPercentage >= 0.0 && gapPercentage <= 1.0);
final Paint paint = borderSide.toPaint();
final RRect outer = borderRadius.toRRect(rect);
if (gapStart == null || gapExtent <= 0.0 || gapPercentage == 0.0) {
canvas.drawPath(_notchedCornerPath(outer.middleRect), paint);
} else {
final double extent =
lerpDouble(0.0, gapExtent + gapPadding * 2.0, 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,93 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:scoped_model/scoped_model.dart';
import '../model/app_state_model.dart';
import '../model/product.dart';
class ProductCard extends StatelessWidget {
ProductCard({this.imageAspectRatio = 33 / 49, this.product})
: assert(imageAspectRatio == null || imageAspectRatio > 0);
final double imageAspectRatio;
final Product product;
static final kTextBoxHeight = 65.0;
@override
Widget build(BuildContext context) {
final NumberFormat formatter = NumberFormat.simpleCurrency(
decimalDigits: 0, locale: Localizations.localeOf(context).toString());
final ThemeData theme = Theme.of(context);
final imageWidget = Image.asset(
product.assetName,
package: product.assetPackage,
fit: BoxFit.cover,
);
return ScopedModelDescendant<AppStateModel>(
builder: (context, child, model) => GestureDetector(
onTap: () {
model.addProductToCart(product.id);
// TODO: Add Snackbar
},
child: child,
),
child: Stack(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
AspectRatio(
aspectRatio: imageAspectRatio,
child: imageWidget,
),
SizedBox(
height: kTextBoxHeight * MediaQuery.of(context).textScaleFactor,
width: 121.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
product == null ? '' : product.name,
style: theme.textTheme.button,
softWrap: false,
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
SizedBox(height: 4.0),
Text(
product == null ? '' : formatter.format(product.price),
style: theme.textTheme.caption,
),
],
),
),
],
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Icon(Icons.add_shopping_cart),
),
],
),
);
}
}

View File

@@ -0,0 +1,89 @@
// Copyright 2018-present the Flutter authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:flutter/material.dart';
import '../model/product.dart';
import 'product_card.dart';
class TwoProductCardColumn extends StatelessWidget {
TwoProductCardColumn({
this.bottom,
this.top,
}) : assert(bottom != null);
final Product bottom, top;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
const spacerHeight = 44.0;
double heightOfCards =
(constraints.biggest.height - spacerHeight) / 2.0;
double heightOfImages = heightOfCards - ProductCard.kTextBoxHeight;
double imageAspectRatio = (heightOfImages >= 0.0 &&
constraints.biggest.width > heightOfImages)
? constraints.biggest.width / heightOfImages
: 33 / 49;
return ListView(
children: <Widget>[
Padding(
padding: EdgeInsetsDirectional.only(start: 28.0),
child: top != null
? ProductCard(
imageAspectRatio: imageAspectRatio,
product: top,
)
: SizedBox(
height: heightOfCards > 0 ? heightOfCards : spacerHeight,
),
),
SizedBox(height: spacerHeight),
Padding(
padding: EdgeInsetsDirectional.only(end: 28.0),
child: ProductCard(
imageAspectRatio: imageAspectRatio,
product: bottom,
),
),
],
);
},
);
}
}
class OneProductCardColumn extends StatelessWidget {
OneProductCardColumn({this.product});
final Product product;
@override
Widget build(BuildContext context) {
return ListView(
reverse: true,
children: <Widget>[
SizedBox(
height: 40.0,
),
ProductCard(
product: product,
),
],
);
}
}