1
0
mirror of https://github.com/flutter/samples.git synced 2025-11-11 15:28:44 +00:00

Add flutter_web samples (#75)

This commit is contained in:
Kevin Moore
2019-05-07 13:32:08 -07:00
committed by Andrew Brogdon
parent 42f2dce01b
commit 3fe927cb29
697 changed files with 241026 additions and 0 deletions

View File

@@ -0,0 +1,254 @@
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'shrine_types.dart';
const String _kGalleryAssetsPackage = null;
const Vendor _ali = Vendor(
name: 'Alis shop',
avatarAsset: 'people/square/ali.png',
avatarAssetPackage: _kGalleryAssetsPackage,
description:
'Ali Connors makes custom goods for folks of all shapes and sizes '
'made by hand and sometimes by machine, but always with love and care. '
'Custom orders are available upon request if you need something extra special.');
const Vendor _peter = Vendor(
name: 'Peters shop',
avatarAsset: 'people/square/peter.png',
avatarAssetPackage: _kGalleryAssetsPackage,
description:
'Peter makes great stuff for awesome people like you. Super cool and extra '
'awesome all of his shops goods are handmade with love. Custom orders are '
'available upon request if you need something extra special.');
const Vendor _sandra = Vendor(
name: 'Sandras shop',
avatarAsset: 'people/square/sandra.png',
avatarAssetPackage: _kGalleryAssetsPackage,
description:
'Sandra specializes in furniture, beauty and travel products with a classic vibe. '
'Custom orders are available if youre looking for a certain color or material.');
const Vendor _stella = Vendor(
name: 'Stellas shop',
avatarAsset: 'people/square/stella.png',
avatarAssetPackage: _kGalleryAssetsPackage,
description:
'Stella sells awesome stuff at lovely prices. made by hand and sometimes by '
'machine, but always with love and care. Custom orders are available upon request '
'if you need something extra special.');
const Vendor _trevor = Vendor(
name: 'Trevors shop',
avatarAsset: 'people/square/trevor.png',
avatarAssetPackage: _kGalleryAssetsPackage,
description:
'Trevor makes great stuff for awesome people like you. Super cool and extra '
'awesome all of his shops goods are handmade with love. Custom orders are '
'available upon request if you need something extra special.');
const List<Product> _allProducts = <Product>[
Product(
name: 'Vintage Brown Belt',
imageAsset: 'products/belt.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['fashion', 'latest'],
price: 300.00,
vendor: _sandra,
description:
'Isnt it cool when things look old, but they\'re not. Looks Old But Not makes '
'awesome vintage goods that are super smart. This ol belt just got an upgrade. '),
Product(
name: 'Sunglasses',
imageAsset: 'products/sunnies.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['travel', 'fashion', 'beauty'],
price: 20.00,
vendor: _trevor,
description:
'Be an optimist. Carry Sunglasses with you at all times. All Tints and '
'Shades products come with polarized lenses and super duper UV protection '
'so you can look at the sun for however long you want. Sunglasses make you '
'look cool, wear them.'),
Product(
name: 'Flatwear',
imageAsset: 'products/flatwear.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['furniture'],
price: 30.00,
vendor: _trevor,
description:
'Leave the tunnel and the rain is fallin amazing things happen when you wait'),
Product(
name: 'Salmon Sweater',
imageAsset: 'products/sweater.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['fashion'],
price: 300.00,
vendor: _stella,
description:
'Looks can be deceiving. This sweater comes in a wide variety of '
'flavors, including salmon, that pop as soon as they hit your eyes. '
'Sweaters heat quickly, so savor the warmth.'),
Product(
name: 'Pine Table',
imageAsset: 'products/table.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['furniture'],
price: 63.00,
vendor: _stella,
description:
'Leave the tunnel and the rain is fallin amazing things happen when you wait'),
Product(
name: 'Green Comfort Jacket',
imageAsset: 'products/jacket.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['fashion'],
price: 36.00,
vendor: _ali,
description:
'Leave the tunnel and the rain is fallin amazing things happen when you wait'),
Product(
name: 'Chambray Top',
imageAsset: 'products/top.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['fashion'],
price: 125.00,
vendor: _peter,
description:
'Leave the tunnel and the rain is fallin amazing things happen when you wait'),
Product(
name: 'Blue Cup',
imageAsset: 'products/cup.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['travel', 'furniture'],
price: 75.00,
vendor: _sandra,
description:
'Drinksy has been making extraordinary mugs for decades. With each '
'cup purchased Drinksy donates a cup to those in need. Buy yourself a mug, '
'buy someone else a mug.'),
Product(
name: 'Tea Set',
imageAsset: 'products/teaset.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['furniture', 'fashion'],
price: 70.00,
vendor: _trevor,
featureTitle: 'Beautiful glass teapot',
featureDescription:
'Teapot holds extremely hot liquids and pours them from the spout.',
description:
'Impress your guests with Tea Set by Kitchen Stuff. Teapot holds extremely '
'hot liquids and pours them from the spout. Use the handle, shown on the right, '
'so your fingers dont get burnt while pouring.'),
Product(
name: 'Blue linen napkins',
imageAsset: 'products/napkins.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['furniture', 'fashion'],
price: 89.00,
vendor: _trevor,
description:
'Blue linen napkins were meant to go with friends, so you may want to pick '
'up a bunch of these. These things are absorbant.'),
Product(
name: 'Dipped Earrings',
imageAsset: 'products/earrings.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['fashion', 'beauty'],
price: 25.00,
vendor: _stella,
description:
'WeDipIt does it again. These hand-dipped 4 inch earrings are perfect for '
'the office or the beach. Just be sure you dont drop it in a bucket of '
'red paint, then they wont look dipped anymore.'),
Product(
name: 'Perfect Planters',
imageAsset: 'products/planters.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['latest', 'furniture'],
price: 30.00,
vendor: _ali,
description:
'The Perfect Planter Co makes the best vessels for just about anything you '
'can pot. This set of Perfect Planters holds succulents and cuttings perfectly. '
'Looks great in any room. Keep out of reach from cats.'),
Product(
name: 'Cloud-White Dress',
imageAsset: 'products/dress.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['fashion'],
price: 54.00,
vendor: _sandra,
description:
'Trying to find the perfect outift to match your mood? Try no longer. '
'This Cloud-White Dress has you covered for those nights when you need '
'to get out, or even if youre just headed to work.'),
Product(
name: 'Backpack',
imageAsset: 'products/backpack.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['travel', 'fashion'],
price: 25.00,
vendor: _peter,
description:
'This backpack by Bags n stuff can hold just about anything: a laptop, '
'a pen, a protractor, notebooks, small animals, plugs for your devices, '
'sunglasses, gym clothes, shoes, gloves, two kittens, and even lunch!'),
Product(
name: 'Charcoal Straw Hat',
imageAsset: 'products/hat.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['travel', 'fashion', 'latest'],
price: 25.00,
vendor: _ali,
description:
'This is the helmet for those warm summer days on the road. '
'Jetset approved, these hats have been rigorously tested. Keep that face '
'protected from the sun.'),
Product(
name: 'Ginger Scarf',
imageAsset: 'products/scarf.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['latest', 'fashion'],
price: 17.00,
vendor: _peter,
description:
'Leave the tunnel and the rain is fallin amazing things happen when you wait'),
Product(
name: 'Blush Sweats',
imageAsset: 'products/sweats.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['travel', 'fashion', 'latest'],
price: 25.00,
vendor: _stella,
description:
'Leave the tunnel and the rain is fallin amazing things happen when you wait'),
Product(
name: 'Mint Jumper',
imageAsset: 'products/jumper.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['travel', 'fashion', 'beauty'],
price: 25.00,
vendor: _peter,
description:
'Leave the tunnel and the rain is fallin amazing things happen when you wait'),
Product(
name: 'Ochre Shirt',
imageAsset: 'products/shirt.png',
imageAssetPackage: _kGalleryAssetsPackage,
categories: <String>['fashion', 'latest'],
price: 120.00,
vendor: _stella,
description:
'Leave the tunnel and the rain is fallin amazing things happen when you wait')
];
List<Product> allProducts() {
assert(_allProducts.every((Product product) => product.isValid()));
return List<Product>.unmodifiable(_allProducts);
}

View File

@@ -0,0 +1,434 @@
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter_web/material.dart';
import 'package:flutter_web/rendering.dart';
import 'package:meta/meta.dart';
import 'shrine_data.dart';
import 'shrine_order.dart';
import 'shrine_page.dart';
import 'shrine_theme.dart';
import 'shrine_types.dart';
const double unitSize = kToolbarHeight;
final List<Product> _products = List<Product>.from(allProducts());
final Map<Product, Order> _shoppingCart = <Product, Order>{};
const int _childrenPerBlock = 8;
const int _rowsPerBlock = 5;
int _minIndexInRow(int rowIndex) {
final int blockIndex = rowIndex ~/ _rowsPerBlock;
return const <int>[0, 2, 4, 6, 7][rowIndex % _rowsPerBlock] +
blockIndex * _childrenPerBlock;
}
int _maxIndexInRow(int rowIndex) {
final int blockIndex = rowIndex ~/ _rowsPerBlock;
return const <int>[1, 3, 5, 6, 7][rowIndex % _rowsPerBlock] +
blockIndex * _childrenPerBlock;
}
int _rowAtIndex(int index) {
final int blockCount = index ~/ _childrenPerBlock;
return const <int>[
0,
0,
1,
1,
2,
2,
3,
4
][index - blockCount * _childrenPerBlock] +
blockCount * _rowsPerBlock;
}
int _columnAtIndex(int index) {
return const <int>[0, 1, 0, 1, 0, 1, 0, 0][index % _childrenPerBlock];
}
int _columnSpanAtIndex(int index) {
return const <int>[1, 1, 1, 1, 1, 1, 2, 2][index % _childrenPerBlock];
}
// The Shrine home page arranges the product cards into two columns. The card
// on every 4th and 5th row spans two columns.
class _ShrineGridLayout extends SliverGridLayout {
const _ShrineGridLayout({
@required this.rowStride,
@required this.columnStride,
@required this.tileHeight,
@required this.tileWidth,
});
final double rowStride;
final double columnStride;
final double tileHeight;
final double tileWidth;
@override
int getMinChildIndexForScrollOffset(double scrollOffset) {
return _minIndexInRow(scrollOffset ~/ rowStride);
}
@override
int getMaxChildIndexForScrollOffset(double scrollOffset) {
return _maxIndexInRow(scrollOffset ~/ rowStride);
}
@override
SliverGridGeometry getGeometryForChildIndex(int index) {
final int row = _rowAtIndex(index);
final int column = _columnAtIndex(index);
final int columnSpan = _columnSpanAtIndex(index);
return SliverGridGeometry(
scrollOffset: row * rowStride,
crossAxisOffset: column * columnStride,
mainAxisExtent: tileHeight,
crossAxisExtent: tileWidth + (columnSpan - 1) * columnStride,
);
}
@override
double computeMaxScrollOffset(int childCount) {
if (childCount == 0) return 0.0;
final int rowCount = _rowAtIndex(childCount - 1) + 1;
final double rowSpacing = rowStride - tileHeight;
return rowStride * rowCount - rowSpacing;
}
}
class _ShrineGridDelegate extends SliverGridDelegate {
static const double _spacing = 8.0;
@override
SliverGridLayout getLayout(SliverConstraints constraints) {
final double tileWidth = (constraints.crossAxisExtent - _spacing) / 2.0;
const double tileHeight = 40.0 + 144.0 + 40.0;
return _ShrineGridLayout(
tileWidth: tileWidth,
tileHeight: tileHeight,
rowStride: tileHeight + _spacing,
columnStride: tileWidth + _spacing,
);
}
@override
bool shouldRelayout(covariant SliverGridDelegate oldDelegate) => false;
}
// Displays the Vendor's name and avatar.
class _VendorItem extends StatelessWidget {
const _VendorItem({Key key, @required this.vendor})
: assert(vendor != null),
super(key: key);
final Vendor vendor;
@override
Widget build(BuildContext context) {
return SizedBox(
height: 24.0,
child: Row(
children: <Widget>[
SizedBox(
width: 24.0,
child: ClipRRect(
borderRadius: BorderRadius.circular(12.0),
child: Image.asset(
vendor.avatarAsset,
package: vendor.avatarAssetPackage,
fit: BoxFit.cover,
),
),
),
const SizedBox(width: 8.0),
Expanded(
child: Text(vendor.name,
style: ShrineTheme.of(context).vendorItemStyle),
),
],
),
);
}
}
// Displays the product's price. If the product is in the shopping cart then the
// background is highlighted.
abstract class _PriceItem extends StatelessWidget {
const _PriceItem({Key key, @required this.product})
: assert(product != null),
super(key: key);
final Product product;
Widget buildItem(BuildContext context, TextStyle style, EdgeInsets padding) {
BoxDecoration decoration;
if (_shoppingCart[product] != null)
decoration =
BoxDecoration(color: ShrineTheme.of(context).priceHighlightColor);
return Container(
padding: padding,
decoration: decoration,
child: Text(product.priceString, style: style),
);
}
}
class _ProductPriceItem extends _PriceItem {
const _ProductPriceItem({Key key, Product product})
: super(key: key, product: product);
@override
Widget build(BuildContext context) {
return buildItem(
context,
ShrineTheme.of(context).priceStyle,
const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
);
}
}
class _FeaturePriceItem extends _PriceItem {
const _FeaturePriceItem({Key key, Product product})
: super(key: key, product: product);
@override
Widget build(BuildContext context) {
return buildItem(
context,
ShrineTheme.of(context).featurePriceStyle,
const EdgeInsets.symmetric(horizontal: 24.0, vertical: 16.0),
);
}
}
class _HeadingLayout extends MultiChildLayoutDelegate {
_HeadingLayout();
static const String price = 'price';
static const String image = 'image';
static const String title = 'title';
static const String description = 'description';
static const String vendor = 'vendor';
@override
void performLayout(Size size) {
final Size priceSize = layoutChild(price, BoxConstraints.loose(size));
positionChild(price, Offset(size.width - priceSize.width, 0.0));
final double halfWidth = size.width / 2.0;
final double halfHeight = size.height / 2.0;
const double halfUnit = unitSize / 2.0;
const double margin = 16.0;
final Size imageSize = layoutChild(image, BoxConstraints.loose(size));
final double imageX = imageSize.width < halfWidth - halfUnit
? halfWidth / 2.0 - imageSize.width / 2.0 - halfUnit
: halfWidth - imageSize.width;
positionChild(image, Offset(imageX, halfHeight - imageSize.height / 2.0));
final double maxTitleWidth = halfWidth + unitSize - margin;
final BoxConstraints titleBoxConstraints =
BoxConstraints(maxWidth: maxTitleWidth);
final Size titleSize = layoutChild(title, titleBoxConstraints);
final double titleX = halfWidth - unitSize;
final double titleY = halfHeight - titleSize.height;
positionChild(title, Offset(titleX, titleY));
final Size descriptionSize = layoutChild(description, titleBoxConstraints);
final double descriptionY = titleY + titleSize.height + margin;
positionChild(description, Offset(titleX, descriptionY));
layoutChild(vendor, titleBoxConstraints);
final double vendorY = descriptionY + descriptionSize.height + margin;
positionChild(vendor, Offset(titleX, vendorY));
}
@override
bool shouldRelayout(_HeadingLayout oldDelegate) => false;
}
// A card that highlights the "featured" catalog item.
class _Heading extends StatelessWidget {
_Heading({Key key, @required this.product})
: assert(product != null),
assert(product.featureTitle != null),
assert(product.featureDescription != null),
super(key: key);
final Product product;
@override
Widget build(BuildContext context) {
final Size screenSize = MediaQuery.of(context).size;
final ShrineTheme theme = ShrineTheme.of(context);
return MergeSemantics(
child: SizedBox(
height: screenSize.width > screenSize.height
? (screenSize.height - kToolbarHeight) * 0.85
: (screenSize.height - kToolbarHeight) * 0.70,
child: Container(
decoration: BoxDecoration(
color: theme.cardBackgroundColor,
border: Border(bottom: BorderSide(color: theme.dividerColor)),
),
child: CustomMultiChildLayout(
delegate: _HeadingLayout(),
children: <Widget>[
LayoutId(
id: _HeadingLayout.price,
child: _FeaturePriceItem(product: product),
),
LayoutId(
id: _HeadingLayout.image,
child: Image.asset(
product.imageAsset,
package: product.imageAssetPackage,
fit: BoxFit.cover,
),
),
LayoutId(
id: _HeadingLayout.title,
child:
Text(product.featureTitle, style: theme.featureTitleStyle),
),
LayoutId(
id: _HeadingLayout.description,
child:
Text(product.featureDescription, style: theme.featureStyle),
),
LayoutId(
id: _HeadingLayout.vendor,
child: _VendorItem(vendor: product.vendor),
),
],
),
),
),
);
}
}
// A card that displays a product's image, price, and vendor. The _ProductItem
// cards appear in a grid below the heading.
class _ProductItem extends StatelessWidget {
const _ProductItem({Key key, @required this.product, this.onPressed})
: assert(product != null),
super(key: key);
final Product product;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
return MergeSemantics(
child: Card(
child: Stack(
children: <Widget>[
Column(
children: <Widget>[
Align(
alignment: Alignment.centerRight,
child: _ProductPriceItem(product: product),
),
Container(
width: 144.0,
height: 144.0,
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Hero(
tag: product.tag,
child: Image.asset(
product.imageAsset,
package: product.imageAssetPackage,
fit: BoxFit.contain,
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: _VendorItem(vendor: product.vendor),
),
],
),
Material(
type: MaterialType.transparency,
child: InkWell(onTap: onPressed),
),
],
),
),
);
}
}
// The Shrine app's home page. Displays the featured item above a grid
// of the product items.
class ShrineHome extends StatefulWidget {
@override
_ShrineHomeState createState() => _ShrineHomeState();
}
class _ShrineHomeState extends State<ShrineHome> {
static final GlobalKey<ScaffoldState> _scaffoldKey =
GlobalKey<ScaffoldState>(debugLabel: 'Shrine Home');
static final _ShrineGridDelegate gridDelegate = _ShrineGridDelegate();
Future<void> _showOrderPage(Product product) async {
final Order order = _shoppingCart[product] ?? Order(product: product);
final Order completedOrder = await Navigator.push(
context,
ShrineOrderRoute(
order: order,
builder: (BuildContext context) {
return OrderPage(
order: order,
products: _products,
shoppingCart: _shoppingCart,
);
}));
assert(completedOrder.product != null);
if (completedOrder.quantity == 0)
_shoppingCart.remove(completedOrder.product);
}
@override
Widget build(BuildContext context) {
final Product featured = _products
.firstWhere((Product product) => product.featureDescription != null);
return ShrinePage(
scaffoldKey: _scaffoldKey,
products: _products,
shoppingCart: _shoppingCart,
body: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(child: _Heading(product: featured)),
SliverSafeArea(
top: false,
minimum: const EdgeInsets.all(16.0),
sliver: SliverGrid(
gridDelegate: gridDelegate,
delegate: SliverChildListDelegate(
_products.map<Widget>((Product product) {
return _ProductItem(
product: product,
onPressed: () {
_showOrderPage(product);
},
);
}).toList(),
),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,353 @@
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_web/material.dart';
import 'package:flutter_web/rendering.dart';
import '../shrine_demo.dart' show ShrinePageRoute;
import 'shrine_page.dart';
import 'shrine_theme.dart';
import 'shrine_types.dart';
// Displays the product title's, description, and order quantity dropdown.
class _ProductItem extends StatelessWidget {
const _ProductItem({
Key key,
@required this.product,
@required this.quantity,
@required this.onChanged,
}) : assert(product != null),
assert(quantity != null),
assert(onChanged != null),
super(key: key);
final Product product;
final int quantity;
final ValueChanged<int> onChanged;
@override
Widget build(BuildContext context) {
final ShrineTheme theme = ShrineTheme.of(context);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(product.name, style: theme.featureTitleStyle),
const SizedBox(height: 24.0),
Text(product.description, style: theme.featureStyle),
const SizedBox(height: 16.0),
Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 8.0, right: 88.0),
child: DropdownButtonHideUnderline(
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: const Color(0xFFD9D9D9),
),
),
child: DropdownButton<int>(
items: <int>[0, 1, 2, 3, 4, 5]
.map<DropdownMenuItem<int>>((int value) {
return DropdownMenuItem<int>(
value: value,
child: Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Text('Quantity $value',
style: theme.quantityMenuStyle),
),
);
}).toList(),
value: quantity,
onChanged: onChanged,
),
),
),
),
],
);
}
}
// Vendor name and description
class _VendorItem extends StatelessWidget {
const _VendorItem({Key key, @required this.vendor})
: assert(vendor != null),
super(key: key);
final Vendor vendor;
@override
Widget build(BuildContext context) {
final ShrineTheme theme = ShrineTheme.of(context);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
SizedBox(
height: 24.0,
child: Align(
alignment: Alignment.bottomLeft,
child: Text(vendor.name, style: theme.vendorTitleStyle),
),
),
const SizedBox(height: 16.0),
Text(vendor.description, style: theme.vendorStyle),
],
);
}
}
// Layout the order page's heading: the product's image, the
// title/description/dropdown product item, and the vendor item.
class _HeadingLayout extends MultiChildLayoutDelegate {
_HeadingLayout();
static const String image = 'image';
static const String icon = 'icon';
static const String product = 'product';
static const String vendor = 'vendor';
@override
void performLayout(Size size) {
const double margin = 56.0;
final bool landscape = size.width > size.height;
final double imageWidth =
(landscape ? size.width / 2.0 : size.width) - margin * 2.0;
final BoxConstraints imageConstraints =
BoxConstraints(maxHeight: 224.0, maxWidth: imageWidth);
final Size imageSize = layoutChild(image, imageConstraints);
const double imageY = 0.0;
positionChild(image, const Offset(margin, imageY));
final double productWidth =
landscape ? size.width / 2.0 : size.width - margin;
final BoxConstraints productConstraints =
BoxConstraints(maxWidth: productWidth);
final Size productSize = layoutChild(product, productConstraints);
final double productX = landscape ? size.width / 2.0 : margin;
final double productY = landscape ? 0.0 : imageY + imageSize.height + 16.0;
positionChild(product, Offset(productX, productY));
final Size iconSize = layoutChild(icon, BoxConstraints.loose(size));
positionChild(
icon, Offset(productX - iconSize.width - 16.0, productY + 8.0));
final double vendorWidth = landscape ? size.width - margin : productWidth;
layoutChild(vendor, BoxConstraints(maxWidth: vendorWidth));
final double vendorX = landscape ? margin : productX;
final double vendorY = productY + productSize.height + 16.0;
positionChild(vendor, Offset(vendorX, vendorY));
}
@override
bool shouldRelayout(_HeadingLayout oldDelegate) => true;
}
// Describes a product and vendor in detail, supports specifying
// a order quantity (0-5). Appears at the top of the OrderPage.
class _Heading extends StatelessWidget {
const _Heading({
Key key,
@required this.product,
@required this.quantity,
this.quantityChanged,
}) : assert(product != null),
assert(quantity != null && quantity >= 0 && quantity <= 5),
super(key: key);
final Product product;
final int quantity;
final ValueChanged<int> quantityChanged;
@override
Widget build(BuildContext context) {
final Size screenSize = MediaQuery.of(context).size;
return SizedBox(
height: (screenSize.height - kToolbarHeight) * 1.35,
child: Material(
type: MaterialType.card,
elevation: 0.0,
child: Padding(
padding: const EdgeInsets.only(
left: 16.0, top: 18.0, right: 16.0, bottom: 24.0),
child: CustomMultiChildLayout(
delegate: _HeadingLayout(),
children: <Widget>[
LayoutId(
id: _HeadingLayout.image,
child: Hero(
tag: product.tag,
child: Image.asset(
product.imageAsset,
package: product.imageAssetPackage,
fit: BoxFit.contain,
alignment: Alignment.center,
),
),
),
LayoutId(
id: _HeadingLayout.icon,
child: const Icon(
Icons.info_outline,
size: 24.0,
color: Color(0xFFFFE0E0),
),
),
LayoutId(
id: _HeadingLayout.product,
child: _ProductItem(
product: product,
quantity: quantity,
onChanged: quantityChanged,
),
),
LayoutId(
id: _HeadingLayout.vendor,
child: _VendorItem(vendor: product.vendor),
),
],
),
),
),
);
}
}
class OrderPage extends StatefulWidget {
OrderPage({
Key key,
@required this.order,
@required this.products,
@required this.shoppingCart,
}) : assert(order != null),
assert(products != null && products.isNotEmpty),
assert(shoppingCart != null),
super(key: key);
final Order order;
final List<Product> products;
final Map<Product, Order> shoppingCart;
@override
_OrderPageState createState() => _OrderPageState();
}
// Displays a product's heading above photos of all of the other products
// arranged in two columns. Enables the user to specify a quantity and add an
// order to the shopping cart.
class _OrderPageState extends State<OrderPage> {
GlobalKey<ScaffoldState> scaffoldKey;
@override
void initState() {
super.initState();
scaffoldKey =
GlobalKey<ScaffoldState>(debugLabel: 'Shrine Order ${widget.order}');
}
Order get currentOrder => ShrineOrderRoute.of(context).order;
set currentOrder(Order value) {
ShrineOrderRoute.of(context).order = value;
}
void updateOrder({int quantity, bool inCart}) {
final Order newOrder =
currentOrder.copyWith(quantity: quantity, inCart: inCart);
if (currentOrder != newOrder) {
setState(() {
widget.shoppingCart[newOrder.product] = newOrder;
currentOrder = newOrder;
});
}
}
void showSnackBarMessage(String message) {
scaffoldKey.currentState.showSnackBar(SnackBar(content: Text(message)));
}
@override
Widget build(BuildContext context) {
return ShrinePage(
scaffoldKey: scaffoldKey,
products: widget.products,
shoppingCart: widget.shoppingCart,
floatingActionButton: FloatingActionButton(
onPressed: () {
updateOrder(inCart: true);
final int n = currentOrder.quantity;
final String item = currentOrder.product.name;
showSnackBarMessage(
'There ${n == 1 ? "is one $item item" : "are $n $item items"} in the shopping cart.');
},
backgroundColor: const Color(0xFF16F0F0),
tooltip: 'Add to cart',
child: const Icon(
Icons.add_shopping_cart,
color: Colors.black,
),
),
body: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(
child: _Heading(
product: widget.order.product,
quantity: currentOrder.quantity,
quantityChanged: (int value) {
updateOrder(quantity: value);
},
),
),
SliverSafeArea(
top: false,
minimum: const EdgeInsets.fromLTRB(8.0, 32.0, 8.0, 8.0),
sliver: SliverGrid(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 248.0,
mainAxisSpacing: 8.0,
crossAxisSpacing: 8.0,
),
delegate: SliverChildListDelegate(
widget.products
.where((Product product) => product != widget.order.product)
.map((Product product) {
return Card(
elevation: 1.0,
child: Image.asset(
product.imageAsset,
package: product.imageAssetPackage,
fit: BoxFit.contain,
),
);
}).toList(),
),
),
),
],
),
);
}
}
// Displays a full-screen modal OrderPage.
//
// The order field will be replaced each time the user reconfigures the order.
// When the user backs out of this route the completer's value will be the
// final value of the order field.
class ShrineOrderRoute extends ShrinePageRoute<Order> {
ShrineOrderRoute({
@required this.order,
WidgetBuilder builder,
RouteSettings settings,
}) : assert(order != null),
super(builder: builder, settings: settings);
Order order;
@override
Order get currentResult => order;
static ShrineOrderRoute of(BuildContext context) =>
ModalRoute.of<Order>(context);
}

