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

@@ -1,51 +0,0 @@
// 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 ContainerApp extends StatelessComponent {
Widget build(BuildContext context) {
return new Column(
children: <Widget>[
new Container(
padding: new EdgeDims.all(10.0),
margin: new EdgeDims.all(10.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFFCCCCCC)),
child: new NetworkImage(
src: "https://raw.githubusercontent.com/dart-lang/logos/master/logos_and_wordmarks/dart-logo.png",
width: 300.0,
height: 300.0
)
),
new Material(
color: const Color(0xFFFFFF00),
child: new Container(
padding: new EdgeDims.symmetric(horizontal: 50.0, vertical: 75.0),
child: new Row(
children: <Widget>[
new RaisedButton(
child: new Text('PRESS ME'),
onPressed: () => print("Hello World")
),
new RaisedButton(
child: new Text('DISABLED')
)
]
)
)
),
new Flexible(
child: new Container(
decoration: new BoxDecoration(backgroundColor: const Color(0xFF00FFFF))
)
),
],
justifyContent: FlexJustifyContent.spaceBetween
);
}
}
void main() {
runApp(new ContainerApp());
}

View File

@@ -1,42 +0,0 @@
// 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 _CustomRenderBox extends RenderConstrainedBox {
_CustomRenderBox() : 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(0xFF00FF00));
Paint paint = new Paint()..color = new Color(0xFF0000FF);
for (Point point in _dots.values)
canvas.drawCircle(point, 50.0, paint);
}
}
class _CustomRenderBoxWidget extends OneChildRenderObjectWidget {
_CustomRenderBox createRenderObject() => new _CustomRenderBox();
}
void main() {
runApp(new _CustomRenderBoxWidget());
}

View File

@@ -1,126 +0,0 @@
// 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.height, this.color);
int value;
double height;
Color color;
String get label => "Card $value";
Key get key => new ObjectKey(this);
}
typedef void TappableCardCallback(BuildContext context);
class TappableCard extends StatelessComponent {
TappableCard({ CardModel cardModel, this.selected, this.onTap })
: cardModel = cardModel, super(key: cardModel.key);
final CardModel cardModel;
final bool selected;
final TappableCardCallback onTap;
static const TextStyle cardLabelStyle = const TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold
);
static const TextStyle selectedCardLabelStyle = const TextStyle(
color: Colors.white,
fontSize: 24.0,
fontWeight: FontWeight.bold
);
Widget build(BuildContext context) {
return new GestureDetector(
onTap: () => onTap(context),
child: new Card(
color: cardModel.color,
child: new Container(
height: cardModel.height,
padding: const EdgeDims.all(8.0),
child: new Center(
child: new Text(
cardModel.label,
style: selected ? selectedCardLabelStyle : cardLabelStyle
)
)
)
)
);
}
}
class EnsureVisibleApp extends StatefulComponent {
EnsureVisibleAppState createState() => new EnsureVisibleAppState();
}
class EnsureVisibleAppState extends State<EnsureVisibleApp> {
List<CardModel> cardModels;
int selectedCardIndex;
void initState() {
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) {
Color color = Color.lerp(Colors.red[300], Colors.blue[900], i / cardHeights.length);
return new CardModel(i, cardHeights[i], color);
});
super.initState();
}
Widget builder(BuildContext context, int index) {
if (index >= cardModels.length)
return null;
return new TappableCard(
cardModel: cardModels[index],
selected: index == selectedCardIndex,
onTap: (BuildContext context) {
Scrollable.ensureVisible(context, duration: const Duration(milliseconds: 200))
.then((_) {
setState(() { selectedCardIndex = index; });
});
}
);
}
Widget build(BuildContext context) {
return new IconTheme(
data: const IconThemeData(color: IconThemeColor.white),
child: new Theme(
data: new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: Colors.blue,
accentColor: Colors.redAccent[200]
),
child: new Title(
title: 'Cards',
child: new Scaffold(
toolBar: new ToolBar(center: new Text('Tap a card, any card')),
body: new Container(
padding: const EdgeDims.symmetric(vertical: 12.0, horizontal: 8.0),
decoration: new BoxDecoration(backgroundColor: Theme.of(context).primarySwatch[50]),
child: new ScrollableMixedWidgetList(
builder: builder,
token: cardModels.length
)
)
)
)
)
);
}
}
void main() {
runApp(new EnsureVisibleApp());
}

View File

