Repackage manual_tests with the current project template (#10057)

See https://github.com/flutter/flutter/pull/10000
This commit is contained in:
Jason Simmons
2017-05-15 10:40:03 -07:00
committed by GitHub
parent ceab6f9784
commit 457b8c05df
37 changed files with 991 additions and 23 deletions

View File

@@ -0,0 +1,382 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart' show debugDumpRenderTree;
class CardModel {
CardModel(this.value, this.height) {
textController = new TextEditingController(text: 'Item $value');
}
int value;
double height;
int get color => ((value % 9) + 1) * 100;
TextEditingController textController;
Key get key => new ObjectKey(this);
}
class CardCollection extends StatefulWidget {
@override
CardCollectionState createState() => new CardCollectionState();
}
class CardCollectionState extends State<CardCollection> {
static const TextStyle cardLabelStyle =
const TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
// TODO(hansmuller): need a local image asset
static const String _sunshineURL = "http://www.walltor.com/images/wallpaper/good-morning-sunshine-58540.jpg";
static const double kCardMargins = 8.0;
static const double kFixedCardHeight = 100.0;
MaterialColor _primaryColor = Colors.deepPurple;
List<CardModel> _cardModels;
DismissDirection _dismissDirection = DismissDirection.horizontal;
TextAlign _textAlign = TextAlign.center;
bool _editable = false;
bool _fixedSizeCards = false;
bool _sunshine = false;
bool _varyFontSizes = false;
void _initVariableSizedCardModels() {
final List<double> cardHeights = <double>[
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
];
_cardModels = new List<CardModel>.generate(
cardHeights.length,
(int i) => new CardModel(i, cardHeights[i])
);
}
void _initFixedSizedCardModels() {
const int cardCount = 27;
_cardModels = new List<CardModel>.generate(
cardCount,
(int i) => new CardModel(i, kFixedCardHeight),
);
}
void _initCardModels() {
if (_fixedSizeCards)
_initFixedSizedCardModels();
else
_initVariableSizedCardModels();
}
@override
void initState() {
super.initState();
_initCardModels();
}
void dismissCard(CardModel card) {
if (_cardModels.contains(card)) {
setState(() {
_cardModels.remove(card);
});
}
}
Widget _buildDrawer() {
return new Drawer(
child: new IconTheme(
data: const IconThemeData(color: Colors.black),
child: new ListView(
children: <Widget>[
const DrawerHeader(child: const Center(child: const Text('Options'))),
buildDrawerCheckbox("Make card labels editable", _editable, _toggleEditable),
buildDrawerCheckbox("Fixed size cards", _fixedSizeCards, _toggleFixedSizeCards),
buildDrawerCheckbox("Let the sun shine", _sunshine, _toggleSunshine),
buildDrawerCheckbox("Vary font sizes", _varyFontSizes, _toggleVaryFontSizes, enabled: !_editable),
const Divider(),
buildDrawerColorRadioItem("Deep Purple", Colors.deepPurple, _primaryColor, _selectColor),
buildDrawerColorRadioItem("Green", Colors.green, _primaryColor, _selectColor),
buildDrawerColorRadioItem("Amber", Colors.amber, _primaryColor, _selectColor),
buildDrawerColorRadioItem("Teal", Colors.teal, _primaryColor, _selectColor),
const Divider(),
buildDrawerDirectionRadioItem("Dismiss horizontally", DismissDirection.horizontal, _dismissDirection, _changeDismissDirection, icon: Icons.code),
buildDrawerDirectionRadioItem("Dismiss left", DismissDirection.endToStart, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_back),
buildDrawerDirectionRadioItem("Dismiss right", DismissDirection.startToEnd, _dismissDirection, _changeDismissDirection, icon: Icons.arrow_forward),
const Divider(),
buildFontRadioItem("Left-align text", TextAlign.left, _textAlign, _changeTextAlign, icon: Icons.format_align_left, enabled: !_editable),
buildFontRadioItem("Center-align text", TextAlign.center, _textAlign, _changeTextAlign, icon: Icons.format_align_center, enabled: !_editable),
buildFontRadioItem("Right-align text", TextAlign.right, _textAlign, _changeTextAlign, icon: Icons.format_align_right, enabled: !_editable),
const Divider(),
new ListTile(
leading: const Icon(Icons.dvr),
onTap: () { debugDumpApp(); debugDumpRenderTree(); },
title: const Text('Dump App to Console'),
),
],
),
),
);
}
String _dismissDirectionText(DismissDirection direction) {
final String s = direction.toString();
return "dismiss ${s.substring(s.indexOf('.') + 1)}";
}
void _toggleEditable() {
setState(() {
_editable = !_editable;
});
}
void _toggleFixedSizeCards() {
setState(() {
_fixedSizeCards = !_fixedSizeCards;
_initCardModels();
});
}
void _toggleSunshine() {
setState(() {
_sunshine = !_sunshine;
});
}
void _toggleVaryFontSizes() {
setState(() {
_varyFontSizes = !_varyFontSizes;
});
}
void _selectColor(MaterialColor selection) {
setState(() {
_primaryColor = selection;
});
}
void _changeDismissDirection(DismissDirection newDismissDirection) {
setState(() {
_dismissDirection = newDismissDirection;
});
}
void _changeTextAlign(TextAlign newTextAlign) {
setState(() {
_textAlign = newTextAlign;
});
}
Widget buildDrawerCheckbox(String label, bool value, void callback(), { bool enabled: true }) {
return new ListTile(
onTap: enabled ? callback : null,
title: new Text(label),
trailing: new Checkbox(
value: value,
onChanged: enabled ? (_) { callback(); } : null,
),
);
}
Widget buildDrawerColorRadioItem(String label, MaterialColor itemValue, MaterialColor currentValue, ValueChanged<MaterialColor> onChanged, { IconData icon, bool enabled: true }) {
return new ListTile(
leading: new Icon(icon),
title: new Text(label),
onTap: enabled ? () { onChanged(itemValue); } : null,
trailing: new Radio<MaterialColor>(
value: itemValue,
groupValue: currentValue,
onChanged: enabled ? onChanged : null,
),
);
}
Widget buildDrawerDirectionRadioItem(String label, DismissDirection itemValue, DismissDirection currentValue, ValueChanged<DismissDirection> onChanged, { IconData icon, bool enabled: true }) {
return new ListTile(
leading: new Icon(icon),
title: new Text(label),
onTap: enabled ? () { onChanged(itemValue); } : null,
trailing: new Radio<DismissDirection>(
value: itemValue,
groupValue: currentValue,
onChanged: enabled ? onChanged : null,
),
);
}
Widget buildFontRadioItem(String label, TextAlign itemValue, TextAlign currentValue, ValueChanged<TextAlign> onChanged, { IconData icon, bool enabled: true }) {
return new ListTile(
leading: new Icon(icon),
title: new Text(label),
onTap: enabled ? () { onChanged(itemValue); } : null,
trailing: new Radio<TextAlign>(
value: itemValue,
groupValue: currentValue,
onChanged: enabled ? onChanged : null,
),
);
}
Widget _buildAppBar(BuildContext context) {
return new AppBar(
actions: <Widget>[
new Text(_dismissDirectionText(_dismissDirection))
],
flexibleSpace: new Container(
padding: const EdgeInsets.only(left: 72.0),
height: 128.0,
alignment: const FractionalOffset(0.0, 0.75),
child: new Text('Swipe Away: ${_cardModels.length}', style: Theme.of(context).primaryTextTheme.title),
),
);
}
Widget _buildCard(BuildContext context, int index) {
final CardModel cardModel = _cardModels[index];
final Widget card = new Dismissible(
key: new ObjectKey(cardModel),
direction: _dismissDirection,
onDismissed: (DismissDirection direction) { dismissCard(cardModel); },
child: new Card(
color: _primaryColor[cardModel.color],
child: new Container(
height: cardModel.height,
padding: const EdgeInsets.all(kCardMargins),
child: _editable ?
new Center(
child: new TextField(
key: new GlobalObjectKey(cardModel),
controller: cardModel.textController,
),
)
: DefaultTextStyle.merge(
style: cardLabelStyle.copyWith(
fontSize: _varyFontSizes ? 5.0 + index : null
),
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(cardModel.textController.text, textAlign: _textAlign),
],
),
),
),
),
);
String backgroundMessage;
switch(_dismissDirection) {
case DismissDirection.horizontal:
backgroundMessage = "Swipe in either direction";
break;
case DismissDirection.endToStart:
backgroundMessage = "Swipe left to dismiss";
break;
case DismissDirection.startToEnd:
backgroundMessage = "Swipe right to dismiss";
break;
default:
backgroundMessage = "Unsupported dismissDirection";
}
// TODO(abarth): This icon is wrong in RTL.
Widget leftArrowIcon = const Icon(Icons.arrow_back, size: 36.0);
if (_dismissDirection == DismissDirection.startToEnd)
leftArrowIcon = new Opacity(opacity: 0.1, child: leftArrowIcon);
// TODO(abarth): This icon is wrong in RTL.
Widget rightArrowIcon = const Icon(Icons.arrow_forward, size: 36.0);
if (_dismissDirection == DismissDirection.endToStart)
rightArrowIcon = new Opacity(opacity: 0.1, child: rightArrowIcon);
final ThemeData theme = Theme.of(context);
final TextStyle backgroundTextStyle = theme.primaryTextTheme.title;
// The background Widget appears behind the Dismissible card when the card
// moves to the left or right. The Positioned widget ensures that the
// size of the background,card Stack will be based only on the card. The
// Viewport ensures that when the card's resize animation occurs, the
// background (text and icons) will just be clipped, not resized.
final Widget background = new Positioned.fill(
child: new Container(
margin: const EdgeInsets.all(4.0),
child: new SingleChildScrollView(
child: new Container(
height: cardModel.height,
color: theme.primaryColor,
child: new Row(
children: <Widget>[
leftArrowIcon,
new Expanded(
child: new Text(backgroundMessage,
style: backgroundTextStyle,
textAlign: TextAlign.center,
),
),
rightArrowIcon,
],
),
),
),
),
);
return new IconTheme(
key: cardModel.key,
data: const IconThemeData(color: Colors.white),
child: new Stack(children: <Widget>[background, card]),
);
}
Shader _createShader(Rect bounds) {
return new LinearGradient(
begin: FractionalOffset.topLeft,
end: FractionalOffset.bottomLeft,
colors: <Color>[const Color(0x00FFFFFF), const Color(0xFFFFFFFF)],
stops: <double>[0.1, 0.35],
)
.createShader(bounds);
}
@override
Widget build(BuildContext context) {
Widget cardCollection = new ListView.builder(
itemExtent: _fixedSizeCards ? kFixedCardHeight : null,
itemCount: _cardModels.length,
itemBuilder: _buildCard,
);
if (_sunshine) {
cardCollection = new Stack(
children: <Widget>[
new Column(children: <Widget>[new Image.network(_sunshineURL)]),
new ShaderMask(child: cardCollection, shaderCallback: _createShader),
],
);
}
final Widget body = new Container(
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
color: _primaryColor.shade50,
child: cardCollection,
);
return new Theme(
data: new ThemeData(
primarySwatch: _primaryColor,
),
child: new Scaffold(
appBar: _buildAppBar(context),
drawer: _buildDrawer(),
body: body,
),
);
}
}
void main() {
runApp(new MaterialApp(
title: 'Cards',
home: new CardCollection(),
));
}

