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

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