@@ -1,219 +0,0 @@
// 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';
class ScaleApp extends StatefulComponent {
ScaleAppState createState() => new ScaleAppState();
}
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 ScaleAppState extends State<ScaleApp> {
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 Theme(
data: new ThemeData.dark(),
child: new Scaffold(
toolBar: new ToolBar(
center: new Text('Gestures Demo')),
body: 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 ScaleApp());

View File

@@ -1,52 +0,0 @@
// 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 Circle extends StatelessComponent {
Circle({ this.margin: EdgeDims.zero });
final EdgeDims margin;
Widget build(BuildContext context) {
return new Container(
width: 50.0,
margin: margin + new EdgeDims.symmetric(horizontal: 2.0),
decoration: new BoxDecoration(
shape: BoxShape.circle,
backgroundColor: const Color(0xFF00FF00)
)
);
}
}
class HorizontalScrollingApp extends StatelessComponent {
Widget build(BuildContext context) {
List<Widget> circles = <Widget>[
new Circle(margin: new EdgeDims.only(left: 10.0)),
new Circle(),
new Circle(),
new Circle(),
new Circle(),
new Circle(),
new Circle(),
new Circle(),
new Circle(),
new Circle(),
new Circle(),
new Circle(margin: new EdgeDims.only(right: 10.0)),
];
return new Center(
child: new Container(
height: 50.0,
child: new Block(children: circles, scrollDirection: Axis.horizontal)
)
);
}
}
void main() {
runApp(new HorizontalScrollingApp());
}

View File

@@ -1,97 +0,0 @@
import 'package:flutter/material.dart';
void main() {
runApp(
new MaterialApp(
title: "Media Query Example",
routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new MediaQueryExample()
}
)
);
}
class AdaptiveItem {
AdaptiveItem(this.name);
String name;
Widget toListItem() {
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)
]
);
}
Widget toCard() {
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"
)
]
)
)
]
)
);
}
}
class MediaQueryExample extends StatelessComponent {
static const double _maxTileWidth = 150.0;
static const double _gridViewBreakpoint = 450.0;
Widget _buildBody(BuildContext context) {
List<AdaptiveItem> items = <AdaptiveItem>[];
for (int i = 0; i < 30; i++)
items.add(new AdaptiveItem("Item $i"));
if (MediaQuery.of(context).size.width < _gridViewBreakpoint) {
return new ScrollableList(
itemExtent: 50.0,
children: items.map((AdaptiveItem item) => item.toListItem())
);
} else {
return new ScrollableGrid(
delegate: new MaxTileWidthGridDelegate(maxTileWidth: _maxTileWidth),
children: items.map((AdaptiveItem item) => item.toCard())
);
}
}
Widget build(BuildContext context) {
return new Scaffold(
toolBar: new ToolBar(
center: new Text("Media Query Example")
),
body: new Material(
child: _buildBody(context)
)
);
}
}

View File

@@ -1,100 +0,0 @@
// 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 Home extends StatelessComponent {
Widget build(BuildContext context) {
return new Material(
child: new Center(
child: new Block(
children: <Widget>[
new Text(
'You are at home.',
style: Theme.of(context).text.display2.copyWith(textAlign: TextAlign.center)
),
new RaisedButton(
child: new Text('GO SHOPPING'),
onPressed: () => Navigator.pushNamed(context, '/shopping')
),
new RaisedButton(
child: new Text('START ADVENTURE'),
onPressed: () => Navigator.pushNamed(context, '/adventure')
)
],
padding: const EdgeDims.all(30.0)
)
)
);
}
}
class Shopping extends StatelessComponent {
Widget build(BuildContext context) {
return new Material(
color: Colors.deepPurple[300],
child: new Center(
child: new Block(
children: <Widget>[
new Text(
'Village Shop',
style: Theme.of(context).text.display2.copyWith(textAlign: TextAlign.center)
),
new RaisedButton(
child: new Text('RETURN HOME'),
onPressed: () => Navigator.pop(context)
),
new RaisedButton(
child: new Text('GO TO DUNGEON'),
onPressed: () => Navigator.pushNamed(context, '/adventure')
)
],
padding: const EdgeDims.all(30.0)
)
)
);
}
}
class Adventure extends StatelessComponent {
Widget build(BuildContext context) {
return new Material(
color: Colors.red[300],
child: new Center(
child: new Block(
children: <Widget>[
new Text(
'Monster\'s Lair',
style: Theme.of(context).text.display2.copyWith(textAlign: TextAlign.center)
),
new RaisedButton(
child: new Text('RUN!!!'),
onPressed: () => Navigator.pop(context)
)
],
padding: const EdgeDims.all(30.0)
)
)
);
}
}
final Map<String, RouteBuilder> routes = <String, RouteBuilder>{
'/': (_) => new Home(),
'/shopping': (_) => new Shopping(),
'/adventure': (_) => new Adventure(),
};
final ThemeData theme = new ThemeData(
brightness: ThemeBrightness.light,
primarySwatch: Colors.purple
);
void main() {
runApp(new MaterialApp(
title: 'Navigation Example',
theme: theme,
routes: routes
));
}

View File

@@ -1,13 +0,0 @@
// 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';
void main() {
runApp(new NetworkImage(
src: "http://38.media.tumblr.com/avatar_497c78dc767d_128.png",
fit: ImageFit.contain,
centerSlice: new Rect.fromLTRB(40.0, 40.0, 88.0, 88.0)
));
}

View File

@@ -1,170 +0,0 @@
// 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 'package:flutter_rendering_examples/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