View File

@@ -0,0 +1,302 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/material.dart';
class ExampleDragTarget extends StatefulWidget {
@override
ExampleDragTargetState createState() => new ExampleDragTargetState();
}
class ExampleDragTargetState extends State<ExampleDragTarget> {
Color _color = Colors.grey;
void _handleAccept(Color data) {
setState(() {
_color = data;
});
}
@override
Widget build(BuildContext context) {
return new DragTarget<Color>(
onAccept: _handleAccept,
builder: (BuildContext context, List<Color> data, List<dynamic> rejectedData) {
return new Container(
height: 100.0,
margin: const EdgeInsets.all(10.0),
decoration: new BoxDecoration(
color: data.isEmpty ? _color : Colors.grey.shade200,
border: new Border.all(
width: 3.0,
color: data.isEmpty ? Colors.white : Colors.blue
),
)
);
}
);
}
}
class Dot extends StatefulWidget {
const Dot({ Key key, this.color, this.size, this.child, this.tappable: false }) : super(key: key);
final Color color;
final double size;
final Widget child;
final bool tappable;
@override
DotState createState() => new DotState();
}
class DotState extends State<Dot> {
int taps = 0;
@override
Widget build(BuildContext context) {
return new GestureDetector(
onTap: widget.tappable ? () { setState(() { taps += 1; }); } : null,
child: new Container(
width: widget.size,
height: widget.size,
decoration: new BoxDecoration(
color: widget.color,
border: new Border.all(width: taps.toDouble()),
shape: BoxShape.circle
),
child: widget.child
)
);
}
}
class ExampleDragSource extends StatelessWidget {
const ExampleDragSource({
Key key,
this.color,
this.heavy: false,
this.under: true,
this.child
}) : super(key: key);
final Color color;
final bool heavy;
final bool under;
final Widget child;
static const double kDotSize = 50.0;
static const double kHeavyMultiplier = 1.5;
static const double kFingerSize = 50.0;
@override
Widget build(BuildContext context) {
double size = kDotSize;
if (heavy)
size *= kHeavyMultiplier;
final Widget contents = new DefaultTextStyle(
style: Theme.of(context).textTheme.body1,
textAlign: TextAlign.center,
child: new Dot(
color: color,
size: size,
child: new Center(child: child)
)
);
Widget feedback = new Opacity(
opacity: 0.75,
child: contents
);
Offset feedbackOffset;
DragAnchor anchor;
if (!under) {
feedback = new Transform(
transform: new Matrix4.identity()
..translate(-size / 2.0, -(size / 2.0 + kFingerSize)),
child: feedback
);
feedbackOffset = const Offset(0.0, -kFingerSize);
anchor = DragAnchor.pointer;
} else {
feedbackOffset = Offset.zero;
anchor = DragAnchor.child;
}
if (heavy) {
return new LongPressDraggable<Color>(
data: color,
child: contents,
feedback: feedback,
feedbackOffset: feedbackOffset,
dragAnchor: anchor
);
} else {
return new Draggable<Color>(
data: color,
child: contents,
feedback: feedback,
feedbackOffset: feedbackOffset,
dragAnchor: anchor
);
}
}
}
class DashOutlineCirclePainter extends CustomPainter {
const DashOutlineCirclePainter();
static const int segments = 17;
static const double deltaTheta = math.PI * 2 / segments; // radians
static const double segmentArc = deltaTheta / 2.0; // radians
static const double startOffset = 1.0; // radians
@override
void paint(Canvas canvas, Size size) {
final double radius = size.shortestSide / 2.0;
final Paint paint = new Paint()
..color = const Color(0xFF000000)
..style = PaintingStyle.stroke
..strokeWidth = radius / 10.0;
final Path path = new Path();
final Rect box = Offset.zero & size;
for (double theta = 0.0; theta < math.PI * 2.0; theta += deltaTheta)
path.addArc(box, theta + startOffset, segmentArc);
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(DashOutlineCirclePainter oldPainter) => false;
}
class MovableBall extends StatelessWidget {
const MovableBall(this.position, this.ballPosition, this.callback);
final int position;
final int ballPosition;
final ValueChanged<int> callback;
static final GlobalKey kBallKey = new GlobalKey();
static const double kBallSize = 50.0;
@override
Widget build(BuildContext context) {
final Widget ball = new DefaultTextStyle(
style: Theme.of(context).primaryTextTheme.body1,
textAlign: TextAlign.center,
child: new Dot(
key: kBallKey,
color: Colors.blue.shade700,
size: kBallSize,
tappable: true,
child: const Center(child: const Text('BALL'))
)
);
final Widget dashedBall = new Container(
width: kBallSize,
height: kBallSize,
child: const CustomPaint(
painter: const DashOutlineCirclePainter()
)
);
if (position == ballPosition) {
return new Draggable<bool>(
data: true,
child: ball,
childWhenDragging: dashedBall,
feedback: ball,
maxSimultaneousDrags: 1
);
} else {
return new DragTarget<bool>(
onAccept: (bool data) { callback(position); },
builder: (BuildContext context, List<bool> accepted, List<dynamic> rejected) {
return dashedBall;
}
);
}
}
}
class DragAndDropApp extends StatefulWidget {
@override
DragAndDropAppState createState() => new DragAndDropAppState();
}
class DragAndDropAppState extends State<DragAndDropApp> {
int position = 1;
void moveBall(int newPosition) {
setState(() { position = newPosition; });
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: const Text('Drag and Drop Flutter Demo')
),
body: new Column(
children: <Widget>[
new Expanded(
child: new Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
new ExampleDragSource(
color: Colors.yellow.shade300,
under: true,
heavy: false,
child: const Text('under')
),
new ExampleDragSource(
color: Colors.green.shade300,
under: false,
heavy: true,
child: const Text('long-press above')
),
new ExampleDragSource(
color: Colors.indigo.shade300,
under: false,
heavy: false,
child: const Text('above')
),
],
)
),
new Expanded(
child: new Row(
children: <Widget>[
new Expanded(child: new ExampleDragTarget()),
new Expanded(child: new ExampleDragTarget()),
new Expanded(child: new ExampleDragTarget()),
new Expanded(child: new ExampleDragTarget()),
]
)
),
new Expanded(
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
new MovableBall(1, position, moveBall),
new MovableBall(2, position, moveBall),
new MovableBall(3, position, moveBall),
],
)
),
]
)
);
}
}
void main() {
runApp(new MaterialApp(
title: 'Drag and Drop Flutter Demo',
home: new DragAndDropApp()
));
}