View File

@@ -0,0 +1,137 @@
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_web/material.dart';
import 'shrine_theme.dart';
import 'shrine_types.dart';
enum ShrineAction { sortByPrice, sortByProduct, emptyCart }
class ShrinePage extends StatefulWidget {
const ShrinePage(
{Key key,
@required this.scaffoldKey,
@required this.body,
this.floatingActionButton,
this.products,
this.shoppingCart})
: assert(body != null),
assert(scaffoldKey != null),
super(key: key);
final GlobalKey<ScaffoldState> scaffoldKey;
final Widget body;
final Widget floatingActionButton;
final List<Product> products;
final Map<Product, Order> shoppingCart;
@override
ShrinePageState createState() => ShrinePageState();
}
/// Defines the Scaffold, AppBar, etc that the demo pages have in common.
class ShrinePageState extends State<ShrinePage> {
double _appBarElevation = 0.0;
bool _handleScrollNotification(ScrollNotification notification) {
final double elevation =
notification.metrics.extentBefore <= 0.0 ? 0.0 : 1.0;
if (elevation != _appBarElevation) {
setState(() {
_appBarElevation = elevation;
});
}
return false;
}
void _showShoppingCart() {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
if (widget.shoppingCart.isEmpty) {
return const Padding(
padding: EdgeInsets.all(24.0),
child: Text('The shopping cart is empty'));
}
return ListView(
padding: kMaterialListPadding,
children: widget.shoppingCart.values.map((Order order) {
return ListTile(
title: Text(order.product.name),
leading: Text('${order.quantity}'),
subtitle: Text(order.product.vendor.name));
}).toList(),
);
});
}
void _sortByPrice() {
widget.products.sort((Product a, Product b) => a.price.compareTo(b.price));
}
void _sortByProduct() {
widget.products.sort((Product a, Product b) => a.name.compareTo(b.name));
}
void _emptyCart() {
widget.shoppingCart.clear();
widget.scaffoldKey.currentState
.showSnackBar(const SnackBar(content: Text('Shopping cart is empty')));
}
@override
Widget build(BuildContext context) {
final ShrineTheme theme = ShrineTheme.of(context);
return Scaffold(
key: widget.scaffoldKey,
appBar: AppBar(
elevation: _appBarElevation,
backgroundColor: theme.appBarBackgroundColor,
iconTheme: Theme.of(context).iconTheme,
brightness: Brightness.light,
flexibleSpace: Container(
decoration: BoxDecoration(
border:
Border(bottom: BorderSide(color: theme.dividerColor)))),
title:
Text('SHRINE', style: ShrineTheme.of(context).appBarTitleStyle),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: const Icon(Icons.shopping_cart),
tooltip: 'Shopping cart',
onPressed: _showShoppingCart),
PopupMenuButton<ShrineAction>(
itemBuilder: (BuildContext context) =>
<PopupMenuItem<ShrineAction>>[
const PopupMenuItem<ShrineAction>(
value: ShrineAction.sortByPrice,
child: Text('Sort by price')),
const PopupMenuItem<ShrineAction>(
value: ShrineAction.sortByProduct,
child: Text('Sort by product')),
const PopupMenuItem<ShrineAction>(
value: ShrineAction.emptyCart,
child: Text('Empty shopping cart'))
],
onSelected: (ShrineAction action) {
switch (action) {
case ShrineAction.sortByPrice:
setState(_sortByPrice);
break;
case ShrineAction.sortByProduct:
setState(_sortByProduct);
break;
case ShrineAction.emptyCart:
setState(_emptyCart);
break;
}
})
]),
floatingActionButton: widget.floatingActionButton,
body: NotificationListener<ScrollNotification>(
onNotification: _handleScrollNotification, child: widget.body));
}
}

