1
0
mirror of https://github.com/flutter/samples.git synced 2026-05-28 09:59:29 +00:00

[Gallery] Fix directory structure (#312)

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

View File

@@ -0,0 +1,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),
);
}
}

View 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);
}

View 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),
),
],
),
);
});
}
}