View File

@@ -0,0 +1,474 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
enum _DragTarget {
start,
end
}
// How close a drag's start position must be to the target point. This is
// a distance squared.
const double _kTargetSlop = 2500.0;
// Used by the Painter classes.
const double _kPointRadius = 6.0;
class _DragHandler extends Drag {
_DragHandler(this.onUpdate, this.onCancel, this.onEnd);
final GestureDragUpdateCallback onUpdate;
final GestureDragCancelCallback onCancel;
final GestureDragEndCallback onEnd;
@override
void update(DragUpdateDetails details) {
onUpdate(details);
}
@override
void cancel() {
onCancel();
}
@override
void end(DragEndDetails details) {
onEnd(details);
}
}
class _IgnoreDrag extends Drag {
}
class _PointDemoPainter extends CustomPainter {
_PointDemoPainter({
Animation<double> repaint,
this.arc
}) : _repaint = repaint, super(repaint: repaint);
final MaterialPointArcTween arc;
final Animation<double> _repaint;
void drawPoint(Canvas canvas, Offset point, Color color) {
final Paint paint = new Paint()
..color = color.withOpacity(0.25)
..style = PaintingStyle.fill;
canvas.drawCircle(point, _kPointRadius, paint);
paint
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 2.0;
canvas.drawCircle(point, _kPointRadius + 1.0, paint);
}
@override
void paint(Canvas canvas, Size size) {
final Paint paint = new Paint();
if (arc.center != null)
drawPoint(canvas, arc.center, Colors.grey.shade400);
paint
..isAntiAlias = false // Work-around for github.com/flutter/flutter/issues/5720
..color = Colors.green.withOpacity(0.25)
..strokeWidth = 4.0
..style = PaintingStyle.stroke;
if (arc.center != null && arc.radius != null)
canvas.drawCircle(arc.center, arc.radius, paint);
else
canvas.drawLine(arc.begin, arc.end, paint);
drawPoint(canvas, arc.begin, Colors.green);
drawPoint(canvas, arc.end, Colors.red);
paint
..color = Colors.green
..style = PaintingStyle.fill;
canvas.drawCircle(arc.lerp(_repaint.value), _kPointRadius, paint);
}
@override
bool hitTest(Offset position) {
return (arc.begin - position).distanceSquared < _kTargetSlop
|| (arc.end - position).distanceSquared < _kTargetSlop;
}
@override
bool shouldRepaint(_PointDemoPainter oldPainter) => arc != oldPainter.arc;
}
class _PointDemo extends StatefulWidget {
const _PointDemo({ Key key, this.controller }) : super(key: key);
final AnimationController controller;
@override
_PointDemoState createState() => new _PointDemoState();
}
class _PointDemoState extends State<_PointDemo> {
final GlobalKey _painterKey = new GlobalKey();
CurvedAnimation _animation;
_DragTarget _dragTarget;
Size _screenSize;
Offset _begin;
Offset _end;
@override
void initState() {
super.initState();
_animation = new CurvedAnimation(parent: widget.controller, curve: Curves.fastOutSlowIn);
}
@override
void dispose() {
widget.controller.value = 0.0;
super.dispose();
}
Drag _handleOnStart(Offset position) {
// TODO(hansmuller): allow the user to drag both points at the same time.
if (_dragTarget != null)
return new _IgnoreDrag();
final RenderBox box = _painterKey.currentContext.findRenderObject();
final double startOffset = (box.localToGlobal(_begin) - position).distanceSquared;
final double endOffset = (box.localToGlobal(_end) - position).distanceSquared;
setState(() {
if (startOffset < endOffset && startOffset < _kTargetSlop)
_dragTarget = _DragTarget.start;
else if (endOffset < _kTargetSlop)
_dragTarget = _DragTarget.end;
else
_dragTarget = null;
});
return new _DragHandler(_handleDragUpdate, _handleDragCancel, _handleDragEnd);
}
void _handleDragUpdate(DragUpdateDetails details) {
switch (_dragTarget) {
case _DragTarget.start:
setState(() {
_begin = _begin + details.delta;
});
break;
case _DragTarget.end:
setState(() {
_end = _end + details.delta;
});
break;
}
}
void _handleDragCancel() {
_dragTarget = null;
widget.controller.value = 0.0;
}
void _handleDragEnd(DragEndDetails details) {
_dragTarget = null;
}
@override
Widget build(BuildContext context) {
final Size screenSize = MediaQuery.of(context).size;
if (_screenSize == null || _screenSize != screenSize) {
_screenSize = screenSize;
_begin = new Offset(screenSize.width * 0.5, screenSize.height * 0.2);
_end = new Offset(screenSize.width * 0.1, screenSize.height * 0.4);
}
final MaterialPointArcTween arc = new MaterialPointArcTween(begin: _begin, end: _end);
return new RawGestureDetector(
behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque,
gestures: <Type, GestureRecognizerFactory>{
ImmediateMultiDragGestureRecognizer: (ImmediateMultiDragGestureRecognizer recognizer) { // ignore: map_value_type_not_assignable, https://github.com/flutter/flutter/issues/5771
return (recognizer ??= new ImmediateMultiDragGestureRecognizer())
..onStart = _handleOnStart;
}
},
child: new ClipRect(
child: new CustomPaint(
key: _painterKey,
foregroundPainter: new _PointDemoPainter(
repaint: _animation,
arc: arc
),
// Watch out: if this IgnorePointer is left out, then gestures that
// fail _PointDemoPainter.hitTest() will still be recognized because
// they do overlap this child, which is as big as the CustomPaint.
child: new IgnorePointer(
child: new Padding(
padding: const EdgeInsets.all(16.0),
child: new Text(
"Tap the refresh button to run the animation. Drag the green "
"and red points to change the animation's path.",
style: Theme.of(context).textTheme.caption.copyWith(fontSize: 16.0)
)
)
)
)
)
);
}
}
class _RectangleDemoPainter extends CustomPainter {
_RectangleDemoPainter({
Animation<double> repaint,
this.arc
}) : _repaint = repaint, super(repaint: repaint);
final MaterialRectArcTween arc;
final Animation<double> _repaint;
void drawPoint(Canvas canvas, Offset p, Color color) {
final Paint paint = new Paint()
..color = color.withOpacity(0.25)
..style = PaintingStyle.fill;
canvas.drawCircle(p, _kPointRadius, paint);
paint
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 2.0;
canvas.drawCircle(p, _kPointRadius + 1.0, paint);
}
void drawRect(Canvas canvas, Rect rect, Color color) {
final Paint paint = new Paint()
..color = color.withOpacity(0.25)
..strokeWidth = 4.0
..style = PaintingStyle.stroke;
canvas.drawRect(rect, paint);
drawPoint(canvas, rect.center, color);
}
@override
void paint(Canvas canvas, Size size) {
drawRect(canvas, arc.begin, Colors.green);
drawRect(canvas, arc.end, Colors.red);
drawRect(canvas, arc.lerp(_repaint.value), Colors.blue);
}
@override
bool hitTest(Offset position) {
return (arc.begin.center - position).distanceSquared < _kTargetSlop
|| (arc.end.center - position).distanceSquared < _kTargetSlop;
}
@override
bool shouldRepaint(_RectangleDemoPainter oldPainter) => arc != oldPainter.arc;
}
class _RectangleDemo extends StatefulWidget {
const _RectangleDemo({ Key key, this.controller }) : super(key: key);
final AnimationController controller;
@override
_RectangleDemoState createState() => new _RectangleDemoState();
}
class _RectangleDemoState extends State<_RectangleDemo> {
final GlobalKey _painterKey = new GlobalKey();
CurvedAnimation _animation;
_DragTarget _dragTarget;
Size _screenSize;
Rect _begin;
Rect _end;
@override
void initState() {
super.initState();
_animation = new CurvedAnimation(parent: widget.controller, curve: Curves.fastOutSlowIn);
}
@override
void dispose() {
widget.controller.value = 0.0;
super.dispose();
}
Drag _handleOnStart(Offset position) {
// TODO(hansmuller): allow the user to drag both points at the same time.
if (_dragTarget != null)
return new _IgnoreDrag();
final RenderBox box = _painterKey.currentContext.findRenderObject();
final double startOffset = (box.localToGlobal(_begin.center) - position).distanceSquared;
final double endOffset = (box.localToGlobal(_end.center) - position).distanceSquared;
setState(() {
if (startOffset < endOffset && startOffset < _kTargetSlop)
_dragTarget = _DragTarget.start;
else if (endOffset < _kTargetSlop)
_dragTarget = _DragTarget.end;
else
_dragTarget = null;
});
return new _DragHandler(_handleDragUpdate, _handleDragCancel, _handleDragEnd);
}
void _handleDragUpdate(DragUpdateDetails details) {
switch (_dragTarget) {
case _DragTarget.start:
setState(() {
_begin = _begin.shift(details.delta);
});
break;
case _DragTarget.end:
setState(() {
_end = _end.shift(details.delta);
});
break;
}
}
void _handleDragCancel() {
_dragTarget = null;
widget.controller.value = 0.0;
}
void _handleDragEnd(DragEndDetails details) {
_dragTarget = null;
}
@override
Widget build(BuildContext context) {
final Size screenSize = MediaQuery.of(context).size;
if (_screenSize == null || _screenSize != screenSize) {
_screenSize = screenSize;
_begin = new Rect.fromLTWH(
screenSize.width * 0.5, screenSize.height * 0.2,
screenSize.width * 0.4, screenSize.height * 0.2
);
_end = new Rect.fromLTWH(
screenSize.width * 0.1, screenSize.height * 0.4,
screenSize.width * 0.3, screenSize.height * 0.3
);
}
final MaterialRectArcTween arc = new MaterialRectArcTween(begin: _begin, end: _end);
return new RawGestureDetector(
behavior: _dragTarget == null ? HitTestBehavior.deferToChild : HitTestBehavior.opaque,
gestures: <Type, GestureRecognizerFactory>{
ImmediateMultiDragGestureRecognizer: (ImmediateMultiDragGestureRecognizer recognizer) { // ignore: map_value_type_not_assignable, https://github.com/flutter/flutter/issues/5771
return (recognizer ??= new ImmediateMultiDragGestureRecognizer())
..onStart = _handleOnStart;
}
},
child: new ClipRect(
child: new CustomPaint(
key: _painterKey,
foregroundPainter: new _RectangleDemoPainter(
repaint: _animation,
arc: arc
),
// Watch out: if this IgnorePointer is left out, then gestures that
// fail _RectDemoPainter.hitTest() will still be recognized because
// they do overlap this child, which is as big as the CustomPaint.
child: new IgnorePointer(
child: new Padding(
padding: const EdgeInsets.all(16.0),
child: new Text(
"Tap the refresh button to run the animation. Drag the rectangles "
"to change the animation's path.",
style: Theme.of(context).textTheme.caption.copyWith(fontSize: 16.0)
)
)
)
)
)
);
}
}
typedef Widget _DemoBuilder(_ArcDemo demo);
class _ArcDemo {
_ArcDemo(this.title, this.builder, TickerProvider vsync)
: controller = new AnimationController(duration: const Duration(milliseconds: 500), vsync: vsync),
key = new GlobalKey(debugLabel: title);
final String title;
final _DemoBuilder builder;
final AnimationController controller;
final GlobalKey key;
}
class AnimationDemo extends StatefulWidget {
const AnimationDemo({ Key key }) : super(key: key);
@override
_AnimationDemoState createState() => new _AnimationDemoState();
}
class _AnimationDemoState extends State<AnimationDemo> with TickerProviderStateMixin {
List<_ArcDemo> _allDemos;
@override
void initState() {
super.initState();
_allDemos = <_ArcDemo>[
new _ArcDemo('POINT', (_ArcDemo demo) {
return new _PointDemo(
key: demo.key,
controller: demo.controller
);
}, this),
new _ArcDemo('RECTANGLE', (_ArcDemo demo) {
return new _RectangleDemo(
key: demo.key,
controller: demo.controller
);
}, this),
];
}
Future<Null> _play(_ArcDemo demo) async {
await demo.controller.forward();
if (demo.key.currentState != null && demo.key.currentState.mounted)
demo.controller.reverse();
}
@override
Widget build(BuildContext context) {
return new DefaultTabController(
length: _allDemos.length,
child: new Scaffold(
appBar: new AppBar(
title: const Text('Animation'),
bottom: new TabBar(
tabs: _allDemos.map((_ArcDemo demo) => new Tab(text: demo.title)).toList(),
),
),
floatingActionButton: new Builder(
builder: (BuildContext context) {
return new FloatingActionButton(
child: const Icon(Icons.refresh),
onPressed: () {
_play(_allDemos[DefaultTabController.of(context).index]);
},
);
},
),
body: new TabBarView(
children: _allDemos.map((_ArcDemo demo) => demo.builder(demo)).toList()
)
)
);
}
}
void main() {
runApp(new MaterialApp(
home: const AnimationDemo()
));
}