View File

@@ -0,0 +1,76 @@
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_web/material.dart';
class ShrineStyle extends TextStyle {
const ShrineStyle.roboto(double size, FontWeight weight, Color color)
: super(
inherit: false,
color: color,
fontSize: size,
fontWeight: weight,
textBaseline: TextBaseline.alphabetic);
const ShrineStyle.abrilFatface(double size, FontWeight weight, Color color)
: super(
inherit: false,
color: color,
fontFamily: 'AbrilFatface',
fontSize: size,
fontWeight: weight,
textBaseline: TextBaseline.alphabetic);
}
TextStyle robotoRegular12(Color color) =>
ShrineStyle.roboto(12.0, FontWeight.w500, color);
TextStyle robotoLight12(Color color) =>
ShrineStyle.roboto(12.0, FontWeight.w300, color);
TextStyle robotoRegular14(Color color) =>
ShrineStyle.roboto(14.0, FontWeight.w500, color);
TextStyle robotoMedium14(Color color) =>
ShrineStyle.roboto(14.0, FontWeight.w600, color);
TextStyle robotoLight14(Color color) =>
ShrineStyle.roboto(14.0, FontWeight.w300, color);
TextStyle robotoRegular16(Color color) =>
ShrineStyle.roboto(16.0, FontWeight.w500, color);
TextStyle robotoRegular20(Color color) =>
ShrineStyle.roboto(20.0, FontWeight.w500, color);
TextStyle abrilFatfaceRegular24(Color color) =>
ShrineStyle.abrilFatface(24.0, FontWeight.w500, color);
TextStyle abrilFatfaceRegular34(Color color) =>
ShrineStyle.abrilFatface(34.0, FontWeight.w500, color);
/// The TextStyles and Colors used for titles, labels, and descriptions. This
/// InheritedWidget is shared by all of the routes and widgets created for
/// the Shrine app.
class ShrineTheme extends InheritedWidget {
ShrineTheme({Key key, @required Widget child})
: assert(child != null),
super(key: key, child: child);
final Color cardBackgroundColor = Colors.white;
final Color appBarBackgroundColor = Colors.white;
final Color dividerColor = const Color(0xFFD9D9D9);
final Color priceHighlightColor = const Color(0xFFFFE0E0);
final TextStyle appBarTitleStyle = robotoRegular20(Colors.black87);
final TextStyle vendorItemStyle = robotoRegular12(const Color(0xFF81959D));
final TextStyle priceStyle = robotoRegular14(Colors.black87);
final TextStyle featureTitleStyle =
abrilFatfaceRegular34(const Color(0xFF0A3142));
final TextStyle featurePriceStyle = robotoRegular16(Colors.black87);
final TextStyle featureStyle = robotoLight14(Colors.black54);
final TextStyle orderTitleStyle = abrilFatfaceRegular24(Colors.black87);
final TextStyle orderStyle = robotoLight14(Colors.black54);
final TextStyle vendorTitleStyle = robotoMedium14(Colors.black87);
final TextStyle vendorStyle = robotoLight14(Colors.black54);
final TextStyle quantityMenuStyle = robotoLight14(Colors.black54);
static ShrineTheme of(BuildContext context) =>
context.inheritFromWidgetOfExactType(ShrineTheme);
@override
bool updateShouldNotify(ShrineTheme oldWidget) => false;
}