@@ -1,113 +0,0 @@
// 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';
final List<Map<int, Color>> _kColors = <Map<int, Color>>[
Colors.amber,
Colors.yellow,
Colors.blue,
Colors.purple,
Colors.indigo,
Colors.deepOrange,
];
class SmoothBlock extends StatefulComponent {
SmoothBlock({ this.color });
final Map<int, Color> color;
SmoothBlockState createState() => new SmoothBlockState();
}
class CardTransition extends StatelessComponent {
CardTransition({
this.child,
this.animation,
this.x,
this.opacity,
this.scale
});
final Widget child;
final Animation<double> animation;
final Animatable<double> x;
final Animatable<double> opacity;
final Animatable<double> scale;
Widget build(BuildContext context) {
return new AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget child) {
double currentScale = scale.evaluate(animation);
Matrix4 transform = new Matrix4.identity()
..translate(x.evaluate(animation))
..scale(currentScale, currentScale);
return new Opacity(
opacity: opacity.evaluate(animation),
child: new Transform(
transform: transform,
child: child
)
);
},
child: child
);
}
}
class SmoothBlockState extends State<SmoothBlock> {
double _height = 100.0;
Widget _handleEnter(Animation<double> animation, Widget child) {
return new CardTransition(
x: new Tween<double>(begin: -200.0, end: 0.0),
opacity: new Tween<double>(begin: 0.0, end: 1.0),
scale: new Tween<double>(begin: 0.8, end: 1.0),
animation: new CurvedAnimation(parent: animation, curve: Curves.ease),
child: child
);
}
Widget _handleExit(Animation<double> animation, Widget child) {
return new CardTransition(
x: new Tween<double>(begin: 0.0, end: 200.0),
opacity: new Tween<double>(begin: 1.0, end: 0.0),
scale: new Tween<double>(begin: 1.0, end: 0.8),
animation: new CurvedAnimation(parent: animation, curve: Curves.ease),
child: child
);
}
Widget build(BuildContext context) {
return new GestureDetector(
onTap: () {
setState(() {
_height = _height == 100.0 ? 200.0 : 100.0;
});
},
child: new EnterExitTransition(
duration: const Duration(milliseconds: 1500),
onEnter: _handleEnter,
onExit: _handleExit,
child: new Container(
key: new ValueKey(_height),
height: _height,
decoration: new BoxDecoration(backgroundColor: config.color[_height.floor() * 4])
)
)
);
}
}
class SmoothResizeDemo extends StatelessComponent {
Widget build(BuildContext context) {
return new Block(children: _kColors.map((Map<int, Color> color) => new SmoothBlock(color: color)).toList());
}
}
void main() {
runApp(new SmoothResizeDemo());
}

View File

@@ -1,102 +0,0 @@
// 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 'package:flutter_rendering_examples/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

@@ -1,121 +0,0 @@
// 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';
typedef Widget TextTransformer(String name, String text);
class StyledTextApp extends StatefulComponent {
StyledTextAppState createState() => new StyledTextAppState();
}
class StyledTextAppState extends State<StyledTextApp> {
void initState() {
super.initState();
toText = toStyledText;
nameLines = dialogText
.split('\n')
.map((String line) => line.split(':'))
.toList();
}
TextTransformer toText;
// From https://en.wikiquote.org/wiki/2001:_A_Space_Odyssey_(film)
final String dialogText = '''
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..."] ...]
List<List<String>> nameLines;
final TextStyle daveStyle = new TextStyle(color: Colors.indigo[400], height: 1.8);
final TextStyle halStyle = new TextStyle(color: Colors.red[400], fontFamily: "monospace");
final TextStyle boldStyle = const TextStyle(fontWeight: FontWeight.bold);
final TextStyle underlineStyle = const TextStyle(
decoration: TextDecoration.underline,
decorationColor: const Color(0xFF000000),
decorationStyle: TextDecorationStyle.wavy
);
Widget toStyledText(String name, String text) {
TextStyle lineStyle = (name == "Dave") ? daveStyle : halStyle;
return new StyledText(
key: new Key(text),
elements: [lineStyle, [boldStyle, [underlineStyle, name], ":"], text]
);
}
Widget toPlainText(String name, String text) => new Text(name + ":" + text);
Widget createSeparator() {
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))
)
)
);
}
void toggleToTextFunction(_) {
setState(() {
toText = (toText == toPlainText) ? toStyledText : toPlainText;
});
}
Widget build(BuildContext context) {
List<Widget> lines = nameLines
.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(createSeparator());
}
}
Widget body = new Container(
padding: new EdgeDims.symmetric(horizontal: 8.0),
child: new Column(
children: children,
justifyContent: FlexJustifyContent.center,
alignItems: FlexAlignItems.start
)
);
Listener interactiveBody = new Listener(
child: body,
onPointerDown: toggleToTextFunction
);
return new Theme(
data: new ThemeData.light(),
child: new Scaffold(
body: new Material(
color: Colors.grey[50],
child: interactiveBody
),
toolBar: new ToolBar(
center: new Text('Hal and Dave')
)
)
);
}
}
void main() {
runApp(new StyledTextApp());
}