View File

@@ -0,0 +1,215 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class CardModel {
CardModel(this.value, this.height, this.color);
int value;
double height;
Color color;
String get label => 'Card $value';
Key get key => new ObjectKey(this);
GlobalKey get targetKey => new GlobalObjectKey(this);
}
enum MarkerType { topLeft, bottomRight, touch }
class _MarkerPainter extends CustomPainter {
const _MarkerPainter({
this.size,
this.type,
});
final double size;
final MarkerType type;
@override
void paint(Canvas canvas, _) {
final Paint paint = new Paint()..color = const Color(0x8000FF00);
final double r = size / 2.0;
canvas.drawCircle(new Offset(r, r), r, paint);
paint
..color = const Color(0xFFFFFFFF)
..style = PaintingStyle.stroke
..strokeWidth = 1.0;
if (type == MarkerType.topLeft) {
canvas.drawLine(new Offset(r, r), new Offset(r + r - 1.0, r), paint);
canvas.drawLine(new Offset(r, r), new Offset(r, r + r - 1.0), paint);
}
if (type == MarkerType.bottomRight) {
canvas.drawLine(new Offset(r, r), new Offset(1.0, r), paint);
canvas.drawLine(new Offset(r, r), new Offset(r, 1.0), paint);
}
}
@override
bool shouldRepaint(_MarkerPainter oldPainter) {
return oldPainter.size != size
|| oldPainter.type != type;
}
}
class Marker extends StatelessWidget {
const Marker({
Key key,
this.type: MarkerType.touch,
this.position,
this.size: 40.0,
}) : super(key: key);
final Offset position;
final double size;
final MarkerType type;
@override
Widget build(BuildContext context) {
return new Positioned(
left: position.dx - size / 2.0,
top: position.dy - size / 2.0,
width: size,
height: size,
child: new IgnorePointer(
child: new CustomPaint(
painter: new _MarkerPainter(
size: size,
type: type,
),
),
),
);
}
}
class OverlayGeometryApp extends StatefulWidget {
@override
OverlayGeometryAppState createState() => new OverlayGeometryAppState();
}
typedef void CardTapCallback(GlobalKey targetKey, Offset globalPosition);
class CardBuilder extends SliverChildDelegate {
CardBuilder({ this.cardModels, this.onTapUp });
final List<CardModel> cardModels;
final CardTapCallback onTapUp;
static const TextStyle cardLabelStyle =
const TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
@override
Widget build(BuildContext context, int index) {
if (index >= cardModels.length)
return null;
final CardModel cardModel = cardModels[index];
return new GestureDetector(
key: cardModel.key,
onTapUp: (TapUpDetails details) { onTapUp(cardModel.targetKey, details.globalPosition); },
child: new Card(
key: cardModel.targetKey,
color: cardModel.color,
child: new Container(
height: cardModel.height,
padding: const EdgeInsets.all(8.0),
child: new Center(child: new Text(cardModel.label, style: cardLabelStyle)),
),
),
);
}
@override
int get estimatedChildCount => cardModels.length;
@override
bool shouldRebuild(CardBuilder oldDelegate) {
return oldDelegate.cardModels != cardModels;
}
}
class OverlayGeometryAppState extends State<OverlayGeometryApp> {
List<CardModel> cardModels;
Map<MarkerType, Offset> markers = <MarkerType, Offset>{};
double markersScrollOffset = 0.0;
@override
void initState() {
super.initState();
final List<double> cardHeights = <double>[
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
48.0, 63.0, 82.0, 146.0, 60.0, 55.0, 84.0, 96.0, 50.0,
];
cardModels = new List<CardModel>.generate(cardHeights.length, (int i) {
final Color color = Color.lerp(Colors.red.shade300, Colors.blue.shade900, i / cardHeights.length);
return new CardModel(i, cardHeights[i], color);
});
}
bool handleScrollNotification(ScrollNotification notification) {
if (notification is ScrollUpdateNotification && notification.depth == 1) {
setState(() {
final double dy = markersScrollOffset - notification.metrics.extentBefore;
markersScrollOffset = notification.metrics.extentBefore;
for (MarkerType type in markers.keys) {
final Offset oldPosition = markers[type];
markers[type] = oldPosition.translate(0.0, dy);
}
});
}
return false;
}
void handleTapUp(GlobalKey target, Offset globalPosition) {
setState(() {
markers[MarkerType.touch] = globalPosition;
final RenderBox box = target.currentContext.findRenderObject();
markers[MarkerType.topLeft] = box.localToGlobal(const Offset(0.0, 0.0));
final Size size = box.size;
markers[MarkerType.bottomRight] = box.localToGlobal(new Offset(size.width, size.height));
final ScrollableState scrollable = Scrollable.of(target.currentContext);
markersScrollOffset = scrollable.position.pixels;
});
}
@override
Widget build(BuildContext context) {
final List<Widget> layers = <Widget>[
new Scaffold(
appBar: new AppBar(title: const Text('Tap a Card')),
body: new Container(
padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
child: new NotificationListener<ScrollNotification>(
onNotification: handleScrollNotification,
child: new ListView.custom(
childrenDelegate: new CardBuilder(
cardModels: cardModels,
onTapUp: handleTapUp,
),
),
),
),
),
];
for (MarkerType type in markers.keys)
layers.add(new Marker(type: type, position: markers[type]));
return new Stack(children: layers);
}
}
void main() {
runApp(new MaterialApp(
theme: new ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.blue,
accentColor: Colors.redAccent,
),
title: 'Cards',
home: new OverlayGeometryApp(),
));
}

