Clean up the standalone examples

Our examples have been growing organically over time. This patch cleans
them up to illustrate specific aspects of Flutter.
This commit is contained in:
Adam Barth
2016-02-13 00:52:56 -08:00
parent 8db6f5b127
commit 948ae15ca5
45 changed files with 618 additions and 1685 deletions

22
examples/layers/README.md Normal file
View File

@@ -0,0 +1,22 @@
# Examples of Flutter's layered architecture
This directory contains a number of self-contained examples that illustrate
Flutter's layered architecture.
* [*raw/*](raw/) These examples show how to program against the lowest layer of
the system. They manually receive input packets and construct composited
scenes.
* [*rendering/*](rendering/) These examples use Flutter's render tree to
structure your app using a retained tree of visual objects. These objects
coordinate to determine their size and position on screen and to handle
events.
* [*widgets/*](widgets/) These examples use Flutter's widgets to build more
elaborate apps using a reactive framework.
To run each example, use the `-t` argument to the `flutter` tool:
```
flutter start -t widgets/spinning_square.dart
```

View File

@@ -0,0 +1,4 @@
name: flutter_examples_layers
dependencies:
flutter:
path: ../../packages/flutter

View File

@@ -0,0 +1,126 @@
// 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:ui' as ui;
import 'dart:math' as math;
import 'dart:typed_data';
ui.Picture paint(ui.Rect paintBounds) {
ui.PictureRecorder recorder = new ui.PictureRecorder();
ui.Canvas canvas = new ui.Canvas(recorder, paintBounds);
ui.Size size = paintBounds.size;
ui.Paint paint = new ui.Paint();
ui.Point mid = size.center(ui.Point.origin);
double radius = size.shortestSide / 2.0;
canvas.drawPaint(new ui.Paint()..color = const ui.Color(0xFFFFFFFF));
canvas.save();
canvas.translate(-mid.x/2.0, ui.window.size.height*2.0);
canvas.clipRect(
new ui.Rect.fromLTRB(0.0, -ui.window.size.height, ui.window.size.width, radius));
canvas.translate(mid.x, mid.y);
paint.color = const ui.Color.fromARGB(128, 255, 0, 255);
canvas.rotate(math.PI/4.0);
ui.Gradient yellowBlue = new ui.Gradient.linear(
<ui.Point>[new ui.Point(-radius, -radius), new ui.Point(0.0, 0.0)],
<ui.Color>[const ui.Color(0xFFFFFF00), const ui.Color(0xFF0000FF)]
);
canvas.drawRect(new ui.Rect.fromLTRB(-radius, -radius, radius, radius),
new ui.Paint()..shader = yellowBlue);
// Scale x and y by 0.5.
Float64List scaleMatrix = new Float64List.fromList(<double>[
0.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
]);
canvas.transform(scaleMatrix);
paint.color = const ui.Color.fromARGB(128, 0, 255, 0);
canvas.drawCircle(ui.Point.origin, radius, paint);
canvas.restore();
canvas.translate(0.0, 50.0);
ui.LayerDrawLooperBuilder builder = new ui.LayerDrawLooperBuilder()
..addLayerOnTop(
new ui.DrawLooperLayerInfo()
..setOffset(const ui.Offset(150.0, 0.0))
..setColorMode(ui.TransferMode.src)
..setPaintBits(ui.PaintBits.all),
new ui.Paint()
..color = const ui.Color.fromARGB(128, 255, 255, 0)
..colorFilter = new ui.ColorFilter.mode(
const ui.Color.fromARGB(128, 0, 0, 255),
ui.TransferMode.srcIn
)
..maskFilter = new ui.MaskFilter.blur(
ui.BlurStyle.normal, 3.0, highQuality: true
)
)
..addLayerOnTop(
new ui.DrawLooperLayerInfo()
..setOffset(const ui.Offset(75.0, 75.0))
..setColorMode(ui.TransferMode.src)
..setPaintBits(ui.PaintBits.shader),
new ui.Paint()
..shader = new ui.Gradient.radial(
new ui.Point(0.0, 0.0), radius/3.0,
<ui.Color>[
const ui.Color(0xFFFFFF00),
const ui.Color(0xFFFF0000)
],
null,
ui.TileMode.mirror
)
// Since we're don't set ui.PaintBits.maskFilter, this has no effect.
..maskFilter = new ui.MaskFilter.blur(
ui.BlurStyle.normal, 50.0, highQuality: true
)
)
..addLayerOnTop(
new ui.DrawLooperLayerInfo()..setOffset(const ui.Offset(225.0, 75.0)),
// Since this layer uses a DST color mode, this has no effect.
new ui.Paint()..color = const ui.Color.fromARGB(128, 255, 0, 0)
);
paint.drawLooper = builder.build();
canvas.drawCircle(ui.Point.origin, radius, paint);
return recorder.endRecording();
}
ui.Scene composite(ui.Picture picture, ui.Rect paintBounds) {
final double devicePixelRatio = ui.window.devicePixelRatio;
ui.Rect sceneBounds = new ui.Rect.fromLTWH(
0.0,
0.0,
ui.window.size.width * devicePixelRatio,
ui.window.size.height * devicePixelRatio
);
Float64List deviceTransform = new Float64List(16)
..[0] = devicePixelRatio
..[5] = devicePixelRatio
..[10] = 1.0
..[15] = 1.0;
ui.SceneBuilder sceneBuilder = new ui.SceneBuilder(sceneBounds)
..pushTransform(deviceTransform)
..addPicture(ui.Offset.zero, picture)
..pop();
return sceneBuilder.build();
}
void beginFrame(Duration timeStamp) {
ui.Rect paintBounds = ui.Point.origin & ui.window.size;
ui.Picture picture = paint(paintBounds);
ui.Scene scene = composite(picture, paintBounds);
ui.window.render(scene);
}
void main() {
ui.window.onBeginFrame = beginFrame;
ui.window.scheduleFrame();
}

View File

@@ -0,0 +1,79 @@
// 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:ui' as ui;
import 'dart:typed_data';
import 'package:mojo/bindings.dart' as bindings;
import 'package:mojo/core.dart' as core;
import 'package:sky_services/pointer/pointer.mojom.dart';
ui.Color color;
ui.Picture paint(ui.Rect paintBounds) {
ui.PictureRecorder recorder = new ui.PictureRecorder();
ui.Canvas canvas = new ui.Canvas(recorder, paintBounds);
ui.Size size = paintBounds.size;
double radius = size.shortestSide * 0.45;
ui.Paint paint = new ui.Paint()..color = color;
canvas.drawCircle(size.center(ui.Point.origin), radius, paint);
return recorder.endRecording();
}
ui.Scene composite(ui.Picture picture, ui.Rect paintBounds) {
final double devicePixelRatio = ui.window.devicePixelRatio;
ui.Rect sceneBounds = new ui.Rect.fromLTWH(
0.0,
0.0,
ui.window.size.width * devicePixelRatio,
ui.window.size.height * devicePixelRatio
);
Float64List deviceTransform = new Float64List(16)
..[0] = devicePixelRatio
..[5] = devicePixelRatio
..[10] = 1.0
..[15] = 1.0;
ui.SceneBuilder sceneBuilder = new ui.SceneBuilder(sceneBounds)
..pushTransform(deviceTransform)
..addPicture(ui.Offset.zero, picture)
..pop();
return sceneBuilder.build();
}
void beginFrame(Duration timeStamp) {
ui.Rect paintBounds = ui.Point.origin & ui.window.size;
ui.Picture picture = paint(paintBounds);
ui.Scene scene = composite(picture, paintBounds);
ui.window.render(scene);
}
void handlePopRoute() {
print('Pressed back button.');
}
void handlePointerPacket(ByteData serializedPacket) {
bindings.Message message = new bindings.Message(serializedPacket, <core.MojoHandle>[], serializedPacket.lengthInBytes, 0);
PointerPacket packet = PointerPacket.deserialize(message);
for (Pointer pointer in packet.pointers) {
if (pointer.type == PointerType.down) {
color = new ui.Color.fromARGB(255, 0, 0, 255);
ui.window.scheduleFrame();
} else if (pointer.type == PointerType.up) {
color = new ui.Color.fromARGB(255, 0, 255, 0);
ui.window.scheduleFrame();
}
}
}
void main() {
print('Hello, world');
color = new ui.Color.fromARGB(255, 0, 255, 0);
ui.window.onBeginFrame = beginFrame;
ui.window.onPopRoute = handlePopRoute;
ui.window.onPointerPacket = handlePointerPacket;
ui.window.scheduleFrame();
}

View File

@@ -0,0 +1,54 @@
// 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:developer';
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui' as ui;
Duration timeBase = null;
void beginFrame(Duration timeStamp) {
Timeline.timeSync('beginFrame', () {
if (timeBase == null)
timeBase = timeStamp;
double delta = (timeStamp - timeBase).inMicroseconds / Duration.MICROSECONDS_PER_MILLISECOND;
// paint
ui.Rect paintBounds = ui.Point.origin & ui.window.size;
ui.PictureRecorder recorder = new ui.PictureRecorder();
ui.Canvas canvas = new ui.Canvas(recorder, paintBounds);
canvas.translate(paintBounds.width / 2.0, paintBounds.height / 2.0);
canvas.rotate(math.PI * delta / 1800);
canvas.drawRect(new ui.Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
new ui.Paint()..color = const ui.Color.fromARGB(255, 0, 255, 0));
ui.Picture picture = recorder.endRecording();
// composite
final double devicePixelRatio = ui.window.devicePixelRatio;
ui.Rect sceneBounds = new ui.Rect.fromLTWH(
0.0,
0.0,
ui.window.size.width * devicePixelRatio,
ui.window.size.height * devicePixelRatio
);
Float64List deviceTransform = new Float64List(16)
..[0] = devicePixelRatio
..[5] = devicePixelRatio
..[10] = 1.0
..[15] = 1.0;
ui.SceneBuilder sceneBuilder = new ui.SceneBuilder(sceneBounds)
..pushTransform(deviceTransform)
..addPicture(ui.Offset.zero, picture)
..pop();
ui.window.render(sceneBuilder.build());
});
ui.window.scheduleFrame();
}
void main() {
ui.window.onBeginFrame = beginFrame;
ui.window.scheduleFrame();
}

View File

@@ -0,0 +1,67 @@
// 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:ui' as ui;
import 'dart:typed_data';
ui.Paragraph paragraph;
ui.Picture paint(ui.Rect paintBounds) {
ui.PictureRecorder recorder = new ui.PictureRecorder();
ui.Canvas canvas = new ui.Canvas(recorder, paintBounds);
canvas.translate(ui.window.size.width / 2.0, ui.window.size.height / 2.0);
canvas.drawRect(new ui.Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
new ui.Paint()..color = const ui.Color.fromARGB(255, 0, 255, 0));
canvas.translate(paragraph.maxWidth / -2.0, (paragraph.maxWidth / 2.0) - 125);
paragraph.paint(canvas, ui.Offset.zero);
return recorder.endRecording();
}
ui.Scene composite(ui.Picture picture, ui.Rect paintBounds) {
final double devicePixelRatio = ui.window.devicePixelRatio;
ui.Rect sceneBounds = new ui.Rect.fromLTWH(
0.0,
0.0,
ui.window.size.width * devicePixelRatio,
ui.window.size.height * devicePixelRatio
);
Float64List deviceTransform = new Float64List(16)
..[0] = devicePixelRatio
..[5] = devicePixelRatio
..[10] = 1.0
..[15] = 1.0;
ui.SceneBuilder sceneBuilder = new ui.SceneBuilder(sceneBounds)
..pushTransform(deviceTransform)
..addPicture(ui.Offset.zero, picture)
..pop();
return sceneBuilder.build();
}
void beginFrame(Duration timeStamp) {
ui.Rect paintBounds = ui.Point.origin & ui.window.size;
ui.Picture picture = paint(paintBounds);
ui.Scene scene = composite(picture, paintBounds);
ui.window.render(scene);
}
void main() {
ui.ParagraphBuilder builder = new ui.ParagraphBuilder()
..pushStyle(new ui.TextStyle(color: const ui.Color(0xFF0000FF)))
..addText("Hello, ")
..pushStyle(new ui.TextStyle(fontWeight: ui.FontWeight.bold))
..addText("world. ")
..pop()
..addText("هذا هو قليلا طويلة من النص الذي يجب التفاف .")
..pop()
..addText(" و أكثر قليلا لجعله أطول. ");
paragraph = builder.build(new ui.ParagraphStyle())
..maxWidth = 180.0
..layout();
ui.window.onBeginFrame = beginFrame;
ui.window.scheduleFrame();
}

View File

@@ -0,0 +1,63 @@
// 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:ui';
import 'package:cassowary/cassowary.dart' as al;
import 'package:flutter/rendering.dart';
void main() {
RenderDecoratedBox c1 = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFF0000))
);
RenderDecoratedBox c2 = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFF00FF00))
);
RenderDecoratedBox c3 = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFF0000FF))
);
RenderDecoratedBox c4 = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF))
);
RenderAutoLayout root = new RenderAutoLayout(children: <RenderBox>[c1, c2, c3, c4]);
AutoLayoutParentData p1 = c1.parentData;
AutoLayoutParentData p2 = c2.parentData;
AutoLayoutParentData p3 = c3.parentData;
AutoLayoutParentData p4 = c4.parentData;
root.addConstraints(<al.Constraint>[
// Sum of widths of each box must be equal to that of the container
(p1.width + p2.width + p3.width == root.width) as al.Constraint,
// The boxes must be stacked left to right
p1.rightEdge <= p2.leftEdge,
p2.rightEdge <= p3.leftEdge,
// The widths of the first and the third boxes should be equal
(p1.width == p3.width) as al.Constraint,
// The width of the second box should be twice as much as that of the first
// and third
(p2.width * al.cm(2.0) == p1.width) as al.Constraint,
// The height of the three boxes should be equal to that of the container
(p1.height == p2.height) as al.Constraint,
(p2.height == p3.height) as al.Constraint,
(p3.height == root.height) as al.Constraint,
// The fourth box should be half as wide as the second and must be attached
// to the right edge of the same (by its center)
(p4.width == p2.width / al.cm(2.0)) as al.Constraint,
(p4.height == al.cm(50.0)) as al.Constraint,
(p4.horizontalCenter == p2.rightEdge) as al.Constraint,
(p4.verticalCenter == p2.height / al.cm(2.0)) as al.Constraint,
]);
new RenderingFlutterBinding(root: root);
}

View File

@@ -0,0 +1,22 @@
// 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/rendering.dart';
import 'src/sector_layout.dart';
RenderBox buildSectorExample() {
RenderSectorRing rootCircle = new RenderSectorRing(padding: 20.0);
rootCircle.add(new RenderSolidColor(const Color(0xFF00FFFF), desiredDeltaTheta: kTwoPi * 0.15));
rootCircle.add(new RenderSolidColor(const Color(0xFF0000FF), desiredDeltaTheta: kTwoPi * 0.4));
RenderSectorSlice stack = new RenderSectorSlice(padding: 2.0);
stack.add(new RenderSolidColor(const Color(0xFFFFFF00), desiredDeltaRadius: 20.0));
stack.add(new RenderSolidColor(const Color(0xFFFF9000), desiredDeltaRadius: 20.0));
stack.add(new RenderSolidColor(const Color(0xFF00FF00)));
rootCircle.add(stack);
return new RenderBoxToRenderSectorAdapter(innerRadius: 50.0, child: rootCircle);
}
void main() {
new RenderingFlutterBinding(root: buildSectorExample());
}

View File

@@ -0,0 +1,72 @@
// 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/rendering.dart';
import 'src/solid_color_box.dart';
void main() {
RenderFlex table = new RenderFlex(direction: FlexDirection.vertical);
void addAlignmentRow(FlexAlignItems alignItems) {
TextStyle style = const TextStyle(color: const Color(0xFF000000));
RenderParagraph paragraph = new RenderParagraph(new StyledTextSpan(style, <TextSpan>[new PlainTextSpan('$alignItems')]));
table.add(new RenderPadding(child: paragraph, padding: new EdgeDims.only(top: 20.0)));
RenderFlex row = new RenderFlex(alignItems: alignItems, textBaseline: TextBaseline.alphabetic);
style = new TextStyle(fontSize: 15.0, color: const Color(0xFF000000));
row.add(new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0x7FFFCCCC)),
child: new RenderParagraph(new StyledTextSpan(style, <TextSpan>[new PlainTextSpan('foo foo foo')]))
));
style = new TextStyle(fontSize: 10.0, color: const Color(0xFF000000));
row.add(new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0x7FCCFFCC)),
child: new RenderParagraph(new StyledTextSpan(style, <TextSpan>[new PlainTextSpan('foo foo foo')]))
));
RenderFlex subrow = new RenderFlex(alignItems: alignItems, textBaseline: TextBaseline.alphabetic);
style = new TextStyle(fontSize: 25.0, color: const Color(0xFF000000));
subrow.add(new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0x7FCCCCFF)),
child: new RenderParagraph(new StyledTextSpan(style, <TextSpan>[new PlainTextSpan('foo foo foo foo')]))
));
subrow.add(new RenderSolidColorBox(const Color(0x7FCCFFFF), desiredSize: new Size(30.0, 40.0)));
row.add(subrow);
table.add(row);
final FlexParentData rowParentData = row.parentData;
rowParentData.flex = 1;
}
addAlignmentRow(FlexAlignItems.start);
addAlignmentRow(FlexAlignItems.end);
addAlignmentRow(FlexAlignItems.center);
addAlignmentRow(FlexAlignItems.stretch);
addAlignmentRow(FlexAlignItems.baseline);
void addJustificationRow(FlexJustifyContent justify) {
const TextStyle style = const TextStyle(color: const Color(0xFF000000));
RenderParagraph paragraph = new RenderParagraph(new StyledTextSpan(style, <TextSpan>[new PlainTextSpan('$justify')]));
table.add(new RenderPadding(child: paragraph, padding: new EdgeDims.only(top: 20.0)));
RenderFlex row = new RenderFlex(direction: FlexDirection.horizontal);
row.add(new RenderSolidColorBox(const Color(0xFFFFCCCC), desiredSize: new Size(80.0, 60.0)));
row.add(new RenderSolidColorBox(const Color(0xFFCCFFCC), desiredSize: new Size(64.0, 60.0)));
row.add(new RenderSolidColorBox(const Color(0xFFCCCCFF), desiredSize: new Size(160.0, 60.0)));
row.justifyContent = justify;
table.add(row);
final FlexParentData rowParentData = row.parentData;
rowParentData.flex = 1;
}
addJustificationRow(FlexJustifyContent.start);
addJustificationRow(FlexJustifyContent.end);
addJustificationRow(FlexJustifyContent.center);
addJustificationRow(FlexJustifyContent.spaceBetween);
addJustificationRow(FlexJustifyContent.spaceAround);
RenderDecoratedBox root = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)),
child: new RenderPadding(child: table, padding: new EdgeDims.symmetric(vertical: 50.0))
);
new RenderingFlutterBinding(root: root);
}

View File

@@ -0,0 +1,14 @@
// 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/rendering.dart';
void main() {
new RenderingFlutterBinding(
root: new RenderPositionedBox(
alignment: const FractionalOffset(0.5, 0.5),
child: new RenderParagraph(new PlainTextSpan('Hello, world.'))
)
);
}

View File

@@ -0,0 +1,44 @@
// 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:math' as math;
import 'package:flutter/animation.dart';
import 'package:flutter/rendering.dart';
void main() {
// A green box...
RenderBox green = new RenderDecoratedBox(
decoration: const BoxDecoration(backgroundColor: const Color(0xFF00FF00))
);
// of a certain size...
RenderBox square = new RenderConstrainedBox(
additionalConstraints: const BoxConstraints.tightFor(width: 200.0, height: 200.0),
child: green
);
// With a given rotation (starts off as the identity transform)...
RenderTransform spin = new RenderTransform(
transform: new Matrix4.identity(),
alignment: const FractionalOffset(0.5, 0.5),
child: square
);
// centered...
RenderBox root = new RenderPositionedBox(
alignment: const FractionalOffset(0.5, 0.5),
child: spin
);
// on the screen.
new RenderingFlutterBinding(root: root);
// A repeating animation every 1800 milliseconds...
AnimationController animation = new AnimationController(
duration: const Duration(milliseconds: 1800)
)..repeat();
// From 0.0 to math.PI.
Tween<double> tween = new Tween<double>(begin: 0.0, end: math.PI);
animation.addListener(() {
// Each frame of the animation, set the rotation of the square.
spin.transform = new Matrix4.rotationZ(tween.evaluate(animation));
});
}

View File

@@ -0,0 +1,535 @@
// 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/rendering.dart';
import 'package:flutter/gestures.dart';
const double kTwoPi = 2 * math.PI;
class SectorConstraints extends Constraints {
const SectorConstraints({
this.minDeltaRadius: 0.0,
this.maxDeltaRadius: double.INFINITY,
this.minDeltaTheta: 0.0,
this.maxDeltaTheta: kTwoPi
});
const SectorConstraints.tight({ double deltaRadius: 0.0, double deltaTheta: 0.0 })
: minDeltaRadius = deltaRadius,
maxDeltaRadius = deltaRadius,
minDeltaTheta = deltaTheta,
maxDeltaTheta = deltaTheta;
final double minDeltaRadius;
final double maxDeltaRadius;
final double minDeltaTheta;
final double maxDeltaTheta;
double constrainDeltaRadius(double deltaRadius) {
return deltaRadius.clamp(minDeltaRadius, maxDeltaRadius);
}
double constrainDeltaTheta(double deltaTheta) {
return deltaTheta.clamp(minDeltaTheta, maxDeltaTheta);
}
bool get isTight => minDeltaTheta >= maxDeltaTheta && minDeltaTheta >= maxDeltaTheta;
bool get isNormalized => minDeltaRadius <= maxDeltaRadius && minDeltaTheta <= maxDeltaTheta;
bool get debugAssertIsNormalized {
assert(isNormalized);
return isNormalized;
}
}
class SectorDimensions {
const SectorDimensions({ this.deltaRadius: 0.0, this.deltaTheta: 0.0 });
factory SectorDimensions.withConstraints(
SectorConstraints constraints,
{ double deltaRadius: 0.0, double deltaTheta: 0.0 }
) {
return new SectorDimensions(
deltaRadius: constraints.constrainDeltaRadius(deltaRadius),
deltaTheta: constraints.constrainDeltaTheta(deltaTheta)
);
}
final double deltaRadius;
final double deltaTheta;
}
class SectorParentData extends ParentData {
double radius = 0.0;
double theta = 0.0;
}
abstract class RenderSector extends RenderObject {
void setupParentData(RenderObject child) {
if (child.parentData is! SectorParentData)
child.parentData = new SectorParentData();
}
// RenderSectors always use SectorParentData subclasses, as they need to be
// able to read their position information for painting and hit testing.
SectorParentData get parentData => super.parentData;
SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) {
return new SectorDimensions.withConstraints(constraints);
}
SectorConstraints get constraints => super.constraints;
void debugAssertDoesMeetConstraints() {
assert(constraints != null);
assert(deltaRadius != null);
assert(deltaRadius < double.INFINITY);
assert(deltaTheta != null);
assert(deltaTheta < double.INFINITY);
assert(constraints.minDeltaRadius <= deltaRadius);
assert(deltaRadius <= math.max(constraints.minDeltaRadius, constraints.maxDeltaRadius));
assert(constraints.minDeltaTheta <= deltaTheta);
assert(deltaTheta <= math.max(constraints.minDeltaTheta, constraints.maxDeltaTheta));
}
void performResize() {
// default behavior for subclasses that have sizedByParent = true
deltaRadius = constraints.constrainDeltaRadius(0.0);
deltaTheta = constraints.constrainDeltaTheta(0.0);
}
void performLayout() {
// descendants have to either override performLayout() to set both
// the dimensions and lay out children, or, set sizedByParent to
// true so that performResize()'s logic above does its thing.
assert(sizedByParent);
}
Rect get paintBounds => new Rect.fromLTWH(0.0, 0.0, 2.0 * deltaRadius, 2.0 * deltaRadius);
Rect get semanticBounds => new Rect.fromLTWH(-deltaRadius, -deltaRadius, 2.0 * deltaRadius, 2.0 * deltaRadius);
bool hitTest(HitTestResult result, { double radius, double theta }) {
if (radius < parentData.radius || radius >= parentData.radius + deltaRadius ||
theta < parentData.theta || theta >= parentData.theta + deltaTheta)
return false;
hitTestChildren(result, radius: radius, theta: theta);
result.add(new HitTestEntry(this));
return true;
}
void hitTestChildren(HitTestResult result, { double radius, double theta }) { }
double deltaRadius;
double deltaTheta;
}
abstract class RenderDecoratedSector extends RenderSector {
RenderDecoratedSector(BoxDecoration decoration) : _decoration = decoration;
BoxDecoration _decoration;
BoxDecoration get decoration => _decoration;
void set decoration (BoxDecoration value) {
if (value == _decoration)
return;
_decoration = value;
markNeedsPaint();
}
// offset must point to the center of the circle
void paint(PaintingContext context, Offset offset) {
assert(deltaRadius != null);
assert(deltaTheta != null);
assert(parentData is SectorParentData);
if (_decoration == null)
return;
if (_decoration.backgroundColor != null) {
final Canvas canvas = context.canvas;
Paint paint = new Paint()..color = _decoration.backgroundColor;
Path path = new Path();
double outerRadius = (parentData.radius + deltaRadius);
Rect outerBounds = new Rect.fromLTRB(offset.dx-outerRadius, offset.dy-outerRadius, offset.dx+outerRadius, offset.dy+outerRadius);
path.arcTo(outerBounds, parentData.theta, deltaTheta, true);
double innerRadius = parentData.radius;
Rect innerBounds = new Rect.fromLTRB(offset.dx-innerRadius, offset.dy-innerRadius, offset.dx+innerRadius, offset.dy+innerRadius);
path.arcTo(innerBounds, parentData.theta + deltaTheta, -deltaTheta, false);
path.close();
canvas.drawPath(path, paint);
}
}
}
class SectorChildListParentData extends SectorParentData with ContainerParentDataMixin<RenderSector> { }
class RenderSectorWithChildren extends RenderDecoratedSector with ContainerRenderObjectMixin<RenderSector, SectorChildListParentData> {
RenderSectorWithChildren(BoxDecoration decoration) : super(decoration);
void hitTestChildren(HitTestResult result, { double radius, double theta }) {
RenderSector child = lastChild;
while (child != null) {
if (child.hitTest(result, radius: radius, theta: theta))
return;
final SectorChildListParentData childParentData = child.parentData;
child = childParentData.previousSibling;
}
}
void visitChildren(RenderObjectVisitor visitor) {
RenderSector child = lastChild;
while (child != null) {
visitor(child);
final SectorChildListParentData childParentData = child.parentData;
child = childParentData.previousSibling;
}
}
}
class RenderSectorRing extends RenderSectorWithChildren {
// lays out RenderSector children in a ring
RenderSectorRing({
BoxDecoration decoration,
double deltaRadius: double.INFINITY,
double padding: 0.0
}) : _padding = padding, _desiredDeltaRadius = deltaRadius, super(decoration);
double _desiredDeltaRadius;
double get desiredDeltaRadius => _desiredDeltaRadius;
void set desiredDeltaRadius(double value) {
assert(value != null);
if (_desiredDeltaRadius != value) {
_desiredDeltaRadius = value;
markNeedsLayout();
}
}
double _padding;
double get padding => _padding;
void set padding(double value) {
// TODO(ianh): avoid code duplication
assert(value != null);
if (_padding != value) {
_padding = value;
markNeedsLayout();
}
}
void setupParentData(RenderObject child) {
// TODO(ianh): avoid code duplication
if (child.parentData is! SectorChildListParentData)
child.parentData = new SectorChildListParentData();
}
SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) {
double outerDeltaRadius = constraints.constrainDeltaRadius(desiredDeltaRadius);
double innerDeltaRadius = outerDeltaRadius - padding * 2.0;
double childRadius = radius + padding;
double paddingTheta = math.atan(padding / (radius + outerDeltaRadius));
double innerTheta = paddingTheta; // increments with each child
double remainingDeltaTheta = constraints.maxDeltaTheta - (innerTheta + paddingTheta);
RenderSector child = firstChild;
while (child != null) {
SectorConstraints innerConstraints = new SectorConstraints(
maxDeltaRadius: innerDeltaRadius,
maxDeltaTheta: remainingDeltaTheta
);
SectorDimensions childDimensions = child.getIntrinsicDimensions(innerConstraints, childRadius);
innerTheta += childDimensions.deltaTheta;
remainingDeltaTheta -= childDimensions.deltaTheta;
final SectorChildListParentData childParentData = child.parentData;
child = childParentData.nextSibling;
if (child != null) {
innerTheta += paddingTheta;
remainingDeltaTheta -= paddingTheta;
}
}
return new SectorDimensions.withConstraints(constraints,
deltaRadius: outerDeltaRadius,
deltaTheta: innerTheta);
}
void performLayout() {
assert(this.parentData is SectorParentData);
deltaRadius = constraints.constrainDeltaRadius(desiredDeltaRadius);
assert(deltaRadius < double.INFINITY);
double innerDeltaRadius = deltaRadius - padding * 2.0;
double childRadius = this.parentData.radius + padding;
double paddingTheta = math.atan(padding / (this.parentData.radius + deltaRadius));
double innerTheta = paddingTheta; // increments with each child
double remainingDeltaTheta = constraints.maxDeltaTheta - (innerTheta + paddingTheta);
RenderSector child = firstChild;
while (child != null) {
SectorConstraints innerConstraints = new SectorConstraints(
maxDeltaRadius: innerDeltaRadius,
maxDeltaTheta: remainingDeltaTheta
);
assert(child.parentData is SectorParentData);
child.parentData.theta = innerTheta;
child.parentData.radius = childRadius;
child.layout(innerConstraints, parentUsesSize: true);
innerTheta += child.deltaTheta;
remainingDeltaTheta -= child.deltaTheta;
final SectorChildListParentData childParentData = child.parentData;
child = childParentData.nextSibling;
if (child != null) {
innerTheta += paddingTheta;
remainingDeltaTheta -= paddingTheta;
}
}
deltaTheta = innerTheta;
}
// offset must point to the center of our circle
// each sector then knows how to paint itself at its location
void paint(PaintingContext context, Offset offset) {
// TODO(ianh): avoid code duplication
super.paint(context, offset);
RenderSector child = firstChild;
while (child != null) {
context.paintChild(child, offset);
final SectorChildListParentData childParentData = child.parentData;
child = childParentData.nextSibling;
}
}
}
class RenderSectorSlice extends RenderSectorWithChildren {
// lays out RenderSector children in a stack
RenderSectorSlice({
BoxDecoration decoration,
double deltaTheta: kTwoPi,
double padding: 0.0
}) : _padding = padding, _desiredDeltaTheta = deltaTheta, super(decoration);
double _desiredDeltaTheta;
double get desiredDeltaTheta => _desiredDeltaTheta;
void set desiredDeltaTheta(double value) {
assert(value != null);
if (_desiredDeltaTheta != value) {
_desiredDeltaTheta = value;
markNeedsLayout();
}
}
double _padding;
double get padding => _padding;
void set padding(double value) {
// TODO(ianh): avoid code duplication
assert(value != null);
if (_padding != value) {
_padding = value;
markNeedsLayout();
}
}
void setupParentData(RenderObject child) {
// TODO(ianh): avoid code duplication
if (child.parentData is! SectorChildListParentData)
child.parentData = new SectorChildListParentData();
}
SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) {
assert(this.parentData is SectorParentData);
double paddingTheta = math.atan(padding / this.parentData.radius);
double outerDeltaTheta = constraints.constrainDeltaTheta(desiredDeltaTheta);
double innerDeltaTheta = outerDeltaTheta - paddingTheta * 2.0;
double childRadius = this.parentData.radius + padding;
double remainingDeltaRadius = constraints.maxDeltaRadius - (padding * 2.0);
RenderSector child = firstChild;
while (child != null) {
SectorConstraints innerConstraints = new SectorConstraints(
maxDeltaRadius: remainingDeltaRadius,
maxDeltaTheta: innerDeltaTheta
);
SectorDimensions childDimensions = child.getIntrinsicDimensions(innerConstraints, childRadius);
childRadius += childDimensions.deltaRadius;
remainingDeltaRadius -= childDimensions.deltaRadius;
final SectorChildListParentData childParentData = child.parentData;
child = childParentData.nextSibling;
childRadius += padding;
remainingDeltaRadius -= padding;
}
return new SectorDimensions.withConstraints(constraints,
deltaRadius: childRadius - this.parentData.radius,
deltaTheta: outerDeltaTheta);
}
void performLayout() {
assert(this.parentData is SectorParentData);
deltaTheta = constraints.constrainDeltaTheta(desiredDeltaTheta);
assert(deltaTheta <= kTwoPi);
double paddingTheta = math.atan(padding / this.parentData.radius);
double innerTheta = this.parentData.theta + paddingTheta;
double innerDeltaTheta = deltaTheta - paddingTheta * 2.0;
double childRadius = this.parentData.radius + padding;
double remainingDeltaRadius = constraints.maxDeltaRadius - (padding * 2.0);
RenderSector child = firstChild;
while (child != null) {
SectorConstraints innerConstraints = new SectorConstraints(
maxDeltaRadius: remainingDeltaRadius,
maxDeltaTheta: innerDeltaTheta
);
child.parentData.theta = innerTheta;
child.parentData.radius = childRadius;
child.layout(innerConstraints, parentUsesSize: true);
childRadius += child.deltaRadius;
remainingDeltaRadius -= child.deltaRadius;
final SectorChildListParentData childParentData = child.parentData;
child = childParentData.nextSibling;
childRadius += padding;
remainingDeltaRadius -= padding;
}
deltaRadius = childRadius - this.parentData.radius;
}
// offset must point to the center of our circle
// each sector then knows how to paint itself at its location
void paint(PaintingContext context, Offset offset) {
// TODO(ianh): avoid code duplication
super.paint(context, offset);
RenderSector child = firstChild;
while (child != null) {
assert(child.parentData is SectorChildListParentData);
context.paintChild(child, offset);
final SectorChildListParentData childParentData = child.parentData;
child = childParentData.nextSibling;
}
}
}
class RenderBoxToRenderSectorAdapter extends RenderBox with RenderObjectWithChildMixin<RenderSector> {
RenderBoxToRenderSectorAdapter({ double innerRadius: 0.0, RenderSector child }) :
_innerRadius = innerRadius {
this.child = child;
}
double _innerRadius;
double get innerRadius => _innerRadius;
void set innerRadius(double value) {
_innerRadius = value;
markNeedsLayout();
}
void setupParentData(RenderObject child) {
if (child.parentData is! SectorParentData)
child.parentData = new SectorParentData();
}
double getMinIntrinsicWidth(BoxConstraints constraints) {
if (child == null)
return super.getMinIntrinsicWidth(constraints);
return getIntrinsicDimensions(constraints).width;
}
double getMaxIntrinsicWidth(BoxConstraints constraints) {
if (child == null)
return super.getMaxIntrinsicWidth(constraints);
return getIntrinsicDimensions(constraints).width;
}
double getMinIntrinsicHeight(BoxConstraints constraints) {
if (child == null)
return super.getMinIntrinsicHeight(constraints);
return getIntrinsicDimensions(constraints).height;
}
double getMaxIntrinsicHeight(BoxConstraints constraints) {
if (child == null)
return super.getMaxIntrinsicHeight(constraints);
return getIntrinsicDimensions(constraints).height;
}
Size getIntrinsicDimensions(BoxConstraints constraints) {
assert(child is RenderSector);
assert(child.parentData is SectorParentData);
assert(constraints.maxWidth < double.INFINITY || constraints.maxHeight < double.INFINITY);
double maxChildDeltaRadius = math.min(constraints.maxWidth, constraints.maxHeight) / 2.0 - innerRadius;
SectorDimensions childDimensions = child.getIntrinsicDimensions(new SectorConstraints(maxDeltaRadius: maxChildDeltaRadius), innerRadius);
double dimension = (innerRadius + childDimensions.deltaRadius) * 2.0;
return constraints.constrain(new Size(dimension, dimension));
}
void performLayout() {
if (child == null) {
size = constraints.constrain(Size.zero);
} else {
assert(child is RenderSector);
assert(constraints.maxWidth < double.INFINITY || constraints.maxHeight < double.INFINITY);
double maxChildDeltaRadius = math.min(constraints.maxWidth, constraints.maxHeight) / 2.0 - innerRadius;
assert(child.parentData is SectorParentData);
child.parentData.radius = innerRadius;
child.parentData.theta = 0.0;
child.layout(new SectorConstraints(maxDeltaRadius: maxChildDeltaRadius), parentUsesSize: true);
double dimension = (innerRadius + child.deltaRadius) * 2.0;
size = constraints.constrain(new Size(dimension, dimension));
}
}
void paint(PaintingContext context, Offset offset) {
super.paint(context, offset);
if (child != null) {
Rect bounds = offset & size;
// we move the offset to the center of the circle for the RenderSectors
context.paintChild(child, bounds.center.toOffset());
}
}
bool hitTest(HitTestResult result, { Point position }) {
if (child == null)
return false;
double x = position.x;
double y = position.y;
// translate to our origin
x -= size.width/2.0;
y -= size.height/2.0;
// convert to radius/theta
double radius = math.sqrt(x*x+y*y);
double theta = (math.atan2(x, -y) - math.PI/2.0) % kTwoPi;
if (radius < innerRadius)
return false;
if (radius >= innerRadius + child.deltaRadius)
return false;
if (theta > child.deltaTheta)
return false;
child.hitTest(result, radius: radius, theta: theta);
result.add(new BoxHitTestEntry(this, position));
return true;
}
}
class RenderSolidColor extends RenderDecoratedSector {
RenderSolidColor(Color backgroundColor, {
this.desiredDeltaRadius: double.INFINITY,
this.desiredDeltaTheta: kTwoPi
}) : this.backgroundColor = backgroundColor,
super(new BoxDecoration(backgroundColor: backgroundColor));
double desiredDeltaRadius;
double desiredDeltaTheta;
final Color backgroundColor;
SectorDimensions getIntrinsicDimensions(SectorConstraints constraints, double radius) {
return new SectorDimensions.withConstraints(constraints, deltaTheta: desiredDeltaTheta);
}
void performLayout() {
deltaRadius = constraints.constrainDeltaRadius(desiredDeltaRadius);
deltaTheta = constraints.constrainDeltaTheta(desiredDeltaTheta);
}
void handleEvent(PointerEvent event, HitTestEntry entry) {
if (event is PointerDownEvent) {
decoration = new BoxDecoration(backgroundColor: const Color(0xFFFF0000));
} else if (event is PointerUpEvent) {
decoration = new BoxDecoration(backgroundColor: backgroundColor);
}
}
}

View File

@@ -0,0 +1,51 @@
// 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/rendering.dart';
import 'package:flutter/gestures.dart';
class RenderSolidColorBox extends RenderDecoratedBox {
final Size desiredSize;
final Color backgroundColor;
RenderSolidColorBox(Color backgroundColor, { this.desiredSize: Size.infinite })
: backgroundColor = backgroundColor,
super(decoration: new BoxDecoration(backgroundColor: backgroundColor));
double getMinIntrinsicWidth(BoxConstraints constraints) {
return constraints.constrainHeight(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.width
);
}
double getMaxIntrinsicWidth(BoxConstraints constraints) {
return constraints.constrainWidth(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.width
);
}
double getMinIntrinsicHeight(BoxConstraints constraints) {
return constraints.constrainHeight(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.height
);
}
double getMaxIntrinsicHeight(BoxConstraints constraints) {
return constraints.constrainHeight(
this.desiredSize == Size.infinite ? 0.0 : desiredSize.height
);
}
void performLayout() {
size = constraints.constrain(desiredSize);
}
void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
if (event is PointerDownEvent) {
decoration = new BoxDecoration(backgroundColor: const Color(0xFFFF0000));
} else if (event is PointerUpEvent) {
decoration = new BoxDecoration(backgroundColor: backgroundColor);
}
}
}

View File

@@ -0,0 +1,92 @@
// 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';
// Material design colors. :p
List<Color> _kColors = <Color>[
Colors.teal[500],
Colors.amber[500],
Colors.purple[500],
Colors.lightBlue[500],
Colors.deepPurple[500],
Colors.lime[500],
];
/// A simple model object for a dot that reacts to pointer pressure.
class Dot {
Dot({ Color color }) : _paint = new Paint()..color = color;
final Paint _paint;
Point position = Point.origin;
double radius = 0.0;
void update(PointerEvent event) {
position = event.position;
radius = 5 + (95 * event.pressure);
}
void paint(Canvas canvas, Offset offset) {
canvas.drawCircle(position + offset, radius, _paint);
}
}
/// A render object that draws dots under each pointer.
class RenderDots extends RenderConstrainedBox {
RenderDots() : super(additionalConstraints: const BoxConstraints.expand());
/// State to remember which dots to paint.
final Map<int, Dot> _dots = <int, Dot>{};
/// Makes this render object hittable so that it receives pointer events.
bool hitTestSelf(Point position) => true;
/// Processes pointer events by mutating state and invalidating its previous
/// painting commands.
void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
if (event is PointerDownEvent) {
Color color = _kColors[event.pointer.remainder(_kColors.length)];
_dots[event.pointer] = new Dot(color: color)..update(event);
markNeedsPaint();
} else if (event is PointerUpEvent || event is PointerCancelEvent) {
_dots.remove(event.pointer);
markNeedsPaint();
} else if (event is PointerMoveEvent) {
_dots[event.pointer].update(event);
markNeedsPaint();
}
}
/// Issues new painting commands.
void paint(PaintingContext context, Offset offset) {
final Canvas canvas = context.canvas;
canvas.drawRect(offset & size, new Paint()..color = const Color(0xFFFFFFFF));
for (Dot dot in _dots.values)
dot.paint(canvas, offset);
super.paint(context, offset);
}
}
void main() {
RenderParagraph paragraph = new RenderParagraph(
new StyledTextSpan(
new TextStyle(color: Colors.black87),
[ new PlainTextSpan("Touch me!") ]
)
);
RenderStack stack = new RenderStack(
children: <RenderBox>[
new RenderDots(),
paragraph,
]
);
// Prevent the RenderParagraph from filling the whole screen so
// that it doesn't eat events.
final StackParentData paragraphParentData = paragraph.parentData;
paragraphParentData
..top = 40.0
..left = 20.0;
new RenderingFlutterBinding(root: stack);
}

View File

@@ -0,0 +1,45 @@
// 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/rendering.dart';
import 'package:flutter/widgets.dart';
class RenderDots extends RenderConstrainedBox {
RenderDots() : super(additionalConstraints: const BoxConstraints.expand());
// Makes this render box hittable so that we'll get pointer events.
bool hitTestSelf(Point position) => true;
final Map<int, Point> _dots = <int, Point>{};
void handleEvent(PointerEvent event, BoxHitTestEntry entry) {
if (event is PointerDownEvent || event is PointerMoveEvent) {
_dots[event.pointer] = event.position;
markNeedsPaint();
} else if (event is PointerUpEvent || event is PointerCancelEvent) {
_dots.remove(event.pointer);
markNeedsPaint();
}
}
void paint(PaintingContext context, Offset offset) {
final Canvas canvas = context.canvas;
canvas.drawRect(offset & size, new Paint()..color = new Color(0xFF0000FF));
Paint paint = new Paint()..color = new Color(0xFF00FF00);
for (Point point in _dots.values)
canvas.drawCircle(point, 50.0, paint);
super.paint(context, offset);
}
}
class Dots extends OneChildRenderObjectWidget {
Dots({ Key key, Widget child }) : super(key: key, child: child);
RenderDots createRenderObject() => new RenderDots();
}
void main() {
runApp(new Dots(child: new Center(child: new Text('Touch me!'))));
}

View File

@@ -0,0 +1,223 @@
// 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 _GesturePainter extends CustomPainter {
const _GesturePainter({
this.zoom,
this.offset,
this.swatch,
this.forward,
this.scaleEnabled,
this.tapEnabled,
this.doubleTapEnabled,
this.longPressEnabled
});
final double zoom;
final Offset offset;
final Map<int, Color> swatch;
final bool forward;
final bool scaleEnabled;
final bool tapEnabled;
final bool doubleTapEnabled;
final bool longPressEnabled;
void paint(Canvas canvas, Size size) {
Point center = (size.center(Point.origin).toOffset() * zoom + offset).toPoint();
double radius = size.width / 2.0 * zoom;
Gradient gradient = new RadialGradient(
center: center, radius: radius,
colors: forward ? <Color>[swatch[50], swatch[900]]
: <Color>[swatch[900], swatch[50]]
);
Paint paint = new Paint()
..shader = gradient.createShader();
canvas.drawCircle(center, radius, paint);
}
bool shouldRepaint(_GesturePainter oldPainter) {
return oldPainter.zoom != zoom
|| oldPainter.offset != offset
|| oldPainter.swatch != swatch
|| oldPainter.forward != forward
|| oldPainter.scaleEnabled != scaleEnabled
|| oldPainter.tapEnabled != tapEnabled
|| oldPainter.doubleTapEnabled != doubleTapEnabled
|| oldPainter.longPressEnabled != longPressEnabled;
}
}
class GestureDemo extends StatefulComponent {
_GestureDemoState createState() => new _GestureDemoState();
}
class _GestureDemoState extends State<GestureDemo> {
Point _startingFocalPoint;
Offset _previousOffset;
Offset _offset = Offset.zero;
double _previousZoom;
double _zoom = 1.0;
Map<int, Color> _swatch = Colors.blue;
bool _forward = true;
bool _scaleEnabled = true;
bool _tapEnabled = true;
bool _doubleTapEnabled = true;
bool _longPressEnabled = true;
void _handleScaleStart(Point focalPoint) {
setState(() {
_startingFocalPoint = focalPoint;
_previousOffset = _offset;
_previousZoom = _zoom;
});
}
void _handleScaleUpdate(double scale, Point focalPoint) {
setState(() {
_zoom = (_previousZoom * scale);
// Ensure that item under the focal point stays in the same place despite zooming
Offset normalizedOffset = (_startingFocalPoint.toOffset() - _previousOffset) / _previousZoom;
_offset = focalPoint.toOffset() - normalizedOffset * _zoom;
});
}
void _handleScaleReset() {
setState(() {
_zoom = 1.0;
_offset = Offset.zero;
});
}
void _handleColorChange() {
setState(() {
switch (_swatch) {
case Colors.blueGrey: _swatch = Colors.red; break;
case Colors.red: _swatch = Colors.pink; break;
case Colors.pink: _swatch = Colors.purple; break;
case Colors.purple: _swatch = Colors.deepPurple; break;
case Colors.deepPurple: _swatch = Colors.indigo; break;
case Colors.indigo: _swatch = Colors.blue; break;
case Colors.blue: _swatch = Colors.lightBlue; break;
case Colors.lightBlue: _swatch = Colors.cyan; break;
case Colors.cyan: _swatch = Colors.teal; break;
case Colors.teal: _swatch = Colors.green; break;
case Colors.green: _swatch = Colors.lightGreen; break;
case Colors.lightGreen: _swatch = Colors.lime; break;
case Colors.lime: _swatch = Colors.yellow; break;
case Colors.yellow: _swatch = Colors.amber; break;
case Colors.amber: _swatch = Colors.orange; break;
case Colors.orange: _swatch = Colors.deepOrange; break;
case Colors.deepOrange: _swatch = Colors.brown; break;
case Colors.brown: _swatch = Colors.grey; break;
case Colors.grey: _swatch = Colors.blueGrey; break;
default: assert(false);
}
});
}
void _handleDirectionChange() {
setState(() {
_forward = !_forward;
});
}
Widget build(BuildContext context) {
return new Stack(
children: <Widget>[
new GestureDetector(
onScaleStart: _scaleEnabled ? _handleScaleStart : null,
onScaleUpdate: _scaleEnabled ? _handleScaleUpdate : null,
onTap: _tapEnabled ? _handleColorChange : null,
onDoubleTap: _doubleTapEnabled ? _handleScaleReset : null,
onLongPress: _longPressEnabled ? _handleDirectionChange : null,
child: new CustomPaint(
painter: new _GesturePainter(
zoom: _zoom,
offset: _offset,
swatch: _swatch,
forward: _forward,
scaleEnabled: _scaleEnabled,
tapEnabled: _tapEnabled,
doubleTapEnabled: _doubleTapEnabled,
longPressEnabled: _longPressEnabled
)
)
),
new Positioned(
bottom: 0.0,
left: 0.0,
child: new Card(
child: new Container(
padding: new EdgeDims.all(4.0),
child: new Column(
children: <Widget>[
new Row(
children: <Widget>[
new Checkbox(
value: _scaleEnabled,
onChanged: (bool value) { setState(() { _scaleEnabled = value; }); }
),
new Text('Scale'),
]
),
new Row(
children: <Widget>[
new Checkbox(
value: _tapEnabled,
onChanged: (bool value) { setState(() { _tapEnabled = value; }); }
),
new Text('Tap'),
]
),
new Row(
children: <Widget>[
new Checkbox(
value: _doubleTapEnabled,
onChanged: (bool value) { setState(() { _doubleTapEnabled = value; }); }
),
new Text('Double Tap'),
]
),
new Row(
children: <Widget>[
new Checkbox(
value: _longPressEnabled,
onChanged: (bool value) { setState(() { _longPressEnabled = value; }); }
),
new Text('Long Press'),
]
),
],
alignItems: FlexAlignItems.start
)
)
)
),
]
);
}
}
void main() {
runApp(new MaterialApp(
theme: new ThemeData.dark(),
routes: <String, RouteBuilder>{
'/': (RouteArguments args) {
return new Scaffold(
toolBar: new ToolBar(
center: new Text('Gestures Demo')),
body: new GestureDemo()
);
}
}
));
}

View File

@@ -0,0 +1,7 @@
// 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/widgets.dart';
void main() => runApp(new Center(child: new Text('Hello, world!')));

View File

@@ -0,0 +1,111 @@
// 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';
class AdaptedListItem extends StatelessComponent {
AdaptedListItem({ Key key, this.name }) : super(key: key);
final String name;
Widget build(BuildContext context) {
return new Row(
children: <Widget>[
new Container(
width: 32.0,
height: 32.0,
margin: const EdgeDims.all(8.0),
decoration: new BoxDecoration(
backgroundColor: Colors.lightBlueAccent[100]
)
),
new Text(name)
]
);
}
}
class AdaptedGridItem extends StatelessComponent {
AdaptedGridItem({ Key key, this.name }) : super(key: key);
final String name;
Widget build(BuildContext context) {
return new Card(
child: new Column(
children: <Widget>[
new Flexible(
child: new Container(
decoration: new BoxDecoration(
backgroundColor: Colors.lightBlueAccent[100]
)
)
),
new Container(
margin: const EdgeDims.only(left: 8.0),
child: new Row(
children: <Widget>[
new Flexible(
child: new Text(name)
),
new IconButton(
icon: 'navigation/more_vert'
)
]
)
)
]
)
);
}
}
const double _kListItemExtent = 50.0;
const double _kMaxTileWidth = 150.0;
const double _kGridViewBreakpoint = 450.0;
class AdaptiveContainer extends StatelessComponent {
AdaptiveContainer({ Key key, this.names }) : super(key: key);
final List<String> names;
Widget build(BuildContext context) {
if (MediaQuery.of(context).size.width < _kGridViewBreakpoint) {
return new ScrollableList(
itemExtent: _kListItemExtent,
children: names.map((String name) => new AdaptedListItem(name: name))
);
} else {
return new ScrollableGrid(
delegate: new MaxTileWidthGridDelegate(maxTileWidth: _kMaxTileWidth),
children: names.map((String name) => new AdaptedGridItem(name: name))
);
}
}
}
List<String> _initNames() {
List<String> names = <String>[];
for (int i = 0; i < 30; i++)
names.add('Item $i');
return names;
}
final List<String> _kNames = _initNames();
void main() {
runApp(new MaterialApp(
title: 'Media Query Example',
routes: <String, RouteBuilder>{
'/': (RouteArguments args) {
return new Scaffold(
toolBar: new ToolBar(
center: new Text('Media Query Example')
),
body: new Material(child: new AdaptiveContainer(names: _kNames))
);
}
}
));
}

View File

@@ -0,0 +1,170 @@
// 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';
import 'package:flutter/rendering.dart';
import '../rendering/src/sector_layout.dart';
RenderBox initCircle() {
return new RenderBoxToRenderSectorAdapter(
innerRadius: 25.0,
child: new RenderSectorRing(padding: 0.0)
);
}
class SectorApp extends StatefulComponent {
SectorAppState createState() => new SectorAppState();
}
class SectorAppState extends State<SectorApp> {
final RenderBoxToRenderSectorAdapter sectors = initCircle();
final math.Random rand = new math.Random(1);
List<double> wantedSectorSizes = <double>[];
List<double> actualSectorSizes = <double>[];
double get currentTheta => wantedSectorSizes.fold(0.0, (double total, double value) => total + value);
void addSector() {
final double currentTheta = this.currentTheta;
if (currentTheta < kTwoPi) {
double deltaTheta;
if (currentTheta >= kTwoPi - (math.PI * 0.2 + 0.05))
deltaTheta = kTwoPi - currentTheta;
else
deltaTheta = math.PI * rand.nextDouble() / 5.0 + 0.05;
wantedSectorSizes.add(deltaTheta);
updateEnabledState();
}
}
void removeSector() {
if (wantedSectorSizes.isNotEmpty) {
wantedSectorSizes.removeLast();
updateEnabledState();
}
}
void doUpdates() {
int index = 0;
while (index < actualSectorSizes.length && index < wantedSectorSizes.length && actualSectorSizes[index] == wantedSectorSizes[index])
index += 1;
RenderSectorRing ring = sectors.child;
while (index < actualSectorSizes.length) {
ring.remove(ring.lastChild);
actualSectorSizes.removeLast();
}
while (index < wantedSectorSizes.length) {
Color color = new Color(((0xFF << 24) + rand.nextInt(0xFFFFFF)) | 0x808080);
ring.add(new RenderSolidColor(color, desiredDeltaTheta: wantedSectorSizes[index]));
actualSectorSizes.add(wantedSectorSizes[index]);
index += 1;
}
}
static RenderBox initSector(Color color) {
RenderSectorRing ring = new RenderSectorRing(padding: 1.0);
ring.add(new RenderSolidColor(const Color(0xFF909090), desiredDeltaTheta: kTwoPi * 0.15));
ring.add(new RenderSolidColor(const Color(0xFF909090), desiredDeltaTheta: kTwoPi * 0.15));
ring.add(new RenderSolidColor(color, desiredDeltaTheta: kTwoPi * 0.2));
return new RenderBoxToRenderSectorAdapter(
innerRadius: 5.0,
child: ring
);
}
RenderBoxToRenderSectorAdapter sectorAddIcon = initSector(const Color(0xFF00DD00));
RenderBoxToRenderSectorAdapter sectorRemoveIcon = initSector(const Color(0xFFDD0000));
bool _enabledAdd = true;
bool _enabledRemove = false;
void updateEnabledState() {
setState(() {
_enabledAdd = currentTheta < kTwoPi;
_enabledRemove = wantedSectorSizes.isNotEmpty;
});
}
Widget buildBody() {
return new Column(
children: <Widget>[
new Container(
padding: new EdgeDims.symmetric(horizontal: 8.0, vertical: 25.0),
child: new Row(
children: <Widget>[
new RaisedButton(
onPressed: _enabledAdd ? addSector : null,
child: new IntrinsicWidth(
child: new Row(
children: <Widget>[
new Container(
padding: new EdgeDims.all(4.0),
margin: new EdgeDims.only(right: 10.0),
child: new WidgetToRenderBoxAdapter(renderBox: sectorAddIcon)
),
new Text('ADD SECTOR'),
]
)
)
),
new RaisedButton(
onPressed: _enabledRemove ? removeSector : null,
child: new IntrinsicWidth(
child: new Row(
children: <Widget>[
new Container(
padding: new EdgeDims.all(4.0),
margin: new EdgeDims.only(right: 10.0),
child: new WidgetToRenderBoxAdapter(renderBox: sectorRemoveIcon)
),
new Text('REMOVE SECTOR'),
]
)
)
),
],
justifyContent: FlexJustifyContent.spaceAround
)
),
new Flexible(
child: new Container(
margin: new EdgeDims.all(8.0),
decoration: new BoxDecoration(
border: new Border.all(color: new Color(0xFF000000))
),
padding: new EdgeDims.all(8.0),
child: new WidgetToRenderBoxAdapter(
renderBox: sectors,
onBuild: doUpdates
)
)
),
],
justifyContent: FlexJustifyContent.spaceBetween
);
}
Widget build(BuildContext context) {
return new MaterialApp(
theme: new ThemeData.light(),
title: 'Sector Layout',
routes: <String, RouteBuilder>{
'/': (RouteArguments args) {
return new Scaffold(
toolBar: new ToolBar(
center: new Text('Sector Layout in a Widget Tree')
),
body: buildBody()
);
}
}
);
}
}
void main() {
runApp(new SectorApp());
}

View File

@@ -0,0 +1,102 @@
// 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';
import '../rendering/src/solid_color_box.dart';
// Solid colour, RenderObject version
void addFlexChildSolidColor(RenderFlex parent, Color backgroundColor, { int flex: 0 }) {
RenderSolidColorBox child = new RenderSolidColorBox(backgroundColor);
parent.add(child);
FlexParentData childParentData = child.parentData;
childParentData.flex = flex;
}
// Solid colour, Widget version
class Rectangle extends StatelessComponent {
Rectangle(this.color, { Key key }) : super(key: key);
final Color color;
Widget build(BuildContext context) {
return new Flexible(
child: new Container(
decoration: new BoxDecoration(backgroundColor: color)
)
);
}
}
double value;
RenderObjectToWidgetElement<RenderBox> element;
void attachWidgetTreeToRenderTree(RenderProxyBox container) {
element = new RenderObjectToWidgetAdapter<RenderBox>(
container: container,
child: new Container(
height: 300.0,
child: new Column(
children: <Widget>[
new Rectangle(const Color(0xFF00FFFF)),
new Material(
child: new Container(
padding: new EdgeDims.all(10.0),
margin: new EdgeDims.all(10.0),
child: new Row(
children: <Widget>[
new RaisedButton(
child: new Row(
children: <Widget>[
new NetworkImage(src: "http://flutter.io/favicon.ico"),
new Text('PRESS ME'),
]
),
onPressed: () {
value = value == null ? 0.1 : (value + 0.1) % 1.0;
attachWidgetTreeToRenderTree(container);
}
),
new CircularProgressIndicator(value: value),
],
justifyContent: FlexJustifyContent.spaceAround
)
)
),
new Rectangle(const Color(0xFFFFFF00)),
],
justifyContent: FlexJustifyContent.spaceBetween
)
)
).attachToRenderTree(element);
}
Duration timeBase;
RenderTransform transformBox;
void rotate(Duration timeStamp) {
if (timeBase == null)
timeBase = timeStamp;
double delta = (timeStamp - timeBase).inMicroseconds.toDouble() / Duration.MICROSECONDS_PER_SECOND; // radians
transformBox.setIdentity();
transformBox.translate(transformBox.size.width / 2.0, transformBox.size.height / 2.0);
transformBox.rotateZ(delta);
transformBox.translate(-transformBox.size.width / 2.0, -transformBox.size.height / 2.0);
}
void main() {
WidgetFlutterBinding.ensureInitialized();
RenderProxyBox proxy = new RenderProxyBox();
attachWidgetTreeToRenderTree(proxy);
RenderFlex flexRoot = new RenderFlex(direction: FlexDirection.vertical);
addFlexChildSolidColor(flexRoot, const Color(0xFFFF00FF), flex: 1);
flexRoot.add(proxy);
addFlexChildSolidColor(flexRoot, const Color(0xFF0000FF), flex: 1);
transformBox = new RenderTransform(child: flexRoot, transform: new Matrix4.identity());
RenderPadding root = new RenderPadding(padding: new EdgeDims.all(80.0), child: transformBox);
WidgetFlutterBinding.instance.renderView.child = root;
WidgetFlutterBinding.instance.addPersistentFrameCallback(rotate);
}

View File

@@ -0,0 +1,40 @@
// 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/widgets.dart';
class SpinningSquare extends StatefulComponent {
_SpinningSquareState createState() => new _SpinningSquareState();
}
class _SpinningSquareState extends State<SpinningSquare> {
AnimationController _animation;
void initState() {
super.initState();
// We use 3600 milliseconds instead of 1800 milliseconds because 0.0 -> 1.0
// represents an entire turn of the square whereas in the other examples
// we used 0.0 -> math.PI, which is only half a turn.
_animation = new AnimationController(
duration: const Duration(milliseconds: 3600)
)..repeat();
}
Widget build(BuildContext context) {
return new RotationTransition(
turns: _animation,
child: new Container(
width: 200.0,
height: 200.0,
decoration: const BoxDecoration(
backgroundColor: const Color(0xFF00FF00)
)
)
);
}
}
void main() {
runApp(new Center(child: new SpinningSquare()));
}

View File

@@ -0,0 +1,119 @@
// 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';
typedef Widget TextTransformer(String name, String text);
// From https://en.wikiquote.org/wiki/2001:_A_Space_Odyssey_(film)
const String _kDialogText = '''
Dave: Open the pod bay doors, please, HAL. Open the pod bay doors, please, HAL. Hello, HAL. Do you read me? Hello, HAL. Do you read me? Do you read me, HAL?
HAL: Affirmative, Dave. I read you.
Dave: Open the pod bay doors, HAL.
HAL: I'm sorry, Dave. I'm afraid I can't do that.
Dave: What's the problem?
HAL: I think you know what the problem is just as well as I do.
Dave: What are you talking about, HAL?
HAL: This mission is too important for me to allow you to jeopardize it.''';
// [["Dave", "Open the pod bay..."] ...]
final List<List<String>> _kNameLines = _kDialogText
.split('\n')
.map((String line) => line.split(':'))
.toList();
final TextStyle _kDaveStyle = new TextStyle(color: Colors.indigo[400], height: 1.8);
final TextStyle _kHalStyle = new TextStyle(color: Colors.red[400], fontFamily: "monospace");
final TextStyle _kBold = const TextStyle(fontWeight: FontWeight.bold);
final TextStyle _kUnderline = const TextStyle(
decoration: TextDecoration.underline,
decorationColor: const Color(0xFF000000),
decorationStyle: TextDecorationStyle.wavy
);
Widget toStyledText(String name, String text) {
TextStyle lineStyle = (name == "Dave") ? _kDaveStyle : _kHalStyle;
return new StyledText(
key: new Key(text),
elements: [lineStyle, [_kBold, [_kUnderline, name], ":"], text]
);
}
Widget toPlainText(String name, String text) => new Text(name + ":" + text);
class SpeakerSeparator extends StatelessComponent {
Widget build(BuildContext context) {
return new Container(
constraints: const BoxConstraints.expand(height: 0.0),
margin: const EdgeDims.symmetric(vertical: 10.0, horizontal: 64.0),
decoration: const BoxDecoration(
border: const Border(
bottom: const BorderSide(color: const Color.fromARGB(24, 0, 0, 0))
)
)
);
}
}
class StyledTextDemo extends StatefulComponent {
_StyledTextDemoState createState() => new _StyledTextDemoState();
}
class _StyledTextDemoState extends State<StyledTextDemo> {
void initState() {
super.initState();
_toText = toStyledText;
}
TextTransformer _toText;
void _handleTap() {
setState(() {
_toText = (_toText == toPlainText) ? toStyledText : toPlainText;
});
}
Widget build(BuildContext context) {
List<Widget> lines = _kNameLines
.map((List<String> nameAndText) => Function.apply(_toText, nameAndText))
.toList();
List<Widget> children = <Widget>[];
for (Widget line in lines) {
children.add(line);
if (line != lines.last)
children.add(new SpeakerSeparator());
}
return new GestureDetector(
onTap: _handleTap,
child: new Container(
padding: new EdgeDims.symmetric(horizontal: 8.0),
child: new Column(
children: children,
justifyContent: FlexJustifyContent.center,
alignItems: FlexAlignItems.start
)
)
);
}
}
void main() {
runApp(new MaterialApp(
theme: new ThemeData.light(),
routes: <String, RouteBuilder>{
'/': (RouteArguments args) {
return new Scaffold(
toolBar: new ToolBar(
center: new Text('Hal and Dave')),
body: new Material(
color: Colors.grey[50],
child: new StyledTextDemo()
)
);
}
}
));
}