View File

@@ -0,0 +1,100 @@
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_web/foundation.dart';
import 'package:flutter_web_ui/ui.dart' show hashValues;
class Vendor {
const Vendor({
this.name,
this.description,
this.avatarAsset,
this.avatarAssetPackage,
});
final String name;
final String description;
final String avatarAsset;
final String avatarAssetPackage;
bool isValid() {
return name != null && description != null && avatarAsset != null;
}
@override
String toString() => 'Vendor($name)';
}
class Product {
const Product(
{this.name,
this.description,
this.featureTitle,
this.featureDescription,
this.imageAsset,
this.imageAssetPackage,
this.categories,
this.price,
this.vendor});
final String name;
final String description;
final String featureTitle;
final String featureDescription;
final String imageAsset;
final String imageAssetPackage;
final List<String> categories;
final double price;
final Vendor vendor;
String get tag => name; // Unique value for Heroes
String get priceString => '\$${price.floor()}';
bool isValid() {
return name != null &&
description != null &&
imageAsset != null &&
categories != null &&
categories.isNotEmpty &&
price != null &&
vendor.isValid();
}
@override
String toString() => 'Product($name)';
}
class Order {
Order({@required this.product, this.quantity = 1, this.inCart = false})
: assert(product != null),
assert(quantity != null && quantity >= 0),
assert(inCart != null);
final Product product;
final int quantity;
final bool inCart;
Order copyWith({Product product, int quantity, bool inCart}) {
return Order(
product: product ?? this.product,
quantity: quantity ?? this.quantity,
inCart: inCart ?? this.inCart);
}
@override
bool operator ==(dynamic other) {
if (identical(this, other)) return true;
if (other.runtimeType != runtimeType) return false;
final Order typedOther = other;
return product == typedOther.product &&
quantity == typedOther.quantity &&
inCart == typedOther.inCart;
}
@override
int get hashCode => hashValues(product, quantity, inCart);
@override
String toString() => 'Order($product, quantity=$quantity, inCart=$inCart)';
}