View File

@@ -0,0 +1,151 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
class CardModel {
CardModel(this.value, this.size, this.color);
int value;
Size size;
Color color;
String get label => 'Card $value';
Key get key => new ObjectKey(this);
}
class PageViewApp extends StatefulWidget {
@override
PageViewAppState createState() => new PageViewAppState();
}
class PageViewAppState extends State<PageViewApp> {
@override
void initState() {
super.initState();
const List<Size> cardSizes = const <Size>[
const Size(100.0, 300.0),
const Size(300.0, 100.0),
const Size(200.0, 400.0),
const Size(400.0, 400.0),
const Size(300.0, 400.0),
];
cardModels = new List<CardModel>.generate(cardSizes.length, (int i) {
final Color color = Color.lerp(Colors.red.shade300, Colors.blue.shade900, i / cardSizes.length);
return new CardModel(i, cardSizes[i], color);
});
}
static const TextStyle cardLabelStyle =
const TextStyle(color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold);
List<CardModel> cardModels;
Size pageSize = const Size(200.0, 200.0);
Axis scrollDirection = Axis.horizontal;
bool itemsWrap = false;
Widget buildCard(CardModel cardModel) {
final Widget card = new Card(
color: cardModel.color,
child: new Container(
width: cardModel.size.width,
height: cardModel.size.height,
padding: const EdgeInsets.all(8.0),
child: new Center(child: new Text(cardModel.label, style: cardLabelStyle)),
),
);
final BoxConstraints constraints = (scrollDirection == Axis.vertical)
? new BoxConstraints.tightFor(height: pageSize.height)
: new BoxConstraints.tightFor(width: pageSize.width);
return new Container(
key: cardModel.key,
constraints: constraints,
child: new Center(child: card),
);
}
void switchScrollDirection() {
setState(() {
scrollDirection = (scrollDirection == Axis.vertical)
? Axis.horizontal
: Axis.vertical;
});
}
void toggleItemsWrap() {
setState(() {
itemsWrap = !itemsWrap;
});
}
Widget _buildDrawer() {
return new Drawer(
child: new ListView(
children: <Widget>[
const DrawerHeader(child: const Center(child: const Text('Options'))),
new ListTile(
leading: const Icon(Icons.more_horiz),
selected: scrollDirection == Axis.horizontal,
trailing: const Text('Horizontal Layout'),
onTap: switchScrollDirection,
),
new ListTile(
leading: const Icon(Icons.more_vert),
selected: scrollDirection == Axis.vertical,
trailing: const Text('Vertical Layout'),
onTap: switchScrollDirection,
),
new ListTile(
onTap: toggleItemsWrap,
title: const Text('Scrolling wraps around'),
// TODO(abarth): Actually make this checkbox change this value.
trailing: new Checkbox(value: itemsWrap, onChanged: null),
),
],
),
);
}
Widget _buildAppBar() {
return new AppBar(
title: const Text('PageView'),
actions: <Widget>[
new Text(scrollDirection == Axis.horizontal ? "horizontal" : "vertical"),
],
);
}
Widget _buildBody(BuildContext context) {
return new PageView(
children: cardModels.map(buildCard).toList(),
// TODO(abarth): itemsWrap: itemsWrap,
scrollDirection: scrollDirection,
);
}
@override
Widget build(BuildContext context) {
return new IconTheme(
data: const IconThemeData(color: Colors.white),
child: new Scaffold(
appBar: _buildAppBar(),
drawer: _buildDrawer(),
body: _buildBody(context),
),
);
}
}
void main() {
runApp(new MaterialApp(
title: 'PageView',
theme: new ThemeData(
brightness: Brightness.light,
primarySwatch: Colors.blue,
accentColor: Colors.redAccent,
),
home: new PageViewApp(),
));
}

