mirror of
https://github.com/flutter/samples.git
synced 2025-11-12 07:48:55 +00:00
[Gallery] Fix directory structure (#312)
This commit is contained in:
67
gallery/lib/studies/crane/app.dart
Normal file
67
gallery/lib/studies/crane/app.dart
Normal file
@@ -0,0 +1,67 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/studies/crane/backdrop.dart';
|
||||
import 'package:gallery/studies/crane/eat_form.dart';
|
||||
import 'package:gallery/studies/crane/fly_form.dart';
|
||||
import 'package:gallery/studies/crane/sleep_form.dart';
|
||||
import 'package:gallery/studies/crane/theme.dart';
|
||||
|
||||
class CraneApp extends StatefulWidget {
|
||||
const CraneApp({Key key, this.navigatorKey}) : super(key: key);
|
||||
|
||||
final GlobalKey<NavigatorState> navigatorKey;
|
||||
|
||||
@override
|
||||
_CraneAppState createState() => _CraneAppState();
|
||||
}
|
||||
|
||||
class _CraneAppState extends State<CraneApp> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
navigatorKey: widget.navigatorKey,
|
||||
title: 'Crane',
|
||||
debugShowCheckedModeBanner: false,
|
||||
localizationsDelegates: GalleryLocalizations.localizationsDelegates,
|
||||
supportedLocales: GalleryLocalizations.supportedLocales,
|
||||
locale: GalleryOptions.of(context).locale,
|
||||
initialRoute: '/',
|
||||
onGenerateRoute: _getRoute,
|
||||
theme: craneTheme.copyWith(
|
||||
platform: GalleryOptions.of(context).platform,
|
||||
),
|
||||
darkTheme: craneTheme.copyWith(
|
||||
platform: GalleryOptions.of(context).platform,
|
||||
),
|
||||
home: ApplyTextOptions(
|
||||
child: Backdrop(
|
||||
frontLayer: Container(),
|
||||
backLayerItems: [
|
||||
FlyForm(index: 0),
|
||||
SleepForm(index: 1),
|
||||
EatForm(index: 2),
|
||||
],
|
||||
frontTitle: Text('CRANE'),
|
||||
backTitle: Text('MENU'),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Route<dynamic> _getRoute(RouteSettings settings) {
|
||||
if (settings.name != '/') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return MaterialPageRoute<void>(
|
||||
settings: settings,
|
||||
builder: (context) => CraneApp(),
|
||||
fullscreenDialog: true,
|
||||
);
|
||||
}
|
||||
281
gallery/lib/studies/crane/backdrop.dart
Normal file
281
gallery/lib/studies/crane/backdrop.dart
Normal file
@@ -0,0 +1,281 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/studies/crane/border_tab_indicator.dart';
|
||||
import 'package:gallery/studies/crane/backlayer.dart';
|
||||
import 'package:gallery/studies/crane/colors.dart';
|
||||
import 'package:gallery/studies/crane/header_form.dart';
|
||||
import 'package:gallery/studies/crane/item_cards.dart';
|
||||
|
||||
class _FrontLayer extends StatelessWidget {
|
||||
const _FrontLayer({
|
||||
Key key,
|
||||
this.title,
|
||||
this.index,
|
||||
}) : super(key: key);
|
||||
|
||||
final String title;
|
||||
final int index;
|
||||
|
||||
static const frontLayerBorderRadius = 16.0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
final isSmallDesktop = isDisplaySmallDesktop(context);
|
||||
|
||||
return DefaultFocusTraversal(
|
||||
policy: ReadingOrderTraversalPolicy(),
|
||||
child: PhysicalShape(
|
||||
elevation: 16,
|
||||
color: cranePrimaryWhite,
|
||||
clipper: ShapeBorderClipper(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: Radius.circular(frontLayerBorderRadius),
|
||||
topRight: Radius.circular(frontLayerBorderRadius),
|
||||
),
|
||||
),
|
||||
),
|
||||
child: ListView(
|
||||
padding: isDesktop
|
||||
? EdgeInsets.symmetric(
|
||||
horizontal:
|
||||
isSmallDesktop ? appPaddingSmall : appPaddingLarge,
|
||||
vertical: 22)
|
||||
: EdgeInsets.all(20),
|
||||
children: [
|
||||
Text(title, style: Theme.of(context).textTheme.subtitle),
|
||||
SizedBox(height: 20),
|
||||
ItemCards(index: index),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 List<BackLayerItem> backLayerItems;
|
||||
final Widget frontTitle;
|
||||
final Widget backTitle;
|
||||
|
||||
const Backdrop({
|
||||
@required this.frontLayer,
|
||||
@required this.backLayerItems,
|
||||
@required this.frontTitle,
|
||||
@required this.backTitle,
|
||||
}) : assert(frontLayer != null),
|
||||
assert(backLayerItems != null),
|
||||
assert(frontTitle != null),
|
||||
assert(backTitle != null);
|
||||
|
||||
@override
|
||||
_BackdropState createState() => _BackdropState();
|
||||
}
|
||||
|
||||
class _BackdropState extends State<Backdrop> with TickerProviderStateMixin {
|
||||
TabController _tabController;
|
||||
Animation<Offset> _flyLayerOffset;
|
||||
Animation<Offset> _sleepLayerOffset;
|
||||
Animation<Offset> _eatLayerOffset;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tabController = TabController(length: 3, vsync: this);
|
||||
|
||||
// Offsets to create a gap between front layers.
|
||||
_flyLayerOffset = _tabController.animation
|
||||
.drive(Tween<Offset>(begin: Offset(0, 0), end: Offset(-0.05, 0)));
|
||||
|
||||
_sleepLayerOffset = _tabController.animation
|
||||
.drive(Tween<Offset>(begin: Offset(0.05, 0), end: Offset(0, 0)));
|
||||
|
||||
_eatLayerOffset = _tabController.animation
|
||||
.drive(Tween<Offset>(begin: Offset(0.10, 0), end: Offset(0.05, 0)));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_tabController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _handleTabs(int tabIndex) {
|
||||
_tabController.animateTo(tabIndex,
|
||||
duration: const Duration(milliseconds: 300));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
final textScaleFactor = GalleryOptions.of(context).textScaleFactor(context);
|
||||
|
||||
return Material(
|
||||
color: cranePurple800,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(top: 12),
|
||||
child: DefaultFocusTraversal(
|
||||
policy: ReadingOrderTraversalPolicy(),
|
||||
child: Scaffold(
|
||||
backgroundColor: cranePurple800,
|
||||
appBar: AppBar(
|
||||
brightness: Brightness.dark,
|
||||
elevation: 0,
|
||||
titleSpacing: 0,
|
||||
flexibleSpace: CraneAppBar(
|
||||
tabController: _tabController,
|
||||
tabHandler: _handleTabs,
|
||||
),
|
||||
),
|
||||
body: FocusScope(
|
||||
child: Stack(
|
||||
children: [
|
||||
BackLayer(
|
||||
tabController: _tabController,
|
||||
backLayerItems: widget.backLayerItems,
|
||||
),
|
||||
Container(
|
||||
margin: EdgeInsets.only(
|
||||
top: isDesktop
|
||||
? (isDisplaySmallDesktop(context)
|
||||
? textFieldHeight * 2
|
||||
: textFieldHeight) +
|
||||
20 * textScaleFactor / 2
|
||||
: 175 + 140 * textScaleFactor / 2,
|
||||
),
|
||||
child: TabBarView(
|
||||
physics: isDesktop
|
||||
? NeverScrollableScrollPhysics()
|
||||
: null, // use default TabBarView physics
|
||||
controller: _tabController,
|
||||
children: [
|
||||
SlideTransition(
|
||||
position: _flyLayerOffset,
|
||||
child: _FrontLayer(
|
||||
title: GalleryLocalizations.of(context)
|
||||
.craneFlySubhead,
|
||||
index: 0,
|
||||
),
|
||||
),
|
||||
SlideTransition(
|
||||
position: _sleepLayerOffset,
|
||||
child: _FrontLayer(
|
||||
title: GalleryLocalizations.of(context)
|
||||
.craneSleepSubhead,
|
||||
index: 1,
|
||||
),
|
||||
),
|
||||
SlideTransition(
|
||||
position: _eatLayerOffset,
|
||||
child: _FrontLayer(
|
||||
title: GalleryLocalizations.of(context)
|
||||
.craneEatSubhead,
|
||||
index: 2,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CraneAppBar extends StatefulWidget {
|
||||
final Function(int) tabHandler;
|
||||
final TabController tabController;
|
||||
|
||||
const CraneAppBar({Key key, this.tabHandler, this.tabController})
|
||||
: super(key: key);
|
||||
|
||||
@override
|
||||
_CraneAppBarState createState() => _CraneAppBarState();
|
||||
}
|
||||
|
||||
class _CraneAppBarState extends State<CraneAppBar> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
final isSmallDesktop = isDisplaySmallDesktop(context);
|
||||
final textScaleFactor = GalleryOptions.of(context).textScaleFactor(context);
|
||||
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal:
|
||||
isDesktop && !isSmallDesktop ? appPaddingLarge : appPaddingSmall,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
ExcludeSemantics(
|
||||
child: Image.asset(
|
||||
'assets/crane/logo/logo.png',
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(start: 24),
|
||||
child: Theme(
|
||||
data: Theme.of(context).copyWith(
|
||||
splashColor: Colors.transparent,
|
||||
),
|
||||
child: TabBar(
|
||||
indicator: BorderTabIndicator(
|
||||
indicatorHeight: isDesktop ? 28 : 32,
|
||||
textScaleFactor: textScaleFactor,
|
||||
),
|
||||
controller: widget.tabController,
|
||||
labelPadding: isDesktop
|
||||
? const EdgeInsets.symmetric(horizontal: 32)
|
||||
: EdgeInsets.zero,
|
||||
isScrollable: isDesktop, // left-align tabs on desktop
|
||||
labelStyle: Theme.of(context).textTheme.button,
|
||||
labelColor: cranePrimaryWhite,
|
||||
unselectedLabelColor: cranePrimaryWhite.withOpacity(.6),
|
||||
onTap: (index) => widget.tabController.animateTo(
|
||||
index,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
),
|
||||
tabs: [
|
||||
Tab(text: GalleryLocalizations.of(context).craneFly),
|
||||
Tab(text: GalleryLocalizations.of(context).craneSleep),
|
||||
Tab(text: GalleryLocalizations.of(context).craneEat),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
49
gallery/lib/studies/crane/backlayer.dart
Normal file
49
gallery/lib/studies/crane/backlayer.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
abstract class BackLayerItem extends StatefulWidget {
|
||||
final int index;
|
||||
|
||||
BackLayerItem({Key key, this.index}) : super(key: key);
|
||||
}
|
||||
|
||||
class BackLayer extends StatefulWidget {
|
||||
final List<BackLayerItem> backLayerItems;
|
||||
final TabController tabController;
|
||||
|
||||
const BackLayer({Key key, this.backLayerItems, this.tabController})
|
||||
: super(key: key);
|
||||
|
||||
@override
|
||||
_BackLayerState createState() => _BackLayerState();
|
||||
}
|
||||
|
||||
class _BackLayerState extends State<BackLayer> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.tabController.addListener(() => setState(() {}));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final tabIndex = widget.tabController.index;
|
||||
return DefaultFocusTraversal(
|
||||
policy: WidgetOrderFocusTraversalPolicy(),
|
||||
child: IndexedStack(
|
||||
index: tabIndex,
|
||||
children: [
|
||||
for (BackLayerItem backLayerItem in widget.backLayerItems)
|
||||
Focus(
|
||||
canRequestFocus: backLayerItem.index == tabIndex,
|
||||
debugLabel: 'backLayerItem: $backLayerItem',
|
||||
child: backLayerItem,
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
52
gallery/lib/studies/crane/border_tab_indicator.dart
Normal file
52
gallery/lib/studies/crane/border_tab_indicator.dart
Normal file
@@ -0,0 +1,52 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
class BorderTabIndicator extends Decoration {
|
||||
BorderTabIndicator({this.indicatorHeight, this.textScaleFactor}) : super();
|
||||
|
||||
final double indicatorHeight;
|
||||
final double textScaleFactor;
|
||||
|
||||
@override
|
||||
_BorderPainter createBoxPainter([VoidCallback onChanged]) {
|
||||
return _BorderPainter(
|
||||
this, indicatorHeight, this.textScaleFactor, onChanged);
|
||||
}
|
||||
}
|
||||
|
||||
class _BorderPainter extends BoxPainter {
|
||||
_BorderPainter(
|
||||
this.decoration,
|
||||
this.indicatorHeight,
|
||||
this.textScaleFactor,
|
||||
VoidCallback onChanged,
|
||||
) : assert(decoration != null),
|
||||
assert(indicatorHeight >= 0),
|
||||
super(onChanged);
|
||||
|
||||
final BorderTabIndicator decoration;
|
||||
final double indicatorHeight;
|
||||
final double textScaleFactor;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
|
||||
assert(configuration != null);
|
||||
assert(configuration.size != null);
|
||||
final horizontalInset = 16 - 4 * textScaleFactor;
|
||||
final rect = Offset(offset.dx + horizontalInset,
|
||||
(configuration.size.height / 2) - indicatorHeight / 2 - 1) &
|
||||
Size(configuration.size.width - 2 * horizontalInset, indicatorHeight);
|
||||
final paint = Paint();
|
||||
paint.color = Colors.white;
|
||||
paint.style = PaintingStyle.stroke;
|
||||
paint.strokeWidth = 2;
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(rect, Radius.circular(56)),
|
||||
paint,
|
||||
);
|
||||
}
|
||||
}
|
||||
20
gallery/lib/studies/crane/colors.dart
Normal file
20
gallery/lib/studies/crane/colors.dart
Normal file
@@ -0,0 +1,20 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
const cranePurple700 = Color(0xFF720D5D);
|
||||
const cranePurple800 = Color(0xFF5D1049);
|
||||
const cranePurple900 = Color(0xFF4E0D3A);
|
||||
|
||||
const craneRed700 = Color(0xFFE30425);
|
||||
|
||||
const craneWhite60 = Color(0x99FFFFFF);
|
||||
const cranePrimaryWhite = Color(0xFFFFFFFF);
|
||||
const craneErrorOrange = Color(0xFFFF9100);
|
||||
|
||||
const craneAlpha = Color(0x00FFFFFF);
|
||||
|
||||
const craneGrey = Color(0xFF747474);
|
||||
const craneBlack = Color(0XFF1E252D);
|
||||
51
gallery/lib/studies/crane/eat_form.dart
Normal file
51
gallery/lib/studies/crane/eat_form.dart
Normal file
@@ -0,0 +1,51 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/studies/crane/backlayer.dart';
|
||||
import 'package:gallery/studies/crane/header_form.dart';
|
||||
|
||||
class EatForm extends BackLayerItem {
|
||||
EatForm({int index}) : super(index: index);
|
||||
|
||||
@override
|
||||
_EatFormState createState() => _EatFormState();
|
||||
}
|
||||
|
||||
class _EatFormState extends State<EatForm> {
|
||||
final dinerController = TextEditingController();
|
||||
final dateController = TextEditingController();
|
||||
final timeController = TextEditingController();
|
||||
final locationController = TextEditingController();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return HeaderForm(
|
||||
fields: <HeaderFormField>[
|
||||
HeaderFormField(
|
||||
iconData: Icons.person,
|
||||
title: GalleryLocalizations.of(context).craneFormDiners,
|
||||
textController: dinerController,
|
||||
),
|
||||
HeaderFormField(
|
||||
iconData: Icons.date_range,
|
||||
title: GalleryLocalizations.of(context).craneFormDate,
|
||||
textController: dateController,
|
||||
),
|
||||
HeaderFormField(
|
||||
iconData: Icons.access_time,
|
||||
title: GalleryLocalizations.of(context).craneFormTime,
|
||||
textController: timeController,
|
||||
),
|
||||
HeaderFormField(
|
||||
iconData: Icons.restaurant_menu,
|
||||
title: GalleryLocalizations.of(context).craneFormLocation,
|
||||
textController: locationController,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
51
gallery/lib/studies/crane/fly_form.dart
Normal file
51
gallery/lib/studies/crane/fly_form.dart
Normal file
@@ -0,0 +1,51 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/studies/crane/backlayer.dart';
|
||||
import 'package:gallery/studies/crane/header_form.dart';
|
||||
|
||||
class FlyForm extends BackLayerItem {
|
||||
FlyForm({int index}) : super(index: index);
|
||||
|
||||
@override
|
||||
_FlyFormState createState() => _FlyFormState();
|
||||
}
|
||||
|
||||
class _FlyFormState extends State<FlyForm> {
|
||||
final travelerController = TextEditingController();
|
||||
final countryDestinationController = TextEditingController();
|
||||
final destinationController = TextEditingController();
|
||||
final dateController = TextEditingController();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return HeaderForm(
|
||||
fields: <HeaderFormField>[
|
||||
HeaderFormField(
|
||||
iconData: Icons.person,
|
||||
title: GalleryLocalizations.of(context).craneFormTravelers,
|
||||
textController: travelerController,
|
||||
),
|
||||
HeaderFormField(
|
||||
iconData: Icons.place,
|
||||
title: GalleryLocalizations.of(context).craneFormOrigin,
|
||||
textController: countryDestinationController,
|
||||
),
|
||||
HeaderFormField(
|
||||
iconData: Icons.airplanemode_active,
|
||||
title: GalleryLocalizations.of(context).craneFormDestination,
|
||||
textController: destinationController,
|
||||
),
|
||||
HeaderFormField(
|
||||
iconData: Icons.date_range,
|
||||
title: GalleryLocalizations.of(context).craneFormDates,
|
||||
textController: dateController,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
102
gallery/lib/studies/crane/header_form.dart
Normal file
102
gallery/lib/studies/crane/header_form.dart
Normal file
@@ -0,0 +1,102 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/studies/crane/colors.dart';
|
||||
|
||||
const textFieldHeight = 60.0;
|
||||
const appPaddingLarge = 120.0;
|
||||
const appPaddingSmall = 24.0;
|
||||
|
||||
class HeaderFormField {
|
||||
final IconData iconData;
|
||||
final String title;
|
||||
final TextEditingController textController;
|
||||
|
||||
const HeaderFormField({this.iconData, this.title, this.textController});
|
||||
}
|
||||
|
||||
class HeaderForm extends StatelessWidget {
|
||||
final List<HeaderFormField> fields;
|
||||
|
||||
const HeaderForm({Key key, this.fields}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
final isSmallDesktop = isDisplaySmallDesktop(context);
|
||||
return Padding(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal:
|
||||
isDesktop && !isSmallDesktop ? appPaddingLarge : appPaddingSmall,
|
||||
),
|
||||
child: isDesktop
|
||||
? LayoutBuilder(builder: (context, constraints) {
|
||||
var crossAxisCount = isSmallDesktop ? 2 : 4;
|
||||
if (fields.length < crossAxisCount) {
|
||||
crossAxisCount = fields.length;
|
||||
}
|
||||
final itemWidth = constraints.maxWidth / crossAxisCount;
|
||||
return GridView.count(
|
||||
crossAxisCount: crossAxisCount,
|
||||
childAspectRatio: itemWidth / textFieldHeight,
|
||||
physics: NeverScrollableScrollPhysics(),
|
||||
children: [
|
||||
for (final field in fields)
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 16),
|
||||
child: _HeaderTextField(field: field),
|
||||
)
|
||||
],
|
||||
);
|
||||
})
|
||||
: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final field in fields)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: _HeaderTextField(field: field),
|
||||
)
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HeaderTextField extends StatelessWidget {
|
||||
final HeaderFormField field;
|
||||
|
||||
_HeaderTextField({this.field});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TextField(
|
||||
controller: field.textController,
|
||||
cursorColor: Theme.of(context).colorScheme.secondary,
|
||||
style: Theme.of(context).textTheme.body2.copyWith(color: Colors.white),
|
||||
onTap: () {},
|
||||
decoration: InputDecoration(
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
borderSide: BorderSide(
|
||||
width: 0,
|
||||
style: BorderStyle.none,
|
||||
),
|
||||
),
|
||||
contentPadding: EdgeInsets.all(16),
|
||||
fillColor: cranePurple700,
|
||||
filled: true,
|
||||
hintText: field.title,
|
||||
hasFloatingPlaceholder: false,
|
||||
prefixIcon: Icon(
|
||||
field.iconData,
|
||||
size: 24,
|
||||
color: Theme.of(context).iconTheme.color,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
179
gallery/lib/studies/crane/item_cards.dart
Normal file
179
gallery/lib/studies/crane/item_cards.dart
Normal file
@@ -0,0 +1,179 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/layout/highlight_focus.dart';
|
||||
import 'package:gallery/studies/crane/model/data.dart';
|
||||
import 'package:gallery/studies/crane/model/destination.dart';
|
||||
|
||||
class ItemCards extends StatefulWidget {
|
||||
final int index;
|
||||
|
||||
const ItemCards({Key key, this.index}) : super(key: key);
|
||||
|
||||
static const totalColumns = 4;
|
||||
|
||||
@override
|
||||
_ItemCardsState createState() => _ItemCardsState();
|
||||
}
|
||||
|
||||
class _ItemCardsState extends State<ItemCards> {
|
||||
List<Destination> flyDestinations;
|
||||
List<Destination> sleepDestinations;
|
||||
List<Destination> eatDestinations;
|
||||
|
||||
List<Widget> _buildDestinationCards({int listIndex}) {
|
||||
final List<Destination> destinations = [
|
||||
if (listIndex == 0) ...flyDestinations,
|
||||
if (listIndex == 1) ...sleepDestinations,
|
||||
if (listIndex == 2) ...eatDestinations,
|
||||
];
|
||||
|
||||
return destinations
|
||||
.map(
|
||||
(d) => HighlightFocus(
|
||||
debugLabel: 'DestinationCard: ${d.destination}',
|
||||
highlightColor: Colors.red.withOpacity(0.5),
|
||||
onPressed: () {},
|
||||
child: RepaintBoundary(
|
||||
child: _DestinationCard(destination: d),
|
||||
),
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
// We use didChangeDependencies because the initialization involves an
|
||||
// InheritedWidget (for localization). However, we don't need to get
|
||||
// destinations again when, say, resizing the window.
|
||||
if (flyDestinations == null) {
|
||||
flyDestinations = getFlyDestinations(context);
|
||||
sleepDestinations = getSleepDestinations(context);
|
||||
eatDestinations = getEatDestinations(context);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
final List<Widget> destinationCards =
|
||||
_buildDestinationCards(listIndex: widget.index);
|
||||
|
||||
if (isDesktop) {
|
||||
var columns = List<List<Widget>>(ItemCards.totalColumns);
|
||||
for (var i = 0; i < destinationCards.length; i++) {
|
||||
final col = i % ItemCards.totalColumns;
|
||||
|
||||
if (columns[col] == null) {
|
||||
columns[col] = List<Widget>();
|
||||
}
|
||||
|
||||
columns[col].add(
|
||||
// TODO: determine why this is isn't always respected
|
||||
Semantics(
|
||||
sortKey: OrdinalSortKey(i.toDouble(), name: 'destination'),
|
||||
child: destinationCards[i],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
for (var column in columns)
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 16),
|
||||
child: Column(
|
||||
children: column,
|
||||
),
|
||||
),
|
||||
)
|
||||
],
|
||||
);
|
||||
} else {
|
||||
return Column(children: destinationCards);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _DestinationCard extends StatelessWidget {
|
||||
_DestinationCard({this.destination}) : assert(destination != null);
|
||||
final Destination destination;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final imageWidget = Semantics(
|
||||
child: ExcludeSemantics(
|
||||
child: Image.asset(
|
||||
destination.assetName,
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
),
|
||||
label: destination.assetSemanticLabel,
|
||||
);
|
||||
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
|
||||
if (isDesktop) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 40),
|
||||
child: Semantics(
|
||||
container: true,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: const BorderRadius.all(Radius.circular(4)),
|
||||
child: imageWidget,
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 20, bottom: 10),
|
||||
child: Text(
|
||||
destination.destination,
|
||||
style: textTheme.subhead,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
destination.subtitle(context),
|
||||
semanticsLabel: destination.subtitleSemantics(context),
|
||||
style: textTheme.subtitle,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ListTile(
|
||||
contentPadding: EdgeInsetsDirectional.only(end: 8),
|
||||
leading: ClipRRect(
|
||||
borderRadius: const BorderRadius.all(Radius.circular(4)),
|
||||
child: SizedBox(
|
||||
height: 60,
|
||||
width: 60,
|
||||
child: imageWidget,
|
||||
),
|
||||
),
|
||||
title: Text(destination.destination, style: textTheme.subhead),
|
||||
subtitle: Text(
|
||||
destination.subtitle(context),
|
||||
semanticsLabel: destination.subtitleSemantics(context),
|
||||
style: textTheme.subtitle,
|
||||
),
|
||||
),
|
||||
Divider(),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
294
gallery/lib/studies/crane/model/data.dart
Normal file
294
gallery/lib/studies/crane/model/data.dart
Normal file
@@ -0,0 +1,294 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/studies/crane/model/destination.dart';
|
||||
|
||||
// TODO: localize durations
|
||||
|
||||
List<FlyDestination> getFlyDestinations(BuildContext context) =>
|
||||
<FlyDestination>[
|
||||
FlyDestination(
|
||||
id: 0,
|
||||
destination: GalleryLocalizations.of(context).craneFly0,
|
||||
stops: 1,
|
||||
duration: Duration(hours: 6, minutes: 15),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly0SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 1,
|
||||
destination: GalleryLocalizations.of(context).craneFly1,
|
||||
stops: 0,
|
||||
duration: Duration(hours: 13, minutes: 30),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly1SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 2,
|
||||
destination: GalleryLocalizations.of(context).craneFly2,
|
||||
stops: 0,
|
||||
duration: Duration(hours: 5, minutes: 16),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly2SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 3,
|
||||
destination: GalleryLocalizations.of(context).craneFly3,
|
||||
stops: 2,
|
||||
duration: Duration(hours: 19, minutes: 40),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly3SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 4,
|
||||
destination: GalleryLocalizations.of(context).craneFly4,
|
||||
stops: 0,
|
||||
duration: Duration(hours: 8, minutes: 24),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly4SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 5,
|
||||
destination: GalleryLocalizations.of(context).craneFly5,
|
||||
stops: 1,
|
||||
duration: Duration(hours: 14, minutes: 12),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly5SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 6,
|
||||
destination: GalleryLocalizations.of(context).craneFly6,
|
||||
stops: 0,
|
||||
duration: Duration(hours: 5, minutes: 24),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly6SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 7,
|
||||
destination: GalleryLocalizations.of(context).craneFly7,
|
||||
stops: 1,
|
||||
duration: Duration(hours: 5, minutes: 43),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly7SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 8,
|
||||
destination: GalleryLocalizations.of(context).craneFly8,
|
||||
stops: 0,
|
||||
duration: Duration(hours: 8, minutes: 25),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly8SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 9,
|
||||
destination: GalleryLocalizations.of(context).craneFly9,
|
||||
stops: 1,
|
||||
duration: Duration(hours: 15, minutes: 52),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly9SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 10,
|
||||
destination: GalleryLocalizations.of(context).craneFly10,
|
||||
stops: 0,
|
||||
duration: Duration(hours: 5, minutes: 57),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly10SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 11,
|
||||
destination: GalleryLocalizations.of(context).craneFly11,
|
||||
stops: 1,
|
||||
duration: Duration(hours: 13, minutes: 24),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly11SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 12,
|
||||
destination: GalleryLocalizations.of(context).craneFly12,
|
||||
stops: 2,
|
||||
duration: Duration(hours: 10, minutes: 20),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly12SemanticLabel,
|
||||
),
|
||||
FlyDestination(
|
||||
id: 13,
|
||||
destination: GalleryLocalizations.of(context).craneFly13,
|
||||
stops: 0,
|
||||
duration: Duration(hours: 7, minutes: 15),
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneFly13SemanticLabel,
|
||||
),
|
||||
];
|
||||
|
||||
List<SleepDestination> getSleepDestinations(BuildContext context) =>
|
||||
<SleepDestination>[
|
||||
SleepDestination(
|
||||
id: 0,
|
||||
destination: GalleryLocalizations.of(context).craneSleep0,
|
||||
total: 2241,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep0SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 1,
|
||||
destination: GalleryLocalizations.of(context).craneSleep1,
|
||||
total: 876,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep1SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 2,
|
||||
destination: GalleryLocalizations.of(context).craneSleep2,
|
||||
total: 1286,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep2SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 3,
|
||||
destination: GalleryLocalizations.of(context).craneSleep3,
|
||||
total: 496,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep3SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 4,
|
||||
destination: GalleryLocalizations.of(context).craneSleep4,
|
||||
total: 390,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep4SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 5,
|
||||
destination: GalleryLocalizations.of(context).craneSleep5,
|
||||
total: 876,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep5SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 6,
|
||||
destination: GalleryLocalizations.of(context).craneSleep6,
|
||||
total: 989,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep6SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 7,
|
||||
destination: GalleryLocalizations.of(context).craneSleep7,
|
||||
total: 306,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep7SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 8,
|
||||
destination: GalleryLocalizations.of(context).craneSleep8,
|
||||
total: 385,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep8SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 9,
|
||||
destination: GalleryLocalizations.of(context).craneSleep9,
|
||||
total: 989,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep9SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 10,
|
||||
destination: GalleryLocalizations.of(context).craneSleep10,
|
||||
total: 1380,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep10SemanticLabel,
|
||||
),
|
||||
SleepDestination(
|
||||
id: 11,
|
||||
destination: GalleryLocalizations.of(context).craneSleep11,
|
||||
total: 1109,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneSleep11SemanticLabel,
|
||||
),
|
||||
];
|
||||
|
||||
List<EatDestination> getEatDestinations(BuildContext context) =>
|
||||
<EatDestination>[
|
||||
EatDestination(
|
||||
id: 0,
|
||||
destination: GalleryLocalizations.of(context).craneEat0,
|
||||
total: 354,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat0SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 1,
|
||||
destination: GalleryLocalizations.of(context).craneEat1,
|
||||
total: 623,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat1SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 2,
|
||||
destination: GalleryLocalizations.of(context).craneEat2,
|
||||
total: 124,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat2SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 3,
|
||||
destination: GalleryLocalizations.of(context).craneEat3,
|
||||
total: 495,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat3SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 4,
|
||||
destination: GalleryLocalizations.of(context).craneEat4,
|
||||
total: 683,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat4SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 5,
|
||||
destination: GalleryLocalizations.of(context).craneEat5,
|
||||
total: 786,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat5SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 6,
|
||||
destination: GalleryLocalizations.of(context).craneEat6,
|
||||
total: 323,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat6SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 7,
|
||||
destination: GalleryLocalizations.of(context).craneEat7,
|
||||
total: 285,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat7SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 8,
|
||||
destination: GalleryLocalizations.of(context).craneEat8,
|
||||
total: 323,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat8SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 9,
|
||||
destination: GalleryLocalizations.of(context).craneEat9,
|
||||
total: 1406,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat9SemanticLabel,
|
||||
),
|
||||
EatDestination(
|
||||
id: 10,
|
||||
destination: GalleryLocalizations.of(context).craneEat10,
|
||||
total: 849,
|
||||
assetSemanticLabel:
|
||||
GalleryLocalizations.of(context).craneEat10SemanticLabel,
|
||||
),
|
||||
];
|
||||
127
gallery/lib/studies/crane/model/destination.dart
Normal file
127
gallery/lib/studies/crane/model/destination.dart
Normal file
@@ -0,0 +1,127 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
|
||||
import 'package:gallery/studies/crane/model/formatters.dart';
|
||||
|
||||
import '../../../l10n/gallery_localizations.dart';
|
||||
|
||||
abstract class Destination {
|
||||
const Destination({
|
||||
@required this.id,
|
||||
@required this.destination,
|
||||
@required this.assetSemanticLabel,
|
||||
}) : assert(id != null),
|
||||
assert(destination != null);
|
||||
|
||||
final int id;
|
||||
final String destination;
|
||||
final String assetSemanticLabel;
|
||||
|
||||
String get assetName;
|
||||
|
||||
String subtitle(BuildContext context);
|
||||
String subtitleSemantics(BuildContext context) => subtitle(context);
|
||||
|
||||
@override
|
||||
String toString() => '$destination (id=$id)';
|
||||
}
|
||||
|
||||
class FlyDestination extends Destination {
|
||||
const FlyDestination({
|
||||
@required int id,
|
||||
@required String destination,
|
||||
@required String assetSemanticLabel,
|
||||
@required this.stops,
|
||||
this.duration,
|
||||
}) : assert(stops != null),
|
||||
assert(destination != null),
|
||||
super(
|
||||
id: id,
|
||||
destination: destination,
|
||||
assetSemanticLabel: assetSemanticLabel,
|
||||
);
|
||||
|
||||
final int stops;
|
||||
final Duration duration;
|
||||
|
||||
String get assetName => 'assets/crane/destinations/fly_$id.jpg';
|
||||
|
||||
String subtitle(BuildContext context) {
|
||||
final stopsText = GalleryLocalizations.of(context).craneFlyStops(stops);
|
||||
|
||||
if (duration == null) {
|
||||
return stopsText;
|
||||
} else {
|
||||
final textDirection = GalleryOptions.of(context).textDirection();
|
||||
final durationText =
|
||||
formattedDuration(context, duration, abbreviated: true);
|
||||
return textDirection == TextDirection.ltr
|
||||
? '$stopsText · $durationText'
|
||||
: '$durationText · $stopsText';
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
String subtitleSemantics(BuildContext context) {
|
||||
final stopsText = GalleryLocalizations.of(context).craneFlyStops(stops);
|
||||
|
||||
if (duration == null) {
|
||||
return stopsText;
|
||||
} else {
|
||||
final durationText =
|
||||
formattedDuration(context, duration, abbreviated: false);
|
||||
return '$stopsText, $durationText';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class SleepDestination extends Destination {
|
||||
const SleepDestination({
|
||||
@required int id,
|
||||
@required String destination,
|
||||
@required String assetSemanticLabel,
|
||||
@required this.total,
|
||||
}) : assert(total != null),
|
||||
assert(destination != null),
|
||||
super(
|
||||
id: id,
|
||||
destination: destination,
|
||||
assetSemanticLabel: assetSemanticLabel,
|
||||
);
|
||||
|
||||
final int total;
|
||||
|
||||
String get assetName => 'assets/crane/destinations/sleep_$id.jpg';
|
||||
|
||||
String subtitle(BuildContext context) {
|
||||
return GalleryLocalizations.of(context).craneSleepProperties(total);
|
||||
}
|
||||
}
|
||||
|
||||
class EatDestination extends Destination {
|
||||
const EatDestination({
|
||||
@required int id,
|
||||
@required String destination,
|
||||
@required String assetSemanticLabel,
|
||||
@required this.total,
|
||||
}) : assert(total != null),
|
||||
assert(destination != null),
|
||||
super(
|
||||
id: id,
|
||||
destination: destination,
|
||||
assetSemanticLabel: assetSemanticLabel,
|
||||
);
|
||||
|
||||
final int total;
|
||||
|
||||
String get assetName => 'assets/crane/destinations/eat_$id.jpg';
|
||||
|
||||
String subtitle(BuildContext context) {
|
||||
return GalleryLocalizations.of(context).craneEatRestaurants(total);
|
||||
}
|
||||
}
|
||||
17
gallery/lib/studies/crane/model/formatters.dart
Normal file
17
gallery/lib/studies/crane/model/formatters.dart
Normal file
@@ -0,0 +1,17 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
|
||||
// Duration of time (e.g. 16h 12m)
|
||||
String formattedDuration(BuildContext context, Duration duration,
|
||||
{bool abbreviated}) {
|
||||
final hoursShortForm =
|
||||
GalleryLocalizations.of(context).craneHours(duration.inHours.toInt());
|
||||
final minutesShortForm =
|
||||
GalleryLocalizations.of(context).craneMinutes(duration.inMinutes % 60);
|
||||
return GalleryLocalizations.of(context)
|
||||
.craneFlightDuration(hoursShortForm, minutesShortForm);
|
||||
}
|
||||
45
gallery/lib/studies/crane/sleep_form.dart
Normal file
45
gallery/lib/studies/crane/sleep_form.dart
Normal file
@@ -0,0 +1,45 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
|
||||
import 'package:gallery/studies/crane/backlayer.dart';
|
||||
import 'package:gallery/studies/crane/header_form.dart';
|
||||
|
||||
class SleepForm extends BackLayerItem {
|
||||
SleepForm({int index}) : super(index: index);
|
||||
|
||||
@override
|
||||
_SleepFormState createState() => _SleepFormState();
|
||||
}
|
||||
|
||||
class _SleepFormState extends State<SleepForm> {
|
||||
final travelerController = TextEditingController();
|
||||
final dateController = TextEditingController();
|
||||
final locationController = TextEditingController();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return HeaderForm(
|
||||
fields: <HeaderFormField>[
|
||||
HeaderFormField(
|
||||
iconData: Icons.person,
|
||||
title: GalleryLocalizations.of(context).craneFormTravelers,
|
||||
textController: travelerController,
|
||||
),
|
||||
HeaderFormField(
|
||||
iconData: Icons.date_range,
|
||||
title: GalleryLocalizations.of(context).craneFormDates,
|
||||
textController: dateController,
|
||||
),
|
||||
HeaderFormField(
|
||||
iconData: Icons.hotel,
|
||||
title: GalleryLocalizations.of(context).craneFormLocation,
|
||||
textController: locationController,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
106
gallery/lib/studies/crane/theme.dart
Normal file
106
gallery/lib/studies/crane/theme.dart
Normal file
@@ -0,0 +1,106 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
|
||||
import 'package:gallery/studies/crane/colors.dart';
|
||||
|
||||
final ThemeData craneTheme = _buildCraneTheme();
|
||||
|
||||
IconThemeData _customIconTheme(IconThemeData original, Color color) {
|
||||
return original.copyWith(color: color);
|
||||
}
|
||||
|
||||
ThemeData _buildCraneTheme() {
|
||||
final ThemeData base = ThemeData.light();
|
||||
|
||||
return base.copyWith(
|
||||
colorScheme: ColorScheme.light().copyWith(
|
||||
primary: cranePurple800,
|
||||
secondary: craneRed700,
|
||||
),
|
||||
accentColor: cranePurple700,
|
||||
primaryColor: cranePurple800,
|
||||
buttonColor: craneRed700,
|
||||
hintColor: craneWhite60,
|
||||
indicatorColor: cranePrimaryWhite,
|
||||
scaffoldBackgroundColor: cranePrimaryWhite,
|
||||
cardColor: cranePrimaryWhite,
|
||||
textSelectionColor: cranePurple700,
|
||||
errorColor: craneErrorOrange,
|
||||
highlightColor: Colors.transparent,
|
||||
buttonTheme: ButtonThemeData(
|
||||
textTheme: ButtonTextTheme.accent,
|
||||
),
|
||||
textTheme: _buildCraneTextTheme(base.textTheme),
|
||||
primaryTextTheme: _buildCraneTextTheme(base.primaryTextTheme),
|
||||
accentTextTheme: _buildCraneTextTheme(base.accentTextTheme),
|
||||
iconTheme: _customIconTheme(base.iconTheme, craneWhite60),
|
||||
primaryIconTheme: _customIconTheme(base.iconTheme, cranePrimaryWhite),
|
||||
);
|
||||
}
|
||||
|
||||
TextTheme _buildCraneTextTheme(TextTheme base) {
|
||||
return GoogleFonts.ralewayTextTheme(
|
||||
base.copyWith(
|
||||
display4: base.display4.copyWith(
|
||||
fontWeight: FontWeight.w300,
|
||||
fontSize: 96,
|
||||
),
|
||||
display3: base.display3.copyWith(
|
||||
fontWeight: FontWeight.w400,
|
||||
fontSize: 60,
|
||||
),
|
||||
display2: base.display2.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 48,
|
||||
),
|
||||
display1: base.display1.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 34,
|
||||
),
|
||||
headline: base.headline.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 24,
|
||||
),
|
||||
title: base.title.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 20,
|
||||
),
|
||||
subhead: base.subhead.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 16,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
subtitle: base.subtitle.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 12,
|
||||
color: craneGrey,
|
||||
),
|
||||
body2: base.body2.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 16,
|
||||
),
|
||||
body1: base.body1.copyWith(
|
||||
fontWeight: FontWeight.w400,
|
||||
fontSize: 14,
|
||||
),
|
||||
button: base.button.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 13,
|
||||
letterSpacing: 0.8,
|
||||
),
|
||||
caption: base.caption.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 12,
|
||||
color: craneGrey,
|
||||
),
|
||||
overline: base.overline.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
163
gallery/lib/studies/fortnightly/app.dart
Normal file
163
gallery/lib/studies/fortnightly/app.dart
Normal file
@@ -0,0 +1,163 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/studies/fortnightly/shared.dart';
|
||||
|
||||
const fortnightlyTitle = 'Fortnightly';
|
||||
|
||||
class FortnightlyApp extends StatelessWidget {
|
||||
const FortnightlyApp({Key key, this.navigatorKey}) : super(key: key);
|
||||
|
||||
final GlobalKey<NavigatorState> navigatorKey;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final home = isDisplayDesktop(context)
|
||||
? _FortnightlyHomeDesktop()
|
||||
: _FortnightlyHomeMobile();
|
||||
return MaterialApp(
|
||||
navigatorKey: navigatorKey,
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: buildTheme(context).copyWith(
|
||||
platform: GalleryOptions.of(context).platform,
|
||||
),
|
||||
home: ApplyTextOptions(child: home),
|
||||
// L10n settings.
|
||||
localizationsDelegates: GalleryLocalizations.localizationsDelegates,
|
||||
supportedLocales: GalleryLocalizations.supportedLocales,
|
||||
locale: GalleryOptions.of(context).locale,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FortnightlyHomeMobile extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
drawer: Drawer(
|
||||
child: SafeArea(
|
||||
child: NavigationMenu(isCloseable: true),
|
||||
),
|
||||
),
|
||||
appBar: AppBar(
|
||||
title: Semantics(
|
||||
label: fortnightlyTitle,
|
||||
child: Image.asset(
|
||||
'assets/fortnightly/fortnightly_title.png',
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.search),
|
||||
tooltip: GalleryLocalizations.of(context).shrineTooltipSearch,
|
||||
onPressed: () {},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: SafeArea(
|
||||
child: ListView(
|
||||
children: [
|
||||
HashtagBar(),
|
||||
for (final item in buildArticlePreviewItems(context))
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: item,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FortnightlyHomeDesktop extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final menuWidth = 200.0;
|
||||
final spacer = SizedBox(width: 20);
|
||||
final headerHeight = 40 * reducedTextScale(context);
|
||||
|
||||
return Scaffold(
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: headerHeight,
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: menuWidth,
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
margin: EdgeInsets.only(left: 12),
|
||||
child: Semantics(
|
||||
label: fortnightlyTitle,
|
||||
child: Image.asset(
|
||||
'assets/fortnightly/fortnightly_title.png',
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
spacer,
|
||||
Flexible(
|
||||
flex: 2,
|
||||
child: HashtagBar(),
|
||||
),
|
||||
spacer,
|
||||
Flexible(
|
||||
fit: FlexFit.tight,
|
||||
child: Container(
|
||||
alignment: AlignmentDirectional.centerEnd,
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.search),
|
||||
tooltip: GalleryLocalizations.of(context)
|
||||
.shrineTooltipSearch,
|
||||
onPressed: () {},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: menuWidth,
|
||||
child: NavigationMenu(),
|
||||
),
|
||||
spacer,
|
||||
Flexible(
|
||||
flex: 2,
|
||||
child: ListView(
|
||||
children: buildArticlePreviewItems(context),
|
||||
),
|
||||
),
|
||||
spacer,
|
||||
Flexible(
|
||||
flex: 1,
|
||||
fit: FlexFit.tight,
|
||||
child: ListView(
|
||||
children: [
|
||||
...buildStockItems(context),
|
||||
SizedBox(height: 32),
|
||||
...buildVideoPreviewItems(context),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
549
gallery/lib/studies/fortnightly/shared.dart
Normal file
549
gallery/lib/studies/fortnightly/shared.dart
Normal file
@@ -0,0 +1,549 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
class ArticleData {
|
||||
ArticleData({this.imageUrl, this.category, this.title, this.snippet});
|
||||
|
||||
final String imageUrl;
|
||||
final String category;
|
||||
final String title;
|
||||
final String snippet;
|
||||
}
|
||||
|
||||
class HorizontalArticlePreview extends StatelessWidget {
|
||||
HorizontalArticlePreview({this.data, this.minutes});
|
||||
|
||||
final ArticleData data;
|
||||
final int minutes;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
TextTheme textTheme = Theme.of(context).textTheme;
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
data.category,
|
||||
style: textTheme.subhead,
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Text(
|
||||
data.title,
|
||||
style: textTheme.headline.copyWith(fontSize: 16),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (minutes != null) ...[
|
||||
Text(
|
||||
GalleryLocalizations.of(context).craneMinutes(minutes),
|
||||
style: textTheme.body2,
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
],
|
||||
Image.asset(
|
||||
data.imageUrl,
|
||||
fit: BoxFit.cover,
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class VerticalArticlePreview extends StatelessWidget {
|
||||
VerticalArticlePreview({
|
||||
this.data,
|
||||
this.width,
|
||||
this.headlineTextStyle,
|
||||
this.showSnippet = false,
|
||||
});
|
||||
|
||||
final ArticleData data;
|
||||
final double width;
|
||||
final TextStyle headlineTextStyle;
|
||||
final bool showSnippet;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
TextTheme textTheme = Theme.of(context).textTheme;
|
||||
|
||||
return SizedBox(
|
||||
width: width ?? double.infinity,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: Image.asset(
|
||||
data.imageUrl,
|
||||
fit: BoxFit.fitWidth,
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Text(
|
||||
data.category,
|
||||
style: textTheme.subhead,
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Text(
|
||||
data.title,
|
||||
style: headlineTextStyle ?? textTheme.headline,
|
||||
),
|
||||
if (showSnippet) ...[
|
||||
SizedBox(height: 4),
|
||||
Text(
|
||||
data.snippet,
|
||||
style: textTheme.body1,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
List<Widget> buildArticlePreviewItems(BuildContext context) {
|
||||
Widget articleDivider = Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 16),
|
||||
color: Colors.black.withOpacity(0.07),
|
||||
height: 1,
|
||||
);
|
||||
Widget sectionDivider = Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 16),
|
||||
color: Colors.black.withOpacity(0.2),
|
||||
height: 1,
|
||||
);
|
||||
TextTheme textTheme = Theme.of(context).textTheme;
|
||||
|
||||
return <Widget>[
|
||||
VerticalArticlePreview(
|
||||
data: ArticleData(
|
||||
imageUrl: 'assets/fortnightly/fortnightly_healthcare.jpg',
|
||||
category:
|
||||
GalleryLocalizations.of(context).fortnightlyMenuWorld.toUpperCase(),
|
||||
title: GalleryLocalizations.of(context).fortnightlyHeadlineHealthcare,
|
||||
),
|
||||
headlineTextStyle: textTheme.headline.copyWith(fontSize: 20),
|
||||
),
|
||||
articleDivider,
|
||||
HorizontalArticlePreview(
|
||||
data: ArticleData(
|
||||
imageUrl: 'assets/fortnightly/fortnightly_war.png',
|
||||
category: GalleryLocalizations.of(context)
|
||||
.fortnightlyMenuPolitics
|
||||
.toUpperCase(),
|
||||
title: GalleryLocalizations.of(context).fortnightlyHeadlineWar,
|
||||
),
|
||||
),
|
||||
articleDivider,
|
||||
HorizontalArticlePreview(
|
||||
data: ArticleData(
|
||||
imageUrl: 'assets/fortnightly/fortnightly_gas.png',
|
||||
category:
|
||||
GalleryLocalizations.of(context).fortnightlyMenuTech.toUpperCase(),
|
||||
title: GalleryLocalizations.of(context).fortnightlyHeadlineGasoline,
|
||||
),
|
||||
),
|
||||
sectionDivider,
|
||||
Text(
|
||||
GalleryLocalizations.of(context).fortnightlyLatestUpdates,
|
||||
style: textTheme.title,
|
||||
),
|
||||
articleDivider,
|
||||
HorizontalArticlePreview(
|
||||
data: ArticleData(
|
||||
imageUrl: 'assets/fortnightly/fortnightly_army.png',
|
||||
category: GalleryLocalizations.of(context)
|
||||
.fortnightlyMenuPolitics
|
||||
.toUpperCase(),
|
||||
title: GalleryLocalizations.of(context).fortnightlyHeadlineArmy,
|
||||
),
|
||||
minutes: 2,
|
||||
),
|
||||
articleDivider,
|
||||
HorizontalArticlePreview(
|
||||
data: ArticleData(
|
||||
imageUrl: 'assets/fortnightly/fortnightly_stocks.png',
|
||||
category:
|
||||
GalleryLocalizations.of(context).fortnightlyMenuWorld.toUpperCase(),
|
||||
title: GalleryLocalizations.of(context).fortnightlyHeadlineStocks,
|
||||
),
|
||||
minutes: 5,
|
||||
),
|
||||
articleDivider,
|
||||
HorizontalArticlePreview(
|
||||
data: ArticleData(
|
||||
imageUrl: 'assets/fortnightly/fortnightly_fabrics.png',
|
||||
category:
|
||||
GalleryLocalizations.of(context).fortnightlyMenuTech.toUpperCase(),
|
||||
title: GalleryLocalizations.of(context).fortnightlyHeadlineFabrics,
|
||||
),
|
||||
minutes: 4,
|
||||
),
|
||||
articleDivider,
|
||||
];
|
||||
}
|
||||
|
||||
class HashtagBar extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final verticalDivider = Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
width: 1,
|
||||
);
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
final height = 32 * reducedTextScale(context);
|
||||
|
||||
return SizedBox(
|
||||
height: height,
|
||||
child: ListView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
children: [
|
||||
SizedBox(width: 16),
|
||||
Center(
|
||||
child: Text(
|
||||
'#${GalleryLocalizations.of(context).fortnightlyTrendingTechDesign}',
|
||||
style: textTheme.subtitle,
|
||||
),
|
||||
),
|
||||
verticalDivider,
|
||||
Center(
|
||||
child: Text(
|
||||
'#${GalleryLocalizations.of(context).fortnightlyTrendingReform}',
|
||||
style: textTheme.subtitle,
|
||||
),
|
||||
),
|
||||
verticalDivider,
|
||||
Center(
|
||||
child: Text(
|
||||
'#${GalleryLocalizations.of(context).fortnightlyTrendingHealthcareRevolution}',
|
||||
style: textTheme.subtitle,
|
||||
),
|
||||
),
|
||||
verticalDivider,
|
||||
Center(
|
||||
child: Text(
|
||||
'#${GalleryLocalizations.of(context).fortnightlyTrendingGreenArmy}',
|
||||
style: textTheme.subtitle,
|
||||
),
|
||||
),
|
||||
verticalDivider,
|
||||
Center(
|
||||
child: Text(
|
||||
'#${GalleryLocalizations.of(context).fortnightlyTrendingStocks}',
|
||||
style: textTheme.subtitle,
|
||||
),
|
||||
),
|
||||
verticalDivider,
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NavigationMenu extends StatelessWidget {
|
||||
NavigationMenu({this.isCloseable = false});
|
||||
|
||||
final bool isCloseable;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
children: [
|
||||
if (isCloseable)
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
icon: Icon(Icons.close),
|
||||
tooltip: MaterialLocalizations.of(context).closeButtonTooltip,
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
Image.asset(
|
||||
'assets/fortnightly/fortnightly_title.png',
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 32),
|
||||
MenuItem(
|
||||
GalleryLocalizations.of(context).fortnightlyMenuFrontPage,
|
||||
header: true,
|
||||
),
|
||||
MenuItem(GalleryLocalizations.of(context).fortnightlyMenuWorld),
|
||||
MenuItem(GalleryLocalizations.of(context).fortnightlyMenuUS),
|
||||
MenuItem(GalleryLocalizations.of(context).fortnightlyMenuPolitics),
|
||||
MenuItem(GalleryLocalizations.of(context).fortnightlyMenuBusiness),
|
||||
MenuItem(GalleryLocalizations.of(context).fortnightlyMenuTech),
|
||||
MenuItem(GalleryLocalizations.of(context).fortnightlyMenuScience),
|
||||
MenuItem(GalleryLocalizations.of(context).fortnightlyMenuSports),
|
||||
MenuItem(GalleryLocalizations.of(context).fortnightlyMenuTravel),
|
||||
MenuItem(GalleryLocalizations.of(context).fortnightlyMenuCulture),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MenuItem extends StatelessWidget {
|
||||
MenuItem(this.title, {this.header = false});
|
||||
|
||||
final String title;
|
||||
final bool header;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 32,
|
||||
alignment: Alignment.centerLeft,
|
||||
child: header ? null : Icon(Icons.arrow_drop_down),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.subhead.copyWith(
|
||||
fontWeight: header ? FontWeight.w700 : FontWeight.w600,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class StockItem extends StatelessWidget {
|
||||
StockItem({this.ticker, this.price, this.percent});
|
||||
|
||||
final String ticker;
|
||||
final String price;
|
||||
final double percent;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
final percentFormat = NumberFormat.decimalPercentPattern(
|
||||
locale: GalleryOptions.of(context).locale.toString(),
|
||||
decimalDigits: 2,
|
||||
);
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(ticker, style: textTheme.subhead),
|
||||
SizedBox(height: 2),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
price,
|
||||
style: textTheme.subtitle.copyWith(
|
||||
color: textTheme.subtitle.color.withOpacity(0.75),
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
percent > 0 ? '+' : '-',
|
||||
style: textTheme.subtitle.copyWith(
|
||||
fontSize: 12,
|
||||
color: percent > 0 ? Color(0xff20CF63) : Color(0xff661FFF),
|
||||
),
|
||||
),
|
||||
SizedBox(width: 4),
|
||||
Text(
|
||||
percentFormat.format(percent.abs() / 100),
|
||||
style: textTheme.caption.copyWith(
|
||||
fontSize: 12,
|
||||
color: textTheme.subtitle.color.withOpacity(0.75),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
List<Widget> buildStockItems(BuildContext context) {
|
||||
Widget articleDivider = Container(
|
||||
margin: EdgeInsets.symmetric(vertical: 16),
|
||||
color: Colors.black.withOpacity(0.07),
|
||||
height: 1,
|
||||
);
|
||||
|
||||
return <Widget>[
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: Image.asset(
|
||||
'assets/fortnightly/fortnightly_chart.png',
|
||||
fit: BoxFit.contain,
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
),
|
||||
articleDivider,
|
||||
StockItem(
|
||||
ticker: 'DIJA',
|
||||
price: '7,031.21',
|
||||
percent: -0.48,
|
||||
),
|
||||
articleDivider,
|
||||
StockItem(
|
||||
ticker: 'SP',
|
||||
price: '1,967.84',
|
||||
percent: -0.23,
|
||||
),
|
||||
articleDivider,
|
||||
StockItem(
|
||||
ticker: 'Nasdaq',
|
||||
price: '6,211.46',
|
||||
percent: 0.52,
|
||||
),
|
||||
articleDivider,
|
||||
StockItem(
|
||||
ticker: 'Nikkei',
|
||||
price: '5,891',
|
||||
percent: 1.16,
|
||||
),
|
||||
articleDivider,
|
||||
StockItem(
|
||||
ticker: 'DJ Total',
|
||||
price: '89.02',
|
||||
percent: 0.80,
|
||||
),
|
||||
articleDivider,
|
||||
];
|
||||
}
|
||||
|
||||
class VideoPreview extends StatelessWidget {
|
||||
VideoPreview({this.data, this.time});
|
||||
|
||||
final ArticleData data;
|
||||
final String time;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
TextTheme textTheme = Theme.of(context).textTheme;
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: Image.asset(
|
||||
data.imageUrl,
|
||||
fit: BoxFit.contain,
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(data.category, style: textTheme.subhead),
|
||||
),
|
||||
Text(time, style: textTheme.body2)
|
||||
],
|
||||
),
|
||||
SizedBox(height: 4),
|
||||
Text(data.title, style: textTheme.headline.copyWith(fontSize: 16)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
List<Widget> buildVideoPreviewItems(BuildContext context) {
|
||||
return <Widget>[
|
||||
VideoPreview(
|
||||
data: ArticleData(
|
||||
imageUrl: 'assets/fortnightly/fortnightly_feminists.jpg',
|
||||
category: GalleryLocalizations.of(context)
|
||||
.fortnightlyMenuPolitics
|
||||
.toUpperCase(),
|
||||
title: GalleryLocalizations.of(context).fortnightlyHeadlineFeminists,
|
||||
),
|
||||
time: '2:31',
|
||||
),
|
||||
SizedBox(height: 32),
|
||||
VideoPreview(
|
||||
data: ArticleData(
|
||||
imageUrl: 'assets/fortnightly/fortnightly_bees.jpg',
|
||||
category:
|
||||
GalleryLocalizations.of(context).fortnightlyMenuUS.toUpperCase(),
|
||||
title: GalleryLocalizations.of(context).fortnightlyHeadlineBees,
|
||||
),
|
||||
time: '1:37',
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
ThemeData buildTheme(BuildContext context) {
|
||||
TextTheme textTheme = Theme.of(context).textTheme;
|
||||
return ThemeData(
|
||||
scaffoldBackgroundColor: Colors.white,
|
||||
appBarTheme: AppBarTheme(
|
||||
color: Colors.white,
|
||||
elevation: 0,
|
||||
iconTheme: IconTheme.of(context).copyWith(color: Colors.black),
|
||||
),
|
||||
highlightColor: Colors.transparent,
|
||||
textTheme: textTheme.copyWith(
|
||||
// preview snippet
|
||||
body1: GoogleFonts.merriweather(
|
||||
fontWeight: FontWeight.w300,
|
||||
fontSize: 16,
|
||||
textStyle: textTheme.body1,
|
||||
),
|
||||
// time in latest updates
|
||||
body2: GoogleFonts.libreFranklin(
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 11,
|
||||
color: Colors.black.withOpacity(0.5),
|
||||
textStyle: textTheme.body2,
|
||||
),
|
||||
// preview headlines
|
||||
headline: GoogleFonts.libreFranklin(
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 16,
|
||||
textStyle: textTheme.headline,
|
||||
),
|
||||
// TODO: Use GoogleFonts.robotoCondensed when available
|
||||
// (caption 2), preview category, stock ticker
|
||||
subhead: textTheme.subhead.copyWith(
|
||||
fontFamily: 'Roboto Condensed',
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 16,
|
||||
),
|
||||
subtitle: GoogleFonts.libreFranklin(
|
||||
fontWeight: FontWeight.w400,
|
||||
fontSize: 14,
|
||||
textStyle: textTheme.subtitle,
|
||||
),
|
||||
// section titles: Top Highlights, Last Updated...
|
||||
title: GoogleFonts.merriweather(
|
||||
fontWeight: FontWeight.w700,
|
||||
fontStyle: FontStyle.italic,
|
||||
fontSize: 14,
|
||||
textStyle: textTheme.title,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
95
gallery/lib/studies/rally/app.dart
Normal file
95
gallery/lib/studies/rally/app.dart
Normal file
@@ -0,0 +1,95 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
|
||||
import 'package:gallery/studies/rally/colors.dart';
|
||||
import 'package:gallery/studies/rally/home.dart';
|
||||
import 'package:gallery/studies/rally/login.dart';
|
||||
|
||||
/// The RallyApp is a MaterialApp with a theme and 2 routes.
|
||||
///
|
||||
/// The home route is the main page with tabs for sub pages.
|
||||
/// The login route is the initial route.
|
||||
class RallyApp extends StatelessWidget {
|
||||
const RallyApp({Key key, this.navigatorKey}) : super(key: key);
|
||||
|
||||
final GlobalKey<NavigatorState> navigatorKey;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MaterialApp(
|
||||
navigatorKey: navigatorKey,
|
||||
title: 'Rally',
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: _buildRallyTheme().copyWith(
|
||||
platform: GalleryOptions.of(context).platform,
|
||||
),
|
||||
localizationsDelegates: GalleryLocalizations.localizationsDelegates,
|
||||
supportedLocales: GalleryLocalizations.supportedLocales,
|
||||
locale: GalleryOptions.of(context).locale,
|
||||
home: HomePage(),
|
||||
initialRoute: '/login',
|
||||
routes: <String, WidgetBuilder>{
|
||||
'/login': (context) => LoginPage(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
ThemeData _buildRallyTheme() {
|
||||
final base = ThemeData.dark();
|
||||
return ThemeData(
|
||||
scaffoldBackgroundColor: RallyColors.primaryBackground,
|
||||
primaryColor: RallyColors.primaryBackground,
|
||||
focusColor: RallyColors.focusColor,
|
||||
textTheme: _buildRallyTextTheme(base.textTheme),
|
||||
inputDecorationTheme: InputDecorationTheme(
|
||||
labelStyle: const TextStyle(
|
||||
color: RallyColors.gray,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
filled: true,
|
||||
fillColor: RallyColors.inputBackground,
|
||||
focusedBorder: InputBorder.none,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
TextTheme _buildRallyTextTheme(TextTheme base) {
|
||||
return base
|
||||
.copyWith(
|
||||
// TODO: Use GoogleFonts.robotoCondensed when available
|
||||
body1: base.body1.copyWith(
|
||||
fontFamily: 'Roboto Condensed',
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
body2: GoogleFonts.eczar(
|
||||
fontSize: 40,
|
||||
fontWeight: FontWeight.w400,
|
||||
letterSpacing: 1.4,
|
||||
textStyle: base.body2,
|
||||
),
|
||||
// TODO: Use GoogleFonts.robotoCondensed when available
|
||||
button: base.button.copyWith(
|
||||
fontFamily: 'Roboto Condensed',
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: 2.8,
|
||||
),
|
||||
headline: GoogleFonts.eczar(
|
||||
fontSize: 40,
|
||||
fontWeight: FontWeight.w600,
|
||||
letterSpacing: 1.4,
|
||||
textStyle: base.body2,
|
||||
),
|
||||
)
|
||||
.apply(
|
||||
displayColor: Colors.white,
|
||||
bodyColor: Colors.white,
|
||||
);
|
||||
}
|
||||
}
|
||||
287
gallery/lib/studies/rally/charts/line_chart.dart
Normal file
287
gallery/lib/studies/rally/charts/line_chart.dart
Normal file
@@ -0,0 +1,287 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:intl/intl.dart' as intl;
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/semantics.dart';
|
||||
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/studies/rally/colors.dart';
|
||||
import 'package:gallery/studies/rally/data.dart';
|
||||
import 'package:gallery/studies/rally/formatters.dart';
|
||||
|
||||
class RallyLineChart extends StatelessWidget {
|
||||
const RallyLineChart({this.events = const <DetailedEventData>[]})
|
||||
: assert(events != null);
|
||||
|
||||
final List<DetailedEventData> events;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CustomPaint(
|
||||
painter: RallyLineChartPainter(
|
||||
dateFormat: dateFormatMonthYear(context),
|
||||
numberFormat: usdWithSignFormat(context),
|
||||
events: events,
|
||||
labelStyle: Theme.of(context).textTheme.body1,
|
||||
textDirection: GalleryOptions.of(context).textDirection(),
|
||||
textScaleFactor: reducedTextScale(context),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class RallyLineChartPainter extends CustomPainter {
|
||||
RallyLineChartPainter({
|
||||
@required this.dateFormat,
|
||||
@required this.numberFormat,
|
||||
@required this.events,
|
||||
@required this.labelStyle,
|
||||
@required this.textDirection,
|
||||
@required this.textScaleFactor,
|
||||
});
|
||||
|
||||
// The style for the labels.
|
||||
final TextStyle labelStyle;
|
||||
|
||||
// The text direction for the text.
|
||||
final TextDirection textDirection;
|
||||
|
||||
// The text scale factor for the text.
|
||||
final double textScaleFactor;
|
||||
|
||||
// The format for the dates.
|
||||
final intl.DateFormat dateFormat;
|
||||
|
||||
// The currency format.
|
||||
final intl.NumberFormat numberFormat;
|
||||
|
||||
// Events to plot on the line as points.
|
||||
final List<DetailedEventData> events;
|
||||
|
||||
// Number of days to plot.
|
||||
// This is hardcoded to reflect the dummy data, but would be dynamic in a real
|
||||
// app.
|
||||
final int numDays = 52;
|
||||
|
||||
// Beginning of window. The end is this plus numDays.
|
||||
// This is hardcoded to reflect the dummy data, but would be dynamic in a real
|
||||
// app.
|
||||
final DateTime startDate = DateTime.utc(2018, 12, 1);
|
||||
|
||||
// Ranges uses to lerp the pixel points.
|
||||
// This is hardcoded to reflect the dummy data, but would be dynamic in a real
|
||||
// app.
|
||||
final double maxAmount = 2000; // minAmount is assumed to be 0
|
||||
|
||||
// The number of milliseconds in a day. This is the inherit period fot the
|
||||
// points in this line.
|
||||
static const int millisInDay = 24 * 60 * 60 * 1000;
|
||||
|
||||
// Amount to shift the tick drawing by so that the Sunday ticks do not start
|
||||
// on the edge.
|
||||
final int tickShift = 3;
|
||||
|
||||
// Arbitrary unit of space for absolute positioned painting.
|
||||
final double space = 16;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
final labelHeight = space + space * (textScaleFactor - 1);
|
||||
final ticksHeight = 3 * space;
|
||||
final ticksTop = size.height - labelHeight - ticksHeight - space;
|
||||
final labelsTop = size.height - labelHeight;
|
||||
_drawLine(
|
||||
canvas,
|
||||
Rect.fromLTWH(0, 0, size.width, size.height - labelHeight - ticksHeight),
|
||||
);
|
||||
_drawXAxisTicks(
|
||||
canvas,
|
||||
Rect.fromLTWH(0, ticksTop, size.width, ticksHeight),
|
||||
);
|
||||
_drawXAxisLabels(
|
||||
canvas,
|
||||
Rect.fromLTWH(0, labelsTop, size.width, labelHeight),
|
||||
);
|
||||
}
|
||||
|
||||
// Since we're only using fixed dummy data, we can set this to false. In a
|
||||
// real app we would have the data as part of the state and repaint when it's
|
||||
// changed.
|
||||
@override
|
||||
bool shouldRepaint(CustomPainter oldDelegate) => false;
|
||||
|
||||
@override
|
||||
SemanticsBuilderCallback get semanticsBuilder {
|
||||
return (size) {
|
||||
final amounts = _amountsPerDay(numDays);
|
||||
|
||||
// We divide the graph and the amounts into [numGroups] groups, with
|
||||
// [numItemsPerGroup] amounts per group.
|
||||
final numGroups = 10;
|
||||
final numItemsPerGroup = amounts.length ~/ numGroups;
|
||||
|
||||
// For each group we calculate the median value.
|
||||
final medians = List.generate(
|
||||
numGroups,
|
||||
(i) {
|
||||
final middleIndex = i * numItemsPerGroup + numItemsPerGroup ~/ 2;
|
||||
if (numItemsPerGroup.isEven) {
|
||||
return (amounts[middleIndex] + amounts[middleIndex + 1]) / 2;
|
||||
} else {
|
||||
return amounts[middleIndex];
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Return a list of [CustomPainterSemantics] with the length of
|
||||
// [numGroups], all have the same width with the median amount as label.
|
||||
return List.generate(numGroups, (i) {
|
||||
return CustomPainterSemantics(
|
||||
rect: Offset((i / numGroups) * size.width, 0) &
|
||||
Size(size.width / numGroups, size.height),
|
||||
properties: SemanticsProperties(
|
||||
label: numberFormat.format(medians[i]),
|
||||
textDirection: textDirection,
|
||||
),
|
||||
);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/// Returns the amount of money in the account for the [numDays] given
|
||||
/// from the [startDate].
|
||||
List<double> _amountsPerDay(int numDays) {
|
||||
// Arbitrary value for the first point. In a real app, a wider range of
|
||||
// points would be used that go beyond the boundaries of the screen.
|
||||
double lastAmount = 600;
|
||||
|
||||
// Align the points with equal deltas (1 day) as a cumulative sum.
|
||||
int startMillis = startDate.millisecondsSinceEpoch;
|
||||
|
||||
final amounts = <double>[];
|
||||
for (var i = 0; i < numDays; i++) {
|
||||
final endMillis = startMillis + millisInDay * 1;
|
||||
final filteredEvents = events.where(
|
||||
(e) {
|
||||
return startMillis <= e.date.millisecondsSinceEpoch &&
|
||||
e.date.millisecondsSinceEpoch < endMillis;
|
||||
},
|
||||
).toList();
|
||||
lastAmount += sumOf<DetailedEventData>(filteredEvents, (e) => e.amount);
|
||||
amounts.add(lastAmount);
|
||||
startMillis = endMillis;
|
||||
}
|
||||
return amounts;
|
||||
}
|
||||
|
||||
void _drawLine(Canvas canvas, Rect rect) {
|
||||
final Paint linePaint = Paint()
|
||||
..color = RallyColors.accountColor(2)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2;
|
||||
|
||||
// Try changing this value between 1, 7, 15, etc.
|
||||
const smoothing = 1;
|
||||
|
||||
final amounts = _amountsPerDay(numDays + smoothing);
|
||||
final points = <Offset>[];
|
||||
for (int i = 0; i < amounts.length; i++) {
|
||||
final x = i / numDays * rect.width;
|
||||
final y = (maxAmount - amounts[i]) / maxAmount * rect.height;
|
||||
points.add(Offset(x, y));
|
||||
}
|
||||
|
||||
// Add last point of the graph to make sure we take up the full width.
|
||||
points.add(
|
||||
Offset(
|
||||
rect.width,
|
||||
(maxAmount - amounts[numDays - 1]) / maxAmount * rect.height,
|
||||
),
|
||||
);
|
||||
|
||||
final path = Path();
|
||||
path.moveTo(points[0].dx, points[0].dy);
|
||||
for (int i = 1; i < numDays - smoothing + 2; i += smoothing) {
|
||||
final x1 = points[i].dx;
|
||||
final y1 = points[i].dy;
|
||||
final x2 = (x1 + points[i + smoothing].dx) / 2;
|
||||
final y2 = (y1 + points[i + smoothing].dy) / 2;
|
||||
path.quadraticBezierTo(x1, y1, x2, y2);
|
||||
}
|
||||
canvas.drawPath(path, linePaint);
|
||||
}
|
||||
|
||||
/// Draw the X-axis increment markers at constant width intervals.
|
||||
void _drawXAxisTicks(Canvas canvas, Rect rect) {
|
||||
for (int i = 0; i < numDays; i++) {
|
||||
final double x = rect.width / numDays * i;
|
||||
canvas.drawRect(
|
||||
Rect.fromPoints(
|
||||
Offset(x, i % 7 == tickShift ? rect.top : rect.center.dy),
|
||||
Offset(x, rect.bottom),
|
||||
),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1
|
||||
..color = RallyColors.gray25,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Set X-axis labels under the X-axis increment markers.
|
||||
void _drawXAxisLabels(Canvas canvas, Rect rect) {
|
||||
final selectedLabelStyle = labelStyle.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: labelStyle.fontSize * textScaleFactor,
|
||||
);
|
||||
final unselectedLabelStyle = labelStyle.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
color: RallyColors.gray25,
|
||||
fontSize: labelStyle.fontSize * textScaleFactor,
|
||||
);
|
||||
|
||||
// We use toUpperCase to format the dates. This function uses the language
|
||||
// independent Unicode mapping and thus only works in some languages.
|
||||
final leftLabel = TextPainter(
|
||||
text: TextSpan(
|
||||
text: dateFormat.format(startDate).toUpperCase(),
|
||||
style: unselectedLabelStyle,
|
||||
),
|
||||
textDirection: textDirection,
|
||||
);
|
||||
leftLabel.layout();
|
||||
leftLabel.paint(canvas, Offset(rect.left + space / 2, rect.topCenter.dy));
|
||||
|
||||
final centerLabel = TextPainter(
|
||||
text: TextSpan(
|
||||
text: dateFormat
|
||||
.format(DateTime(startDate.year, startDate.month + 1))
|
||||
.toUpperCase(),
|
||||
style: selectedLabelStyle,
|
||||
),
|
||||
textDirection: textDirection,
|
||||
);
|
||||
centerLabel.layout();
|
||||
final x = (rect.width - centerLabel.width) / 2;
|
||||
final y = rect.topCenter.dy;
|
||||
centerLabel.paint(canvas, Offset(x, y));
|
||||
|
||||
final rightLabel = TextPainter(
|
||||
text: TextSpan(
|
||||
text: dateFormat
|
||||
.format(DateTime(startDate.year, startDate.month + 2))
|
||||
.toUpperCase(),
|
||||
style: unselectedLabelStyle,
|
||||
),
|
||||
textDirection: textDirection,
|
||||
);
|
||||
rightLabel.layout();
|
||||
rightLabel.paint(
|
||||
canvas,
|
||||
Offset(rect.right - centerLabel.width - space / 2, rect.topCenter.dy),
|
||||
);
|
||||
}
|
||||
}
|
||||
278
gallery/lib/studies/rally/charts/pie_chart.dart
Normal file
278
gallery/lib/studies/rally/charts/pie_chart.dart
Normal file
@@ -0,0 +1,278 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/studies/rally/colors.dart';
|
||||
import 'package:gallery/studies/rally/data.dart';
|
||||
import 'package:gallery/studies/rally/formatters.dart';
|
||||
|
||||
/// A colored piece of the [RallyPieChart].
|
||||
class RallyPieChartSegment {
|
||||
const RallyPieChartSegment({this.color, this.value});
|
||||
|
||||
final Color color;
|
||||
final double value;
|
||||
}
|
||||
|
||||
/// The max height and width of the [RallyPieChart].
|
||||
const pieChartMaxSize = 500.0;
|
||||
|
||||
List<RallyPieChartSegment> buildSegmentsFromAccountItems(
|
||||
List<AccountData> items) {
|
||||
return List<RallyPieChartSegment>.generate(
|
||||
items.length,
|
||||
(i) {
|
||||
return RallyPieChartSegment(
|
||||
color: RallyColors.accountColor(i),
|
||||
value: items[i].primaryAmount,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
List<RallyPieChartSegment> buildSegmentsFromBillItems(List<BillData> items) {
|
||||
return List<RallyPieChartSegment>.generate(
|
||||
items.length,
|
||||
(i) {
|
||||
return RallyPieChartSegment(
|
||||
color: RallyColors.billColor(i),
|
||||
value: items[i].primaryAmount,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
List<RallyPieChartSegment> buildSegmentsFromBudgetItems(
|
||||
List<BudgetData> items) {
|
||||
return List<RallyPieChartSegment>.generate(
|
||||
items.length,
|
||||
(i) {
|
||||
return RallyPieChartSegment(
|
||||
color: RallyColors.budgetColor(i),
|
||||
value: items[i].primaryAmount - items[i].amountUsed,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// An animated circular pie chart to represent pieces of a whole, which can
|
||||
/// have empty space.
|
||||
class RallyPieChart extends StatefulWidget {
|
||||
const RallyPieChart(
|
||||
{this.heroLabel, this.heroAmount, this.wholeAmount, this.segments});
|
||||
|
||||
final String heroLabel;
|
||||
final double heroAmount;
|
||||
final double wholeAmount;
|
||||
final List<RallyPieChartSegment> segments;
|
||||
|
||||
@override
|
||||
_RallyPieChartState createState() => _RallyPieChartState();
|
||||
}
|
||||
|
||||
class _RallyPieChartState extends State<RallyPieChart>
|
||||
with SingleTickerProviderStateMixin {
|
||||
AnimationController controller;
|
||||
Animation<double> animation;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
controller = AnimationController(
|
||||
duration: const Duration(milliseconds: 600),
|
||||
vsync: this,
|
||||
);
|
||||
animation = CurvedAnimation(
|
||||
parent: TweenSequence<double>(<TweenSequenceItem<double>>[
|
||||
TweenSequenceItem<double>(
|
||||
tween: Tween<double>(begin: 0, end: 0),
|
||||
weight: 1,
|
||||
),
|
||||
TweenSequenceItem<double>(
|
||||
tween: Tween<double>(begin: 0, end: 1),
|
||||
weight: 1.5,
|
||||
),
|
||||
]).animate(controller),
|
||||
curve: Curves.decelerate);
|
||||
controller.forward();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MergeSemantics(
|
||||
child: _AnimatedRallyPieChart(
|
||||
animation: animation,
|
||||
centerLabel: widget.heroLabel,
|
||||
centerAmount: widget.heroAmount,
|
||||
total: widget.wholeAmount,
|
||||
segments: widget.segments,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AnimatedRallyPieChart extends AnimatedWidget {
|
||||
const _AnimatedRallyPieChart({
|
||||
Key key,
|
||||
this.animation,
|
||||
this.centerLabel,
|
||||
this.centerAmount,
|
||||
this.total,
|
||||
this.segments,
|
||||
}) : super(key: key, listenable: animation);
|
||||
|
||||
final Animation<double> animation;
|
||||
final String centerLabel;
|
||||
final double centerAmount;
|
||||
final double total;
|
||||
final List<RallyPieChartSegment> segments;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
final labelTextStyle = textTheme.body1.copyWith(
|
||||
fontSize: 14,
|
||||
letterSpacing: 0.5,
|
||||
);
|
||||
|
||||
return LayoutBuilder(builder: (context, constraints) {
|
||||
// When the widget is larger, we increase the font size.
|
||||
TextStyle headlineStyle = constraints.maxHeight >= pieChartMaxSize
|
||||
? textTheme.headline.copyWith(fontSize: 70)
|
||||
: textTheme.headline;
|
||||
|
||||
// With a large text scale factor, we set a max font size.
|
||||
if (GalleryOptions.of(context).textScaleFactor(context) > 1.0) {
|
||||
headlineStyle = headlineStyle.copyWith(
|
||||
fontSize: (headlineStyle.fontSize / reducedTextScale(context)),
|
||||
);
|
||||
}
|
||||
|
||||
return DecoratedBox(
|
||||
decoration: _RallyPieChartOutlineDecoration(
|
||||
maxFraction: animation.value,
|
||||
total: total,
|
||||
segments: segments,
|
||||
),
|
||||
child: Container(
|
||||
height: constraints.maxHeight,
|
||||
alignment: Alignment.center,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
centerLabel,
|
||||
style: labelTextStyle,
|
||||
),
|
||||
Text(
|
||||
usdWithSignFormat(context).format(centerAmount),
|
||||
style: headlineStyle,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _RallyPieChartOutlineDecoration extends Decoration {
|
||||
const _RallyPieChartOutlineDecoration(
|
||||
{this.maxFraction, this.total, this.segments});
|
||||
|
||||
final double maxFraction;
|
||||
final double total;
|
||||
final List<RallyPieChartSegment> segments;
|
||||
|
||||
@override
|
||||
BoxPainter createBoxPainter([VoidCallback onChanged]) {
|
||||
return _RallyPieChartOutlineBoxPainter(
|
||||
maxFraction: maxFraction,
|
||||
wholeAmount: total,
|
||||
segments: segments,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RallyPieChartOutlineBoxPainter extends BoxPainter {
|
||||
_RallyPieChartOutlineBoxPainter(
|
||||
{this.maxFraction, this.wholeAmount, this.segments});
|
||||
|
||||
final double maxFraction;
|
||||
final double wholeAmount;
|
||||
final List<RallyPieChartSegment> segments;
|
||||
static const double wholeRadians = 2 * math.pi;
|
||||
static const double spaceRadians = wholeRadians / 180;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
|
||||
// Create two padded reacts to draw arcs in: one for colored arcs and one for
|
||||
// inner bg arc.
|
||||
const strokeWidth = 4.0;
|
||||
final outerRadius = math.min(
|
||||
configuration.size.width,
|
||||
configuration.size.height,
|
||||
) /
|
||||
2;
|
||||
final outerRect = Rect.fromCircle(
|
||||
center: configuration.size.center(offset),
|
||||
radius: outerRadius - strokeWidth * 3,
|
||||
);
|
||||
final innerRect = Rect.fromCircle(
|
||||
center: configuration.size.center(offset),
|
||||
radius: outerRadius - strokeWidth * 4,
|
||||
);
|
||||
|
||||
// Paint each arc with spacing.
|
||||
double cumulativeSpace = 0;
|
||||
double cumulativeTotal = 0;
|
||||
for (RallyPieChartSegment segment in segments) {
|
||||
final paint = Paint()..color = segment.color;
|
||||
final startAngle = _calculateStartAngle(cumulativeTotal, cumulativeSpace);
|
||||
final sweepAngle = _calculateSweepAngle(segment.value, 0);
|
||||
canvas.drawArc(outerRect, startAngle, sweepAngle, true, paint);
|
||||
cumulativeTotal += segment.value;
|
||||
cumulativeSpace += spaceRadians;
|
||||
}
|
||||
|
||||
// Paint any remaining space black (e.g. budget amount remaining).
|
||||
final remaining = wholeAmount - cumulativeTotal;
|
||||
if (remaining > 0) {
|
||||
final paint = Paint()..color = Colors.black;
|
||||
final startAngle =
|
||||
_calculateStartAngle(cumulativeTotal, spaceRadians * segments.length);
|
||||
final sweepAngle = _calculateSweepAngle(remaining, -spaceRadians);
|
||||
canvas.drawArc(outerRect, startAngle, sweepAngle, true, paint);
|
||||
}
|
||||
|
||||
// Paint a smaller inner circle to cover the painted arcs, so they are
|
||||
// display as segments.
|
||||
final bgPaint = Paint()..color = RallyColors.primaryBackground;
|
||||
canvas.drawArc(innerRect, 0, 2 * math.pi, true, bgPaint);
|
||||
}
|
||||
|
||||
double _calculateAngle(double amount, double offset) {
|
||||
final wholeMinusSpacesRadians =
|
||||
wholeRadians - (segments.length * spaceRadians);
|
||||
return maxFraction *
|
||||
(amount / wholeAmount * wholeMinusSpacesRadians + offset);
|
||||
}
|
||||
|
||||
double _calculateStartAngle(double total, double offset) =>
|
||||
_calculateAngle(total, offset) - math.pi / 2;
|
||||
|
||||
double _calculateSweepAngle(double total, double offset) =>
|
||||
_calculateAngle(total, offset);
|
||||
}
|
||||
36
gallery/lib/studies/rally/charts/vertical_fraction_bar.dart
Normal file
36
gallery/lib/studies/rally/charts/vertical_fraction_bar.dart
Normal file
@@ -0,0 +1,36 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class VerticalFractionBar extends StatelessWidget {
|
||||
const VerticalFractionBar({this.color, this.fraction});
|
||||
|
||||
final Color color;
|
||||
final double fraction;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(builder: (context, constraints) {
|
||||
return SizedBox(
|
||||
height: constraints.maxHeight,
|
||||
width: 4,
|
||||
child: Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: (1 - fraction) * constraints.maxHeight,
|
||||
child: Container(
|
||||
color: Colors.black,
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: fraction * constraints.maxHeight,
|
||||
child: Container(color: color),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
61
gallery/lib/studies/rally/colors.dart
Normal file
61
gallery/lib/studies/rally/colors.dart
Normal file
@@ -0,0 +1,61 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:ui';
|
||||
|
||||
/// Most color assignments in Rally are not like the the typical color
|
||||
/// assignments that are common in other apps. Instead of primarily mapping to
|
||||
/// component type and part, they are assigned round robin based on layout.
|
||||
class RallyColors {
|
||||
static const List<Color> accountColors = <Color>[
|
||||
Color(0xFF005D57),
|
||||
Color(0xFF04B97F),
|
||||
Color(0xFF37EFBA),
|
||||
Color(0xFF007D51),
|
||||
];
|
||||
|
||||
static const List<Color> billColors = <Color>[
|
||||
Color(0xFFFFDC78),
|
||||
Color(0xFFFF6951),
|
||||
Color(0xFFFFD7D0),
|
||||
Color(0xFFFFAC12),
|
||||
];
|
||||
|
||||
static const List<Color> budgetColors = <Color>[
|
||||
Color(0xFFB2F2FF),
|
||||
Color(0xFFB15DFF),
|
||||
Color(0xFF72DEFF),
|
||||
Color(0xFF0082FB),
|
||||
];
|
||||
|
||||
static const Color gray = Color(0xFFD8D8D8);
|
||||
static const Color gray60 = Color(0x99D8D8D8);
|
||||
static const Color gray25 = Color(0x40D8D8D8);
|
||||
static const Color white60 = Color(0x99FFFFFF);
|
||||
static const Color primaryBackground = Color(0xFF33333D);
|
||||
static const Color inputBackground = Color(0xFF26282F);
|
||||
static const Color cardBackground = Color(0x03FEFEFE);
|
||||
static const Color buttonColor = Color(0xFF09AF79);
|
||||
static const Color focusColor = Color(0xCCFFFFFF);
|
||||
|
||||
/// Convenience method to get a single account color with position i.
|
||||
static Color accountColor(int i) {
|
||||
return cycledColor(accountColors, i);
|
||||
}
|
||||
|
||||
/// Convenience method to get a single bill color with position i.
|
||||
static Color billColor(int i) {
|
||||
return cycledColor(billColors, i);
|
||||
}
|
||||
|
||||
/// Convenience method to get a single budget color with position i.
|
||||
static Color budgetColor(int i) {
|
||||
return cycledColor(budgetColors, i);
|
||||
}
|
||||
|
||||
/// Gets a color from a list that is considered to be infinitely repeating.
|
||||
static Color cycledColor(List<Color> colors, int i) {
|
||||
return colors[i % colors.length];
|
||||
}
|
||||
}
|
||||
323
gallery/lib/studies/rally/data.dart
Normal file
323
gallery/lib/studies/rally/data.dart
Normal file
@@ -0,0 +1,323 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/studies/rally/formatters.dart';
|
||||
|
||||
/// Calculates the sum of the primary amounts of a list of [AccountData].
|
||||
double sumAccountDataPrimaryAmount(List<AccountData> items) =>
|
||||
sumOf<AccountData>(items, (item) => item.primaryAmount);
|
||||
|
||||
/// Calculates the sum of the primary amounts of a list of [BillData].
|
||||
double sumBillDataPrimaryAmount(List<BillData> items) =>
|
||||
sumOf<BillData>(items, (item) => item.primaryAmount);
|
||||
|
||||
/// Calculates the sum of the primary amounts of a list of [BudgetData].
|
||||
double sumBudgetDataPrimaryAmount(List<BudgetData> items) =>
|
||||
sumOf<BudgetData>(items, (item) => item.primaryAmount);
|
||||
|
||||
/// Calculates the sum of the amounts used of a list of [BudgetData].
|
||||
double sumBudgetDataAmountUsed(List<BudgetData> items) =>
|
||||
sumOf<BudgetData>(items, (item) => item.amountUsed);
|
||||
|
||||
/// Utility function to sum up values in a list.
|
||||
double sumOf<T>(List<T> list, double getValue(T elt)) {
|
||||
double sum = 0;
|
||||
for (T elt in list) {
|
||||
sum += getValue(elt);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
/// A data model for an account.
|
||||
///
|
||||
/// The [primaryAmount] is the balance of the account in USD.
|
||||
class AccountData {
|
||||
const AccountData({this.name, this.primaryAmount, this.accountNumber});
|
||||
|
||||
/// The display name of this entity.
|
||||
final String name;
|
||||
|
||||
/// The primary amount or value of this entity.
|
||||
final double primaryAmount;
|
||||
|
||||
/// The full displayable account number.
|
||||
final String accountNumber;
|
||||
}
|
||||
|
||||
/// A data model for a bill.
|
||||
///
|
||||
/// The [primaryAmount] is the amount due in USD.
|
||||
class BillData {
|
||||
const BillData({this.name, this.primaryAmount, this.dueDate});
|
||||
|
||||
/// The display name of this entity.
|
||||
final String name;
|
||||
|
||||
/// The primary amount or value of this entity.
|
||||
final double primaryAmount;
|
||||
|
||||
/// The due date of this bill.
|
||||
final String dueDate;
|
||||
}
|
||||
|
||||
/// A data model for a budget.
|
||||
///
|
||||
/// The [primaryAmount] is the budget cap in USD.
|
||||
class BudgetData {
|
||||
const BudgetData({this.name, this.primaryAmount, this.amountUsed});
|
||||
|
||||
/// The display name of this entity.
|
||||
final String name;
|
||||
|
||||
/// The primary amount or value of this entity.
|
||||
final double primaryAmount;
|
||||
|
||||
/// Amount of the budget that is consumed or used.
|
||||
final double amountUsed;
|
||||
}
|
||||
|
||||
/// A data model for an alert.
|
||||
class AlertData {
|
||||
AlertData({this.message, this.iconData});
|
||||
|
||||
/// The alert message to display.
|
||||
final String message;
|
||||
|
||||
/// The icon to display with the alert.
|
||||
final IconData iconData;
|
||||
}
|
||||
|
||||
class DetailedEventData {
|
||||
const DetailedEventData({
|
||||
this.title,
|
||||
this.date,
|
||||
this.amount,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final DateTime date;
|
||||
final double amount;
|
||||
}
|
||||
|
||||
/// A data model for account data.
|
||||
class AccountDetailData {
|
||||
AccountDetailData({this.title, this.value});
|
||||
|
||||
/// The display name of this entity.
|
||||
final String title;
|
||||
|
||||
/// The value of this entity.
|
||||
final String value;
|
||||
}
|
||||
|
||||
/// Class to return dummy data lists.
|
||||
///
|
||||
/// In a real app, this might be replaced with some asynchronous service.
|
||||
class DummyDataService {
|
||||
static List<AccountData> getAccountDataList(BuildContext context) {
|
||||
return <AccountData>[
|
||||
AccountData(
|
||||
name: GalleryLocalizations.of(context).rallyAccountDataChecking,
|
||||
primaryAmount: 2215.13,
|
||||
accountNumber: '1234561234',
|
||||
),
|
||||
AccountData(
|
||||
name: GalleryLocalizations.of(context).rallyAccountDataHomeSavings,
|
||||
primaryAmount: 8678.88,
|
||||
accountNumber: '8888885678',
|
||||
),
|
||||
AccountData(
|
||||
name: GalleryLocalizations.of(context).rallyAccountDataCarSavings,
|
||||
primaryAmount: 987.48,
|
||||
accountNumber: '8888889012',
|
||||
),
|
||||
AccountData(
|
||||
name: GalleryLocalizations.of(context).rallyAccountDataVacation,
|
||||
primaryAmount: 253,
|
||||
accountNumber: '1231233456',
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
static List<AccountDetailData> getAccountDetailList(BuildContext context) {
|
||||
return <AccountDetailData>[
|
||||
AccountDetailData(
|
||||
title: GalleryLocalizations.of(context)
|
||||
.rallyAccountDetailDataAnnualPercentageYield,
|
||||
value: percentFormat(context).format(0.001),
|
||||
),
|
||||
AccountDetailData(
|
||||
title:
|
||||
GalleryLocalizations.of(context).rallyAccountDetailDataInterestRate,
|
||||
value: usdWithSignFormat(context).format(1676.14),
|
||||
),
|
||||
AccountDetailData(
|
||||
title:
|
||||
GalleryLocalizations.of(context).rallyAccountDetailDataInterestYtd,
|
||||
value: usdWithSignFormat(context).format(81.45),
|
||||
),
|
||||
AccountDetailData(
|
||||
title: GalleryLocalizations.of(context)
|
||||
.rallyAccountDetailDataInterestPaidLastYear,
|
||||
value: usdWithSignFormat(context).format(987.12),
|
||||
),
|
||||
AccountDetailData(
|
||||
title: GalleryLocalizations.of(context)
|
||||
.rallyAccountDetailDataNextStatement,
|
||||
value: shortDateFormat(context).format(DateTime.utc(2019, 12, 25)),
|
||||
),
|
||||
AccountDetailData(
|
||||
title:
|
||||
GalleryLocalizations.of(context).rallyAccountDetailDataAccountOwner,
|
||||
value: 'Philip Cao',
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
static List<DetailedEventData> getDetailedEventItems() {
|
||||
// The following titles are not localized as they're product/brand names.
|
||||
return <DetailedEventData>[
|
||||
DetailedEventData(
|
||||
title: 'Genoe',
|
||||
date: DateTime.utc(2019, 1, 24),
|
||||
amount: -16.54,
|
||||
),
|
||||
DetailedEventData(
|
||||
title: 'Fortnightly Subscribe',
|
||||
date: DateTime.utc(2019, 1, 5),
|
||||
amount: -12.54,
|
||||
),
|
||||
DetailedEventData(
|
||||
title: 'Circle Cash',
|
||||
date: DateTime.utc(2019, 1, 5),
|
||||
amount: 365.65,
|
||||
),
|
||||
DetailedEventData(
|
||||
title: 'Crane Hospitality',
|
||||
date: DateTime.utc(2019, 1, 4),
|
||||
amount: -705.13,
|
||||
),
|
||||
DetailedEventData(
|
||||
title: 'ABC Payroll',
|
||||
date: DateTime.utc(2018, 12, 15),
|
||||
amount: 1141.43,
|
||||
),
|
||||
DetailedEventData(
|
||||
title: 'Shrine',
|
||||
date: DateTime.utc(2018, 12, 15),
|
||||
amount: -88.88,
|
||||
),
|
||||
DetailedEventData(
|
||||
title: 'Foodmates',
|
||||
date: DateTime.utc(2018, 12, 4),
|
||||
amount: -11.69,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
static List<BillData> getBillDataList(BuildContext context) {
|
||||
// The following names are not localized as they're product/brand names.
|
||||
return <BillData>[
|
||||
BillData(
|
||||
name: 'RedPay Credit',
|
||||
primaryAmount: 45.36,
|
||||
dueDate: dateFormatAbbreviatedMonthDay(context)
|
||||
.format(DateTime.utc(2019, 1, 29)),
|
||||
),
|
||||
BillData(
|
||||
name: 'Rent',
|
||||
primaryAmount: 1200,
|
||||
dueDate: dateFormatAbbreviatedMonthDay(context)
|
||||
.format(DateTime.utc(2019, 2, 9)),
|
||||
),
|
||||
BillData(
|
||||
name: 'TabFine Credit',
|
||||
primaryAmount: 87.33,
|
||||
dueDate: dateFormatAbbreviatedMonthDay(context)
|
||||
.format(DateTime.utc(2019, 2, 22)),
|
||||
),
|
||||
BillData(
|
||||
name: 'ABC Loans',
|
||||
primaryAmount: 400,
|
||||
dueDate: dateFormatAbbreviatedMonthDay(context)
|
||||
.format(DateTime.utc(2019, 2, 29)),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
static List<BudgetData> getBudgetDataList(BuildContext context) {
|
||||
return <BudgetData>[
|
||||
BudgetData(
|
||||
name: GalleryLocalizations.of(context).rallyBudgetCategoryCoffeeShops,
|
||||
primaryAmount: 70,
|
||||
amountUsed: 45.49,
|
||||
),
|
||||
BudgetData(
|
||||
name: GalleryLocalizations.of(context).rallyBudgetCategoryGroceries,
|
||||
primaryAmount: 170,
|
||||
amountUsed: 16.45,
|
||||
),
|
||||
BudgetData(
|
||||
name: GalleryLocalizations.of(context).rallyBudgetCategoryRestaurants,
|
||||
primaryAmount: 170,
|
||||
amountUsed: 123.25,
|
||||
),
|
||||
BudgetData(
|
||||
name: GalleryLocalizations.of(context).rallyBudgetCategoryClothing,
|
||||
primaryAmount: 70,
|
||||
amountUsed: 19.45,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
static List<String> getSettingsTitles(BuildContext context) {
|
||||
return <String>[
|
||||
GalleryLocalizations.of(context).rallySettingsManageAccounts,
|
||||
GalleryLocalizations.of(context).rallySettingsTaxDocuments,
|
||||
GalleryLocalizations.of(context).rallySettingsPasscodeAndTouchId,
|
||||
GalleryLocalizations.of(context).rallySettingsNotifications,
|
||||
GalleryLocalizations.of(context).rallySettingsPersonalInformation,
|
||||
GalleryLocalizations.of(context).rallySettingsPaperlessSettings,
|
||||
GalleryLocalizations.of(context).rallySettingsFindAtms,
|
||||
GalleryLocalizations.of(context).rallySettingsHelp,
|
||||
GalleryLocalizations.of(context).rallySettingsSignOut,
|
||||
];
|
||||
}
|
||||
|
||||
static List<AlertData> getAlerts(BuildContext context) {
|
||||
return <AlertData>[
|
||||
AlertData(
|
||||
message: GalleryLocalizations.of(context)
|
||||
.rallyAlertsMessageHeadsUpShopping(
|
||||
percentFormat(context, decimalDigits: 0).format(0.9)),
|
||||
iconData: Icons.sort,
|
||||
),
|
||||
AlertData(
|
||||
message: GalleryLocalizations.of(context)
|
||||
.rallyAlertsMessageSpentOnRestaurants(
|
||||
usdWithSignFormat(context, decimalDigits: 0).format(120)),
|
||||
iconData: Icons.sort,
|
||||
),
|
||||
AlertData(
|
||||
message: GalleryLocalizations.of(context).rallyAlertsMessageATMFees(
|
||||
usdWithSignFormat(context, decimalDigits: 0).format(24)),
|
||||
iconData: Icons.credit_card,
|
||||
),
|
||||
AlertData(
|
||||
message: GalleryLocalizations.of(context)
|
||||
.rallyAlertsMessageCheckingAccount(
|
||||
percentFormat(context, decimalDigits: 0).format(0.04)),
|
||||
iconData: Icons.attach_money,
|
||||
),
|
||||
AlertData(
|
||||
message: GalleryLocalizations.of(context)
|
||||
.rallyAlertsMessageUnassignedTransactions(16),
|
||||
iconData: Icons.not_interested,
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
406
gallery/lib/studies/rally/finance.dart
Normal file
406
gallery/lib/studies/rally/finance.dart
Normal file
@@ -0,0 +1,406 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/studies/rally/charts/line_chart.dart';
|
||||
import 'package:gallery/studies/rally/charts/pie_chart.dart';
|
||||
import 'package:gallery/studies/rally/charts/vertical_fraction_bar.dart';
|
||||
import 'package:gallery/studies/rally/colors.dart';
|
||||
import 'package:gallery/studies/rally/data.dart';
|
||||
import 'package:gallery/studies/rally/formatters.dart';
|
||||
|
||||
class FinancialEntityView extends StatelessWidget {
|
||||
const FinancialEntityView({
|
||||
this.heroLabel,
|
||||
this.heroAmount,
|
||||
this.wholeAmount,
|
||||
this.segments,
|
||||
this.financialEntityCards,
|
||||
}) : assert(segments.length == financialEntityCards.length);
|
||||
|
||||
/// The amounts to assign each item.
|
||||
final List<RallyPieChartSegment> segments;
|
||||
final String heroLabel;
|
||||
final double heroAmount;
|
||||
final double wholeAmount;
|
||||
final List<FinancialEntityCategoryView> financialEntityCards;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final maxWidth = pieChartMaxSize + (cappedTextScale(context) - 1.0) * 100.0;
|
||||
return LayoutBuilder(builder: (context, constraints) {
|
||||
return Column(
|
||||
children: [
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
// We decrease the max height to ensure the [RallyPieChart] does
|
||||
// not take up the full height when it is smaller than
|
||||
// [kPieChartMaxSize].
|
||||
maxHeight: math.min(
|
||||
constraints.biggest.shortestSide * 0.9,
|
||||
maxWidth,
|
||||
),
|
||||
),
|
||||
child: RallyPieChart(
|
||||
heroLabel: heroLabel,
|
||||
heroAmount: heroAmount,
|
||||
wholeAmount: wholeAmount,
|
||||
segments: segments,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Container(
|
||||
height: 1,
|
||||
constraints: BoxConstraints(maxWidth: maxWidth),
|
||||
color: RallyColors.inputBackground,
|
||||
),
|
||||
Container(
|
||||
constraints: BoxConstraints(maxWidth: maxWidth),
|
||||
color: RallyColors.cardBackground,
|
||||
child: Column(
|
||||
children: financialEntityCards,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A reusable widget to show balance information of a single entity as a card.
|
||||
class FinancialEntityCategoryView extends StatelessWidget {
|
||||
const FinancialEntityCategoryView({
|
||||
@required this.indicatorColor,
|
||||
@required this.indicatorFraction,
|
||||
@required this.title,
|
||||
@required this.subtitle,
|
||||
@required this.semanticsLabel,
|
||||
@required this.amount,
|
||||
@required this.suffix,
|
||||
});
|
||||
|
||||
final Color indicatorColor;
|
||||
final double indicatorFraction;
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final String semanticsLabel;
|
||||
final String amount;
|
||||
final Widget suffix;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
return Semantics.fromProperties(
|
||||
properties: SemanticsProperties(
|
||||
button: true,
|
||||
label: semanticsLabel,
|
||||
),
|
||||
excludeSemantics: true,
|
||||
child: FlatButton(
|
||||
onPressed: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute<FinancialEntityCategoryDetailsPage>(
|
||||
builder: (context) => FinancialEntityCategoryDetailsPage(),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(vertical: 16),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
alignment: Alignment.center,
|
||||
height: 32 + 60 * (cappedTextScale(context) - 1),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12),
|
||||
child: VerticalFractionBar(
|
||||
color: indicatorColor,
|
||||
fraction: indicatorFraction,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: textTheme.body1.copyWith(fontSize: 16),
|
||||
),
|
||||
Text(
|
||||
subtitle,
|
||||
style: textTheme.body1
|
||||
.copyWith(color: RallyColors.gray60),
|
||||
),
|
||||
],
|
||||
),
|
||||
Text(
|
||||
amount,
|
||||
style: textTheme.body2.copyWith(
|
||||
fontSize: 20,
|
||||
color: RallyColors.gray,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Container(
|
||||
constraints: BoxConstraints(minWidth: 32),
|
||||
padding: EdgeInsetsDirectional.only(start: 12),
|
||||
child: suffix,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(
|
||||
height: 1,
|
||||
indent: 16,
|
||||
endIndent: 16,
|
||||
color: Color(0xAA282828),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Data model for [FinancialEntityCategoryView].
|
||||
class FinancialEntityCategoryModel {
|
||||
const FinancialEntityCategoryModel(
|
||||
this.indicatorColor,
|
||||
this.indicatorFraction,
|
||||
this.title,
|
||||
this.subtitle,
|
||||
this.usdAmount,
|
||||
this.suffix,
|
||||
);
|
||||
|
||||
final Color indicatorColor;
|
||||
final double indicatorFraction;
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final double usdAmount;
|
||||
final Widget suffix;
|
||||
}
|
||||
|
||||
FinancialEntityCategoryView buildFinancialEntityFromAccountData(
|
||||
AccountData model,
|
||||
int accountDataIndex,
|
||||
BuildContext context,
|
||||
) {
|
||||
final amount = usdWithSignFormat(context).format(model.primaryAmount);
|
||||
final shortAccountNumber = model.accountNumber.substring(6);
|
||||
return FinancialEntityCategoryView(
|
||||
suffix: const Icon(Icons.chevron_right, color: Colors.grey),
|
||||
title: model.name,
|
||||
subtitle: '• • • • • • $shortAccountNumber',
|
||||
semanticsLabel: GalleryLocalizations.of(context).rallyAccountAmount(
|
||||
model.name,
|
||||
shortAccountNumber,
|
||||
amount,
|
||||
),
|
||||
indicatorColor: RallyColors.accountColor(accountDataIndex),
|
||||
indicatorFraction: 1,
|
||||
amount: amount,
|
||||
);
|
||||
}
|
||||
|
||||
FinancialEntityCategoryView buildFinancialEntityFromBillData(
|
||||
BillData model,
|
||||
int billDataIndex,
|
||||
BuildContext context,
|
||||
) {
|
||||
final amount = usdWithSignFormat(context).format(model.primaryAmount);
|
||||
return FinancialEntityCategoryView(
|
||||
suffix: const Icon(Icons.chevron_right, color: Colors.grey),
|
||||
title: model.name,
|
||||
subtitle: model.dueDate,
|
||||
semanticsLabel: GalleryLocalizations.of(context).rallyBillAmount(
|
||||
model.name,
|
||||
model.dueDate,
|
||||
amount,
|
||||
),
|
||||
indicatorColor: RallyColors.billColor(billDataIndex),
|
||||
indicatorFraction: 1,
|
||||
amount: amount,
|
||||
);
|
||||
}
|
||||
|
||||
FinancialEntityCategoryView buildFinancialEntityFromBudgetData(
|
||||
BudgetData model,
|
||||
int budgetDataIndex,
|
||||
BuildContext context,
|
||||
) {
|
||||
final amountUsed = usdWithSignFormat(context).format(model.amountUsed);
|
||||
final primaryAmount = usdWithSignFormat(context).format(model.primaryAmount);
|
||||
final amount =
|
||||
usdWithSignFormat(context).format(model.primaryAmount - model.amountUsed);
|
||||
|
||||
return FinancialEntityCategoryView(
|
||||
suffix: Text(
|
||||
GalleryLocalizations.of(context).rallyFinanceLeft,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.body1
|
||||
.copyWith(color: RallyColors.gray60, fontSize: 10),
|
||||
),
|
||||
title: model.name,
|
||||
subtitle: amountUsed + ' / ' + primaryAmount,
|
||||
semanticsLabel: GalleryLocalizations.of(context).rallyBudgetAmount(
|
||||
model.name,
|
||||
model.amountUsed,
|
||||
model.primaryAmount,
|
||||
amount,
|
||||
),
|
||||
indicatorColor: RallyColors.budgetColor(budgetDataIndex),
|
||||
indicatorFraction: model.amountUsed / model.primaryAmount,
|
||||
amount: amount,
|
||||
);
|
||||
}
|
||||
|
||||
List<FinancialEntityCategoryView> buildAccountDataListViews(
|
||||
List<AccountData> items,
|
||||
BuildContext context,
|
||||
) {
|
||||
return List<FinancialEntityCategoryView>.generate(
|
||||
items.length,
|
||||
(i) => buildFinancialEntityFromAccountData(items[i], i, context),
|
||||
);
|
||||
}
|
||||
|
||||
List<FinancialEntityCategoryView> buildBillDataListViews(
|
||||
List<BillData> items,
|
||||
BuildContext context,
|
||||
) {
|
||||
return List<FinancialEntityCategoryView>.generate(
|
||||
items.length,
|
||||
(i) => buildFinancialEntityFromBillData(items[i], i, context),
|
||||
);
|
||||
}
|
||||
|
||||
List<FinancialEntityCategoryView> buildBudgetDataListViews(
|
||||
List<BudgetData> items,
|
||||
BuildContext context,
|
||||
) {
|
||||
return <FinancialEntityCategoryView>[
|
||||
for (int i = 0; i < items.length; i++)
|
||||
buildFinancialEntityFromBudgetData(items[i], i, context)
|
||||
];
|
||||
}
|
||||
|
||||
class FinancialEntityCategoryDetailsPage extends StatelessWidget {
|
||||
final List<DetailedEventData> items =
|
||||
DummyDataService.getDetailedEventItems();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final List<_DetailedEventCard> cards = items.map((detailedEventData) {
|
||||
return _DetailedEventCard(
|
||||
title: detailedEventData.title,
|
||||
date: detailedEventData.date,
|
||||
amount: detailedEventData.amount,
|
||||
);
|
||||
}).toList();
|
||||
|
||||
return ApplyTextOptions(
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
elevation: 0,
|
||||
centerTitle: true,
|
||||
title: Text(
|
||||
GalleryLocalizations.of(context).rallyAccountDataChecking,
|
||||
style: Theme.of(context).textTheme.body1.copyWith(fontSize: 18),
|
||||
),
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 200,
|
||||
width: double.infinity,
|
||||
child: RallyLineChart(events: items),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView(shrinkWrap: true, children: cards),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DetailedEventCard extends StatelessWidget {
|
||||
const _DetailedEventCard({
|
||||
@required this.title,
|
||||
@required this.date,
|
||||
@required this.amount,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final DateTime date;
|
||||
final double amount;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
return FlatButton(
|
||||
onPressed: () {},
|
||||
padding: EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(vertical: 16),
|
||||
width: double.infinity,
|
||||
child: Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: textTheme.body1.copyWith(fontSize: 16),
|
||||
),
|
||||
Text(
|
||||
shortDateFormat(context).format(date),
|
||||
semanticsLabel: longDateFormat(context).format(date),
|
||||
style:
|
||||
textTheme.body1.copyWith(color: RallyColors.gray60),
|
||||
),
|
||||
],
|
||||
),
|
||||
Text(
|
||||
usdWithSignFormat(context).format(amount),
|
||||
style: textTheme.body2
|
||||
.copyWith(fontSize: 20, color: RallyColors.gray),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 1,
|
||||
child: Container(
|
||||
color: const Color(0xAA282828),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
44
gallery/lib/studies/rally/formatters.dart
Normal file
44
gallery/lib/studies/rally/formatters.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
/// Get the locale string for the context.
|
||||
String locale(BuildContext context) =>
|
||||
GalleryOptions.of(context).locale.toString();
|
||||
|
||||
/// Currency formatter for USD.
|
||||
NumberFormat usdWithSignFormat(BuildContext context, {int decimalDigits = 2}) {
|
||||
return NumberFormat.currency(
|
||||
locale: locale(context),
|
||||
name: '\$',
|
||||
decimalDigits: decimalDigits,
|
||||
);
|
||||
}
|
||||
|
||||
/// Percent formatter with two decimal points.
|
||||
NumberFormat percentFormat(BuildContext context, {int decimalDigits = 2}) {
|
||||
return NumberFormat.decimalPercentPattern(
|
||||
locale: locale(context),
|
||||
decimalDigits: decimalDigits,
|
||||
);
|
||||
}
|
||||
|
||||
/// Date formatter with year / number month / day.
|
||||
DateFormat shortDateFormat(BuildContext context) =>
|
||||
DateFormat.yMd(locale(context));
|
||||
|
||||
/// Date formatter with year / month / day.
|
||||
DateFormat longDateFormat(BuildContext context) =>
|
||||
DateFormat.yMMMMd(locale(context));
|
||||
|
||||
/// Date formatter with abbreviated month and day.
|
||||
DateFormat dateFormatAbbreviatedMonthDay(BuildContext context) =>
|
||||
DateFormat.MMMd(locale(context));
|
||||
|
||||
/// Date formatter with year and abbreviated month.
|
||||
DateFormat dateFormatMonthYear(BuildContext context) =>
|
||||
DateFormat.yMMM(locale(context));
|
||||
368
gallery/lib/studies/rally/home.dart
Normal file
368
gallery/lib/studies/rally/home.dart
Normal file
@@ -0,0 +1,368 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/pages/home.dart';
|
||||
import 'package:gallery/layout/focus_traversal_policy.dart';
|
||||
import 'package:gallery/studies/rally/tabs/accounts.dart';
|
||||
import 'package:gallery/studies/rally/tabs/bills.dart';
|
||||
import 'package:gallery/studies/rally/tabs/budgets.dart';
|
||||
import 'package:gallery/studies/rally/tabs/overview.dart';
|
||||
import 'package:gallery/studies/rally/tabs/settings.dart';
|
||||
|
||||
const int tabCount = 5;
|
||||
const int turnsToRotateRight = 1;
|
||||
const int turnsToRotateLeft = 3;
|
||||
|
||||
class HomePage extends StatefulWidget {
|
||||
@override
|
||||
_HomePageState createState() => _HomePageState();
|
||||
}
|
||||
|
||||
class _HomePageState extends State<HomePage>
|
||||
with SingleTickerProviderStateMixin {
|
||||
TabController _tabController;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tabController = TabController(length: tabCount, vsync: this)
|
||||
..addListener(() {
|
||||
// Set state to make sure that the [_RallyTab] widgets get updated when changing tabs.
|
||||
setState(() {});
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_tabController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final ThemeData theme = Theme.of(context);
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
Widget tabBarView;
|
||||
if (isDesktop) {
|
||||
final isTextDirectionRtl =
|
||||
GalleryOptions.of(context).textDirection() == TextDirection.rtl;
|
||||
final verticalRotation =
|
||||
isTextDirectionRtl ? turnsToRotateLeft : turnsToRotateRight;
|
||||
final revertVerticalRotation =
|
||||
isTextDirectionRtl ? turnsToRotateRight : turnsToRotateLeft;
|
||||
tabBarView = Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 150 + 50 * (cappedTextScale(context) - 1),
|
||||
alignment: Alignment.topCenter,
|
||||
padding: const EdgeInsets.symmetric(vertical: 32),
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 24),
|
||||
ExcludeSemantics(
|
||||
child: SizedBox(
|
||||
height: 80,
|
||||
child: Image.asset(
|
||||
'logo.png',
|
||||
package: 'rally_assets',
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
// Rotate the tab bar, so the animation is vertical for desktops.
|
||||
RotatedBox(
|
||||
quarterTurns: verticalRotation,
|
||||
child: _RallyTabBar(
|
||||
tabs: _buildTabs(
|
||||
context: context, theme: theme, isVertical: true)
|
||||
.map(
|
||||
(widget) {
|
||||
// Revert the rotation on the tabs.
|
||||
return RotatedBox(
|
||||
quarterTurns: revertVerticalRotation,
|
||||
child: widget,
|
||||
);
|
||||
},
|
||||
).toList(),
|
||||
tabController: _tabController,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
// Rotate the tab views so we can swipe up and down.
|
||||
child: RotatedBox(
|
||||
quarterTurns: verticalRotation,
|
||||
child: TabBarView(
|
||||
controller: _tabController,
|
||||
children: _buildTabViews().map(
|
||||
(widget) {
|
||||
// Revert the rotation on the tab views.
|
||||
return RotatedBox(
|
||||
quarterTurns: revertVerticalRotation,
|
||||
child: widget,
|
||||
);
|
||||
},
|
||||
).toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
tabBarView = Column(
|
||||
children: [
|
||||
_RallyTabBar(
|
||||
tabs: _buildTabs(context: context, theme: theme),
|
||||
tabController: _tabController,
|
||||
),
|
||||
Expanded(
|
||||
child: TabBarView(
|
||||
controller: _tabController,
|
||||
children: _buildTabViews(),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
final backButtonFocusNode =
|
||||
InheritedFocusNodes.of(context).backButtonFocusNode;
|
||||
|
||||
return DefaultFocusTraversal(
|
||||
policy: EdgeChildrenFocusTraversalPolicy(
|
||||
firstFocusNodeOutsideScope: backButtonFocusNode,
|
||||
lastFocusNodeOutsideScope: backButtonFocusNode,
|
||||
focusScope: FocusScope.of(context),
|
||||
),
|
||||
child: ApplyTextOptions(
|
||||
child: Scaffold(
|
||||
body: SafeArea(
|
||||
// For desktop layout we do not want to have SafeArea at the top and
|
||||
// bottom to display 100% height content on the accounts view.
|
||||
top: !isDesktop,
|
||||
bottom: !isDesktop,
|
||||
child: Theme(
|
||||
// This theme effectively removes the default visual touch
|
||||
// feedback for tapping a tab, which is replaced with a custom
|
||||
// animation.
|
||||
data: theme.copyWith(
|
||||
splashColor: Colors.transparent,
|
||||
highlightColor: Colors.transparent,
|
||||
),
|
||||
child: tabBarView,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _buildTabs(
|
||||
{BuildContext context, ThemeData theme, bool isVertical = false}) {
|
||||
return [
|
||||
_RallyTab(
|
||||
theme: theme,
|
||||
iconData: Icons.pie_chart,
|
||||
title: GalleryLocalizations.of(context).rallyTitleOverview,
|
||||
tabIndex: 0,
|
||||
tabController: _tabController,
|
||||
isVertical: isVertical,
|
||||
),
|
||||
_RallyTab(
|
||||
theme: theme,
|
||||
iconData: Icons.attach_money,
|
||||
title: GalleryLocalizations.of(context).rallyTitleAccounts,
|
||||
tabIndex: 1,
|
||||
tabController: _tabController,
|
||||
isVertical: isVertical,
|
||||
),
|
||||
_RallyTab(
|
||||
theme: theme,
|
||||
iconData: Icons.money_off,
|
||||
title: GalleryLocalizations.of(context).rallyTitleBills,
|
||||
tabIndex: 2,
|
||||
tabController: _tabController,
|
||||
isVertical: isVertical,
|
||||
),
|
||||
_RallyTab(
|
||||
theme: theme,
|
||||
iconData: Icons.table_chart,
|
||||
title: GalleryLocalizations.of(context).rallyTitleBudgets,
|
||||
tabIndex: 3,
|
||||
tabController: _tabController,
|
||||
isVertical: isVertical,
|
||||
),
|
||||
_RallyTab(
|
||||
theme: theme,
|
||||
iconData: Icons.settings,
|
||||
title: GalleryLocalizations.of(context).rallyTitleSettings,
|
||||
tabIndex: 4,
|
||||
tabController: _tabController,
|
||||
isVertical: isVertical,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
List<Widget> _buildTabViews() {
|
||||
return [
|
||||
OverviewView(),
|
||||
AccountsView(),
|
||||
BillsView(),
|
||||
BudgetsView(),
|
||||
SettingsView(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
class _RallyTabBar extends StatelessWidget {
|
||||
const _RallyTabBar({Key key, this.tabs, this.tabController})
|
||||
: super(key: key);
|
||||
|
||||
final List<Widget> tabs;
|
||||
final TabController tabController;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return TabBar(
|
||||
// Setting isScrollable to true prevents the tabs from being
|
||||
// wrapped in [Expanded] widgets, which allows for more
|
||||
// flexible sizes and size animations among tabs.
|
||||
isScrollable: true,
|
||||
labelPadding: EdgeInsets.zero,
|
||||
tabs: tabs,
|
||||
controller: tabController,
|
||||
// This hides the tab indicator.
|
||||
indicatorColor: Colors.transparent,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RallyTab extends StatefulWidget {
|
||||
_RallyTab({
|
||||
ThemeData theme,
|
||||
IconData iconData,
|
||||
String title,
|
||||
int tabIndex,
|
||||
TabController tabController,
|
||||
this.isVertical,
|
||||
}) : titleText = Text(title, style: theme.textTheme.button),
|
||||
isExpanded = tabController.index == tabIndex,
|
||||
icon = Icon(iconData, semanticLabel: title);
|
||||
|
||||
final Text titleText;
|
||||
final Icon icon;
|
||||
final bool isExpanded;
|
||||
final bool isVertical;
|
||||
|
||||
@override
|
||||
_RallyTabState createState() => _RallyTabState();
|
||||
}
|
||||
|
||||
class _RallyTabState extends State<_RallyTab>
|
||||
with SingleTickerProviderStateMixin {
|
||||
Animation<double> _titleSizeAnimation;
|
||||
Animation<double> _titleFadeAnimation;
|
||||
Animation<double> _iconFadeAnimation;
|
||||
AnimationController _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = AnimationController(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
vsync: this,
|
||||
);
|
||||
_titleSizeAnimation = _controller.view;
|
||||
_titleFadeAnimation = _controller.drive(CurveTween(curve: Curves.easeOut));
|
||||
_iconFadeAnimation = _controller.drive(Tween<double>(begin: 0.6, end: 1));
|
||||
if (widget.isExpanded) {
|
||||
_controller.value = 1;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(_RallyTab oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.isExpanded) {
|
||||
_controller.forward();
|
||||
} else {
|
||||
_controller.reverse();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (widget.isVertical) {
|
||||
return Column(
|
||||
children: [
|
||||
const SizedBox(height: 18),
|
||||
FadeTransition(
|
||||
child: widget.icon,
|
||||
opacity: _iconFadeAnimation,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
FadeTransition(
|
||||
child: SizeTransition(
|
||||
child: Center(child: ExcludeSemantics(child: widget.titleText)),
|
||||
axis: Axis.vertical,
|
||||
axisAlignment: -1,
|
||||
sizeFactor: _titleSizeAnimation,
|
||||
),
|
||||
opacity: _titleFadeAnimation,
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Calculate the width of each unexpanded tab by counting the number of
|
||||
// units and dividing it into the screen width. Each unexpanded tab is 1
|
||||
// unit, and there is always 1 expanded tab which is 1 unit + any extra
|
||||
// space determined by the multiplier.
|
||||
final width = MediaQuery.of(context).size.width;
|
||||
const expandedTitleWidthMultiplier = 2;
|
||||
final unitWidth = width / (tabCount + expandedTitleWidthMultiplier);
|
||||
|
||||
return ConstrainedBox(
|
||||
constraints: BoxConstraints(minHeight: 56),
|
||||
child: Row(
|
||||
children: [
|
||||
FadeTransition(
|
||||
child: SizedBox(
|
||||
width: unitWidth,
|
||||
child: widget.icon,
|
||||
),
|
||||
opacity: _iconFadeAnimation,
|
||||
),
|
||||
FadeTransition(
|
||||
child: SizeTransition(
|
||||
child: SizedBox(
|
||||
width: unitWidth * expandedTitleWidthMultiplier,
|
||||
child: Center(
|
||||
child: ExcludeSemantics(child: widget.titleText),
|
||||
),
|
||||
),
|
||||
axis: Axis.horizontal,
|
||||
axisAlignment: -1,
|
||||
sizeFactor: _titleSizeAnimation,
|
||||
),
|
||||
opacity: _titleFadeAnimation,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
412
gallery/lib/studies/rally/login.dart
Normal file
412
gallery/lib/studies/rally/login.dart
Normal file
@@ -0,0 +1,412 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/pages/home.dart';
|
||||
import 'package:gallery/studies/rally/colors.dart';
|
||||
import 'package:gallery/layout/focus_traversal_policy.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) {
|
||||
final backButtonFocusNode =
|
||||
InheritedFocusNodes.of(context).backButtonFocusNode;
|
||||
|
||||
return DefaultFocusTraversal(
|
||||
policy: EdgeChildrenFocusTraversalPolicy(
|
||||
firstFocusNodeOutsideScope: backButtonFocusNode,
|
||||
lastFocusNodeOutsideScope: backButtonFocusNode,
|
||||
focusScope: FocusScope.of(context),
|
||||
),
|
||||
child: ApplyTextOptions(
|
||||
child: Scaffold(
|
||||
body: SafeArea(
|
||||
child: _MainView(
|
||||
usernameController: _usernameController,
|
||||
passwordController: _passwordController,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_usernameController.dispose();
|
||||
_passwordController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class _MainView extends StatelessWidget {
|
||||
const _MainView({
|
||||
Key key,
|
||||
this.usernameController,
|
||||
this.passwordController,
|
||||
}) : super(key: key);
|
||||
|
||||
final TextEditingController usernameController;
|
||||
final TextEditingController passwordController;
|
||||
|
||||
void _login(BuildContext context) {
|
||||
Navigator.pop(context);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
List<Widget> listViewChildren;
|
||||
|
||||
if (isDesktop) {
|
||||
final desktopMaxWidth = 400.0 + 100.0 * (cappedTextScale(context) - 1);
|
||||
listViewChildren = [
|
||||
_UsernameInput(
|
||||
maxWidth: desktopMaxWidth,
|
||||
usernameController: usernameController,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_PasswordInput(
|
||||
maxWidth: desktopMaxWidth,
|
||||
passwordController: passwordController,
|
||||
),
|
||||
_LoginButton(
|
||||
maxWidth: desktopMaxWidth,
|
||||
onTap: () {
|
||||
_login(context);
|
||||
},
|
||||
),
|
||||
];
|
||||
} else {
|
||||
listViewChildren = [
|
||||
_SmallLogo(),
|
||||
_UsernameInput(
|
||||
usernameController: usernameController,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
_PasswordInput(
|
||||
passwordController: passwordController,
|
||||
),
|
||||
_ThumbButton(
|
||||
onTap: () {
|
||||
_login(context);
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
if (isDesktop) _TopBar(),
|
||||
Expanded(
|
||||
child: Align(
|
||||
alignment: isDesktop ? Alignment.center : Alignment.topCenter,
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
children: listViewChildren,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TopBar extends StatelessWidget {
|
||||
const _TopBar({
|
||||
Key key,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final spacing = const SizedBox(width: 30);
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
margin: const EdgeInsets.only(top: 8),
|
||||
padding: EdgeInsets.symmetric(horizontal: 30),
|
||||
child: Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ExcludeSemantics(
|
||||
child: SizedBox(
|
||||
height: 80,
|
||||
child: Image.asset(
|
||||
'logo.png',
|
||||
package: 'rally_assets',
|
||||
),
|
||||
),
|
||||
),
|
||||
spacing,
|
||||
Text(
|
||||
GalleryLocalizations.of(context).rallyLoginLoginToRally,
|
||||
style: Theme.of(context).textTheme.body2.copyWith(
|
||||
fontSize: 35 / reducedTextScale(context),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
GalleryLocalizations.of(context).rallyLoginNoAccount,
|
||||
style: Theme.of(context).textTheme.subhead,
|
||||
),
|
||||
spacing,
|
||||
_BorderButton(
|
||||
text: GalleryLocalizations.of(context).rallyLoginSignUp,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SmallLogo extends StatelessWidget {
|
||||
const _SmallLogo({
|
||||
Key key,
|
||||
}) : super(key: key);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 64),
|
||||
child: SizedBox(
|
||||
height: 160,
|
||||
child: ExcludeSemantics(
|
||||
child: Image.asset(
|
||||
'logo.png',
|
||||
package: 'rally_assets',
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _UsernameInput extends StatelessWidget {
|
||||
const _UsernameInput({
|
||||
Key key,
|
||||
this.maxWidth,
|
||||
this.usernameController,
|
||||
}) : super(key: key);
|
||||
|
||||
final double maxWidth;
|
||||
final TextEditingController usernameController;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Align(
|
||||
alignment: Alignment.center,
|
||||
child: Container(
|
||||
constraints: BoxConstraints(maxWidth: maxWidth ?? double.infinity),
|
||||
child: TextField(
|
||||
controller: usernameController,
|
||||
decoration: InputDecoration(
|
||||
labelText: GalleryLocalizations.of(context).rallyLoginUsername,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PasswordInput extends StatelessWidget {
|
||||
const _PasswordInput({
|
||||
Key key,
|
||||
this.maxWidth,
|
||||
this.passwordController,
|
||||
}) : super(key: key);
|
||||
|
||||
final double maxWidth;
|
||||
final TextEditingController passwordController;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Align(
|
||||
alignment: Alignment.center,
|
||||
child: Container(
|
||||
constraints: BoxConstraints(maxWidth: maxWidth ?? double.infinity),
|
||||
child: TextField(
|
||||
controller: passwordController,
|
||||
decoration: InputDecoration(
|
||||
labelText: GalleryLocalizations.of(context).rallyLoginPassword,
|
||||
),
|
||||
obscureText: true,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ThumbButton extends StatefulWidget {
|
||||
_ThumbButton({
|
||||
@required this.onTap,
|
||||
});
|
||||
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
_ThumbButtonState createState() => _ThumbButtonState();
|
||||
}
|
||||
|
||||
class _ThumbButtonState extends State<_ThumbButton> {
|
||||
BoxDecoration borderDecoration;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Semantics(
|
||||
button: true,
|
||||
enabled: true,
|
||||
label: GalleryLocalizations.of(context).rallyLoginLabelLogin,
|
||||
child: GestureDetector(
|
||||
onTap: widget.onTap,
|
||||
child: Focus(
|
||||
onKey: (node, event) {
|
||||
if (event is RawKeyDownEvent) {
|
||||
if (event.logicalKey == LogicalKeyboardKey.enter ||
|
||||
event.logicalKey == LogicalKeyboardKey.space) {
|
||||
widget.onTap();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
onFocusChange: (hasFocus) {
|
||||
if (hasFocus) {
|
||||
setState(() {
|
||||
borderDecoration = BoxDecoration(
|
||||
border: Border.all(
|
||||
color: Colors.white.withOpacity(0.5),
|
||||
width: 2,
|
||||
),
|
||||
);
|
||||
});
|
||||
} else {
|
||||
setState(() {
|
||||
borderDecoration = null;
|
||||
});
|
||||
}
|
||||
},
|
||||
child: Container(
|
||||
decoration: borderDecoration,
|
||||
height: 120,
|
||||
child: ExcludeSemantics(
|
||||
child: Image.asset(
|
||||
'thumb.png',
|
||||
package: 'rally_assets',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LoginButton extends StatelessWidget {
|
||||
const _LoginButton({
|
||||
Key key,
|
||||
@required this.onTap,
|
||||
this.maxWidth,
|
||||
}) : super(key: key);
|
||||
|
||||
final double maxWidth;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Align(
|
||||
alignment: Alignment.center,
|
||||
child: Container(
|
||||
constraints: BoxConstraints(maxWidth: maxWidth ?? double.infinity),
|
||||
padding: const EdgeInsets.symmetric(vertical: 30),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle_outline, color: RallyColors.buttonColor),
|
||||
const SizedBox(width: 12),
|
||||
Text(GalleryLocalizations.of(context).rallyLoginRememberMe),
|
||||
const Expanded(child: SizedBox.shrink()),
|
||||
_FilledButton(
|
||||
text: GalleryLocalizations.of(context).rallyLoginButtonLogin,
|
||||
onTap: onTap,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BorderButton extends StatelessWidget {
|
||||
const _BorderButton({Key key, @required this.text}) : super(key: key);
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return OutlineButton(
|
||||
borderSide: const BorderSide(color: RallyColors.buttonColor),
|
||||
color: RallyColors.buttonColor,
|
||||
highlightedBorderColor: RallyColors.buttonColor,
|
||||
focusColor: RallyColors.buttonColor.withOpacity(0.8),
|
||||
padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 24),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
textColor: Colors.white,
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
},
|
||||
child: Text(text),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FilledButton extends StatelessWidget {
|
||||
const _FilledButton({Key key, @required this.text, @required this.onTap})
|
||||
: super(key: key);
|
||||
|
||||
final String text;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FlatButton(
|
||||
color: RallyColors.buttonColor,
|
||||
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 24),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
onPressed: onTap,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.lock),
|
||||
const SizedBox(width: 6),
|
||||
Text(text),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
92
gallery/lib/studies/rally/tabs/accounts.dart
Normal file
92
gallery/lib/studies/rally/tabs/accounts.dart
Normal file
@@ -0,0 +1,92 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/studies/rally/charts/pie_chart.dart';
|
||||
import 'package:gallery/studies/rally/colors.dart';
|
||||
import 'package:gallery/studies/rally/data.dart';
|
||||
import 'package:gallery/studies/rally/finance.dart';
|
||||
|
||||
/// A page that shows a summary of accounts.
|
||||
class AccountsView extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final items = DummyDataService.getAccountDataList(context);
|
||||
final detailItems = DummyDataService.getAccountDetailList(context);
|
||||
final balanceTotal = sumAccountDataPrimaryAmount(items);
|
||||
final view = FinancialEntityView(
|
||||
heroLabel: GalleryLocalizations.of(context).rallyAccountTotal,
|
||||
heroAmount: balanceTotal,
|
||||
segments: buildSegmentsFromAccountItems(items),
|
||||
wholeAmount: balanceTotal,
|
||||
financialEntityCards: buildAccountDataListViews(items, context),
|
||||
);
|
||||
if (isDisplayDesktop(context)) {
|
||||
return Row(
|
||||
children: [
|
||||
Flexible(
|
||||
flex: 2,
|
||||
child: SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 24),
|
||||
child: view,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
flex: 1,
|
||||
child: Container(
|
||||
color: RallyColors.inputBackground,
|
||||
padding: EdgeInsetsDirectional.only(start: 24),
|
||||
height: double.infinity,
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: [
|
||||
for (AccountDetailData item in detailItems)
|
||||
_AccountDetail(title: item.title, value: item.value),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
return SingleChildScrollView(child: view);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _AccountDetail extends StatelessWidget {
|
||||
const _AccountDetail({Key key, this.value, this.title}) : super(key: key);
|
||||
|
||||
final String value;
|
||||
final String title;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
title,
|
||||
style:
|
||||
textTheme.body1.copyWith(fontSize: 16, color: RallyColors.gray60),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
value,
|
||||
style: textTheme.body2.copyWith(fontSize: 20),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Container(color: RallyColors.primaryBackground, height: 1),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
38
gallery/lib/studies/rally/tabs/bills.dart
Normal file
38
gallery/lib/studies/rally/tabs/bills.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/studies/rally/charts/pie_chart.dart';
|
||||
import 'package:gallery/studies/rally/data.dart';
|
||||
import 'package:gallery/studies/rally/finance.dart';
|
||||
|
||||
/// A page that shows a summary of bills.
|
||||
class BillsView extends StatefulWidget {
|
||||
@override
|
||||
_BillsViewState createState() => _BillsViewState();
|
||||
}
|
||||
|
||||
class _BillsViewState extends State<BillsView>
|
||||
with SingleTickerProviderStateMixin {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
List<BillData> items = DummyDataService.getBillDataList(context);
|
||||
final dueTotal = sumBillDataPrimaryAmount(items);
|
||||
return SingleChildScrollView(
|
||||
child: Container(
|
||||
padding: isDisplayDesktop(context) ? EdgeInsets.only(top: 24) : null,
|
||||
child: FinancialEntityView(
|
||||
heroLabel: GalleryLocalizations.of(context).rallyBillsDue,
|
||||
heroAmount: dueTotal,
|
||||
segments: buildSegmentsFromBillItems(items),
|
||||
wholeAmount: dueTotal,
|
||||
financialEntityCards: buildBillDataListViews(items, context),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
38
gallery/lib/studies/rally/tabs/budgets.dart
Normal file
38
gallery/lib/studies/rally/tabs/budgets.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/studies/rally/charts/pie_chart.dart';
|
||||
import 'package:gallery/studies/rally/data.dart';
|
||||
import 'package:gallery/studies/rally/finance.dart';
|
||||
|
||||
class BudgetsView extends StatefulWidget {
|
||||
@override
|
||||
_BudgetsViewState createState() => _BudgetsViewState();
|
||||
}
|
||||
|
||||
class _BudgetsViewState extends State<BudgetsView>
|
||||
with SingleTickerProviderStateMixin {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final items = DummyDataService.getBudgetDataList(context);
|
||||
final capTotal = sumBudgetDataPrimaryAmount(items);
|
||||
final usedTotal = sumBudgetDataAmountUsed(items);
|
||||
return SingleChildScrollView(
|
||||
child: Container(
|
||||
padding: isDisplayDesktop(context) ? EdgeInsets.only(top: 24) : null,
|
||||
child: FinancialEntityView(
|
||||
heroLabel: GalleryLocalizations.of(context).rallyBudgetLeft,
|
||||
heroAmount: capTotal - usedTotal,
|
||||
segments: buildSegmentsFromBudgetItems(items),
|
||||
wholeAmount: capTotal,
|
||||
financialEntityCards: buildBudgetDataListViews(items, context),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
279
gallery/lib/studies/rally/tabs/overview.dart
Normal file
279
gallery/lib/studies/rally/tabs/overview.dart
Normal file
@@ -0,0 +1,279 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/studies/rally/colors.dart';
|
||||
import 'package:gallery/studies/rally/data.dart';
|
||||
import 'package:gallery/studies/rally/finance.dart';
|
||||
import 'package:gallery/studies/rally/formatters.dart';
|
||||
|
||||
/// A page that shows a status overview.
|
||||
class OverviewView extends StatefulWidget {
|
||||
@override
|
||||
_OverviewViewState createState() => _OverviewViewState();
|
||||
}
|
||||
|
||||
class _OverviewViewState extends State<OverviewView> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final alerts = DummyDataService.getAlerts(context);
|
||||
|
||||
if (isDisplayDesktop(context)) {
|
||||
const sortKeyName = 'Overview';
|
||||
return SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 24),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Flexible(
|
||||
flex: 7,
|
||||
child: Semantics(
|
||||
sortKey: const OrdinalSortKey(1, name: sortKeyName),
|
||||
child: _OverviewGrid(spacing: 24),
|
||||
),
|
||||
),
|
||||
SizedBox(width: 24),
|
||||
Flexible(
|
||||
flex: 3,
|
||||
child: Container(
|
||||
width: 400,
|
||||
child: Semantics(
|
||||
sortKey: const OrdinalSortKey(2, name: sortKeyName),
|
||||
child: _AlertsView(alerts: alerts),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
child: Column(
|
||||
children: [
|
||||
_AlertsView(alerts: alerts.sublist(0, 1)),
|
||||
SizedBox(height: 12),
|
||||
_OverviewGrid(spacing: 12),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _OverviewGrid extends StatelessWidget {
|
||||
const _OverviewGrid({Key key, @required this.spacing}) : super(key: key);
|
||||
|
||||
final double spacing;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final accountDataList = DummyDataService.getAccountDataList(context);
|
||||
final billDataList = DummyDataService.getBillDataList(context);
|
||||
final budgetDataList = DummyDataService.getBudgetDataList(context);
|
||||
|
||||
return LayoutBuilder(builder: (context, constraints) {
|
||||
final textScaleFactor =
|
||||
GalleryOptions.of(context).textScaleFactor(context);
|
||||
|
||||
// Only display multiple columns when the constraints allow it and we
|
||||
// have a regular text scale factor.
|
||||
final minWidthForTwoColumns = 600;
|
||||
final hasMultipleColumns = isDisplayDesktop(context) &&
|
||||
constraints.maxWidth > minWidthForTwoColumns &&
|
||||
textScaleFactor <= 2;
|
||||
final boxWidth = hasMultipleColumns
|
||||
? constraints.maxWidth / 2 - spacing / 2
|
||||
: double.infinity;
|
||||
|
||||
return Wrap(
|
||||
runSpacing: spacing,
|
||||
children: [
|
||||
Container(
|
||||
width: boxWidth,
|
||||
child: _FinancialView(
|
||||
title: GalleryLocalizations.of(context).rallyAccounts,
|
||||
total: sumAccountDataPrimaryAmount(accountDataList),
|
||||
financialItemViews:
|
||||
buildAccountDataListViews(accountDataList, context),
|
||||
buttonSemanticsLabel:
|
||||
GalleryLocalizations.of(context).rallySeeAllAccounts,
|
||||
),
|
||||
),
|
||||
if (hasMultipleColumns) SizedBox(width: spacing),
|
||||
Container(
|
||||
width: boxWidth,
|
||||
child: _FinancialView(
|
||||
title: GalleryLocalizations.of(context).rallyBills,
|
||||
total: sumBillDataPrimaryAmount(billDataList),
|
||||
financialItemViews: buildBillDataListViews(billDataList, context),
|
||||
buttonSemanticsLabel:
|
||||
GalleryLocalizations.of(context).rallySeeAllBills,
|
||||
),
|
||||
),
|
||||
_FinancialView(
|
||||
title: GalleryLocalizations.of(context).rallyBudgets,
|
||||
total: sumBudgetDataPrimaryAmount(budgetDataList),
|
||||
financialItemViews:
|
||||
buildBudgetDataListViews(budgetDataList, context),
|
||||
buttonSemanticsLabel:
|
||||
GalleryLocalizations.of(context).rallySeeAllBudgets,
|
||||
),
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class _AlertsView extends StatelessWidget {
|
||||
const _AlertsView({Key key, this.alerts}) : super(key: key);
|
||||
|
||||
final List<AlertData> alerts;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsetsDirectional.only(start: 16, top: 4, bottom: 4),
|
||||
color: RallyColors.cardBackground,
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: isDesktop ? EdgeInsets.symmetric(vertical: 16) : null,
|
||||
child: MergeSemantics(
|
||||
child: Wrap(
|
||||
alignment: WrapAlignment.spaceBetween,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Text(GalleryLocalizations.of(context).rallyAlerts),
|
||||
if (!isDesktop)
|
||||
FlatButton(
|
||||
onPressed: () {},
|
||||
child: Text(GalleryLocalizations.of(context).rallySeeAll),
|
||||
textColor: Colors.white,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
for (AlertData alert in alerts) ...[
|
||||
Container(color: RallyColors.primaryBackground, height: 1),
|
||||
_Alert(alert: alert),
|
||||
]
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Alert extends StatelessWidget {
|
||||
const _Alert({
|
||||
Key key,
|
||||
@required this.alert,
|
||||
}) : super(key: key);
|
||||
|
||||
final AlertData alert;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MergeSemantics(
|
||||
child: Container(
|
||||
padding: isDisplayDesktop(context)
|
||||
? EdgeInsets.symmetric(vertical: 8)
|
||||
: null,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(alert.message),
|
||||
),
|
||||
SizedBox(
|
||||
width: 100,
|
||||
child: Align(
|
||||
alignment: Alignment.topRight,
|
||||
child: IconButton(
|
||||
onPressed: () {},
|
||||
icon: Icon(alert.iconData, color: RallyColors.white60),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FinancialView extends StatelessWidget {
|
||||
const _FinancialView({
|
||||
this.title,
|
||||
this.total,
|
||||
this.financialItemViews,
|
||||
this.buttonSemanticsLabel,
|
||||
});
|
||||
|
||||
final String title;
|
||||
final String buttonSemanticsLabel;
|
||||
final double total;
|
||||
final List<FinancialEntityCategoryView> financialItemViews;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Container(
|
||||
color: RallyColors.cardBackground,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
MergeSemantics(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(title),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 16, right: 16),
|
||||
child: Text(
|
||||
usdWithSignFormat(context).format(total),
|
||||
style: theme.textTheme.body2.copyWith(
|
||||
fontSize: 44 / reducedTextScale(context),
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
...financialItemViews.sublist(
|
||||
0, math.min(financialItemViews.length, 3)),
|
||||
FlatButton(
|
||||
child: Text(
|
||||
GalleryLocalizations.of(context).rallySeeAll,
|
||||
semanticsLabel: buttonSemanticsLabel,
|
||||
),
|
||||
textColor: Colors.white,
|
||||
onPressed: () {},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
54
gallery/lib/studies/rally/tabs/settings.dart
Normal file
54
gallery/lib/studies/rally/tabs/settings.dart
Normal file
@@ -0,0 +1,54 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/studies/rally/data.dart';
|
||||
import 'package:gallery/studies/rally/login.dart';
|
||||
|
||||
class SettingsView extends StatefulWidget {
|
||||
@override
|
||||
_SettingsViewState createState() => _SettingsViewState();
|
||||
}
|
||||
|
||||
class _SettingsViewState extends State<SettingsView> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final items = DummyDataService.getSettingsTitles(context)
|
||||
.map((title) => _SettingsItem(title))
|
||||
.toList();
|
||||
return Container(
|
||||
padding: EdgeInsets.only(top: isDisplayDesktop(context) ? 24 : 0),
|
||||
child: ListView(
|
||||
shrinkWrap: true,
|
||||
children: items,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SettingsItem extends StatelessWidget {
|
||||
const _SettingsItem(this.title);
|
||||
|
||||
final String title;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return FlatButton(
|
||||
textColor: Colors.white,
|
||||
child: Container(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
padding: EdgeInsets.symmetric(vertical: 24, horizontal: 12),
|
||||
child: Text(title),
|
||||
),
|
||||
onPressed: () {
|
||||
Navigator.push<void>(
|
||||
context,
|
||||
MaterialPageRoute<void>(builder: (context) => LoginPage()),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
147
gallery/lib/studies/shrine/app.dart
Normal file
147
gallery/lib/studies/shrine/app.dart
Normal file
@@ -0,0 +1,147 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/studies/shrine/backdrop.dart';
|
||||
import 'package:gallery/studies/shrine/category_menu_page.dart';
|
||||
import 'package:gallery/studies/shrine/expanding_bottom_sheet.dart';
|
||||
import 'package:gallery/studies/shrine/home.dart';
|
||||
import 'package:gallery/studies/shrine/login.dart';
|
||||
import 'package:gallery/studies/shrine/model/app_state_model.dart';
|
||||
import 'package:gallery/studies/shrine/page_status.dart';
|
||||
import 'package:gallery/studies/shrine/scrim.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/layout_cache.dart';
|
||||
import 'package:gallery/studies/shrine/theme.dart';
|
||||
import 'package:scoped_model/scoped_model.dart';
|
||||
|
||||
class ShrineApp extends StatefulWidget {
|
||||
const ShrineApp({Key key, this.navigatorKey}) : super(key: key);
|
||||
|
||||
final GlobalKey<NavigatorState> navigatorKey;
|
||||
|
||||
@override
|
||||
_ShrineAppState createState() => _ShrineAppState();
|
||||
}
|
||||
|
||||
class _ShrineAppState extends State<ShrineApp> with TickerProviderStateMixin {
|
||||
// Controller to coordinate both the opening/closing of backdrop and sliding
|
||||
// of expanding bottom sheet
|
||||
AnimationController _controller;
|
||||
|
||||
// Animation Controller for expanding/collapsing the cart menu.
|
||||
AnimationController _expandingController;
|
||||
|
||||
AppStateModel _model;
|
||||
|
||||
Map<String, List<List<int>>> _layouts = {};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 450),
|
||||
value: 1,
|
||||
);
|
||||
_expandingController = AnimationController(
|
||||
duration: const Duration(milliseconds: 500),
|
||||
vsync: this,
|
||||
);
|
||||
_model = AppStateModel()..loadProducts();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
_expandingController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Widget mobileBackdrop() {
|
||||
return Backdrop(
|
||||
frontLayer: const ProductPage(),
|
||||
backLayer: CategoryMenuPage(onCategoryTap: () => _controller.forward()),
|
||||
frontTitle: const Text('SHRINE'),
|
||||
backTitle: Text(GalleryLocalizations.of(context).shrineMenuCaption),
|
||||
controller: _controller,
|
||||
);
|
||||
}
|
||||
|
||||
Widget desktopBackdrop() {
|
||||
return DesktopBackdrop(
|
||||
frontLayer: ProductPage(),
|
||||
backLayer: CategoryMenuPage(),
|
||||
);
|
||||
}
|
||||
|
||||
// Closes the bottom sheet if it is open.
|
||||
Future<bool> _onWillPop() async {
|
||||
final status = _expandingController.status;
|
||||
if (status == AnimationStatus.completed ||
|
||||
status == AnimationStatus.forward) {
|
||||
_expandingController.reverse();
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
final Widget backdrop = isDesktop ? desktopBackdrop() : mobileBackdrop();
|
||||
|
||||
return ScopedModel<AppStateModel>(
|
||||
model: _model,
|
||||
child: WillPopScope(
|
||||
onWillPop: _onWillPop,
|
||||
child: MaterialApp(
|
||||
navigatorKey: widget.navigatorKey,
|
||||
title: 'Shrine',
|
||||
debugShowCheckedModeBanner: false,
|
||||
home: LayoutCache(
|
||||
layouts: _layouts,
|
||||
child: PageStatus(
|
||||
menuController: _controller,
|
||||
cartController: _expandingController,
|
||||
child: HomePage(
|
||||
backdrop: backdrop,
|
||||
scrim: Scrim(controller: _expandingController),
|
||||
expandingBottomSheet: ExpandingBottomSheet(
|
||||
hideController: _controller,
|
||||
expandingController: _expandingController,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
initialRoute: '/login',
|
||||
onGenerateRoute: _getRoute,
|
||||
theme: shrineTheme.copyWith(
|
||||
platform: GalleryOptions.of(context).platform,
|
||||
),
|
||||
// L10n settings.
|
||||
localizationsDelegates: GalleryLocalizations.localizationsDelegates,
|
||||
supportedLocales: GalleryLocalizations.supportedLocales,
|
||||
locale: GalleryOptions.of(context).locale,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Route<dynamic> _getRoute(RouteSettings settings) {
|
||||
if (settings.name != '/login') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return MaterialPageRoute<void>(
|
||||
settings: settings,
|
||||
builder: (context) => LoginPage(),
|
||||
fullscreenDialog: true,
|
||||
);
|
||||
}
|
||||
400
gallery/lib/studies/shrine/backdrop.dart
Normal file
400
gallery/lib/studies/shrine/backdrop.dart
Normal file
@@ -0,0 +1,400 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/studies/shrine/page_status.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/studies/shrine/category_menu_page.dart';
|
||||
|
||||
const Cubic _accelerateCurve = Cubic(0.548, 0, 0.757, 0.464);
|
||||
const Cubic _decelerateCurve = Cubic(0.23, 0.94, 0.41, 1);
|
||||
const _peakVelocityTime = 0.248210;
|
||||
const _peakVelocityProgress = 0.379146;
|
||||
|
||||
class _FrontLayer extends StatelessWidget {
|
||||
const _FrontLayer({
|
||||
Key key,
|
||||
this.onTap,
|
||||
this.child,
|
||||
}) : super(key: key);
|
||||
|
||||
final VoidCallback onTap;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// An area at the top of the product page.
|
||||
// When the menu page is shown, tapping this area will close the menu
|
||||
// page and reveal the product page.
|
||||
final Widget pageTopArea = Container(
|
||||
height: 40,
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
);
|
||||
|
||||
return Material(
|
||||
elevation: 16,
|
||||
shape: const BeveledRectangleBorder(
|
||||
borderRadius:
|
||||
BorderRadiusDirectional.only(topStart: Radius.circular(46)),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
onTap != null
|
||||
? GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
excludeFromSemantics:
|
||||
true, // Because there is already a "Close Menu" button on screen.
|
||||
onTap: onTap,
|
||||
child: pageTopArea,
|
||||
)
|
||||
: pageTopArea,
|
||||
Expanded(
|
||||
child: child,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BackdropTitle extends AnimatedWidget {
|
||||
const _BackdropTitle({
|
||||
Key key,
|
||||
this.listenable,
|
||||
this.onPress,
|
||||
@required this.frontTitle,
|
||||
@required this.backTitle,
|
||||
}) : assert(frontTitle != null),
|
||||
assert(backTitle != null),
|
||||
super(key: key, listenable: listenable);
|
||||
|
||||
final Animation<double> listenable;
|
||||
|
||||
final void Function() onPress;
|
||||
final Widget frontTitle;
|
||||
final Widget backTitle;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Animation<double> animation = CurvedAnimation(
|
||||
parent: listenable,
|
||||
curve: const Interval(0, 0.78),
|
||||
);
|
||||
|
||||
final double textDirectionScalar =
|
||||
Directionality.of(context) == TextDirection.ltr ? 1 : -1;
|
||||
|
||||
final slantedMenuIcon =
|
||||
ImageIcon(AssetImage('packages/shrine_images/slanted_menu.png'));
|
||||
|
||||
final directionalSlantedMenuIcon =
|
||||
Directionality.of(context) == TextDirection.ltr
|
||||
? slantedMenuIcon
|
||||
: Transform(
|
||||
alignment: Alignment.center,
|
||||
transform: Matrix4.rotationY(pi),
|
||||
child: slantedMenuIcon,
|
||||
);
|
||||
|
||||
final String menuButtonTooltip = animation.isCompleted
|
||||
? GalleryLocalizations.of(context).shrineTooltipOpenMenu
|
||||
: animation.isDismissed
|
||||
? GalleryLocalizations.of(context).shrineTooltipCloseMenu
|
||||
: null;
|
||||
|
||||
return DefaultTextStyle(
|
||||
style: Theme.of(context).primaryTextTheme.title,
|
||||
softWrap: false,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
child: Row(children: [
|
||||
// branded icon
|
||||
SizedBox(
|
||||
width: 72,
|
||||
child: Semantics(
|
||||
container: true,
|
||||
child: IconButton(
|
||||
padding: const EdgeInsetsDirectional.only(end: 8),
|
||||
onPressed: onPress,
|
||||
tooltip: menuButtonTooltip,
|
||||
icon: Stack(children: [
|
||||
Opacity(
|
||||
opacity: animation.value,
|
||||
child: directionalSlantedMenuIcon,
|
||||
),
|
||||
FractionalTranslation(
|
||||
translation: Tween<Offset>(
|
||||
begin: Offset.zero,
|
||||
end: Offset(1 * textDirectionScalar, 0),
|
||||
).evaluate(animation),
|
||||
child: const ImageIcon(
|
||||
AssetImage('packages/shrine_images/diamond.png'),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
// Here, we do a custom cross fade between backTitle and frontTitle.
|
||||
// This makes a smooth animation between the two texts.
|
||||
Stack(
|
||||
children: [
|
||||
Opacity(
|
||||
opacity: CurvedAnimation(
|
||||
parent: ReverseAnimation(animation),
|
||||
curve: const Interval(0.5, 1),
|
||||
).value,
|
||||
child: FractionalTranslation(
|
||||
translation: Tween<Offset>(
|
||||
begin: Offset.zero,
|
||||
end: Offset(0.5 * textDirectionScalar, 0),
|
||||
).evaluate(animation),
|
||||
child: backTitle,
|
||||
),
|
||||
),
|
||||
Opacity(
|
||||
opacity: CurvedAnimation(
|
||||
parent: animation,
|
||||
curve: const Interval(0.5, 1),
|
||||
).value,
|
||||
child: FractionalTranslation(
|
||||
translation: Tween<Offset>(
|
||||
begin: Offset(-0.25 * textDirectionScalar, 0),
|
||||
end: Offset.zero,
|
||||
).evaluate(animation),
|
||||
child: frontTitle,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a Backdrop.
|
||||
///
|
||||
/// A Backdrop widget has two layers, front and back. The front layer is shown
|
||||
/// by default, and slides down to show the back layer, from which a user
|
||||
/// can make a selection. The user can also configure the titles for when the
|
||||
/// front or back layer is showing.
|
||||
class Backdrop extends StatefulWidget {
|
||||
const Backdrop({
|
||||
@required this.frontLayer,
|
||||
@required this.backLayer,
|
||||
@required this.frontTitle,
|
||||
@required this.backTitle,
|
||||
@required this.controller,
|
||||
}) : assert(frontLayer != null),
|
||||
assert(backLayer != null),
|
||||
assert(frontTitle != null),
|
||||
assert(backTitle != null),
|
||||
assert(controller != null);
|
||||
|
||||
final Widget frontLayer;
|
||||
final Widget backLayer;
|
||||
final Widget frontTitle;
|
||||
final Widget backTitle;
|
||||
final AnimationController controller;
|
||||
|
||||
@override
|
||||
_BackdropState createState() => _BackdropState();
|
||||
}
|
||||
|
||||
class _BackdropState extends State<Backdrop>
|
||||
with SingleTickerProviderStateMixin {
|
||||
final GlobalKey _backdropKey = GlobalKey(debugLabel: 'Backdrop');
|
||||
AnimationController _controller;
|
||||
Animation<RelativeRect> _layerAnimation;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = widget.controller;
|
||||
}
|
||||
|
||||
bool get _frontLayerVisible {
|
||||
final AnimationStatus status = _controller.status;
|
||||
return status == AnimationStatus.completed ||
|
||||
status == AnimationStatus.forward;
|
||||
}
|
||||
|
||||
void _toggleBackdropLayerVisibility() {
|
||||
// Call setState here to update layerAnimation if that's necessary
|
||||
setState(() {
|
||||
_frontLayerVisible ? _controller.reverse() : _controller.forward();
|
||||
});
|
||||
}
|
||||
|
||||
// _layerAnimation animates the front layer between open and close.
|
||||
// _getLayerAnimation adjusts the values in the TweenSequence so the
|
||||
// curve and timing are correct in both directions.
|
||||
Animation<RelativeRect> _getLayerAnimation(Size layerSize, double layerTop) {
|
||||
Curve firstCurve; // Curve for first TweenSequenceItem
|
||||
Curve secondCurve; // Curve for second TweenSequenceItem
|
||||
double firstWeight; // Weight of first TweenSequenceItem
|
||||
double secondWeight; // Weight of second TweenSequenceItem
|
||||
Animation<double> animation; // Animation on which TweenSequence runs
|
||||
|
||||
if (_frontLayerVisible) {
|
||||
firstCurve = _accelerateCurve;
|
||||
secondCurve = _decelerateCurve;
|
||||
firstWeight = _peakVelocityTime;
|
||||
secondWeight = 1 - _peakVelocityTime;
|
||||
animation = CurvedAnimation(
|
||||
parent: _controller.view,
|
||||
curve: const Interval(0, 0.78),
|
||||
);
|
||||
} else {
|
||||
// These values are only used when the controller runs from t=1.0 to t=0.0
|
||||
firstCurve = _decelerateCurve.flipped;
|
||||
secondCurve = _accelerateCurve.flipped;
|
||||
firstWeight = 1 - _peakVelocityTime;
|
||||
secondWeight = _peakVelocityTime;
|
||||
animation = _controller.view;
|
||||
}
|
||||
|
||||
return TweenSequence<RelativeRect>(
|
||||
[
|
||||
TweenSequenceItem<RelativeRect>(
|
||||
tween: RelativeRectTween(
|
||||
begin: RelativeRect.fromLTRB(
|
||||
0,
|
||||
layerTop,
|
||||
0,
|
||||
layerTop - layerSize.height,
|
||||
),
|
||||
end: RelativeRect.fromLTRB(
|
||||
0,
|
||||
layerTop * _peakVelocityProgress,
|
||||
0,
|
||||
(layerTop - layerSize.height) * _peakVelocityProgress,
|
||||
),
|
||||
).chain(CurveTween(curve: firstCurve)),
|
||||
weight: firstWeight,
|
||||
),
|
||||
TweenSequenceItem<RelativeRect>(
|
||||
tween: RelativeRectTween(
|
||||
begin: RelativeRect.fromLTRB(
|
||||
0,
|
||||
layerTop * _peakVelocityProgress,
|
||||
0,
|
||||
(layerTop - layerSize.height) * _peakVelocityProgress,
|
||||
),
|
||||
end: RelativeRect.fill,
|
||||
).chain(CurveTween(curve: secondCurve)),
|
||||
weight: secondWeight,
|
||||
),
|
||||
],
|
||||
).animate(animation);
|
||||
}
|
||||
|
||||
Widget _buildStack(BuildContext context, BoxConstraints constraints) {
|
||||
const double layerTitleHeight = 48;
|
||||
final Size layerSize = constraints.biggest;
|
||||
final double layerTop = layerSize.height - layerTitleHeight;
|
||||
|
||||
_layerAnimation = _getLayerAnimation(layerSize, layerTop);
|
||||
|
||||
return Stack(
|
||||
key: _backdropKey,
|
||||
children: [
|
||||
ExcludeSemantics(
|
||||
excluding: _frontLayerVisible,
|
||||
child: widget.backLayer,
|
||||
),
|
||||
PositionedTransition(
|
||||
rect: _layerAnimation,
|
||||
child: ExcludeSemantics(
|
||||
excluding: !_frontLayerVisible,
|
||||
child: AnimatedBuilder(
|
||||
animation: PageStatus.of(context).cartController,
|
||||
builder: (context, child) => AnimatedBuilder(
|
||||
animation: PageStatus.of(context).menuController,
|
||||
builder: (context, child) => _FrontLayer(
|
||||
onTap: menuPageIsVisible(context)
|
||||
? _toggleBackdropLayerVisibility
|
||||
: null,
|
||||
child: widget.frontLayer,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final AppBar appBar = AppBar(
|
||||
brightness: Brightness.light,
|
||||
elevation: 0,
|
||||
titleSpacing: 0,
|
||||
title: _BackdropTitle(
|
||||
listenable: _controller.view,
|
||||
onPress: _toggleBackdropLayerVisibility,
|
||||
frontTitle: widget.frontTitle,
|
||||
backTitle: widget.backTitle,
|
||||
),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.search),
|
||||
tooltip: GalleryLocalizations.of(context).shrineTooltipSearch,
|
||||
onPressed: () {},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.tune),
|
||||
tooltip: GalleryLocalizations.of(context).shrineTooltipSettings,
|
||||
onPressed: () {},
|
||||
),
|
||||
],
|
||||
);
|
||||
return AnimatedBuilder(
|
||||
animation: PageStatus.of(context).cartController,
|
||||
builder: (context, child) => ExcludeSemantics(
|
||||
excluding: cartPageIsVisible(context),
|
||||
child: Scaffold(
|
||||
appBar: appBar,
|
||||
body: LayoutBuilder(
|
||||
builder: _buildStack,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopBackdrop extends StatelessWidget {
|
||||
const DesktopBackdrop({
|
||||
@required this.frontLayer,
|
||||
@required this.backLayer,
|
||||
});
|
||||
|
||||
final Widget frontLayer;
|
||||
final Widget backLayer;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Stack(
|
||||
children: [
|
||||
backLayer,
|
||||
Padding(
|
||||
padding: EdgeInsetsDirectional.only(
|
||||
start: desktopCategoryMenuPageWidth(context: context),
|
||||
),
|
||||
child: Material(
|
||||
elevation: 16,
|
||||
color: Colors.white,
|
||||
child: frontLayer,
|
||||
),
|
||||
)
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
211
gallery/lib/studies/shrine/category_menu_page.dart
Normal file
211
gallery/lib/studies/shrine/category_menu_page.dart
Normal file
@@ -0,0 +1,211 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:scoped_model/scoped_model.dart';
|
||||
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/studies/shrine/colors.dart';
|
||||
import 'package:gallery/studies/shrine/login.dart';
|
||||
import 'package:gallery/studies/shrine/model/app_state_model.dart';
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
import 'package:gallery/studies/shrine/page_status.dart';
|
||||
import 'package:gallery/studies/shrine/triangle_category_indicator.dart';
|
||||
|
||||
double desktopCategoryMenuPageWidth({
|
||||
BuildContext context,
|
||||
}) {
|
||||
return 232 * reducedTextScale(context);
|
||||
}
|
||||
|
||||
class CategoryMenuPage extends StatelessWidget {
|
||||
const CategoryMenuPage({
|
||||
Key key,
|
||||
this.onCategoryTap,
|
||||
}) : super(key: key);
|
||||
|
||||
final VoidCallback onCategoryTap;
|
||||
|
||||
Widget _buttonText(String caption, TextStyle style) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 16),
|
||||
child: Text(
|
||||
caption,
|
||||
style: style,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _divider({BuildContext context}) {
|
||||
return Container(
|
||||
width: 56 * GalleryOptions.of(context).textScaleFactor(context),
|
||||
height: 1,
|
||||
color: Color(0xFF8F716D),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCategory(Category category, BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
final String categoryString = category.name(context);
|
||||
|
||||
final TextStyle selectedCategoryTextStyle = Theme.of(context)
|
||||
.textTheme
|
||||
.body2
|
||||
.copyWith(fontSize: isDesktop ? 17 : 19);
|
||||
|
||||
final TextStyle unselectedCategoryTextStyle = selectedCategoryTextStyle
|
||||
.copyWith(color: shrineBrown900.withOpacity(0.6));
|
||||
|
||||
final double indicatorHeight = (isDesktop ? 28 : 30) *
|
||||
GalleryOptions.of(context).textScaleFactor(context);
|
||||
final double indicatorWidth = indicatorHeight * 34 / 28;
|
||||
|
||||
return ScopedModelDescendant<AppStateModel>(
|
||||
builder: (context, child, model) => Semantics(
|
||||
selected: model.selectedCategory == category,
|
||||
button: true,
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
model.setCategory(category);
|
||||
if (onCategoryTap != null) {
|
||||
onCategoryTap();
|
||||
}
|
||||
},
|
||||
child: model.selectedCategory == category
|
||||
? CustomPaint(
|
||||
painter: TriangleCategoryIndicator(
|
||||
indicatorWidth,
|
||||
indicatorHeight,
|
||||
),
|
||||
child: _buttonText(categoryString, selectedCategoryTextStyle),
|
||||
)
|
||||
: _buttonText(categoryString, unselectedCategoryTextStyle),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
final TextStyle logoutTextStyle =
|
||||
Theme.of(context).textTheme.body2.copyWith(
|
||||
fontSize: isDesktop ? 17 : 19,
|
||||
color: shrineBrown900.withOpacity(0.6),
|
||||
);
|
||||
|
||||
if (isDesktop) {
|
||||
return AnimatedBuilder(
|
||||
animation: PageStatus.of(context).cartController,
|
||||
builder: (context, child) => ExcludeSemantics(
|
||||
excluding: !menuPageIsVisible(context),
|
||||
child: Material(
|
||||
child: Container(
|
||||
color: shrinePink100,
|
||||
width: desktopCategoryMenuPageWidth(context: context),
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 64),
|
||||
Image.asset(
|
||||
'packages/shrine_images/diamond.png',
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Semantics(
|
||||
container: true,
|
||||
child: Text(
|
||||
'SHRINE',
|
||||
style: Theme.of(context).textTheme.headline,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
for (final category in categories)
|
||||
_buildCategory(category, context),
|
||||
_divider(context: context),
|
||||
Semantics(
|
||||
button: true,
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
Navigator.push<void>(
|
||||
context,
|
||||
MaterialPageRoute<void>(
|
||||
builder: (context) => LoginPage(),
|
||||
),
|
||||
);
|
||||
},
|
||||
child: _buttonText(
|
||||
GalleryLocalizations.of(context)
|
||||
.shrineLogoutButtonCaption,
|
||||
logoutTextStyle,
|
||||
),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.search),
|
||||
tooltip:
|
||||
GalleryLocalizations.of(context).shrineTooltipSearch,
|
||||
onPressed: () {},
|
||||
),
|
||||
const SizedBox(height: 72),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return AnimatedBuilder(
|
||||
animation: PageStatus.of(context).cartController,
|
||||
builder: (context, child) => AnimatedBuilder(
|
||||
animation: PageStatus.of(context).menuController,
|
||||
builder: (context, child) => ExcludeSemantics(
|
||||
excluding: !menuPageIsVisible(context),
|
||||
child: Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.only(top: 40),
|
||||
color: shrinePink100,
|
||||
child: ListView(
|
||||
children: [
|
||||
for (final category in categories)
|
||||
_buildCategory(category, context),
|
||||
Center(
|
||||
child: _divider(context: context),
|
||||
),
|
||||
Semantics(
|
||||
button: true,
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
if (onCategoryTap != null) {
|
||||
onCategoryTap();
|
||||
}
|
||||
Navigator.push<void>(
|
||||
context,
|
||||
MaterialPageRoute<void>(
|
||||
builder: (context) => LoginPage()),
|
||||
);
|
||||
},
|
||||
child: _buttonText(
|
||||
GalleryLocalizations.of(context)
|
||||
.shrineLogoutButtonCaption,
|
||||
logoutTextStyle,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
18
gallery/lib/studies/shrine/colors.dart
Normal file
18
gallery/lib/studies/shrine/colors.dart
Normal file
@@ -0,0 +1,18 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
const Color shrinePink50 = Color(0xFFFEEAE6);
|
||||
const Color shrinePink100 = Color(0xFFFEDBD0);
|
||||
const Color shrinePink300 = Color(0xFFFBB8AC);
|
||||
const Color shrinePink400 = Color(0xFFEAA4A4);
|
||||
|
||||
const Color shrineBrown900 = Color(0xFF442B2D);
|
||||
const Color shrineBrown600 = Color(0xFF7D4F52);
|
||||
|
||||
const Color shrineErrorRed = Color(0xFFC5032B);
|
||||
|
||||
const Color shrineSurfaceWhite = Color(0xFFFFFBFA);
|
||||
const Color shrineBackgroundWhite = Colors.white;
|
||||
820
gallery/lib/studies/shrine/expanding_bottom_sheet.dart
Normal file
820
gallery/lib/studies/shrine/expanding_bottom_sheet.dart
Normal file
@@ -0,0 +1,820 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:scoped_model/scoped_model.dart';
|
||||
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/studies/shrine/colors.dart';
|
||||
import 'package:gallery/studies/shrine/model/app_state_model.dart';
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
import 'package:gallery/studies/shrine/page_status.dart';
|
||||
import 'package:gallery/studies/shrine/shopping_cart.dart';
|
||||
|
||||
// These curves define the emphasized easing curve.
|
||||
const Cubic _accelerateCurve = Cubic(0.548, 0, 0.757, 0.464);
|
||||
const Cubic _decelerateCurve = Cubic(0.23, 0.94, 0.41, 1);
|
||||
// The time at which the accelerate and decelerate curves switch off
|
||||
const _peakVelocityTime = 0.248210;
|
||||
// Percent (as a decimal) of animation that should be completed at _peakVelocityTime
|
||||
const _peakVelocityProgress = 0.379146;
|
||||
// Radius of the shape on the top start of the sheet for mobile layouts.
|
||||
const _mobileCornerRadius = 24.0;
|
||||
// Radius of the shape on the top start and bottom start of the sheet for mobile layouts.
|
||||
const _desktopCornerRadius = 12.0;
|
||||
// Width for just the cart icon and no thumbnails.
|
||||
const _cartIconWidth = 64.0;
|
||||
// Height for just the cart icon and no thumbnails.
|
||||
const _cartIconHeight = 56.0;
|
||||
// Height of a thumbnail.
|
||||
const _defaultThumbnailHeight = 40.0;
|
||||
// Gap between thumbnails.
|
||||
const _thumbnailGap = 16.0;
|
||||
|
||||
// Maximum number of thumbnails shown in the cart.
|
||||
const _maxThumbnailCount = 3;
|
||||
|
||||
double _thumbnailHeight(BuildContext context) {
|
||||
return _defaultThumbnailHeight * reducedTextScale(context);
|
||||
}
|
||||
|
||||
double _paddedThumbnailHeight(BuildContext context) {
|
||||
return _thumbnailHeight(context) + _thumbnailGap;
|
||||
}
|
||||
|
||||
class ExpandingBottomSheet extends StatefulWidget {
|
||||
const ExpandingBottomSheet({
|
||||
Key key,
|
||||
@required this.hideController,
|
||||
@required this.expandingController,
|
||||
}) : assert(hideController != null),
|
||||
assert(expandingController != null),
|
||||
super(key: key);
|
||||
|
||||
final AnimationController hideController;
|
||||
final AnimationController expandingController;
|
||||
|
||||
@override
|
||||
_ExpandingBottomSheetState createState() => _ExpandingBottomSheetState();
|
||||
|
||||
static _ExpandingBottomSheetState of(BuildContext context,
|
||||
{bool isNullOk = false}) {
|
||||
assert(isNullOk != null);
|
||||
assert(context != null);
|
||||
final _ExpandingBottomSheetState result =
|
||||
context.findAncestorStateOfType<_ExpandingBottomSheetState>();
|
||||
if (isNullOk || result != null) {
|
||||
return result;
|
||||
}
|
||||
throw FlutterError(
|
||||
'ExpandingBottomSheet.of() called with a context that does not contain a ExpandingBottomSheet.\n');
|
||||
}
|
||||
}
|
||||
|
||||
// Emphasized Easing is a motion curve that has an organic, exciting feeling.
|
||||
// It's very fast to begin with and then very slow to finish. Unlike standard
|
||||
// curves, like [Curves.fastOutSlowIn], it can't be expressed in a cubic bezier
|
||||
// curve formula. It's quintic, not cubic. But it _can_ be expressed as one
|
||||
// curve followed by another, which we do here.
|
||||
Animation<T> _getEmphasizedEasingAnimation<T>({
|
||||
@required T begin,
|
||||
@required T peak,
|
||||
@required T end,
|
||||
@required bool isForward,
|
||||
@required Animation<double> parent,
|
||||
}) {
|
||||
Curve firstCurve;
|
||||
Curve secondCurve;
|
||||
double firstWeight;
|
||||
double secondWeight;
|
||||
|
||||
if (isForward) {
|
||||
firstCurve = _accelerateCurve;
|
||||
secondCurve = _decelerateCurve;
|
||||
firstWeight = _peakVelocityTime;
|
||||
secondWeight = 1 - _peakVelocityTime;
|
||||
} else {
|
||||
firstCurve = _decelerateCurve.flipped;
|
||||
secondCurve = _accelerateCurve.flipped;
|
||||
firstWeight = 1 - _peakVelocityTime;
|
||||
secondWeight = _peakVelocityTime;
|
||||
}
|
||||
|
||||
return TweenSequence<T>(
|
||||
[
|
||||
TweenSequenceItem<T>(
|
||||
weight: firstWeight,
|
||||
tween: Tween<T>(
|
||||
begin: begin,
|
||||
end: peak,
|
||||
).chain(CurveTween(curve: firstCurve)),
|
||||
),
|
||||
TweenSequenceItem<T>(
|
||||
weight: secondWeight,
|
||||
tween: Tween<T>(
|
||||
begin: peak,
|
||||
end: end,
|
||||
).chain(CurveTween(curve: secondCurve)),
|
||||
),
|
||||
],
|
||||
).animate(parent);
|
||||
}
|
||||
|
||||
// Calculates the value where two double Animations should be joined. Used by
|
||||
// callers of _getEmphasisedEasing<double>().
|
||||
double _getPeakPoint({double begin, double end}) {
|
||||
return begin + (end - begin) * _peakVelocityProgress;
|
||||
}
|
||||
|
||||
class _ExpandingBottomSheetState extends State<ExpandingBottomSheet>
|
||||
with TickerProviderStateMixin {
|
||||
final GlobalKey _expandingBottomSheetKey =
|
||||
GlobalKey(debugLabel: 'Expanding bottom sheet');
|
||||
|
||||
// The width of the Material, calculated by _widthFor() & based on the number
|
||||
// of products in the cart. 64.0 is the width when there are 0 products
|
||||
// (_kWidthForZeroProducts)
|
||||
double _width = _cartIconWidth;
|
||||
double _height = _cartIconHeight;
|
||||
|
||||
// Controller for the opening and closing of the ExpandingBottomSheet
|
||||
AnimationController get _controller => widget.expandingController;
|
||||
|
||||
// Animations for the opening and closing of the ExpandingBottomSheet
|
||||
Animation<double> _widthAnimation;
|
||||
Animation<double> _heightAnimation;
|
||||
Animation<double> _thumbnailOpacityAnimation;
|
||||
Animation<double> _cartOpacityAnimation;
|
||||
Animation<double> _topStartShapeAnimation;
|
||||
Animation<double> _bottomStartShapeAnimation;
|
||||
Animation<Offset> _slideAnimation;
|
||||
Animation<double> _gapAnimation;
|
||||
|
||||
Animation<double> _getWidthAnimation(double screenWidth) {
|
||||
if (_controller.status == AnimationStatus.forward) {
|
||||
// Opening animation
|
||||
return Tween<double>(begin: _width, end: screenWidth).animate(
|
||||
CurvedAnimation(
|
||||
parent: _controller.view,
|
||||
curve: const Interval(0, 0.3, curve: Curves.fastOutSlowIn),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
// Closing animation
|
||||
return _getEmphasizedEasingAnimation(
|
||||
begin: _width,
|
||||
peak: _getPeakPoint(begin: _width, end: screenWidth),
|
||||
end: screenWidth,
|
||||
isForward: false,
|
||||
parent: CurvedAnimation(
|
||||
parent: _controller.view, curve: const Interval(0, 0.87)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Animation<double> _getHeightAnimation(double screenHeight) {
|
||||
if (_controller.status == AnimationStatus.forward) {
|
||||
// Opening animation
|
||||
|
||||
return _getEmphasizedEasingAnimation(
|
||||
begin: _height,
|
||||
peak: _getPeakPoint(begin: _height, end: screenHeight),
|
||||
end: screenHeight,
|
||||
isForward: true,
|
||||
parent: _controller.view,
|
||||
);
|
||||
} else {
|
||||
// Closing animation
|
||||
return Tween<double>(
|
||||
begin: _height,
|
||||
end: screenHeight,
|
||||
).animate(
|
||||
CurvedAnimation(
|
||||
parent: _controller.view,
|
||||
curve: const Interval(0.434, 1, curve: Curves.linear), // not used
|
||||
// only the reverseCurve will be used
|
||||
reverseCurve: Interval(0.434, 1, curve: Curves.fastOutSlowIn.flipped),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Animation<double> _getDesktopGapAnimation(double gapHeight) {
|
||||
final double _collapsedGapHeight = gapHeight;
|
||||
final double _expandedGapHeight = 0;
|
||||
|
||||
if (_controller.status == AnimationStatus.forward) {
|
||||
// Opening animation
|
||||
|
||||
return _getEmphasizedEasingAnimation(
|
||||
begin: _collapsedGapHeight,
|
||||
peak: _collapsedGapHeight +
|
||||
(_expandedGapHeight - _collapsedGapHeight) * _peakVelocityProgress,
|
||||
end: _expandedGapHeight,
|
||||
isForward: true,
|
||||
parent: _controller.view,
|
||||
);
|
||||
} else {
|
||||
// Closing animation
|
||||
return Tween<double>(
|
||||
begin: _collapsedGapHeight,
|
||||
end: _expandedGapHeight,
|
||||
).animate(
|
||||
CurvedAnimation(
|
||||
parent: _controller.view,
|
||||
curve: const Interval(0.434, 1), // not used
|
||||
// only the reverseCurve will be used
|
||||
reverseCurve: Interval(0.434, 1, curve: Curves.fastOutSlowIn.flipped),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Animation of the top-start cut corner. It's cut when closed and not cut when open.
|
||||
Animation<double> _getShapeTopStartAnimation(BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
final double cornerRadius =
|
||||
isDesktop ? _desktopCornerRadius : _mobileCornerRadius;
|
||||
|
||||
if (_controller.status == AnimationStatus.forward) {
|
||||
return Tween<double>(begin: cornerRadius, end: 0).animate(
|
||||
CurvedAnimation(
|
||||
parent: _controller.view,
|
||||
curve: const Interval(0, 0.3, curve: Curves.fastOutSlowIn),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return _getEmphasizedEasingAnimation(
|
||||
begin: cornerRadius,
|
||||
peak: _getPeakPoint(begin: cornerRadius, end: 0),
|
||||
end: 0,
|
||||
isForward: false,
|
||||
parent: _controller.view,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Animation of the bottom-start cut corner. It's cut when closed and not cut when open.
|
||||
Animation<double> _getShapeBottomStartAnimation(BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
final double cornerRadius = isDesktop ? _desktopCornerRadius : 0;
|
||||
|
||||
if (_controller.status == AnimationStatus.forward) {
|
||||
return Tween<double>(begin: cornerRadius, end: 0).animate(
|
||||
CurvedAnimation(
|
||||
parent: _controller.view,
|
||||
curve: const Interval(0, 0.3, curve: Curves.fastOutSlowIn),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
return _getEmphasizedEasingAnimation(
|
||||
begin: cornerRadius,
|
||||
peak: _getPeakPoint(begin: cornerRadius, end: 0),
|
||||
end: 0,
|
||||
isForward: false,
|
||||
parent: _controller.view,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Animation<double> _getThumbnailOpacityAnimation() {
|
||||
return Tween<double>(begin: 1, end: 0).animate(
|
||||
CurvedAnimation(
|
||||
parent: _controller.view,
|
||||
curve: _controller.status == AnimationStatus.forward
|
||||
? const Interval(0, 0.3)
|
||||
: const Interval(0.532, 0.766),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Animation<double> _getCartOpacityAnimation() {
|
||||
return CurvedAnimation(
|
||||
parent: _controller.view,
|
||||
curve: _controller.status == AnimationStatus.forward
|
||||
? const Interval(0.3, 0.6)
|
||||
: const Interval(0.766, 1),
|
||||
);
|
||||
}
|
||||
|
||||
// Returns the correct width of the ExpandingBottomSheet based on the number of
|
||||
// products and the text scaling options in the cart in the mobile layout.
|
||||
double _mobileWidthFor(int numProducts, BuildContext context) {
|
||||
final double cartThumbnailGap = numProducts > 0 ? 16 : 0;
|
||||
final double thumbnailsWidth =
|
||||
min(numProducts, _maxThumbnailCount) * _paddedThumbnailHeight(context);
|
||||
final double overflowNumberWidth =
|
||||
numProducts > _maxThumbnailCount ? 30 * cappedTextScale(context) : 0;
|
||||
return _cartIconWidth +
|
||||
cartThumbnailGap +
|
||||
thumbnailsWidth +
|
||||
overflowNumberWidth;
|
||||
}
|
||||
|
||||
// Returns the correct height of the ExpandingBottomSheet based on the text scaling
|
||||
// options in the mobile layout.
|
||||
double _mobileHeightFor(BuildContext context) {
|
||||
return _paddedThumbnailHeight(context);
|
||||
}
|
||||
|
||||
// Returns the correct width of the ExpandingBottomSheet based on the text scaling
|
||||
// options in the desktop layout.
|
||||
double _desktopWidthFor(BuildContext context) {
|
||||
return _paddedThumbnailHeight(context) + 8;
|
||||
}
|
||||
|
||||
// Returns the correct height of the ExpandingBottomSheet based on the number of
|
||||
// products and the text scaling options in the cart in the desktop layout.
|
||||
double _desktopHeightFor(int numProducts, BuildContext context) {
|
||||
final double cartThumbnailGap = numProducts > 0 ? 8 : 0;
|
||||
final double thumbnailsHeight =
|
||||
min(numProducts, _maxThumbnailCount) * _paddedThumbnailHeight(context);
|
||||
final double overflowNumberHeight =
|
||||
numProducts > _maxThumbnailCount ? 28 * reducedTextScale(context) : 0;
|
||||
return _cartIconHeight +
|
||||
cartThumbnailGap +
|
||||
thumbnailsHeight +
|
||||
overflowNumberHeight;
|
||||
}
|
||||
|
||||
// Returns true if the cart is open or opening and false otherwise.
|
||||
bool get _isOpen {
|
||||
final AnimationStatus status = _controller.status;
|
||||
return status == AnimationStatus.completed ||
|
||||
status == AnimationStatus.forward;
|
||||
}
|
||||
|
||||
// Opens the ExpandingBottomSheet if it's closed, otherwise does nothing.
|
||||
void open() {
|
||||
if (!_isOpen) {
|
||||
_controller.forward();
|
||||
}
|
||||
}
|
||||
|
||||
// Closes the ExpandingBottomSheet if it's open or opening, otherwise does nothing.
|
||||
void close() {
|
||||
if (_isOpen) {
|
||||
_controller.reverse();
|
||||
}
|
||||
}
|
||||
|
||||
// Changes the padding between the start edge of the Material and the cart icon
|
||||
// based on the number of products in the cart (padding increases when > 0
|
||||
// products.)
|
||||
EdgeInsetsDirectional _horizontalCartPaddingFor(int numProducts) {
|
||||
return (numProducts == 0)
|
||||
? const EdgeInsetsDirectional.only(start: 20, end: 8)
|
||||
: const EdgeInsetsDirectional.only(start: 32, end: 8);
|
||||
}
|
||||
|
||||
// Changes the padding above and below the cart icon
|
||||
// based on the number of products in the cart (padding increases when > 0
|
||||
// products.)
|
||||
EdgeInsets _verticalCartPaddingFor(int numProducts) {
|
||||
return (numProducts == 0)
|
||||
? const EdgeInsets.only(top: 16, bottom: 16)
|
||||
: const EdgeInsets.only(top: 16, bottom: 24);
|
||||
}
|
||||
|
||||
bool get _cartIsVisible => _thumbnailOpacityAnimation.value == 0;
|
||||
|
||||
// We take 16 pts off of the bottom padding to ensure the collapsed shopping
|
||||
// cart is not too tall.
|
||||
double get _bottomSafeArea {
|
||||
return max(MediaQuery.of(context).viewPadding.bottom - 16, 0);
|
||||
}
|
||||
|
||||
Widget _buildThumbnails(BuildContext context, int numProducts) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
Widget thumbnails;
|
||||
|
||||
if (isDesktop) {
|
||||
thumbnails = Column(
|
||||
children: [
|
||||
AnimatedPadding(
|
||||
padding: _verticalCartPaddingFor(numProducts),
|
||||
child: const Icon(Icons.shopping_cart),
|
||||
duration: const Duration(milliseconds: 225),
|
||||
),
|
||||
Container(
|
||||
width: _width,
|
||||
height: min(numProducts, _maxThumbnailCount) *
|
||||
_paddedThumbnailHeight(context),
|
||||
child: ProductThumbnailRow(),
|
||||
),
|
||||
ExtraProductsNumber(),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
thumbnails = Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
AnimatedPadding(
|
||||
padding: _horizontalCartPaddingFor(numProducts),
|
||||
child: const Icon(Icons.shopping_cart),
|
||||
duration: const Duration(milliseconds: 225),
|
||||
),
|
||||
Container(
|
||||
// Accounts for the overflow number
|
||||
width: min(numProducts, _maxThumbnailCount) *
|
||||
_paddedThumbnailHeight(context) +
|
||||
(numProducts > 0 ? _thumbnailGap : 0),
|
||||
height: _height - _bottomSafeArea,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: ProductThumbnailRow(),
|
||||
),
|
||||
ExtraProductsNumber(),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return ExcludeSemantics(
|
||||
child: Opacity(
|
||||
opacity: _thumbnailOpacityAnimation.value,
|
||||
child: thumbnails,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildShoppingCartPage() {
|
||||
return Opacity(
|
||||
opacity: _cartOpacityAnimation.value,
|
||||
child: ShoppingCartPage(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCart(BuildContext context) {
|
||||
// numProducts is the number of different products in the cart (does not
|
||||
// include multiples of the same product).
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
final AppStateModel model = ScopedModel.of<AppStateModel>(context);
|
||||
final int numProducts = model.productsInCart.keys.length;
|
||||
final int totalCartQuantity = model.totalCartQuantity;
|
||||
final Size screenSize = MediaQuery.of(context).size;
|
||||
final double screenWidth = screenSize.width;
|
||||
final double screenHeight = screenSize.height;
|
||||
|
||||
final double expandedCartWidth = isDesktop
|
||||
? (360 * cappedTextScale(context)).clamp(360, screenWidth).toDouble()
|
||||
: screenWidth;
|
||||
|
||||
_width = isDesktop
|
||||
? _desktopWidthFor(context)
|
||||
: _mobileWidthFor(numProducts, context);
|
||||
_widthAnimation = _getWidthAnimation(expandedCartWidth);
|
||||
_height = isDesktop
|
||||
? _desktopHeightFor(numProducts, context)
|
||||
: _mobileHeightFor(context) + _bottomSafeArea;
|
||||
_heightAnimation = _getHeightAnimation(screenHeight);
|
||||
_topStartShapeAnimation = _getShapeTopStartAnimation(context);
|
||||
_bottomStartShapeAnimation = _getShapeBottomStartAnimation(context);
|
||||
_thumbnailOpacityAnimation = _getThumbnailOpacityAnimation();
|
||||
_cartOpacityAnimation = _getCartOpacityAnimation();
|
||||
_gapAnimation =
|
||||
isDesktop ? _getDesktopGapAnimation(116) : AlwaysStoppedAnimation(0);
|
||||
|
||||
final Widget child = Container(
|
||||
width: _widthAnimation.value,
|
||||
height: _heightAnimation.value,
|
||||
child: Material(
|
||||
animationDuration: const Duration(milliseconds: 0),
|
||||
shape: BeveledRectangleBorder(
|
||||
borderRadius: BorderRadiusDirectional.only(
|
||||
topStart: Radius.circular(_topStartShapeAnimation.value),
|
||||
bottomStart: Radius.circular(_bottomStartShapeAnimation.value),
|
||||
),
|
||||
),
|
||||
elevation: 4,
|
||||
color: shrinePink50,
|
||||
child: _cartIsVisible
|
||||
? _buildShoppingCartPage()
|
||||
: _buildThumbnails(context, numProducts),
|
||||
),
|
||||
);
|
||||
|
||||
final Widget childWithInteraction = productPageIsVisible(context)
|
||||
? Semantics(
|
||||
button: true,
|
||||
label: GalleryLocalizations.of(context)
|
||||
.shrineScreenReaderCart(totalCartQuantity),
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: open,
|
||||
child: child,
|
||||
),
|
||||
)
|
||||
: child;
|
||||
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(top: _gapAnimation.value),
|
||||
child: childWithInteraction,
|
||||
);
|
||||
}
|
||||
|
||||
// Builder for the hide and reveal animation when the backdrop opens and closes
|
||||
Widget _buildSlideAnimation(BuildContext context, Widget child) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
if (isDesktop) {
|
||||
return child;
|
||||
} else {
|
||||
final double textDirectionScalar =
|
||||
Directionality.of(context) == TextDirection.ltr ? 1 : -1;
|
||||
|
||||
_slideAnimation = _getEmphasizedEasingAnimation(
|
||||
begin: Offset(1 * textDirectionScalar, 0),
|
||||
peak: Offset(_peakVelocityProgress * textDirectionScalar, 0),
|
||||
end: const Offset(0, 0),
|
||||
isForward: widget.hideController.status == AnimationStatus.forward,
|
||||
parent: widget.hideController,
|
||||
);
|
||||
|
||||
return SlideTransition(
|
||||
position: _slideAnimation,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedSize(
|
||||
key: _expandingBottomSheetKey,
|
||||
duration: const Duration(milliseconds: 225),
|
||||
curve: Curves.easeInOut,
|
||||
vsync: this,
|
||||
alignment: AlignmentDirectional.topStart,
|
||||
child: AnimatedBuilder(
|
||||
animation: widget.hideController,
|
||||
builder: (context, child) => AnimatedBuilder(
|
||||
animation: widget.expandingController,
|
||||
builder: (context, child) => ScopedModelDescendant<AppStateModel>(
|
||||
builder: (context, child, model) =>
|
||||
_buildSlideAnimation(context, _buildCart(context)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ProductThumbnailRow extends StatefulWidget {
|
||||
@override
|
||||
_ProductThumbnailRowState createState() => _ProductThumbnailRowState();
|
||||
}
|
||||
|
||||
class _ProductThumbnailRowState extends State<ProductThumbnailRow> {
|
||||
final GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
|
||||
|
||||
// _list represents what's currently on screen. If _internalList updates,
|
||||
// it will need to be updated to match it.
|
||||
_ListModel _list;
|
||||
|
||||
// _internalList represents the list as it is updated by the AppStateModel.
|
||||
List<int> _internalList;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_list = _ListModel(
|
||||
listKey: _listKey,
|
||||
initialItems:
|
||||
ScopedModel.of<AppStateModel>(context).productsInCart.keys.toList(),
|
||||
removedItemBuilder: _buildRemovedThumbnail,
|
||||
);
|
||||
_internalList = List<int>.from(_list.list);
|
||||
}
|
||||
|
||||
Product _productWithId(int productId) {
|
||||
final AppStateModel model = ScopedModel.of<AppStateModel>(context);
|
||||
final Product product = model.getProductById(productId);
|
||||
assert(product != null);
|
||||
return product;
|
||||
}
|
||||
|
||||
Widget _buildRemovedThumbnail(
|
||||
int item, BuildContext context, Animation<double> animation) {
|
||||
return ProductThumbnail(animation, animation, _productWithId(item));
|
||||
}
|
||||
|
||||
Widget _buildThumbnail(
|
||||
BuildContext context, int index, Animation<double> animation) {
|
||||
final Animation<double> thumbnailSize =
|
||||
Tween<double>(begin: 0.8, end: 1).animate(
|
||||
CurvedAnimation(
|
||||
curve: const Interval(0.33, 1, curve: Curves.easeIn),
|
||||
parent: animation,
|
||||
),
|
||||
);
|
||||
|
||||
final Animation<double> opacity = CurvedAnimation(
|
||||
curve: const Interval(0.33, 1, curve: Curves.linear),
|
||||
parent: animation,
|
||||
);
|
||||
|
||||
return ProductThumbnail(
|
||||
thumbnailSize, opacity, _productWithId(_list[index]));
|
||||
}
|
||||
|
||||
// If the lists are the same length, assume nothing has changed.
|
||||
// If the internalList is shorter than the ListModel, an item has been removed.
|
||||
// If the internalList is longer, then an item has been added.
|
||||
void _updateLists() {
|
||||
// Update _internalList based on the model
|
||||
_internalList =
|
||||
ScopedModel.of<AppStateModel>(context).productsInCart.keys.toList();
|
||||
final Set<int> internalSet = Set<int>.from(_internalList);
|
||||
final Set<int> listSet = Set<int>.from(_list.list);
|
||||
|
||||
final Set<int> difference = internalSet.difference(listSet);
|
||||
if (difference.isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (int product in difference) {
|
||||
if (_internalList.length < _list.length) {
|
||||
_list.remove(product);
|
||||
} else if (_internalList.length > _list.length) {
|
||||
_list.add(product);
|
||||
}
|
||||
}
|
||||
|
||||
while (_internalList.length != _list.length) {
|
||||
int index = 0;
|
||||
// Check bounds and that the list elements are the same
|
||||
while (_internalList.isNotEmpty &&
|
||||
_list.length > 0 &&
|
||||
index < _internalList.length &&
|
||||
index < _list.length &&
|
||||
_internalList[index] == _list[index]) {
|
||||
index++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildAnimatedList(BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
return AnimatedList(
|
||||
key: _listKey,
|
||||
shrinkWrap: true,
|
||||
itemBuilder: _buildThumbnail,
|
||||
initialItemCount: _list.length,
|
||||
scrollDirection: isDesktop ? Axis.vertical : Axis.horizontal,
|
||||
physics: const NeverScrollableScrollPhysics(), // Cart shouldn't scroll
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
_updateLists();
|
||||
return ScopedModelDescendant<AppStateModel>(
|
||||
builder: (context, child, model) => _buildAnimatedList(context),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ExtraProductsNumber extends StatelessWidget {
|
||||
// Calculates the number to be displayed at the end of the row if there are
|
||||
// more than three products in the cart. This calculates overflow products,
|
||||
// including their duplicates (but not duplicates of products shown as
|
||||
// thumbnails).
|
||||
int _calculateOverflow(AppStateModel model) {
|
||||
final Map<int, int> productMap = model.productsInCart;
|
||||
// List created to be able to access products by index instead of ID.
|
||||
// Order is guaranteed because productsInCart returns a LinkedHashMap.
|
||||
final List<int> products = productMap.keys.toList();
|
||||
int overflow = 0;
|
||||
final int numProducts = products.length;
|
||||
for (int i = _maxThumbnailCount; i < numProducts; i++) {
|
||||
overflow += productMap[products[i]];
|
||||
}
|
||||
return overflow;
|
||||
}
|
||||
|
||||
Widget _buildOverflow(AppStateModel model, BuildContext context) {
|
||||
if (model.productsInCart.length <= _maxThumbnailCount) {
|
||||
return Container();
|
||||
}
|
||||
|
||||
final int numOverflowProducts = _calculateOverflow(model);
|
||||
// Maximum of 99 so padding doesn't get messy.
|
||||
final int displayedOverflowProducts =
|
||||
numOverflowProducts <= 99 ? numOverflowProducts : 99;
|
||||
return Container(
|
||||
child: Text(
|
||||
'+$displayedOverflowProducts',
|
||||
style: Theme.of(context).primaryTextTheme.button,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ScopedModelDescendant<AppStateModel>(
|
||||
builder: (builder, child, model) => _buildOverflow(model, context),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ProductThumbnail extends StatelessWidget {
|
||||
const ProductThumbnail(this.animation, this.opacityAnimation, this.product);
|
||||
|
||||
final Animation<double> animation;
|
||||
final Animation<double> opacityAnimation;
|
||||
final Product product;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
return FadeTransition(
|
||||
opacity: opacityAnimation,
|
||||
child: ScaleTransition(
|
||||
scale: animation,
|
||||
child: Container(
|
||||
width: _thumbnailHeight(context),
|
||||
height: _thumbnailHeight(context),
|
||||
decoration: BoxDecoration(
|
||||
image: DecorationImage(
|
||||
image: ExactAssetImage(
|
||||
product.assetName, // asset name
|
||||
package: product.assetPackage, // asset package
|
||||
),
|
||||
fit: BoxFit.cover,
|
||||
),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(10)),
|
||||
),
|
||||
margin: isDesktop
|
||||
? const EdgeInsetsDirectional.only(start: 12, end: 12, bottom: 16)
|
||||
: const EdgeInsetsDirectional.only(start: 16),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// _ListModel manipulates an internal list and an AnimatedList
|
||||
class _ListModel {
|
||||
_ListModel({
|
||||
@required this.listKey,
|
||||
@required this.removedItemBuilder,
|
||||
Iterable<int> initialItems,
|
||||
}) : assert(listKey != null),
|
||||
assert(removedItemBuilder != null),
|
||||
_items = initialItems?.toList() ?? [];
|
||||
|
||||
final GlobalKey<AnimatedListState> listKey;
|
||||
final Widget Function(int, BuildContext, Animation<double>)
|
||||
removedItemBuilder;
|
||||
final List<int> _items;
|
||||
|
||||
AnimatedListState get _animatedList => listKey.currentState;
|
||||
|
||||
void add(int product) {
|
||||
_insert(_items.length, product);
|
||||
}
|
||||
|
||||
void _insert(int index, int item) {
|
||||
_items.insert(index, item);
|
||||
_animatedList.insertItem(index,
|
||||
duration: const Duration(milliseconds: 225));
|
||||
}
|
||||
|
||||
void remove(int product) {
|
||||
final int index = _items.indexOf(product);
|
||||
if (index >= 0) {
|
||||
_removeAt(index);
|
||||
}
|
||||
}
|
||||
|
||||
void _removeAt(int index) {
|
||||
final int removedItem = _items.removeAt(index);
|
||||
if (removedItem != null) {
|
||||
_animatedList.removeItem(index, (context, animation) {
|
||||
return removedItemBuilder(removedItem, context, animation);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
int get length => _items.length;
|
||||
|
||||
int operator [](int index) => _items[index];
|
||||
|
||||
int indexOf(int item) => _items.indexOf(item);
|
||||
|
||||
List<int> get list => _items;
|
||||
}
|
||||
74
gallery/lib/studies/shrine/home.dart
Normal file
74
gallery/lib/studies/shrine/home.dart
Normal file
@@ -0,0 +1,74 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/semantics.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/studies/shrine/expanding_bottom_sheet.dart';
|
||||
import 'package:gallery/studies/shrine/model/app_state_model.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/asymmetric_view.dart';
|
||||
import 'package:scoped_model/scoped_model.dart';
|
||||
|
||||
const _ordinalSortKeyName = 'home';
|
||||
|
||||
class ProductPage extends StatelessWidget {
|
||||
const ProductPage();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
return ScopedModelDescendant<AppStateModel>(
|
||||
builder: (context, child, model) {
|
||||
return isDesktop
|
||||
? DesktopAsymmetricView(products: model.getProducts())
|
||||
: MobileAsymmetricView(products: model.getProducts());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class HomePage extends StatelessWidget {
|
||||
const HomePage({
|
||||
this.expandingBottomSheet,
|
||||
this.scrim,
|
||||
this.backdrop,
|
||||
Key key,
|
||||
}) : super(key: key);
|
||||
|
||||
final ExpandingBottomSheet expandingBottomSheet;
|
||||
final Widget scrim;
|
||||
final Widget backdrop;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
// Use sort keys to make sure the cart button is always on the top.
|
||||
// This way, a11y users do not have to scroll through the entire list to
|
||||
// find the cart, and can easily get to the cart from anywhere on the page.
|
||||
return ApplyTextOptions(
|
||||
child: Stack(
|
||||
children: [
|
||||
Semantics(
|
||||
container: true,
|
||||
child: backdrop,
|
||||
sortKey: OrdinalSortKey(1, name: _ordinalSortKeyName),
|
||||
),
|
||||
ExcludeSemantics(child: scrim),
|
||||
Align(
|
||||
child: Semantics(
|
||||
container: true,
|
||||
child: expandingBottomSheet,
|
||||
sortKey: OrdinalSortKey(0, name: _ordinalSortKeyName),
|
||||
),
|
||||
alignment: isDesktop
|
||||
? AlignmentDirectional.topEnd
|
||||
: AlignmentDirectional.bottomEnd,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
230
gallery/lib/studies/shrine/login.dart
Normal file
230
gallery/lib/studies/shrine/login.dart
Normal file
@@ -0,0 +1,230 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/studies/shrine/colors.dart';
|
||||
import 'package:gallery/studies/shrine/theme.dart';
|
||||
|
||||
const _horizontalPadding = 24.0;
|
||||
|
||||
double desktopLoginScreenMainAreaWidth({BuildContext context}) {
|
||||
return min(
|
||||
360 * reducedTextScale(context),
|
||||
MediaQuery.of(context).size.width - 2 * _horizontalPadding,
|
||||
);
|
||||
}
|
||||
|
||||
class LoginPage extends StatefulWidget {
|
||||
@override
|
||||
_LoginPageState createState() => _LoginPageState();
|
||||
}
|
||||
|
||||
class _LoginPageState extends State<LoginPage> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
return ApplyTextOptions(
|
||||
child: isDesktop
|
||||
? LayoutBuilder(
|
||||
builder: (context, constraints) => Scaffold(
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: Container(
|
||||
width: desktopLoginScreenMainAreaWidth(context: context),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: const [
|
||||
_ShrineLogo(),
|
||||
SizedBox(height: 40),
|
||||
_UsernameTextField(),
|
||||
SizedBox(height: 16),
|
||||
_PasswordTextField(),
|
||||
SizedBox(height: 24),
|
||||
_CancelAndNextButtons(),
|
||||
SizedBox(height: 62),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: Scaffold(
|
||||
body: SafeArea(
|
||||
child: ListView(
|
||||
physics: ClampingScrollPhysics(),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: _horizontalPadding,
|
||||
),
|
||||
children: const [
|
||||
SizedBox(height: 80),
|
||||
_ShrineLogo(),
|
||||
SizedBox(height: 120),
|
||||
_UsernameTextField(),
|
||||
SizedBox(height: 12),
|
||||
_PasswordTextField(),
|
||||
_CancelAndNextButtons(),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ShrineLogo extends StatelessWidget {
|
||||
const _ShrineLogo();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ExcludeSemantics(
|
||||
child: Column(
|
||||
children: [
|
||||
Image.asset('packages/shrine_images/diamond.png'),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'SHRINE',
|
||||
style: Theme.of(context).textTheme.headline,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _UsernameTextField extends StatelessWidget {
|
||||
const _UsernameTextField();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final ColorScheme colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
final TextEditingController _usernameController = TextEditingController();
|
||||
|
||||
return PrimaryColorOverride(
|
||||
color: shrineBrown900,
|
||||
child: Container(
|
||||
child: TextField(
|
||||
controller: _usernameController,
|
||||
cursorColor: colorScheme.onSurface,
|
||||
decoration: InputDecoration(
|
||||
labelText:
|
||||
GalleryLocalizations.of(context).shrineLoginUsernameLabel,
|
||||
labelStyle: TextStyle(letterSpacing: mediumLetterSpacing),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PasswordTextField extends StatelessWidget {
|
||||
const _PasswordTextField();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final ColorScheme colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
final TextEditingController _passwordController = TextEditingController();
|
||||
|
||||
return PrimaryColorOverride(
|
||||
color: shrineBrown900,
|
||||
child: Container(
|
||||
child: TextField(
|
||||
controller: _passwordController,
|
||||
cursorColor: colorScheme.onSurface,
|
||||
obscureText: true,
|
||||
decoration: InputDecoration(
|
||||
labelText:
|
||||
GalleryLocalizations.of(context).shrineLoginPasswordLabel,
|
||||
labelStyle: TextStyle(letterSpacing: mediumLetterSpacing),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CancelAndNextButtons extends StatelessWidget {
|
||||
const _CancelAndNextButtons();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final ColorScheme colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
final EdgeInsets buttonTextPadding = isDesktop
|
||||
? EdgeInsets.symmetric(horizontal: 24, vertical: 16)
|
||||
: EdgeInsets.zero;
|
||||
|
||||
return Wrap(
|
||||
children: [
|
||||
ButtonBar(
|
||||
buttonPadding: isDesktop ? EdgeInsets.zero : null,
|
||||
children: [
|
||||
FlatButton(
|
||||
child: Padding(
|
||||
padding: buttonTextPadding,
|
||||
child: Text(
|
||||
GalleryLocalizations.of(context).shrineCancelButtonCaption,
|
||||
style: TextStyle(color: colorScheme.onSurface),
|
||||
),
|
||||
),
|
||||
shape: const BeveledRectangleBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(7)),
|
||||
),
|
||||
onPressed: () {
|
||||
// The login screen is immediately displayed on top of
|
||||
// the Shrine home screen using onGenerateRoute and so
|
||||
// rootNavigator must be set to true in order to get out
|
||||
// of Shrine completely.
|
||||
Navigator.of(context, rootNavigator: true).pop();
|
||||
},
|
||||
),
|
||||
RaisedButton(
|
||||
child: Padding(
|
||||
padding: buttonTextPadding,
|
||||
child: Text(
|
||||
GalleryLocalizations.of(context).shrineNextButtonCaption,
|
||||
style: TextStyle(letterSpacing: largeLetterSpacing),
|
||||
),
|
||||
),
|
||||
elevation: 8,
|
||||
shape: const BeveledRectangleBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(7)),
|
||||
),
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PrimaryColorOverride extends StatelessWidget {
|
||||
const PrimaryColorOverride({Key key, this.color, this.child})
|
||||
: super(key: key);
|
||||
|
||||
final Color color;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Theme(
|
||||
child: child,
|
||||
data: Theme.of(context).copyWith(primaryColor: color),
|
||||
);
|
||||
}
|
||||
}
|
||||
114
gallery/lib/studies/shrine/model/app_state_model.dart
Normal file
114
gallery/lib/studies/shrine/model/app_state_model.dart
Normal file
@@ -0,0 +1,114 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:scoped_model/scoped_model.dart';
|
||||
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
import 'package:gallery/studies/shrine/model/products_repository.dart';
|
||||
|
||||
double _salesTaxRate = 0.06;
|
||||
double _shippingCostPerItem = 7;
|
||||
|
||||
class AppStateModel extends Model {
|
||||
// All the available products.
|
||||
List<Product> _availableProducts;
|
||||
|
||||
// The currently selected category of products.
|
||||
Category _selectedCategory = categoryAll;
|
||||
|
||||
// The IDs and quantities of products currently in the cart.
|
||||
final Map<int, int> _productsInCart = <int, int>{};
|
||||
|
||||
Map<int, int> get productsInCart => Map<int, int>.from(_productsInCart);
|
||||
|
||||
// Total number of items in the cart.
|
||||
int get totalCartQuantity => _productsInCart.values.fold(0, (v, e) => v + e);
|
||||
|
||||
Category get selectedCategory => _selectedCategory;
|
||||
|
||||
// Totaled prices of the items in the cart.
|
||||
double get subtotalCost {
|
||||
return _productsInCart.keys
|
||||
.map((id) => _availableProducts[id].price * _productsInCart[id])
|
||||
.fold(0.0, (sum, e) => sum + e);
|
||||
}
|
||||
|
||||
// Total shipping cost for the items in the cart.
|
||||
double get shippingCost {
|
||||
return _shippingCostPerItem *
|
||||
_productsInCart.values.fold(0.0, (sum, e) => sum + e);
|
||||
}
|
||||
|
||||
// Sales tax for the items in the cart
|
||||
double get tax => subtotalCost * _salesTaxRate;
|
||||
|
||||
// Total cost to order everything in the cart.
|
||||
double get totalCost => subtotalCost + shippingCost + tax;
|
||||
|
||||
// Returns a copy of the list of available products, filtered by category.
|
||||
List<Product> getProducts() {
|
||||
if (_availableProducts == null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (_selectedCategory == categoryAll) {
|
||||
return List<Product>.from(_availableProducts);
|
||||
} else {
|
||||
return _availableProducts
|
||||
.where((p) => p.category == _selectedCategory)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
// Adds a product to the cart.
|
||||
void addProductToCart(int productId) {
|
||||
if (!_productsInCart.containsKey(productId)) {
|
||||
_productsInCart[productId] = 1;
|
||||
} else {
|
||||
_productsInCart[productId]++;
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// Removes an item from the cart.
|
||||
void removeItemFromCart(int productId) {
|
||||
if (_productsInCart.containsKey(productId)) {
|
||||
if (_productsInCart[productId] == 1) {
|
||||
_productsInCart.remove(productId);
|
||||
} else {
|
||||
_productsInCart[productId]--;
|
||||
}
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// Returns the Product instance matching the provided id.
|
||||
Product getProductById(int id) {
|
||||
return _availableProducts.firstWhere((p) => p.id == id);
|
||||
}
|
||||
|
||||
// Removes everything from the cart.
|
||||
void clearCart() {
|
||||
_productsInCart.clear();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// Loads the list of available products from the repo.
|
||||
void loadProducts() {
|
||||
_availableProducts = ProductsRepository.loadProducts(categoryAll);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void setCategory(Category newCategory) {
|
||||
_selectedCategory = newCategory;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AppStateModel(totalCost: $totalCost)';
|
||||
}
|
||||
}
|
||||
70
gallery/lib/studies/shrine/model/product.dart
Normal file
70
gallery/lib/studies/shrine/model/product.dart
Normal file
@@ -0,0 +1,70 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../../l10n/gallery_localizations.dart';
|
||||
|
||||
class Category {
|
||||
const Category({
|
||||
@required this.name,
|
||||
}) : assert(name != null);
|
||||
|
||||
// A function taking a BuildContext as input and
|
||||
// returns the internationalized name of the category.
|
||||
final String Function(BuildContext) name;
|
||||
}
|
||||
|
||||
Category categoryAll = Category(
|
||||
name: (context) => GalleryLocalizations.of(context).shrineCategoryNameAll,
|
||||
);
|
||||
|
||||
Category categoryAccessories = Category(
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineCategoryNameAccessories,
|
||||
);
|
||||
|
||||
Category categoryClothing = Category(
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineCategoryNameClothing,
|
||||
);
|
||||
|
||||
Category categoryHome = Category(
|
||||
name: (context) => GalleryLocalizations.of(context).shrineCategoryNameHome,
|
||||
);
|
||||
|
||||
List<Category> categories = [
|
||||
categoryAll,
|
||||
categoryAccessories,
|
||||
categoryClothing,
|
||||
categoryHome,
|
||||
];
|
||||
|
||||
class Product {
|
||||
const Product({
|
||||
@required this.category,
|
||||
@required this.id,
|
||||
@required this.isFeatured,
|
||||
@required this.name,
|
||||
@required this.price,
|
||||
}) : assert(category != null),
|
||||
assert(id != null),
|
||||
assert(isFeatured != null),
|
||||
assert(name != null),
|
||||
assert(price != null);
|
||||
|
||||
final Category category;
|
||||
final int id;
|
||||
final bool isFeatured;
|
||||
|
||||
// A function taking a BuildContext as input and
|
||||
// returns the internationalized name of the product.
|
||||
final String Function(BuildContext) name;
|
||||
|
||||
final int price;
|
||||
|
||||
String get assetName => '$id-0.jpg';
|
||||
String get assetPackage => 'shrine_images';
|
||||
}
|
||||
323
gallery/lib/studies/shrine/model/products_repository.dart
Normal file
323
gallery/lib/studies/shrine/model/products_repository.dart
Normal file
@@ -0,0 +1,323 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
|
||||
import '../../../l10n/gallery_localizations.dart';
|
||||
|
||||
class ProductsRepository {
|
||||
static List<Product> loadProducts(Category category) {
|
||||
List<Product> allProducts = [
|
||||
Product(
|
||||
category: categoryAccessories,
|
||||
id: 0,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductVagabondSack,
|
||||
price: 120,
|
||||
),
|
||||
Product(
|
||||
category: categoryAccessories,
|
||||
id: 1,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductStellaSunglasses,
|
||||
price: 58,
|
||||
),
|
||||
Product(
|
||||
category: categoryAccessories,
|
||||
id: 2,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductWhitneyBelt,
|
||||
price: 35,
|
||||
),
|
||||
Product(
|
||||
category: categoryAccessories,
|
||||
id: 3,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductGardenStrand,
|
||||
price: 98,
|
||||
),
|
||||
Product(
|
||||
category: categoryAccessories,
|
||||
id: 4,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductStrutEarrings,
|
||||
price: 34,
|
||||
),
|
||||
Product(
|
||||
category: categoryAccessories,
|
||||
id: 5,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductVarsitySocks,
|
||||
price: 12,
|
||||
),
|
||||
Product(
|
||||
category: categoryAccessories,
|
||||
id: 6,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductWeaveKeyring,
|
||||
price: 16,
|
||||
),
|
||||
Product(
|
||||
category: categoryAccessories,
|
||||
id: 7,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductGatsbyHat,
|
||||
price: 40,
|
||||
),
|
||||
Product(
|
||||
category: categoryAccessories,
|
||||
id: 8,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductShrugBag,
|
||||
price: 198,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 9,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductGiltDeskTrio,
|
||||
price: 58,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 10,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductCopperWireRack,
|
||||
price: 18,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 11,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductSootheCeramicSet,
|
||||
price: 28,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 12,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductHurrahsTeaSet,
|
||||
price: 34,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 13,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductBlueStoneMug,
|
||||
price: 18,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 14,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductRainwaterTray,
|
||||
price: 27,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 15,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductChambrayNapkins,
|
||||
price: 16,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 16,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductSucculentPlanters,
|
||||
price: 16,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 17,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductQuartetTable,
|
||||
price: 175,
|
||||
),
|
||||
Product(
|
||||
category: categoryHome,
|
||||
id: 18,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductKitchenQuattro,
|
||||
price: 129,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 19,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductClaySweater,
|
||||
price: 48,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 20,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductSeaTunic,
|
||||
price: 45,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 21,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductPlasterTunic,
|
||||
price: 38,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 22,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductWhitePinstripeShirt,
|
||||
price: 70,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 23,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductChambrayShirt,
|
||||
price: 70,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 24,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductSeabreezeSweater,
|
||||
price: 60,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 25,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductGentryJacket,
|
||||
price: 178,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 26,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductNavyTrousers,
|
||||
price: 74,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 27,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductWalterHenleyWhite,
|
||||
price: 38,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 28,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductSurfAndPerfShirt,
|
||||
price: 48,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 29,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductGingerScarf,
|
||||
price: 98,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 30,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductRamonaCrossover,
|
||||
price: 68,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 31,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductChambrayShirt,
|
||||
price: 38,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 32,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductClassicWhiteCollar,
|
||||
price: 58,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 33,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductCeriseScallopTee,
|
||||
price: 42,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 34,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductShoulderRollsTee,
|
||||
price: 27,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 35,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductGreySlouchTank,
|
||||
price: 24,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 36,
|
||||
isFeatured: false,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductSunshirtDress,
|
||||
price: 58,
|
||||
),
|
||||
Product(
|
||||
category: categoryClothing,
|
||||
id: 37,
|
||||
isFeatured: true,
|
||||
name: (context) =>
|
||||
GalleryLocalizations.of(context).shrineProductFineLinesTee,
|
||||
price: 58,
|
||||
),
|
||||
];
|
||||
if (category == categoryAll) {
|
||||
return allProducts;
|
||||
} else {
|
||||
return allProducts.where((p) => p.category == category).toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
52
gallery/lib/studies/shrine/page_status.dart
Normal file
52
gallery/lib/studies/shrine/page_status.dart
Normal file
@@ -0,0 +1,52 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
|
||||
class PageStatus extends InheritedWidget {
|
||||
const PageStatus({
|
||||
Key key,
|
||||
@required this.cartController,
|
||||
@required this.menuController,
|
||||
@required Widget child,
|
||||
}) : assert(cartController != null),
|
||||
assert(menuController != null),
|
||||
super(key: key, child: child);
|
||||
|
||||
final AnimationController cartController;
|
||||
final AnimationController menuController;
|
||||
|
||||
static PageStatus of(BuildContext context) {
|
||||
return context.dependOnInheritedWidgetOfExactType<PageStatus>();
|
||||
}
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(PageStatus old) =>
|
||||
old.cartController != cartController ||
|
||||
old.menuController != menuController;
|
||||
}
|
||||
|
||||
bool productPageIsVisible(BuildContext context) {
|
||||
return _cartControllerOf(context).isDismissed &&
|
||||
(_menuControllerOf(context).isCompleted || isDisplayDesktop(context));
|
||||
}
|
||||
|
||||
bool menuPageIsVisible(BuildContext context) {
|
||||
return _cartControllerOf(context).isDismissed &&
|
||||
(_menuControllerOf(context).isDismissed || isDisplayDesktop(context));
|
||||
}
|
||||
|
||||
bool cartPageIsVisible(BuildContext context) {
|
||||
return _cartControllerOf(context).isCompleted;
|
||||
}
|
||||
|
||||
AnimationController _cartControllerOf(BuildContext context) {
|
||||
return PageStatus.of(context).cartController;
|
||||
}
|
||||
|
||||
AnimationController _menuControllerOf(BuildContext context) {
|
||||
return PageStatus.of(context).menuController;
|
||||
}
|
||||
46
gallery/lib/studies/shrine/scrim.dart
Normal file
46
gallery/lib/studies/shrine/scrim.dart
Normal file
@@ -0,0 +1,46 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class Scrim extends StatelessWidget {
|
||||
const Scrim({this.controller});
|
||||
|
||||
final AnimationController controller;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Size deviceSize = MediaQuery.of(context).size;
|
||||
return ExcludeSemantics(
|
||||
child: AnimatedBuilder(
|
||||
animation: controller,
|
||||
builder: (context, child) {
|
||||
final Color color =
|
||||
Color(0xFFF0EA).withOpacity(controller.value * 0.87);
|
||||
|
||||
final Widget scrimRectangle = Container(
|
||||
width: deviceSize.width, height: deviceSize.height, color: color);
|
||||
|
||||
final bool ignorePointer =
|
||||
(controller.status == AnimationStatus.dismissed);
|
||||
final bool tapToRevert =
|
||||
(controller.status == AnimationStatus.completed);
|
||||
|
||||
if (tapToRevert) {
|
||||
return GestureDetector(
|
||||
onTap: () {
|
||||
controller.reverse();
|
||||
},
|
||||
child: scrimRectangle,
|
||||
);
|
||||
} else if (ignorePointer) {
|
||||
return IgnorePointer(child: scrimRectangle);
|
||||
} else {
|
||||
return scrimRectangle;
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
345
gallery/lib/studies/shrine/shopping_cart.dart
Normal file
345
gallery/lib/studies/shrine/shopping_cart.dart
Normal file
@@ -0,0 +1,345 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:scoped_model/scoped_model.dart';
|
||||
|
||||
import 'package:gallery/studies/shrine/colors.dart';
|
||||
import 'package:gallery/studies/shrine/expanding_bottom_sheet.dart';
|
||||
import 'package:gallery/studies/shrine/model/app_state_model.dart';
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
import 'package:gallery/studies/shrine/theme.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
|
||||
const _startColumnWidth = 60.0;
|
||||
const _ordinalSortKeyName = 'shopping_cart';
|
||||
|
||||
class ShoppingCartPage extends StatefulWidget {
|
||||
@override
|
||||
_ShoppingCartPageState createState() => _ShoppingCartPageState();
|
||||
}
|
||||
|
||||
class _ShoppingCartPageState extends State<ShoppingCartPage> {
|
||||
List<Widget> _createShoppingCartRows(AppStateModel model) {
|
||||
return model.productsInCart.keys
|
||||
.map(
|
||||
(id) => ShoppingCartRow(
|
||||
product: model.getProductById(id),
|
||||
quantity: model.productsInCart[id],
|
||||
onPressed: () {
|
||||
model.removeItemFromCart(id);
|
||||
},
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final ThemeData localTheme = Theme.of(context);
|
||||
return Scaffold(
|
||||
backgroundColor: shrinePink50,
|
||||
body: SafeArea(
|
||||
child: Container(
|
||||
child: ScopedModelDescendant<AppStateModel>(
|
||||
builder: (context, child, model) {
|
||||
return Stack(
|
||||
children: [
|
||||
ListView(
|
||||
children: [
|
||||
Semantics(
|
||||
sortKey: OrdinalSortKey(0, name: _ordinalSortKeyName),
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: _startColumnWidth,
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.keyboard_arrow_down),
|
||||
onPressed: () =>
|
||||
ExpandingBottomSheet.of(context).close(),
|
||||
tooltip: GalleryLocalizations.of(context)
|
||||
.shrineTooltipCloseCart,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
GalleryLocalizations.of(context)
|
||||
.shrineCartPageCaption,
|
||||
style: localTheme.textTheme.subhead
|
||||
.copyWith(fontWeight: FontWeight.w600),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Text(
|
||||
GalleryLocalizations.of(context)
|
||||
.shrineCartItemCount(
|
||||
model.totalCartQuantity,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Semantics(
|
||||
sortKey: OrdinalSortKey(1, name: _ordinalSortKeyName),
|
||||
child: Column(
|
||||
children: _createShoppingCartRows(model),
|
||||
),
|
||||
),
|
||||
Semantics(
|
||||
sortKey: OrdinalSortKey(2, name: _ordinalSortKeyName),
|
||||
child: ShoppingCartSummary(model: model),
|
||||
),
|
||||
const SizedBox(height: 100),
|
||||
],
|
||||
),
|
||||
PositionedDirectional(
|
||||
bottom: 16,
|
||||
start: 16,
|
||||
end: 16,
|
||||
child: Semantics(
|
||||
sortKey: OrdinalSortKey(3, name: _ordinalSortKeyName),
|
||||
child: RaisedButton(
|
||||
shape: const BeveledRectangleBorder(
|
||||
borderRadius: BorderRadius.all(Radius.circular(7)),
|
||||
),
|
||||
color: shrinePink100,
|
||||
splashColor: shrineBrown600,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 12),
|
||||
child: Text(
|
||||
GalleryLocalizations.of(context)
|
||||
.shrineCartClearButtonCaption,
|
||||
style: TextStyle(letterSpacing: largeLetterSpacing),
|
||||
),
|
||||
),
|
||||
onPressed: () {
|
||||
model.clearCart();
|
||||
ExpandingBottomSheet.of(context).close();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ShoppingCartSummary extends StatelessWidget {
|
||||
const ShoppingCartSummary({this.model});
|
||||
|
||||
final AppStateModel model;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final TextStyle smallAmountStyle =
|
||||
Theme.of(context).textTheme.body1.copyWith(color: shrineBrown600);
|
||||
final TextStyle largeAmountStyle = Theme.of(context)
|
||||
.textTheme
|
||||
.display1
|
||||
.copyWith(letterSpacing: mediumLetterSpacing);
|
||||
final NumberFormat formatter = NumberFormat.simpleCurrency(
|
||||
decimalDigits: 2,
|
||||
locale: Localizations.localeOf(context).toString(),
|
||||
);
|
||||
|
||||
return Row(
|
||||
children: [
|
||||
const SizedBox(width: _startColumnWidth),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 16),
|
||||
child: Column(
|
||||
children: [
|
||||
MergeSemantics(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
GalleryLocalizations.of(context).shrineCartTotalCaption,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
formatter.format(model.totalCost),
|
||||
style: largeAmountStyle,
|
||||
textAlign: TextAlign.end,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
MergeSemantics(
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
GalleryLocalizations.of(context)
|
||||
.shrineCartSubtotalCaption,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
formatter.format(model.subtotalCost),
|
||||
style: smallAmountStyle,
|
||||
textAlign: TextAlign.end,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
MergeSemantics(
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
GalleryLocalizations.of(context)
|
||||
.shrineCartShippingCaption,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
formatter.format(model.shippingCost),
|
||||
style: smallAmountStyle,
|
||||
textAlign: TextAlign.end,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
MergeSemantics(
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
GalleryLocalizations.of(context).shrineCartTaxCaption,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
formatter.format(model.tax),
|
||||
style: smallAmountStyle,
|
||||
textAlign: TextAlign.end,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ShoppingCartRow extends StatelessWidget {
|
||||
const ShoppingCartRow({
|
||||
@required this.product,
|
||||
@required this.quantity,
|
||||
this.onPressed,
|
||||
});
|
||||
|
||||
final Product product;
|
||||
final int quantity;
|
||||
final VoidCallback onPressed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final NumberFormat formatter = NumberFormat.simpleCurrency(
|
||||
decimalDigits: 0,
|
||||
locale: Localizations.localeOf(context).toString(),
|
||||
);
|
||||
final ThemeData localTheme = Theme.of(context);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
child: Row(
|
||||
key: ValueKey<int>(product.id),
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Semantics(
|
||||
container: true,
|
||||
label: GalleryLocalizations.of(context)
|
||||
.shrineScreenReaderRemoveProductButton(product.name(context)),
|
||||
button: true,
|
||||
child: ExcludeSemantics(
|
||||
child: SizedBox(
|
||||
width: _startColumnWidth,
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.remove_circle_outline),
|
||||
onPressed: onPressed,
|
||||
tooltip:
|
||||
GalleryLocalizations.of(context).shrineTooltipRemoveItem,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: 16),
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Image.asset(
|
||||
product.assetName,
|
||||
package: product.assetPackage,
|
||||
fit: BoxFit.cover,
|
||||
width: 75,
|
||||
height: 75,
|
||||
excludeFromSemantics: true,
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: MergeSemantics(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
MergeSemantics(
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
GalleryLocalizations.of(context)
|
||||
.shrineProductQuantity(quantity),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
GalleryLocalizations.of(context)
|
||||
.shrineProductPrice(
|
||||
formatter.format(product.price),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Text(
|
||||
product.name(context),
|
||||
style: localTheme.textTheme.subhead
|
||||
.copyWith(fontWeight: FontWeight.w600),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const Divider(
|
||||
color: shrineBrown900,
|
||||
height: 10,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
295
gallery/lib/studies/shrine/supplemental/asymmetric_view.dart
Normal file
295
gallery/lib/studies/shrine/supplemental/asymmetric_view.dart
Normal file
@@ -0,0 +1,295 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/layout/text_scale.dart';
|
||||
import 'package:gallery/studies/shrine/category_menu_page.dart';
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/balanced_layout.dart';
|
||||
import 'package:gallery/studies/shrine/page_status.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/desktop_product_columns.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/product_columns.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/product_card.dart';
|
||||
|
||||
const _topPadding = 34.0;
|
||||
const _bottomPadding = 44.0;
|
||||
|
||||
const _cardToScreenWidthRatio = 0.59;
|
||||
|
||||
class MobileAsymmetricView extends StatelessWidget {
|
||||
const MobileAsymmetricView({Key key, this.products}) : super(key: key);
|
||||
|
||||
final List<Product> products;
|
||||
|
||||
List<Container> _buildColumns(
|
||||
BuildContext context,
|
||||
BoxConstraints constraints,
|
||||
) {
|
||||
if (products == null || products.isEmpty) {
|
||||
return const [];
|
||||
}
|
||||
|
||||
// Decide whether the page size and text size allow 2-column products.
|
||||
|
||||
final double cardHeight = (constraints.biggest.height -
|
||||
_topPadding -
|
||||
_bottomPadding -
|
||||
TwoProductCardColumn.spacerHeight) /
|
||||
2;
|
||||
|
||||
final double imageWidth =
|
||||
_cardToScreenWidthRatio * constraints.biggest.width -
|
||||
TwoProductCardColumn.horizontalPadding;
|
||||
|
||||
final double imageHeight = cardHeight -
|
||||
MobileProductCard.defaultTextBoxHeight *
|
||||
GalleryOptions.of(context).textScaleFactor(context);
|
||||
|
||||
final bool shouldUseAlternatingLayout =
|
||||
imageHeight > 0 && imageWidth / imageHeight < 49 / 33;
|
||||
|
||||
if (shouldUseAlternatingLayout) {
|
||||
// Alternating layout: a layout of alternating 2-product
|
||||
// and 1-product columns.
|
||||
//
|
||||
// This will return a list of columns. It will oscillate between the two
|
||||
// kinds of columns. Even cases of the index (0, 2, 4, etc) will be
|
||||
// TwoProductCardColumn and the odd cases will be OneProductCardColumn.
|
||||
//
|
||||
// Each pair of columns will advance us 3 products forward (2 + 1). That's
|
||||
// some kinda awkward math so we use _evenCasesIndex and _oddCasesIndex as
|
||||
// helpers for creating the index of the product list that will correspond
|
||||
// to the index of the list of columns.
|
||||
|
||||
return List<Container>.generate(_listItemCount(products.length), (index) {
|
||||
double width =
|
||||
_cardToScreenWidthRatio * MediaQuery.of(context).size.width;
|
||||
Widget column;
|
||||
if (index % 2 == 0) {
|
||||
/// Even cases
|
||||
final int bottom = _evenCasesIndex(index);
|
||||
column = TwoProductCardColumn(
|
||||
bottom: products[bottom],
|
||||
top:
|
||||
products.length - 1 >= bottom + 1 ? products[bottom + 1] : null,
|
||||
imageAspectRatio: imageWidth / imageHeight,
|
||||
);
|
||||
width += 32;
|
||||
} else {
|
||||
/// Odd cases
|
||||
column = OneProductCardColumn(
|
||||
product: products[_oddCasesIndex(index)],
|
||||
reverse: true,
|
||||
);
|
||||
}
|
||||
return Container(
|
||||
width: width,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: column,
|
||||
),
|
||||
);
|
||||
}).toList();
|
||||
} else {
|
||||
// Alternating layout: a layout of 1-product columns.
|
||||
|
||||
return [
|
||||
for (final product in products)
|
||||
Container(
|
||||
width: _cardToScreenWidthRatio * MediaQuery.of(context).size.width,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: OneProductCardColumn(
|
||||
product: product,
|
||||
reverse: false,
|
||||
),
|
||||
),
|
||||
)
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
int _evenCasesIndex(int input) {
|
||||
// The operator ~/ is a cool one. It's the truncating division operator. It
|
||||
// divides the number and if there's a remainder / decimal, it cuts it off.
|
||||
// This is like dividing and then casting the result to int. Also, it's
|
||||
// functionally equivalent to floor() in this case.
|
||||
return input ~/ 2 * 3;
|
||||
}
|
||||
|
||||
int _oddCasesIndex(int input) {
|
||||
assert(input > 0);
|
||||
return (input / 2).ceil() * 3 - 1;
|
||||
}
|
||||
|
||||
int _listItemCount(int totalItems) {
|
||||
return (totalItems % 3 == 0)
|
||||
? totalItems ~/ 3 * 2
|
||||
: (totalItems / 3).ceil() * 2 - 1;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return AnimatedBuilder(
|
||||
animation: PageStatus.of(context).cartController,
|
||||
builder: (context, child) => AnimatedBuilder(
|
||||
animation: PageStatus.of(context).menuController,
|
||||
builder: (context, child) => ExcludeSemantics(
|
||||
excluding: !productPageIsVisible(context),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
return ListView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsetsDirectional.fromSTEB(
|
||||
0,
|
||||
_topPadding,
|
||||
16,
|
||||
_bottomPadding,
|
||||
),
|
||||
children: _buildColumns(context, constraints),
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopAsymmetricView extends StatelessWidget {
|
||||
const DesktopAsymmetricView({Key key, this.products}) : super(key: key);
|
||||
|
||||
final List<Product> products;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Determine the scale factor for the desktop asymmetric view.
|
||||
|
||||
final double textScaleFactor =
|
||||
GalleryOptions.of(context).textScaleFactor(context);
|
||||
|
||||
// When text is larger, the images becomes wider, but at half the rate.
|
||||
final double imageScaleFactor = reducedTextScale(context);
|
||||
|
||||
// When text is larger, horizontal padding becomes smaller.
|
||||
final double paddingScaleFactor = textScaleFactor >= 1.5 ? 0.25 : 1;
|
||||
|
||||
// Calculate number of columns
|
||||
|
||||
final double sidebar = desktopCategoryMenuPageWidth(context: context);
|
||||
final double minimumBoundaryWidth = 84 * paddingScaleFactor;
|
||||
final double columnWidth = 186 * imageScaleFactor;
|
||||
final double columnGapWidth = 24 * imageScaleFactor;
|
||||
final double windowWidth = MediaQuery.of(context).size.width;
|
||||
|
||||
final int idealColumnCount = max(
|
||||
1,
|
||||
((windowWidth + columnGapWidth - 2 * minimumBoundaryWidth - sidebar) /
|
||||
(columnWidth + columnGapWidth))
|
||||
.floor(),
|
||||
);
|
||||
|
||||
// Limit column width to fit within window when there is only one column.
|
||||
final double actualColumnWidth = idealColumnCount == 1
|
||||
? min(
|
||||
columnWidth,
|
||||
windowWidth - sidebar - 2 * minimumBoundaryWidth,
|
||||
)
|
||||
: columnWidth;
|
||||
|
||||
final int columnCount = min(idealColumnCount, max(products.length, 1));
|
||||
|
||||
return AnimatedBuilder(
|
||||
animation: PageStatus.of(context).cartController,
|
||||
builder: (context, child) => ExcludeSemantics(
|
||||
excluding: !productPageIsVisible(context),
|
||||
child: DesktopColumns(
|
||||
columnCount: columnCount,
|
||||
products: products,
|
||||
largeImageWidth: actualColumnWidth,
|
||||
smallImageWidth: columnCount > 1
|
||||
? columnWidth - columnGapWidth
|
||||
: actualColumnWidth,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopColumns extends StatelessWidget {
|
||||
DesktopColumns({
|
||||
@required this.columnCount,
|
||||
@required this.products,
|
||||
@required this.largeImageWidth,
|
||||
@required this.smallImageWidth,
|
||||
});
|
||||
|
||||
final int columnCount;
|
||||
final List<Product> products;
|
||||
final double largeImageWidth;
|
||||
final double smallImageWidth;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Widget _gap = Container(width: 24);
|
||||
|
||||
final List<List<Product>> productCardLists = balancedLayout(
|
||||
context: context,
|
||||
columnCount: columnCount,
|
||||
products: products,
|
||||
largeImageWidth: largeImageWidth,
|
||||
smallImageWidth: smallImageWidth,
|
||||
);
|
||||
|
||||
final List<DesktopProductCardColumn> productCardColumns =
|
||||
List<DesktopProductCardColumn>.generate(
|
||||
columnCount,
|
||||
(column) {
|
||||
final bool alignToEnd =
|
||||
(column % 2 == 1) || (column == columnCount - 1);
|
||||
final bool startLarge = (column % 2 == 1);
|
||||
final bool lowerStart = (column % 2 == 1);
|
||||
return DesktopProductCardColumn(
|
||||
alignToEnd: alignToEnd,
|
||||
startLarge: startLarge,
|
||||
lowerStart: lowerStart,
|
||||
products: productCardLists[column],
|
||||
largeImageWidth: largeImageWidth,
|
||||
smallImageWidth: smallImageWidth,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return ListView(
|
||||
scrollDirection: Axis.vertical,
|
||||
children: [
|
||||
Container(height: 60),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Spacer(),
|
||||
...List<Widget>.generate(
|
||||
2 * columnCount - 1,
|
||||
(generalizedColumnIndex) {
|
||||
if (generalizedColumnIndex % 2 == 0) {
|
||||
return productCardColumns[generalizedColumnIndex ~/ 2];
|
||||
} else {
|
||||
return _gap;
|
||||
}
|
||||
},
|
||||
),
|
||||
Spacer(),
|
||||
],
|
||||
),
|
||||
Container(height: 60),
|
||||
],
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
);
|
||||
}
|
||||
}
|
||||
298
gallery/lib/studies/shrine/supplemental/balanced_layout.dart
Normal file
298
gallery/lib/studies/shrine/supplemental/balanced_layout.dart
Normal file
@@ -0,0 +1,298 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/desktop_product_columns.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/layout_cache.dart';
|
||||
|
||||
/// A placeholder id for an empty element. See [_iterateUntilBalanced]
|
||||
/// for more information.
|
||||
const _emptyElement = -1;
|
||||
|
||||
/// To avoid infinite loops, improvements to the layout are only performed
|
||||
/// when a column's height changes by more than
|
||||
/// [_deviationImprovementThreshold] pixels.
|
||||
const _deviationImprovementThreshold = 10;
|
||||
|
||||
/// Height of a product image, paired with the product's id.
|
||||
class _TaggedHeightData {
|
||||
const _TaggedHeightData({
|
||||
@required this.index,
|
||||
@required this.height,
|
||||
});
|
||||
|
||||
/// The id of the corresponding product.
|
||||
final int index;
|
||||
|
||||
/// The height of the product image.
|
||||
final double height;
|
||||
}
|
||||
|
||||
/// Converts a set of [_TaggedHeightData] elements to a list,
|
||||
/// and add an empty element.
|
||||
/// Used for iteration.
|
||||
List<_TaggedHeightData> toListAndAddEmpty(Set<_TaggedHeightData> set) {
|
||||
List<_TaggedHeightData> result = List<_TaggedHeightData>.from(set);
|
||||
result.add(_TaggedHeightData(index: _emptyElement, height: 0));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Encode parameters for caching.
|
||||
String _encodeParameters({
|
||||
@required int columnCount,
|
||||
@required List<Product> products,
|
||||
@required double largeImageWidth,
|
||||
@required double smallImageWidth,
|
||||
}) {
|
||||
final String productString =
|
||||
[for (final product in products) product.id.toString()].join(',');
|
||||
return '$columnCount;$productString,$largeImageWidth,$smallImageWidth';
|
||||
}
|
||||
|
||||
/// Given a layout, replace integers by their corresponding products.
|
||||
List<List<Product>> _generateLayout({
|
||||
@required List<Product> products,
|
||||
@required List<List<int>> layout,
|
||||
}) {
|
||||
return [
|
||||
for (final column in layout)
|
||||
[
|
||||
for (final index in column) products[index],
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
/// Returns the size of an [Image] widget.
|
||||
Size _imageSize(Image imageWidget) {
|
||||
Size result;
|
||||
|
||||
imageWidget.image.resolve(ImageConfiguration()).addListener(
|
||||
ImageStreamListener(
|
||||
(info, synchronousCall) {
|
||||
final finalImage = info.image;
|
||||
result = Size(
|
||||
finalImage.width.toDouble(),
|
||||
finalImage.height.toDouble(),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Given [columnObjects], list of the set of objects in each column,
|
||||
/// and [columnHeights], list of heights of each column,
|
||||
/// [_iterateUntilBalanced] moves and swaps objects between columns
|
||||
/// until their heights are sufficiently close to each other.
|
||||
/// This prevents the layout having significant, avoidable gaps at the bottom.
|
||||
void _iterateUntilBalanced(
|
||||
List<Set<_TaggedHeightData>> columnObjects,
|
||||
List<double> columnHeights,
|
||||
) {
|
||||
int failedMoves = 0;
|
||||
final int columnCount = columnObjects.length;
|
||||
|
||||
// No need to rearrange a 1-column layout.
|
||||
if (columnCount == 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
while (true) {
|
||||
// Loop through all possible 2-combinations of columns.
|
||||
for (int source = 0; source < columnCount; ++source) {
|
||||
for (int target = source + 1; target < columnCount; ++target) {
|
||||
// Tries to find an object A from source column
|
||||
// and an object B from target column, such that switching them
|
||||
// causes the height of the two columns to be closer.
|
||||
|
||||
// A or B can be empty; in this case, moving an object from one
|
||||
// column to the other is the best choice.
|
||||
|
||||
bool success = false;
|
||||
|
||||
final double bestHeight =
|
||||
(columnHeights[source] + columnHeights[target]) / 2;
|
||||
final double scoreLimit = (columnHeights[source] - bestHeight).abs();
|
||||
|
||||
final List<_TaggedHeightData> sourceObjects =
|
||||
toListAndAddEmpty(columnObjects[source]);
|
||||
final List<_TaggedHeightData> targetObjects =
|
||||
toListAndAddEmpty(columnObjects[target]);
|
||||
|
||||
_TaggedHeightData bestA, bestB;
|
||||
double bestScore;
|
||||
|
||||
for (final a in sourceObjects) {
|
||||
for (final b in targetObjects) {
|
||||
if (a.index == _emptyElement && b.index == _emptyElement) {
|
||||
continue;
|
||||
} else {
|
||||
final double score =
|
||||
(columnHeights[source] - a.height + b.height - bestHeight)
|
||||
.abs();
|
||||
if (score < scoreLimit - _deviationImprovementThreshold) {
|
||||
success = true;
|
||||
if (bestScore == null || score < bestScore) {
|
||||
bestScore = score;
|
||||
bestA = a;
|
||||
bestB = b;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
++failedMoves;
|
||||
} else {
|
||||
failedMoves = 0;
|
||||
|
||||
// Switch A and B.
|
||||
if (bestA.index != _emptyElement) {
|
||||
columnObjects[source].remove(bestA);
|
||||
columnObjects[target].add(bestA);
|
||||
}
|
||||
if (bestB.index != _emptyElement) {
|
||||
columnObjects[target].remove(bestB);
|
||||
columnObjects[source].add(bestB);
|
||||
}
|
||||
columnHeights[source] += bestB.height - bestA.height;
|
||||
columnHeights[target] += bestA.height - bestB.height;
|
||||
}
|
||||
|
||||
// If no two columns' heights can be made closer by switching
|
||||
// elements, the layout is sufficiently balanced.
|
||||
if (failedMoves >= columnCount * (columnCount - 1) ~/ 2) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Given a list of numbers [data], representing the heights of each image,
|
||||
/// and a list of numbers [biases], representing the heights of the space
|
||||
/// above each column, [_balancedDistribution] returns a layout of [data]
|
||||
/// so that the height of each column is sufficiently close to each other,
|
||||
/// represented as a list of lists of integers, each integer being an ID
|
||||
/// for a product.
|
||||
List<List<int>> _balancedDistribution({
|
||||
int columnCount,
|
||||
List<double> data,
|
||||
List<double> biases,
|
||||
}) {
|
||||
assert(biases.length == columnCount);
|
||||
|
||||
List<Set<_TaggedHeightData>> columnObjects =
|
||||
List<Set<_TaggedHeightData>>.generate(columnCount, (column) => Set());
|
||||
|
||||
List<double> columnHeights = List<double>.from(biases);
|
||||
|
||||
for (var i = 0; i < data.length; ++i) {
|
||||
final int column = i % columnCount;
|
||||
columnHeights[column] += data[i];
|
||||
columnObjects[column].add(_TaggedHeightData(index: i, height: data[i]));
|
||||
}
|
||||
|
||||
_iterateUntilBalanced(columnObjects, columnHeights);
|
||||
|
||||
return [
|
||||
for (final column in columnObjects)
|
||||
[for (final object in column) object.index]..sort(),
|
||||
];
|
||||
}
|
||||
|
||||
/// Generates a balanced layout for [columnCount] columns,
|
||||
/// with products specified by the list [products],
|
||||
/// where the larger images have width [largeImageWidth]
|
||||
/// and the smaller images have width [smallImageWidth].
|
||||
/// The current [context] is also given to allow caching.
|
||||
List<List<Product>> balancedLayout({
|
||||
BuildContext context,
|
||||
int columnCount,
|
||||
List<Product> products,
|
||||
double largeImageWidth,
|
||||
double smallImageWidth,
|
||||
}) {
|
||||
final String encodedParameters = _encodeParameters(
|
||||
columnCount: columnCount,
|
||||
products: products,
|
||||
largeImageWidth: largeImageWidth,
|
||||
smallImageWidth: smallImageWidth,
|
||||
);
|
||||
|
||||
// Check if this layout is cached.
|
||||
|
||||
if (LayoutCache.of(context).containsKey(encodedParameters)) {
|
||||
return _generateLayout(
|
||||
products: products,
|
||||
layout: LayoutCache.of(context)[encodedParameters],
|
||||
);
|
||||
}
|
||||
|
||||
final List<Size> productSizes = [
|
||||
for (var product in products)
|
||||
_imageSize(
|
||||
Image.asset(
|
||||
product.assetName,
|
||||
package: product.assetPackage,
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
bool hasNullSize = false;
|
||||
for (final productSize in productSizes) {
|
||||
if (productSize == null) {
|
||||
hasNullSize = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasNullSize) {
|
||||
// If some image sizes are not read, return default layout.
|
||||
// Default layout is not cached.
|
||||
|
||||
List<List<Product>> result =
|
||||
List<List<Product>>.generate(columnCount, (columnIndex) => []);
|
||||
for (var index = 0; index < products.length; ++index) {
|
||||
result[index % columnCount].add(products[index]);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// All images have sizes. Use tailored layout.
|
||||
|
||||
final List<double> productHeights = [
|
||||
for (final productSize in productSizes)
|
||||
productSize.height /
|
||||
productSize.width *
|
||||
(largeImageWidth + smallImageWidth) /
|
||||
2 +
|
||||
productCardAdditionalHeight,
|
||||
];
|
||||
|
||||
final List<List<int>> layout = _balancedDistribution(
|
||||
columnCount: columnCount,
|
||||
data: productHeights,
|
||||
biases: List<double>.generate(
|
||||
columnCount,
|
||||
(column) => (column % 2 == 0 ? 0 : columnTopSpace),
|
||||
),
|
||||
);
|
||||
|
||||
// Add tailored layout to cache.
|
||||
|
||||
LayoutCache.of(context)[encodedParameters] = layout;
|
||||
|
||||
final List<List<Product>> result = _generateLayout(
|
||||
products: products,
|
||||
layout: layout,
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
129
gallery/lib/studies/shrine/supplemental/cut_corners_border.dart
Normal file
129
gallery/lib/studies/shrine/supplemental/cut_corners_border.dart
Normal file
@@ -0,0 +1,129 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:ui' show lerpDouble;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
class CutCornersBorder extends OutlineInputBorder {
|
||||
const CutCornersBorder({
|
||||
BorderSide borderSide = const BorderSide(),
|
||||
BorderRadius borderRadius = const BorderRadius.all(Radius.circular(2)),
|
||||
this.cut = 7,
|
||||
double gapPadding = 2,
|
||||
}) : super(
|
||||
borderSide: borderSide,
|
||||
borderRadius: borderRadius,
|
||||
gapPadding: gapPadding,
|
||||
);
|
||||
|
||||
@override
|
||||
CutCornersBorder copyWith({
|
||||
BorderSide borderSide,
|
||||
BorderRadius borderRadius,
|
||||
double gapPadding,
|
||||
double cut,
|
||||
}) {
|
||||
return CutCornersBorder(
|
||||
borderSide: borderSide ?? this.borderSide,
|
||||
borderRadius: borderRadius ?? this.borderRadius,
|
||||
gapPadding: gapPadding ?? this.gapPadding,
|
||||
cut: cut ?? this.cut,
|
||||
);
|
||||
}
|
||||
|
||||
final double cut;
|
||||
|
||||
@override
|
||||
ShapeBorder lerpFrom(ShapeBorder a, double t) {
|
||||
if (a is CutCornersBorder) {
|
||||
final CutCornersBorder outline = a;
|
||||
return CutCornersBorder(
|
||||
borderRadius: BorderRadius.lerp(outline.borderRadius, borderRadius, t),
|
||||
borderSide: BorderSide.lerp(outline.borderSide, borderSide, t),
|
||||
cut: cut,
|
||||
gapPadding: outline.gapPadding,
|
||||
);
|
||||
}
|
||||
return super.lerpFrom(a, t);
|
||||
}
|
||||
|
||||
@override
|
||||
ShapeBorder lerpTo(ShapeBorder b, double t) {
|
||||
if (b is CutCornersBorder) {
|
||||
final CutCornersBorder outline = b;
|
||||
return CutCornersBorder(
|
||||
borderRadius: BorderRadius.lerp(borderRadius, outline.borderRadius, t),
|
||||
borderSide: BorderSide.lerp(borderSide, outline.borderSide, t),
|
||||
cut: cut,
|
||||
gapPadding: outline.gapPadding,
|
||||
);
|
||||
}
|
||||
return super.lerpTo(b, t);
|
||||
}
|
||||
|
||||
Path _notchedCornerPath(Rect center, [double start = 0, double extent = 0]) {
|
||||
final Path path = Path();
|
||||
if (start > 0 || extent > 0) {
|
||||
path.relativeMoveTo(extent + start, center.top);
|
||||
_notchedSidesAndBottom(center, path);
|
||||
path..lineTo(center.left + cut, center.top)..lineTo(start, center.top);
|
||||
} else {
|
||||
path.moveTo(center.left + cut, center.top);
|
||||
_notchedSidesAndBottom(center, path);
|
||||
path.lineTo(center.left + cut, center.top);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
Path _notchedSidesAndBottom(Rect center, Path path) {
|
||||
return path
|
||||
..lineTo(center.right - cut, center.top)
|
||||
..lineTo(center.right, center.top + cut)
|
||||
..lineTo(center.right, center.top + center.height - cut)
|
||||
..lineTo(center.right - cut, center.top + center.height)
|
||||
..lineTo(center.left + cut, center.top + center.height)
|
||||
..lineTo(center.left, center.top + center.height - cut)
|
||||
..lineTo(center.left, center.top + cut);
|
||||
}
|
||||
|
||||
@override
|
||||
void paint(
|
||||
Canvas canvas,
|
||||
Rect rect, {
|
||||
double gapStart,
|
||||
double gapExtent = 0,
|
||||
double gapPercentage = 0,
|
||||
TextDirection textDirection,
|
||||
}) {
|
||||
assert(gapExtent != null);
|
||||
assert(gapPercentage >= 0 && gapPercentage <= 1);
|
||||
|
||||
final Paint paint = borderSide.toPaint();
|
||||
final RRect outer = borderRadius.toRRect(rect);
|
||||
if (gapStart == null || gapExtent <= 0 || gapPercentage == 0) {
|
||||
canvas.drawPath(_notchedCornerPath(outer.middleRect), paint);
|
||||
} else {
|
||||
final double extent =
|
||||
lerpDouble(0.0, gapExtent + gapPadding * 2, gapPercentage);
|
||||
switch (textDirection) {
|
||||
case TextDirection.rtl:
|
||||
{
|
||||
final Path path = _notchedCornerPath(
|
||||
outer.middleRect, gapStart + gapPadding - extent, extent);
|
||||
canvas.drawPath(path, paint);
|
||||
break;
|
||||
}
|
||||
case TextDirection.ltr:
|
||||
{
|
||||
final Path path = _notchedCornerPath(
|
||||
outer.middleRect, gapStart - gapPadding, extent);
|
||||
canvas.drawPath(path, paint);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/product_card.dart';
|
||||
|
||||
/// Height of the text below each product card.
|
||||
const productCardAdditionalHeight = 84.0 * 2;
|
||||
|
||||
/// Height of the divider between product cards.
|
||||
const productCardDividerHeight = 84.0;
|
||||
|
||||
/// Height of the space at the top of every other column.
|
||||
const columnTopSpace = 84.0;
|
||||
|
||||
class DesktopProductCardColumn extends StatelessWidget {
|
||||
const DesktopProductCardColumn({
|
||||
@required this.alignToEnd,
|
||||
@required this.startLarge,
|
||||
@required this.lowerStart,
|
||||
@required this.products,
|
||||
@required this.largeImageWidth,
|
||||
@required this.smallImageWidth,
|
||||
});
|
||||
|
||||
final List<Product> products;
|
||||
|
||||
final bool alignToEnd;
|
||||
final bool startLarge;
|
||||
final bool lowerStart;
|
||||
|
||||
final double largeImageWidth;
|
||||
final double smallImageWidth;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(builder: (context, constraints) {
|
||||
final int currentColumnProductCount = products.length;
|
||||
final int currentColumnWidgetCount =
|
||||
max(2 * currentColumnProductCount - 1, 0);
|
||||
|
||||
return Container(
|
||||
width: largeImageWidth,
|
||||
child: Column(
|
||||
crossAxisAlignment:
|
||||
alignToEnd ? CrossAxisAlignment.end : CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (lowerStart) Container(height: columnTopSpace),
|
||||
...List<Widget>.generate(currentColumnWidgetCount, (index) {
|
||||
Widget card;
|
||||
if (index % 2 == 0) {
|
||||
// This is a product.
|
||||
final int productCardIndex = index ~/ 2;
|
||||
card = DesktopProductCard(
|
||||
product: products[productCardIndex],
|
||||
imageWidth: startLarge
|
||||
? ((productCardIndex % 2 == 0)
|
||||
? largeImageWidth
|
||||
: smallImageWidth)
|
||||
: ((productCardIndex % 2 == 0)
|
||||
? smallImageWidth
|
||||
: largeImageWidth),
|
||||
);
|
||||
} else {
|
||||
// This is just a divider.
|
||||
card = Container(
|
||||
height: productCardDividerHeight,
|
||||
);
|
||||
}
|
||||
return RepaintBoundary(child: card);
|
||||
}),
|
||||
],
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
22
gallery/lib/studies/shrine/supplemental/layout_cache.dart
Normal file
22
gallery/lib/studies/shrine/supplemental/layout_cache.dart
Normal file
@@ -0,0 +1,22 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class LayoutCache extends InheritedWidget {
|
||||
const LayoutCache({
|
||||
Key key,
|
||||
@required this.layouts,
|
||||
@required Widget child,
|
||||
}) : super(key: key, child: child);
|
||||
|
||||
static Map<String, List<List<int>>> of(BuildContext context) {
|
||||
return context.dependOnInheritedWidgetOfExactType<LayoutCache>().layouts;
|
||||
}
|
||||
|
||||
final Map<String, List<List<int>>> layouts;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(LayoutCache old) => true;
|
||||
}
|
||||
134
gallery/lib/studies/shrine/supplemental/product_card.dart
Normal file
134
gallery/lib/studies/shrine/supplemental/product_card.dart
Normal file
@@ -0,0 +1,134 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import 'package:scoped_model/scoped_model.dart';
|
||||
|
||||
import 'package:gallery/studies/shrine/model/app_state_model.dart';
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
|
||||
class MobileProductCard extends StatelessWidget {
|
||||
const MobileProductCard({this.imageAspectRatio = 33 / 49, this.product})
|
||||
: assert(imageAspectRatio == null || imageAspectRatio > 0);
|
||||
|
||||
final double imageAspectRatio;
|
||||
final Product product;
|
||||
|
||||
static const double defaultTextBoxHeight = 65;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Semantics(
|
||||
container: true,
|
||||
button: true,
|
||||
child: _buildProductCard(
|
||||
context: context,
|
||||
product: product,
|
||||
imageAspectRatio: imageAspectRatio,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class DesktopProductCard extends StatelessWidget {
|
||||
const DesktopProductCard({@required this.product, @required this.imageWidth});
|
||||
|
||||
final Product product;
|
||||
final double imageWidth;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _buildProductCard(
|
||||
context: context,
|
||||
product: product,
|
||||
imageWidth: imageWidth,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildProductCard({
|
||||
BuildContext context,
|
||||
Product product,
|
||||
double imageWidth,
|
||||
double imageAspectRatio,
|
||||
}) {
|
||||
final bool isDesktop = isDisplayDesktop(context);
|
||||
|
||||
final NumberFormat formatter = NumberFormat.simpleCurrency(
|
||||
decimalDigits: 0,
|
||||
locale: Localizations.localeOf(context).toString(),
|
||||
);
|
||||
|
||||
final ThemeData theme = Theme.of(context);
|
||||
|
||||
final Image imageWidget = Image.asset(
|
||||
product.assetName,
|
||||
package: product.assetPackage,
|
||||
fit: BoxFit.cover,
|
||||
width: isDesktop ? imageWidth : null,
|
||||
excludeFromSemantics: true,
|
||||
);
|
||||
|
||||
return ScopedModelDescendant<AppStateModel>(
|
||||
builder: (context, child, model) {
|
||||
return Semantics(
|
||||
hint:
|
||||
GalleryLocalizations.of(context).shrineScreenReaderProductAddToCart,
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
model.addProductToCart(product.id);
|
||||
},
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
},
|
||||
child: Stack(
|
||||
children: [
|
||||
Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
isDesktop
|
||||
? imageWidget
|
||||
: AspectRatio(
|
||||
aspectRatio: imageAspectRatio,
|
||||
child: imageWidget,
|
||||
),
|
||||
SizedBox(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
const SizedBox(height: 23),
|
||||
Container(
|
||||
width: imageWidth,
|
||||
child: Text(
|
||||
product == null ? '' : product.name(context),
|
||||
style: theme.textTheme.button,
|
||||
softWrap: true,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
product == null ? '' : formatter.format(product.price),
|
||||
style: theme.textTheme.caption,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.all(16),
|
||||
child: Icon(Icons.add_shopping_cart),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
80
gallery/lib/studies/shrine/supplemental/product_columns.dart
Normal file
80
gallery/lib/studies/shrine/supplemental/product_columns.dart
Normal file
@@ -0,0 +1,80 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/studies/shrine/model/product.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/product_card.dart';
|
||||
|
||||
class TwoProductCardColumn extends StatelessWidget {
|
||||
const TwoProductCardColumn({
|
||||
@required this.bottom,
|
||||
this.top,
|
||||
@required this.imageAspectRatio,
|
||||
}) : assert(bottom != null);
|
||||
|
||||
static const double spacerHeight = 44;
|
||||
static const double horizontalPadding = 28;
|
||||
|
||||
final Product bottom, top;
|
||||
final double imageAspectRatio;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return LayoutBuilder(builder: (context, constraints) {
|
||||
return ListView(
|
||||
physics: const ClampingScrollPhysics(),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(start: horizontalPadding),
|
||||
child: top != null
|
||||
? MobileProductCard(
|
||||
imageAspectRatio: imageAspectRatio,
|
||||
product: top,
|
||||
)
|
||||
: SizedBox(
|
||||
height: spacerHeight,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: spacerHeight),
|
||||
Padding(
|
||||
padding: const EdgeInsetsDirectional.only(end: horizontalPadding),
|
||||
child: MobileProductCard(
|
||||
imageAspectRatio: imageAspectRatio,
|
||||
product: bottom,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class OneProductCardColumn extends StatelessWidget {
|
||||
const OneProductCardColumn({
|
||||
this.product,
|
||||
@required this.reverse,
|
||||
});
|
||||
|
||||
final Product product;
|
||||
|
||||
// Whether the product column should align to the bottom.
|
||||
final bool reverse;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ListView(
|
||||
physics: const ClampingScrollPhysics(),
|
||||
reverse: reverse,
|
||||
children: [
|
||||
const SizedBox(
|
||||
height: 40,
|
||||
),
|
||||
MobileProductCard(
|
||||
product: product,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
105
gallery/lib/studies/shrine/theme.dart
Normal file
105
gallery/lib/studies/shrine/theme.dart
Normal file
@@ -0,0 +1,105 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:google_fonts/google_fonts.dart';
|
||||
import 'package:gallery/studies/shrine/colors.dart';
|
||||
import 'package:gallery/studies/shrine/supplemental/cut_corners_border.dart';
|
||||
|
||||
const defaultLetterSpacing = 0.03;
|
||||
const mediumLetterSpacing = 0.04;
|
||||
const largeLetterSpacing = 1.0;
|
||||
|
||||
final ThemeData shrineTheme = _buildShrineTheme();
|
||||
|
||||
IconThemeData _customIconTheme(IconThemeData original) {
|
||||
return original.copyWith(color: shrineBrown900);
|
||||
}
|
||||
|
||||
ThemeData _buildShrineTheme() {
|
||||
final ThemeData base = ThemeData.light();
|
||||
return base.copyWith(
|
||||
colorScheme: _shrineColorScheme,
|
||||
accentColor: shrineBrown900,
|
||||
primaryColor: shrinePink100,
|
||||
buttonColor: shrinePink100,
|
||||
scaffoldBackgroundColor: shrineBackgroundWhite,
|
||||
cardColor: shrineBackgroundWhite,
|
||||
textSelectionColor: shrinePink100,
|
||||
errorColor: shrineErrorRed,
|
||||
buttonTheme: const ButtonThemeData(
|
||||
colorScheme: _shrineColorScheme,
|
||||
textTheme: ButtonTextTheme.normal,
|
||||
),
|
||||
primaryIconTheme: _customIconTheme(base.iconTheme),
|
||||
inputDecorationTheme: const InputDecorationTheme(
|
||||
border: CutCornersBorder(
|
||||
borderSide: BorderSide(color: shrineBrown900, width: 0.5),
|
||||
),
|
||||
contentPadding: EdgeInsets.symmetric(vertical: 20, horizontal: 16),
|
||||
),
|
||||
textTheme: _buildShrineTextTheme(base.textTheme),
|
||||
primaryTextTheme: _buildShrineTextTheme(base.primaryTextTheme),
|
||||
accentTextTheme: _buildShrineTextTheme(base.accentTextTheme),
|
||||
iconTheme: _customIconTheme(base.iconTheme),
|
||||
);
|
||||
}
|
||||
|
||||
TextTheme _buildShrineTextTheme(TextTheme base) {
|
||||
return GoogleFonts.rubikTextTheme(base
|
||||
.copyWith(
|
||||
headline: base.headline.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
letterSpacing: defaultLetterSpacing,
|
||||
),
|
||||
title: base.title.copyWith(
|
||||
fontSize: 18,
|
||||
letterSpacing: defaultLetterSpacing,
|
||||
),
|
||||
caption: base.caption.copyWith(
|
||||
fontWeight: FontWeight.w400,
|
||||
fontSize: 14,
|
||||
letterSpacing: defaultLetterSpacing,
|
||||
),
|
||||
body2: base.body2.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 16,
|
||||
letterSpacing: defaultLetterSpacing,
|
||||
),
|
||||
body1: base.body1.copyWith(
|
||||
letterSpacing: defaultLetterSpacing,
|
||||
),
|
||||
subhead: base.subhead.copyWith(
|
||||
letterSpacing: defaultLetterSpacing,
|
||||
),
|
||||
display1: base.display1.copyWith(
|
||||
letterSpacing: defaultLetterSpacing,
|
||||
),
|
||||
button: base.button.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
fontSize: 14,
|
||||
letterSpacing: defaultLetterSpacing,
|
||||
),
|
||||
)
|
||||
.apply(
|
||||
displayColor: shrineBrown900,
|
||||
bodyColor: shrineBrown900,
|
||||
));
|
||||
}
|
||||
|
||||
const ColorScheme _shrineColorScheme = ColorScheme(
|
||||
primary: shrinePink100,
|
||||
primaryVariant: shrineBrown900,
|
||||
secondary: shrinePink50,
|
||||
secondaryVariant: shrineBrown900,
|
||||
surface: shrineSurfaceWhite,
|
||||
background: shrineBackgroundWhite,
|
||||
error: shrineErrorRed,
|
||||
onPrimary: shrineBrown900,
|
||||
onSecondary: shrineBrown900,
|
||||
onSurface: shrineBrown900,
|
||||
onBackground: shrineBrown900,
|
||||
onError: shrineSurfaceWhite,
|
||||
brightness: Brightness.light,
|
||||
);
|
||||
50
gallery/lib/studies/shrine/triangle_category_indicator.dart
Normal file
50
gallery/lib/studies/shrine/triangle_category_indicator.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:gallery/studies/shrine/colors.dart';
|
||||
|
||||
const List<Offset> _vertices = [
|
||||
Offset(0, -14),
|
||||
Offset(-17, 14),
|
||||
Offset(17, 14),
|
||||
Offset(0, -14),
|
||||
Offset(0, -7.37),
|
||||
Offset(10.855, 10.48),
|
||||
Offset(-10.855, 10.48),
|
||||
Offset(0, -7.37),
|
||||
];
|
||||
|
||||
class TriangleCategoryIndicator extends CustomPainter {
|
||||
const TriangleCategoryIndicator(
|
||||
this.triangleWidth,
|
||||
this.triangleHeight,
|
||||
) : assert(triangleWidth != null),
|
||||
assert(triangleHeight != null);
|
||||
|
||||
final double triangleWidth;
|
||||
final double triangleHeight;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
Path myPath = Path()
|
||||
..addPolygon(
|
||||
List.from(_vertices.map<Offset>((vertex) {
|
||||
return Offset(size.width, size.height) / 2 +
|
||||
Offset(vertex.dx * triangleWidth / 34,
|
||||
vertex.dy * triangleHeight / 28);
|
||||
})),
|
||||
true,
|
||||
);
|
||||
Paint myPaint = Paint()..color = shrinePink400;
|
||||
canvas.drawPath(myPath, myPaint);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(TriangleCategoryIndicator oldDelegate) => false;
|
||||
|
||||
@override
|
||||
bool shouldRebuildSemantics(TriangleCategoryIndicator oldDelegate) => false;
|
||||
}
|
||||
93
gallery/lib/studies/starter/app.dart
Normal file
93
gallery/lib/studies/starter/app.dart
Normal file
@@ -0,0 +1,93 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:gallery/data/gallery_options.dart';
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/focus_traversal_policy.dart';
|
||||
import 'package:gallery/pages/home.dart' as home;
|
||||
import 'package:gallery/studies/starter/home.dart';
|
||||
|
||||
const _primaryColor = Color(0xFF6200EE);
|
||||
|
||||
class StarterApp extends StatefulWidget {
|
||||
const StarterApp({Key key, this.navigatorKey}) : super(key: key);
|
||||
|
||||
final GlobalKey<NavigatorState> navigatorKey;
|
||||
|
||||
@override
|
||||
_StarterAppState createState() => _StarterAppState();
|
||||
}
|
||||
|
||||
class _StarterAppState extends State<StarterApp> {
|
||||
FocusNode firstFocusNode;
|
||||
FocusNode lastFocusNode;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
firstFocusNode = FocusNode();
|
||||
lastFocusNode = FocusNode();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
firstFocusNode.dispose();
|
||||
lastFocusNode.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final backButtonFocusNode =
|
||||
home.InheritedFocusNodes.of(context).backButtonFocusNode;
|
||||
|
||||
return MaterialApp(
|
||||
navigatorKey: widget.navigatorKey,
|
||||
title: GalleryLocalizations.of(context).starterAppTitle,
|
||||
debugShowCheckedModeBanner: false,
|
||||
localizationsDelegates: GalleryLocalizations.localizationsDelegates,
|
||||
supportedLocales: GalleryLocalizations.supportedLocales,
|
||||
locale: GalleryOptions.of(context).locale,
|
||||
home: DefaultFocusTraversal(
|
||||
policy: EdgeChildrenFocusTraversalPolicy(
|
||||
firstFocusNodeOutsideScope: backButtonFocusNode,
|
||||
lastFocusNodeOutsideScope: backButtonFocusNode,
|
||||
firstFocusNodeInsideScope: firstFocusNode,
|
||||
lastFocusNodeInsideScope: lastFocusNode,
|
||||
),
|
||||
child: ApplyTextOptions(
|
||||
child: HomePage(
|
||||
firstFocusNode: firstFocusNode,
|
||||
lastFocusNode: lastFocusNode,
|
||||
),
|
||||
),
|
||||
),
|
||||
theme: ThemeData(
|
||||
primaryColor: _primaryColor,
|
||||
highlightColor: Colors.transparent,
|
||||
colorScheme: ColorScheme(
|
||||
primary: _primaryColor,
|
||||
primaryVariant: const Color(0xFF3700B3),
|
||||
secondary: const Color(0xFF03DAC6),
|
||||
secondaryVariant: const Color(0xFF018786),
|
||||
background: Colors.white,
|
||||
surface: Colors.white,
|
||||
onBackground: Colors.black,
|
||||
error: const Color(0xFFB00020),
|
||||
onError: Colors.white,
|
||||
onPrimary: Colors.white,
|
||||
onSecondary: Colors.black,
|
||||
onSurface: Colors.black,
|
||||
brightness: Brightness.light,
|
||||
),
|
||||
dividerTheme: DividerThemeData(
|
||||
thickness: 1,
|
||||
color: const Color(0xFFE5E5E5),
|
||||
),
|
||||
platform: GalleryOptions.of(context).platform,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
225
gallery/lib/studies/starter/home.dart
Normal file
225
gallery/lib/studies/starter/home.dart
Normal file
@@ -0,0 +1,225 @@
|
||||
// Copyright 2019 The Flutter team. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import 'package:gallery/l10n/gallery_localizations.dart';
|
||||
import 'package:gallery/layout/adaptive.dart';
|
||||
|
||||
const appBarDesktopHeight = 128.0;
|
||||
|
||||
class HomePage extends StatelessWidget {
|
||||
const HomePage({
|
||||
Key key,
|
||||
this.firstFocusNode,
|
||||
this.lastFocusNode,
|
||||
}) : super(key: key);
|
||||
|
||||
final FocusNode firstFocusNode;
|
||||
final FocusNode lastFocusNode;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final isDesktop = isDisplayDesktop(context);
|
||||
final body = SafeArea(
|
||||
child: Padding(
|
||||
padding: isDesktop
|
||||
? EdgeInsets.symmetric(horizontal: 72, vertical: 48)
|
||||
: EdgeInsets.symmetric(horizontal: 16, vertical: 24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
GalleryLocalizations.of(context).starterAppGenericHeadline,
|
||||
style: textTheme.display2.copyWith(
|
||||
color: colorScheme.onSecondary,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 10),
|
||||
Text(
|
||||
GalleryLocalizations.of(context).starterAppGenericSubtitle,
|
||||
style: textTheme.subhead,
|
||||
),
|
||||
SizedBox(height: 48),
|
||||
Text(
|
||||
GalleryLocalizations.of(context).starterAppGenericBody,
|
||||
style: textTheme.body2,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (isDesktop) {
|
||||
return Row(
|
||||
children: [
|
||||
ListDrawer(
|
||||
lastFocusNode: lastFocusNode,
|
||||
),
|
||||
VerticalDivider(width: 1),
|
||||
Expanded(
|
||||
child: Scaffold(
|
||||
appBar: AdaptiveAppBar(
|
||||
firstFocusNode: firstFocusNode,
|
||||
isDesktop: true,
|
||||
),
|
||||
body: body,
|
||||
floatingActionButton: FloatingActionButton.extended(
|
||||
onPressed: () {},
|
||||
label: Text(
|
||||
GalleryLocalizations.of(context).starterAppGenericButton,
|
||||
style: TextStyle(color: colorScheme.onSecondary),
|
||||
),
|
||||
icon: Icon(Icons.add, color: colorScheme.onSecondary),
|
||||
tooltip: GalleryLocalizations.of(context).starterAppTooltipAdd,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
} else {
|
||||
return Scaffold(
|
||||
appBar: AdaptiveAppBar(
|
||||
firstFocusNode: firstFocusNode,
|
||||
),
|
||||
body: body,
|
||||
drawer: ListDrawer(),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
onPressed: () {},
|
||||
tooltip: GalleryLocalizations.of(context).starterAppTooltipAdd,
|
||||
child: Icon(
|
||||
Icons.add,
|
||||
color: Theme.of(context).colorScheme.onSecondary,
|
||||
),
|
||||
focusNode: lastFocusNode,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class AdaptiveAppBar extends StatelessWidget implements PreferredSizeWidget {
|
||||
const AdaptiveAppBar({
|
||||
Key key,
|
||||
this.isDesktop = false,
|
||||
this.firstFocusNode,
|
||||
}) : super(key: key);
|
||||
|
||||
final bool isDesktop;
|
||||
final FocusNode firstFocusNode;
|
||||
|
||||
@override
|
||||
Size get preferredSize => isDesktop
|
||||
? const Size.fromHeight(appBarDesktopHeight)
|
||||
: const Size.fromHeight(kToolbarHeight);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final themeData = Theme.of(context);
|
||||
return AppBar(
|
||||
title: isDesktop
|
||||
? null
|
||||
: Text(GalleryLocalizations.of(context).starterAppGenericTitle),
|
||||
bottom: isDesktop
|
||||
? PreferredSize(
|
||||
preferredSize: const Size.fromHeight(26),
|
||||
child: Container(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
margin: EdgeInsetsDirectional.fromSTEB(72, 0, 0, 22),
|
||||
child: Text(
|
||||
GalleryLocalizations.of(context).starterAppGenericTitle,
|
||||
style: themeData.textTheme.title.copyWith(
|
||||
color: themeData.colorScheme.onPrimary,
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: null,
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.share),
|
||||
tooltip: GalleryLocalizations.of(context).starterAppTooltipShare,
|
||||
onPressed: () {},
|
||||
focusNode: firstFocusNode,
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.favorite),
|
||||
tooltip: GalleryLocalizations.of(context).starterAppTooltipFavorite,
|
||||
onPressed: () {},
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.search),
|
||||
tooltip: GalleryLocalizations.of(context).starterAppTooltipSearch,
|
||||
onPressed: () {},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ListDrawer extends StatefulWidget {
|
||||
const ListDrawer({Key key, this.lastFocusNode}) : super(key: key);
|
||||
|
||||
final FocusNode lastFocusNode;
|
||||
|
||||
@override
|
||||
_ListDrawerState createState() => _ListDrawerState();
|
||||
}
|
||||
|
||||
class _ListDrawerState extends State<ListDrawer> {
|
||||
static final numItems = 9;
|
||||
|
||||
int selectedItem = 0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final textTheme = Theme.of(context).textTheme;
|
||||
return Drawer(
|
||||
child: SafeArea(
|
||||
child: ListView(
|
||||
children: [
|
||||
ListTile(
|
||||
title: Text(
|
||||
GalleryLocalizations.of(context).starterAppTitle,
|
||||
style: textTheme.title,
|
||||
),
|
||||
subtitle: Text(
|
||||
GalleryLocalizations.of(context).starterAppGenericSubtitle,
|
||||
style: textTheme.body1,
|
||||
),
|
||||
),
|
||||
Divider(),
|
||||
...Iterable<int>.generate(numItems).toList().map((i) {
|
||||
final listTile = ListTile(
|
||||
enabled: true,
|
||||
selected: i == selectedItem,
|
||||
leading: Icon(Icons.favorite),
|
||||
title: Text(
|
||||
GalleryLocalizations.of(context).starterAppDrawerItem(i + 1),
|
||||
),
|
||||
onTap: () {
|
||||
setState(() {
|
||||
selectedItem = i;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
if (i == numItems - 1 && widget.lastFocusNode != null) {
|
||||
return Focus(
|
||||
focusNode: widget.lastFocusNode,
|
||||
child: listTile,
|
||||
);
|
||||
} else {
|
||||
return listTile;
|
||||
}
|
||||
}),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user