View File

@@ -0,0 +1,90 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(new MaterialApp(
title: 'Hardware Key Demo',
home: new Scaffold(
appBar: new AppBar(
title: const Text('Hardware Key Demo'),
),
body: const Center(
child: const RawKeyboardDemo(),
),
),
));
}
class RawKeyboardDemo extends StatefulWidget {
const RawKeyboardDemo({ Key key }) : super(key: key);
@override
_HardwareKeyDemoState createState() => new _HardwareKeyDemoState();
}
class _HardwareKeyDemoState extends State<RawKeyboardDemo> {
final FocusNode _focusNode = new FocusNode();
RawKeyEvent _event;
@override
void dispose() {
_focusNode.dispose();
super.dispose();
}
void _handleKeyEvent(RawKeyEvent event) {
setState(() {
_event = event;
});
}
@override
Widget build(BuildContext context) {
final TextTheme textTheme = Theme.of(context).textTheme;
return new RawKeyboardListener(
focusNode: _focusNode,
onKey: _handleKeyEvent,
child: new AnimatedBuilder(
animation: _focusNode,
builder: (BuildContext context, Widget child) {
if (!_focusNode.hasFocus) {
return new GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(_focusNode);
},
child: new Text('Tap to focus', style: textTheme.display1),
);
}
if (_event == null)
return new Text('Press a key', style: textTheme.display1);
int codePoint;
int keyCode;
int hidUsage;
final RawKeyEventData data = _event.data;
if (data is RawKeyEventDataAndroid) {
codePoint = data.codePoint;
keyCode = data.keyCode;
} else if (data is RawKeyEventDataFuchsia) {
codePoint = data.codePoint;
hidUsage = data.hidUsage;
}
return new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text('${_event.runtimeType}', style: textTheme.body2),
new Text('codePoint: $codePoint', style: textTheme.display4),
new Text('keyCode: $keyCode', style: textTheme.display4),
new Text('hidUsage: $hidUsage', style: textTheme.display4),
],
);
},
),
);
}
}