Strong modeify the examples

This makes skyanalyzer also check the examples, and fixes everything it
found there.
This commit is contained in:
Hixie 2015-10-22 13:29:12 -07:00
parent 1dbf9bc891
commit a6c473ea95
77 changed files with 598 additions and 564 deletions

View File

@ -17,7 +17,7 @@ class Field extends StatelessComponent {
final String placeholder;
Widget build(BuildContext context) {
return new Row([
return new Row(<Widget>[
new Padding(
padding: const EdgeDims.symmetric(horizontal: 16.0),
child: new Icon(type: icon, size: 24)
@ -37,7 +37,7 @@ class AddressBookHome extends StatelessComponent {
Widget buildToolBar(BuildContext context) {
return new ToolBar(
left: new IconButton(icon: "navigation/arrow_back"),
right: [new IconButton(icon: "navigation/check")]
right: <Widget>[new IconButton(icon: "navigation/check")]
);
}
@ -56,7 +56,7 @@ class AddressBookHome extends StatelessComponent {
static final GlobalKey noteKey = new GlobalKey(label: 'note field');
Widget buildBody(BuildContext context) {
return new Block([
return new Block(<Widget>[
new AspectRatio(
aspectRatio: 16.0 / 9.0,
child: new Container(

View File

@ -10,61 +10,59 @@ class DateUtils {
static const YESTERDAY = 'Yesterday';
static const MS_IN_WEEK =
DateTime.DAYS_PER_WEEK * Duration.MILLISECONDS_PER_DAY;
static const MS_IN_WEEK = DateTime.DAYS_PER_WEEK * Duration.MILLISECONDS_PER_DAY;
// TODO(jmesserly): locale specific date format
static String _twoDigits(int n) {
if (n >= 10) return "${n}";
return "0${n}";
if (n >= 10)
return '$n';
return '0$n';
}
/** Formats a time in H:MM A format */
/// Formats a time in H:MM A format
static String toHourMinutesString(Duration duration) {
assert(duration.inDays == 0);
int hours = duration.inHours;
String a;
if (hours >= 12) {
a = 'pm';
if (hours != 12) {
if (hours != 12)
hours -= 12;
}
} else {
a = 'am';
if (hours == 0) {
if (hours == 0)
hours += 12;
}
}
String twoDigits(int n) {
if (n >= 10) return "${n}";
return "0${n}";
if (n >= 10)
return '$n';
return '0$n';
}
String mm =
twoDigits(duration.inMinutes.remainder(Duration.MINUTES_PER_HOUR));
return "${hours}:${mm} ${a}";
String mm = twoDigits(duration.inMinutes.remainder(Duration.MINUTES_PER_HOUR));
return '$hours:$mm $a';
}
/**
* A date/time formatter that takes into account the current date/time:
* - if it's from today, just show the time
* - if it's from yesterday, just show 'Yesterday'
* - if it's from the same week, just show the weekday
* - otherwise, show just the date
*/
/// A date/time formatter that takes into account the current date/time:
/// - if it's from today, just show the time
/// - if it's from yesterday, just show 'Yesterday'
/// - if it's from the same week, just show the weekday
/// - otherwise, show just the date
static String toRecentTimeString(DateTime then) {
bool datesAreEqual(DateTime d1, DateTime d2) {
return (d1.year == d2.year) && (d1.month == d2.month) &&
(d1.day == d2.day);
return (d1.year == d2.year) &&
(d1.month == d2.month) &&
(d1.day == d2.day);
}
final now = new DateTime.now();
if (datesAreEqual(then, now)) {
return toHourMinutesString(new Duration(
days: 0,
hours: then.hour,
minutes: then.minute,
seconds: then.second,
milliseconds: then.millisecond));
days: 0,
hours: then.hour,
minutes: then.minute,
seconds: then.second,
milliseconds: then.millisecond)
);
}
final today = new DateTime(now.year, now.month, now.day, 0, 0, 0, 0);
@ -76,7 +74,7 @@ class DateUtils {
} else {
String twoDigitMonth = _twoDigits(then.month);
String twoDigitDay = _twoDigits(then.day);
return "${then.year}-${twoDigitMonth}-${twoDigitDay}";
return '${then.year}-$twoDigitMonth-$twoDigitDay';
}
}
@ -84,6 +82,6 @@ class DateUtils {
// TODO(jmesserly): locale specific date format
String twoDigitMonth = _twoDigits(then.month);
String twoDigitDay = _twoDigits(then.day);
return "${then.year}-${twoDigitMonth}-${twoDigitDay}";
return '${then.year}-$twoDigitMonth-$twoDigitDay';
}
}

View File

@ -18,7 +18,7 @@ class FitnessItemList extends StatelessComponent {
padding: const EdgeDims.all(4.0),
items: items,
itemExtent: kFitnessItemHeight,
itemBuilder: (_, item) => item.toRow(onDismissed: onDismissed)
itemBuilder: (BuildContext context, FitnessItem item) => item.toRow(onDismissed: onDismissed)
);
}
}
@ -68,7 +68,7 @@ class FeedFragmentState extends State<FeedFragment> {
void _showDrawer() {
showDrawer(
context: context,
child: new Block([
child: new Block(<Widget>[
new DrawerHeader(child: new Text('Fitness')),
new DrawerItem(
icon: 'action/view_list',
@ -120,7 +120,7 @@ class FeedFragmentState extends State<FeedFragment> {
context: context,
placeholderKey: _snackBarPlaceholderKey,
content: new Text("Item deleted."),
actions: [new SnackBarAction(label: "UNDO", onPressed: () {
actions: <SnackBarAction>[new SnackBarAction(label: "UNDO", onPressed: () {
config.onItemCreated(item);
config.navigator.pop();
})]
@ -172,7 +172,7 @@ class FeedFragmentState extends State<FeedFragment> {
return new Container();
if (config.userData.items.length == 0) {
return new Row(
[new Text("No data yet.\nAdd some!", style: style)],
<Widget>[new Text("No data yet.\nAdd some!", style: style)],
justifyContent: FlexJustifyContent.center
);
}
@ -225,7 +225,7 @@ class AddItemDialog extends StatefulComponent {
class AddItemDialogState extends State<AddItemDialog> {
// TODO(jackson): Internationalize
static final Map<String, String> _labels = {
static final Map<String, String> _labels = <String, String>{
'/measurements/new': 'Measure',
'/meals/new': 'Eat',
};
@ -239,9 +239,9 @@ class AddItemDialogState extends State<AddItemDialog> {
}
Widget build(BuildContext context) {
List<Widget> menuItems = [];
for(String routeName in _labels.keys) {
menuItems.add(new DialogMenuItem([
List<Widget> menuItems = <Widget>[];
for (String routeName in _labels.keys) {
menuItems.add(new DialogMenuItem(<Widget>[
new Flexible(child: new Text(_labels[routeName])),
new Radio(value: routeName, groupValue: _addItemRoute, onChanged: _handleAddItemRouteChanged),
], onPressed: () => _handleAddItemRouteChanged(routeName)));
@ -252,7 +252,7 @@ class AddItemDialogState extends State<AddItemDialog> {
onDismiss: () {
Navigator.of(context).pop();
},
actions: [
actions: <Widget>[
new FlatButton(
child: new Text('CANCEL'),
onPressed: () {

View File

@ -29,7 +29,7 @@ abstract class UserData {
class UserDataImpl extends UserData {
UserDataImpl();
List<FitnessItem> _items = [];
List<FitnessItem> _items = <FitnessItem>[];
BackupMode _backupMode;
BackupMode get backupMode => _backupMode;
@ -46,7 +46,7 @@ class UserDataImpl extends UserData {
List<FitnessItem> get items => _items;
void sort() {
_items.sort((a, b) => a.when.compareTo(b.when));
_items.sort((FitnessItem a, FitnessItem b) => a.when.compareTo(b.when));
}
void add(FitnessItem item) {
@ -69,14 +69,14 @@ class UserDataImpl extends UserData {
return mode.toString() == json['backupMode'];
});
} catch(e) {
print("Failed to load backup mode: ${e}");
print("Failed to load backup mode: $e");
}
_goalWeight = json['goalWeight'];
}
Map toJson() {
Map json = new Map();
json['items'] = _items.map((item) => item.toJson()).toList();
json['items'] = _items.map((FitnessItem item) => item.toJson()).toList();
json['backupMode'] = _backupMode.toString();
json['goalWeight'] = _goalWeight;
return json;
@ -132,7 +132,7 @@ class FitnessAppState extends State<FitnessApp> {
accentColor: Colors.pinkAccent[200]
),
title: 'Fitness',
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) {
return new FeedFragment(
navigator: args.navigator,

View File

@ -20,7 +20,7 @@ class MealRow extends FitnessItemRow {
Widget buildContent(BuildContext context) {
Meal meal = item;
List<Widget> children = [
List<Widget> children = <Widget>[
new Flexible(
child: new Text(
meal.description,
@ -65,7 +65,7 @@ class MealFragmentState extends State<MealFragment> {
icon: "navigation/close",
onPressed: config.navigator.pop),
center: new Text('New Meal'),
right: [
right: <Widget>[
// TODO(abarth): Should this be a FlatButton?
new InkWell(
onTap: _handleSave,
@ -85,10 +85,11 @@ class MealFragmentState extends State<MealFragment> {
Widget buildBody() {
Meal meal = new Meal(when: new DateTime.now());
// TODO(ianh): Fix Block such that we could use that here instead of rolling our own
return new ScrollableViewport(
child: new Container(
padding: const EdgeDims.all(20.0),
child: new BlockBody([
child: new BlockBody(<Widget>[
new Text(meal.displayDate),
new Input(
key: descriptionKey,

View File

@ -6,7 +6,7 @@ part of fitness;
class Measurement extends FitnessItem {
Measurement({ DateTime when, this.weight }) : super(when: when);
Measurement.fromJson(Map json) : super.fromJson(json), weight = json['weight'];
Measurement.fromJson(Map json) : weight = json['weight'], super.fromJson(json);
final double weight;
@ -32,7 +32,7 @@ class MeasurementRow extends FitnessItemRow {
Widget buildContent(BuildContext context) {
Measurement measurement = item;
List<Widget> children = [
List<Widget> children = <Widget>[
new Flexible(
child: new Text(
measurement.displayWeight,
@ -85,7 +85,7 @@ class MeasurementDateDialogState extends State<MeasurementDateDialog> {
onChanged: _handleDateChanged
),
contentPadding: EdgeDims.zero,
actions: [
actions: <Widget>[
new FlatButton(
child: new Text('CANCEL'),
onPressed: () {
@ -140,7 +140,7 @@ class MeasurementFragmentState extends State<MeasurementFragment> {
icon: "navigation/close",
onPressed: config.navigator.pop),
center: new Text('New Measurement'),
right: [
right: <Widget>[
// TODO(abarth): Should this be a FlatButton?
new InkWell(
onTap: _handleSave,
@ -175,12 +175,12 @@ class MeasurementFragmentState extends State<MeasurementFragment> {
// TODO(jackson): Revisit the layout of this pane to be more maintainable
return new Container(
padding: const EdgeDims.all(20.0),
child: new Column([
child: new Column(<Widget>[
new GestureDetector(
onTap: _handleDatePressed,
child: new Container(
height: 50.0,
child: new Column([
child: new Column(<Widget>[
new Text('Measurement Date'),
new Text(measurement.displayDate, style: Theme.of(context).text.caption),
], alignItems: FlexAlignItems.start)

View File

@ -74,7 +74,7 @@ class SettingsFragmentState extends State<SettingsFragment> {
onDismiss: () {
Navigator.of(context).pop();
},
actions: [
actions: <Widget>[
new FlatButton(
child: new Text('CANCEL'),
onPressed: () {
@ -94,20 +94,21 @@ class SettingsFragmentState extends State<SettingsFragment> {
}
Widget buildSettingsPane(BuildContext context) {
// TODO(ianh): Make Block capable of doing this
return new ScrollableViewport(
child: new Container(
padding: const EdgeDims.symmetric(vertical: 20.0),
child: new BlockBody([
child: new BlockBody(<Widget>[
new DrawerItem(
onPressed: () { _handleBackupChanged(!(config.userData.backupMode == BackupMode.enabled)); },
child: new Row([
child: new Row(<Widget>[
new Flexible(child: new Text('Back up data to the cloud')),
new Switch(value: config.userData.backupMode == BackupMode.enabled, onChanged: _handleBackupChanged),
])
),
new DrawerItem(
onPressed: () => _handleGoalWeightPressed(),
child: new Column([
child: new Column(<Widget>[
new Text('Goal Weight'),
new Text(goalWeightText, style: Theme.of(context).text.caption),
],

View File

@ -18,7 +18,7 @@ SpriteSheet _spriteSheet;
main() async {
_images = new ImageMap(_bundle);
await _images.load([
await _images.load(<String>[
'assets/checker.png',
'assets/line_effects.png'
]);
@ -45,7 +45,7 @@ class TestAppState extends State<TestApp> {
TestBed _testBed;
int _selectedLine = 0;
List<String> _labelTexts = [
List<String> _labelTexts = <String>[
"Colored",
"Smoke",
"Electric",
@ -56,14 +56,14 @@ class TestAppState extends State<TestApp> {
return new MaterialApp(
title: 'EffectLine Demo',
theme: _theme,
routes: {
routes: <String, RouteBuilder>{
'/': _buildColumn
}
);
}
Column _buildColumn(RouteArguments args) {
return new Column([
return new Column(<Widget>[
new Flexible(child: _buildSpriteWidget()),
_buildTabBar()
]);
@ -82,10 +82,9 @@ class TestAppState extends State<TestApp> {
}
List<TabLabel> _buildTabLabels() {
List<TabLabel> labels = [];
for(String text in _labelTexts) {
List<TabLabel> labels = <TabLabel>[];
for (String text in _labelTexts)
labels.add(new TabLabel(text: text));
}
return labels;
}
@ -168,7 +167,8 @@ class TestBed extends NodeWithSize {
}
bool handleEvent(SpriteBoxEvent event) {
if (event.type == "pointerdown") _line.points = [];
if (event.type == "pointerdown")
_line.points = <Point>[];
if (event.type == "pointerdown" || event.type == "pointermove") {
Point pos = convertPointToNodeSpace(event.boxPosition);

View File

@ -1,9 +1,11 @@
part of game;
typedef void PointSetterCallback(Point value);
class ActionCircularMove extends ActionInterval {
ActionCircularMove(this.setter, this.center, this.radius, this.startAngle, this.clockWise, double duration) : super (duration);
final Function setter;
final PointSetterCallback setter;
final Point center;
final double radius;
final double startAngle;
@ -21,7 +23,7 @@ class ActionCircularMove extends ActionInterval {
class ActionOscillate extends ActionInterval {
ActionOscillate(this.setter, this.center, this.radius, double duration) : super(duration);
final Function setter;
final PointSetterCallback setter;
final Point center;
final double radius;

View File

@ -31,7 +31,7 @@ class ExplosionBig extends Explosion {
ParticleSystem particlesFire = new ParticleSystem(
sheet["fire_particle.png"],
colorSequence: new ColorSequence([new Color(0xffffff33), new Color(0xffff3333), new Color(0x00ff3333)], [0.0, 0.5, 1.0]),
colorSequence: new ColorSequence(<Color>[new Color(0xffffff33), new Color(0xffff3333), new Color(0x00ff3333)], <double>[0.0, 0.5, 1.0]),
numParticlesToEmit: 25,
emissionRate: 1000.0,
startSize: 0.5,
@ -48,32 +48,32 @@ class ExplosionBig extends Explosion {
addChild(particlesFire);
// Add ring
Sprite sprtRing = new Sprite(sheet["explosion_ring.png"]);
sprtRing.transferMode = ui.TransferMode.plus;
addChild(sprtRing);
Sprite spriteRing = new Sprite(sheet["explosion_ring.png"]);
spriteRing.transferMode = ui.TransferMode.plus;
addChild(spriteRing);
Action scale = new ActionTween( (a) => sprtRing.scale = a, 0.2, 1.0, 0.75);
Action scaleAndRemove = new ActionSequence([scale, new ActionRemoveNode(sprtRing)]);
Action fade = new ActionTween( (a) => sprtRing.opacity = a, 1.0, 0.0, 0.75);
Action scale = new ActionTween((double a) { spriteRing.scale = a; }, 0.2, 1.0, 0.75);
Action scaleAndRemove = new ActionSequence(<Action>[scale, new ActionRemoveNode(spriteRing)]);
Action fade = new ActionTween((double a) { spriteRing.opacity = a; }, 1.0, 0.0, 0.75);
actions.run(scaleAndRemove);
actions.run(fade);
// Add streaks
for (int i = 0; i < 5; i++) {
Sprite sprtFlare = new Sprite(sheet["explosion_flare.png"]);
sprtFlare.pivot = new Point(0.3, 1.0);
sprtFlare.scaleX = 0.3;
sprtFlare.transferMode = ui.TransferMode.plus;
sprtFlare.rotation = randomDouble() * 360.0;
addChild(sprtFlare);
Sprite spriteFlare = new Sprite(sheet["explosion_flare.png"]);
spriteFlare.pivot = new Point(0.3, 1.0);
spriteFlare.scaleX = 0.3;
spriteFlare.transferMode = ui.TransferMode.plus;
spriteFlare.rotation = randomDouble() * 360.0;
addChild(spriteFlare);
double multiplier = randomDouble() * 0.3 + 1.0;
Action scale = new ActionTween( (a) => sprtFlare.scaleY = a, 0.3 * multiplier, 0.8, 0.75 * multiplier);
Action scaleAndRemove = new ActionSequence([scale, new ActionRemoveNode(sprtFlare)]);
Action fadeIn = new ActionTween( (a) => sprtFlare.opacity = a, 0.0, 1.0, 0.25 * multiplier);
Action fadeOut = new ActionTween( (a) => sprtFlare.opacity = a, 1.0, 0.0, 0.5 * multiplier);
Action fadeInOut = new ActionSequence([fadeIn, fadeOut]);
Action scale = new ActionTween((double a) { spriteFlare.scaleY = a; }, 0.3 * multiplier, 0.8, 0.75 * multiplier);
Action scaleAndRemove = new ActionSequence(<Action>[scale, new ActionRemoveNode(spriteFlare)]);
Action fadeIn = new ActionTween((double a) { spriteFlare.opacity = a; }, 0.0, 1.0, 0.25 * multiplier);
Action fadeOut = new ActionTween((double a) { spriteFlare.opacity = a; }, 1.0, 0.0, 0.5 * multiplier);
Action fadeInOut = new ActionSequence(<Action>[fadeIn, fadeOut]);
actions.run(scaleAndRemove);
actions.run(fadeInOut);
}
@ -96,14 +96,14 @@ class ExplosionMini extends Explosion {
rotationEnd = -rotationEnd;
}
ActionTween rotate = new ActionTween((a) => star.rotation = a, rotationStart, rotationEnd, 0.2);
ActionTween rotate = new ActionTween((double a) { star.rotation = a; }, rotationStart, rotationEnd, 0.2);
actions.run(rotate);
ActionTween fade = new ActionTween((a) => star.opacity = a, 1.0, 0.0, 0.2);
ActionTween fade = new ActionTween((double a) { star.opacity = a; }, 1.0, 0.0, 0.2);
actions.run(fade);
}
ActionSequence seq = new ActionSequence([new ActionDelay(0.2), new ActionRemoveNode(this)]);
ActionSequence seq = new ActionSequence(<Action>[new ActionDelay(0.2), new ActionRemoveNode(this)]);
actions.run(seq);
}
}

View File

@ -2,8 +2,8 @@ part of game;
class Flash extends NodeWithSize {
Flash(Size size, this.duration) : super(size) {
ActionTween fade = new ActionTween((a) => _opacity = a, 1.0, 0.0, duration);
ActionSequence seq = new ActionSequence([fade, new ActionRemoveNode(this)]);
ActionTween fade = new ActionTween((double a) { _opacity = a; }, 1.0, 0.0, duration);
ActionSequence seq = new ActionSequence(<Action>[fade, new ActionRemoveNode(this)]);
actions.run(seq);
}

View File

@ -8,6 +8,8 @@ final int _chunksPerLevel = 9;
final bool _drawDebug = false;
typedef void GameOverCallback(int score);
class GameDemoNode extends NodeWithSize {
GameDemoNode(
@ -66,7 +68,7 @@ class GameDemoNode extends NodeWithSize {
SoundEffectPlayer _effectPlayer = SoundEffectPlayer.sharedInstance();
// Callback
Function _gameOverCallback;
GameOverCallback _gameOverCallback;
// Game screen nodes
Node _gameScreen;
@ -133,12 +135,12 @@ class GameDemoNode extends NodeWithSize {
if (_gameOver) return;
// Check for collisions between lasers and objects that can take damage
List<Laser> lasers = [];
List<Laser> lasers = <Laser>[];
for (Node node in _level.children) {
if (node is Laser) lasers.add(node);
}
List<GameObject> damageables = [];
List<GameObject> damageables = <GameObject>[];
for (Node node in _level.children) {
if (node is GameObject && node.canBeDamaged) damageables.add(node);
}
@ -154,7 +156,7 @@ class GameDemoNode extends NodeWithSize {
}
// Check for collsions between ship and objects that can damage the ship
List<Node> nodes = new List.from(_level.children);
List<Node> nodes = new List<Node>.from(_level.children);
for (Node node in nodes) {
if (node is GameObject && node.canDamageShip) {
if (node.collidingWith(_level.ship)) {

View File

@ -104,15 +104,15 @@ class LevelLabel extends GameObject {
class Ship extends GameObject {
Ship(GameObjectFactory f) : super(f) {
// Add main ship sprite
_sprt = new Sprite(f.sheet["ship.png"]);
_sprt.scale = 0.3;
_sprt.rotation = -90.0;
addChild(_sprt);
_sprite = new Sprite(f.sheet["ship.png"]);
_sprite.scale = 0.3;
_sprite.rotation = -90.0;
addChild(_sprite);
_sprtShield = new Sprite(f.sheet["shield.png"]);
_sprtShield.scale = 0.35;
_sprtShield.transferMode = ui.TransferMode.plus;
addChild(_sprtShield);
_spriteShield = new Sprite(f.sheet["shield.png"]);
_spriteShield.scale = 0.35;
_spriteShield.transferMode = ui.TransferMode.plus;
addChild(_spriteShield);
radius = 20.0;
canBeDamaged = false;
@ -122,8 +122,8 @@ class Ship extends GameObject {
position = new Point(0.0, 50.0);
}
Sprite _sprt;
Sprite _sprtShield;
Sprite _sprite;
Sprite _spriteShield;
void applyThrust(Point joystickValue, double scroll) {
Point oldPos = position;
@ -136,19 +136,19 @@ class Ship extends GameObject {
}
void setupActions() {
ActionTween rotate = new ActionTween((a) => _sprtShield.rotation = a, 0.0, 360.0, 1.0);
_sprtShield.actions.run(new ActionRepeatForever(rotate));
ActionTween rotate = new ActionTween((double a) { _spriteShield.rotation = a; }, 0.0, 360.0, 1.0);
_spriteShield.actions.run(new ActionRepeatForever(rotate));
}
void update(double dt) {
// Update shield
if (f.playerState.shieldActive) {
if (f.playerState.shieldDeactivating)
_sprtShield.visible = !_sprtShield.visible;
_spriteShield.visible = !_spriteShield.visible;
else
_sprtShield.visible = true;
_spriteShield.visible = true;
} else {
_sprtShield.visible = false;
_spriteShield.visible = false;
}
}
}
@ -156,7 +156,7 @@ class Ship extends GameObject {
class Laser extends GameObject {
double impact = 0.0;
final List<Color> laserColors = [
final List<Color> laserColors = <Color>[
new Color(0xff95f4fb),
new Color(0xff5bff35),
new Color(0xffff886c),
@ -183,14 +183,14 @@ class Laser extends GameObject {
Color laserColor = laserColors[(level ~/ 3) % laserColors.length];
// Add sprites
List<Sprite> sprites = [];
List<Sprite> sprites = <Sprite>[];
for (int i = 0; i < numLasers; i++) {
Sprite sprt = new Sprite(f.sheet["explosion_particle.png"]);
sprt.scale = 0.5;
sprt.colorOverlay = laserColor;
sprt.transferMode = ui.TransferMode.plus;
addChild(sprt);
sprites.add(sprt);
Sprite sprite = new Sprite(f.sheet["explosion_particle.png"]);
sprite.scale = 0.5;
sprite.colorOverlay = laserColor;
sprite.transferMode = ui.TransferMode.plus;
addChild(sprite);
sprites.add(sprite);
}
// Position the individual sprites
@ -237,21 +237,21 @@ abstract class Obstacle extends GameObject {
abstract class Asteroid extends Obstacle {
Asteroid(GameObjectFactory f) : super(f);
Sprite _sprt;
Sprite _sprite;
void setupActions() {
// Rotate obstacle
int direction = 1;
if (randomBool()) direction = -1;
ActionTween rotate = new ActionTween(
(a) => _sprt.rotation = a,
(double a) { _sprite.rotation = a; },
0.0, 360.0 * direction, 5.0 + 5.0 * randomDouble());
_sprt.actions.run(new ActionRepeatForever(rotate));
_sprite.actions.run(new ActionRepeatForever(rotate));
}
set damage(double d) {
super.damage = d;
_sprt.colorOverlay = colorForDamage(d, maxDamage);
_sprite.colorOverlay = colorForDamage(d, maxDamage);
}
Collectable createPowerUp() {
@ -261,21 +261,21 @@ abstract class Asteroid extends Obstacle {
class AsteroidBig extends Asteroid {
AsteroidBig(GameObjectFactory f) : super(f) {
_sprt = new Sprite(f.sheet["asteroid_big_${randomInt(3)}.png"]);
_sprt.scale = 0.3;
_sprite = new Sprite(f.sheet["asteroid_big_${randomInt(3)}.png"]);
_sprite.scale = 0.3;
radius = 25.0;
maxDamage = 5.0;
addChild(_sprt);
addChild(_sprite);
}
}
class AsteroidSmall extends Asteroid {
AsteroidSmall(GameObjectFactory f) : super(f) {
_sprt = new Sprite(f.sheet["asteroid_small_${randomInt(3)}.png"]);
_sprt.scale = 0.3;
_sprite = new Sprite(f.sheet["asteroid_small_${randomInt(3)}.png"]);
_sprite.scale = 0.3;
radius = 12.0;
maxDamage = 3.0;
addChild(_sprt);
addChild(_sprite);
}
}
@ -289,13 +289,13 @@ class AsteroidPowerUp extends AsteroidBig {
class EnemyScout extends Obstacle {
EnemyScout(GameObjectFactory f) : super(f) {
_sprt = new Sprite(f.sheet["enemy_scout_0.png"]);
_sprt.scale = 0.32;
_sprite = new Sprite(f.sheet["enemy_scout_0.png"]);
_sprite.scale = 0.32;
radius = 12.0;
maxDamage = 1.0;
addChild(_sprt);
addChild(_sprite);
constraints = [new ConstraintRotationToMovement(dampening: 0.5)];
constraints = <Constraint>[new ConstraintRotationToMovement(dampening: 0.5)];
}
final double _swirlSpacing = 80.0;
@ -305,7 +305,7 @@ class EnemyScout extends Obstacle {
double yMove = (randomBool()) ? _swirlSpacing : -_swirlSpacing;
if (randomBool()) {
offsets.addAll([
offsets.addAll(<Offset>[
new Offset(x, y),
new Offset(xMove + x, y),
new Offset(xMove + x, yMove + y),
@ -313,7 +313,7 @@ class EnemyScout extends Obstacle {
new Offset(x, y)
]);
} else {
offsets.addAll([
offsets.addAll(<Offset>[
new Offset(x, y),
new Offset(x, y + yMove),
new Offset(xMove + x, yMove + y),
@ -325,17 +325,17 @@ class EnemyScout extends Obstacle {
void setupActions() {
List<Offset> offsets = [];
List<Offset> offsets = <Offset>[];
_addRandomSquare(offsets, -_swirlSpacing, 0.0);
_addRandomSquare(offsets, _swirlSpacing, 0.0);
offsets.add(new Offset(-_swirlSpacing, 0.0));
List<Point> points = [];
List<Point> points = <Point>[];
for (Offset offset in offsets) {
points.add(position + offset);
}
ActionSpline spline = new ActionSpline((a) => position = a, points, 6.0);
ActionSpline spline = new ActionSpline((Point a) => position = a, points, 6.0);
spline.tension = 0.7;
actions.run(new ActionRepeatForever(spline));
}
@ -344,25 +344,25 @@ class EnemyScout extends Obstacle {
return new Coin(f);
}
Sprite _sprt;
Sprite _sprite;
}
class EnemyDestroyer extends Obstacle {
EnemyDestroyer(GameObjectFactory f) : super(f) {
_sprt = new Sprite(f.sheet["enemy_destroyer_1.png"]);
_sprt.scale = 0.32;
_sprite = new Sprite(f.sheet["enemy_destroyer_1.png"]);
_sprite.scale = 0.32;
radius = 24.0;
maxDamage = 4.0;
addChild(_sprt);
addChild(_sprite);
constraints = [new ConstraintRotationToNode(f.level.ship, dampening: 0.05)];
constraints = <Constraint>[new ConstraintRotationToNode(f.level.ship, dampening: 0.05)];
}
int _countDown = randomInt(120) + 240;
void setupActions() {
ActionCircularMove circle = new ActionCircularMove(
(a) => position = a,
(Point a) { position = a; },
position, 40.0,
360.0 * randomDouble(),
randomBool(),
@ -388,19 +388,19 @@ class EnemyDestroyer extends Obstacle {
set damage(double d) {
super.damage = d;
_sprt.colorOverlay = colorForDamage(d, maxDamage);
_sprite.colorOverlay = colorForDamage(d, maxDamage);
}
Sprite _sprt;
Sprite _sprite;
}
class EnemyLaser extends Obstacle {
EnemyLaser(GameObjectFactory f, double rotation, double speed, Color color) : super(f) {
_sprt = new Sprite(f.sheet["explosion_particle.png"]);
_sprt.scale = 0.5;
_sprt.rotation = rotation + 90;
_sprt.colorOverlay = color;
addChild(_sprt);
_sprite = new Sprite(f.sheet["explosion_particle.png"]);
_sprite.scale = 0.5;
_sprite.rotation = rotation + 90;
_sprite.colorOverlay = color;
addChild(_sprite);
canDamageShip = true;
canBeDamaged = false;
@ -409,7 +409,7 @@ class EnemyLaser extends Obstacle {
_movement = new Offset(math.cos(rad) * speed, math.sin(rad) * speed);
}
Sprite _sprt;
Sprite _sprite;
Offset _movement;
void move() {
@ -420,24 +420,24 @@ class EnemyLaser extends Obstacle {
class EnemyBoss extends Obstacle {
EnemyBoss(GameObjectFactory f) : super(f) {
radius = 48.0;
_sprt = new Sprite(f.sheet["enemy_destroyer_1.png"]);
_sprt.scale = 0.64;
addChild(_sprt);
_sprite = new Sprite(f.sheet["enemy_destroyer_1.png"]);
_sprite.scale = 0.64;
addChild(_sprite);
maxDamage = 40.0;
constraints = [new ConstraintRotationToNode(f.level.ship, dampening: 0.05)];
constraints = <Constraint>[new ConstraintRotationToNode(f.level.ship, dampening: 0.05)];
_powerBar = new PowerBar(new Size(60.0, 10.0));
_powerBar.pivot = new Point(0.5, 0.5);
f.level.addChild(_powerBar);
_powerBar.constraints = [new ConstraintPositionToNode(
_powerBar.constraints = <Constraint>[new ConstraintPositionToNode(
this,
dampening: 0.5,
offset: new Offset(0.0, -70.0)
)];
}
Sprite _sprt;
Sprite _sprite;
PowerBar _powerBar;
int _countDown = randomInt(120) + 240;
@ -466,7 +466,7 @@ class EnemyBoss extends Obstacle {
}
void setupActions() {
ActionOscillate oscillate = new ActionOscillate((a) => position = a, position, 120.0, 3.0);
ActionOscillate oscillate = new ActionOscillate((Point a) { position = a; }, position, 120.0, 3.0);
actions.run(new ActionRepeatForever(oscillate));
}
@ -497,9 +497,9 @@ class EnemyBoss extends Obstacle {
set damage(double d) {
super.damage = d;
_sprt.actions.stopAll();
_sprt.actions.run(new ActionTween(
(a) =>_sprt.colorOverlay = a,
_sprite.actions.stopAll();
_sprite.actions.run(new ActionTween(
(Color a) { _sprite.colorOverlay = a; },
new Color.fromARGB(180, 255, 3, 86),
new Color(0x00000000),
0.3
@ -521,24 +521,24 @@ class Collectable extends GameObject {
class Coin extends Collectable {
Coin(GameObjectFactory f) : super(f) {
_sprt = new Sprite(f.sheet["coin.png"]);
_sprt.scale = 0.7;
addChild(_sprt);
_sprite = new Sprite(f.sheet["coin.png"]);
_sprite.scale = 0.7;
addChild(_sprite);
radius = 7.5;
}
void setupActions() {
// Rotate
ActionTween rotate = new ActionTween((a) => _sprt.rotation = a, 0.0, 360.0, 1.0);
ActionTween rotate = new ActionTween((double a) { _sprite.rotation = a; }, 0.0, 360.0, 1.0);
actions.run(new ActionRepeatForever(rotate));
// Fade in
ActionTween fadeIn = new ActionTween((a) => _sprt.opacity = a, 0.0, 1.0, 0.6);
ActionTween fadeIn = new ActionTween((double a) { _sprite.opacity = a; }, 0.0, 1.0, 0.6);
actions.run(fadeIn);
}
Sprite _sprt;
Sprite _sprite;
void collect() {
f.playerState.addCoin(this);
@ -553,7 +553,7 @@ enum PowerUpType {
speedBoost,
}
List<PowerUpType> _powerUpTypes = new List.from(PowerUpType.values);
List<PowerUpType> _powerUpTypes = new List<PowerUpType>.from(PowerUpType.values);
int _lastPowerUp = _powerUpTypes.length;
PowerUpType nextPowerUpType() {
@ -570,22 +570,22 @@ PowerUpType nextPowerUpType() {
class PowerUp extends Collectable {
PowerUp(GameObjectFactory f, this.type) : super(f) {
_sprt = new Sprite(f.sheet["coin.png"]);
_sprt.scale = 1.2;
addChild(_sprt);
_sprite = new Sprite(f.sheet["coin.png"]);
_sprite.scale = 1.2;
addChild(_sprite);
radius = 10.0;
}
Sprite _sprt;
Sprite _sprite;
PowerUpType type;
void setupActions() {
ActionTween rotate = new ActionTween((a) => _sprt.rotation = a, 0.0, 360.0, 1.0);
ActionTween rotate = new ActionTween((double a) { _sprite.rotation = a; }, 0.0, 360.0, 1.0);
actions.run(new ActionRepeatForever(rotate));
// Fade in
ActionTween fadeIn = new ActionTween((a) => _sprt.opacity = a, 0.0, 1.0, 0.6);
ActionTween fadeIn = new ActionTween((double a) { _sprite.opacity = a; }, 0.0, 1.0, 0.6);
actions.run(fadeIn);
}

View File

@ -23,7 +23,7 @@ final AssetBundle _bundle = _initBundle();
ImageMap _imageMap;
SpriteSheet _spriteSheet;
SpriteSheet _spriteSheetUI;
Map<String,SoundEffect> _sounds = {};
Map<String, SoundEffect> _sounds = <String, SoundEffect>{};
main() async {
_imageMap = new ImageMap(_bundle);
@ -31,7 +31,7 @@ main() async {
// Use a list to wait on all loads in parallel just before starting the app.
List loads = [];
loads.add(_imageMap.load([
loads.add(_imageMap.load(<String>[
'assets/nebula.png',
'assets/sprites.png',
'assets/starfield.png',
@ -84,7 +84,7 @@ class GameDemoState extends State<GameDemo> {
return new MaterialApp(
title: 'Asteroids',
theme: _theme,
routes: {
routes: <String, RouteBuilder>{
'/': _buildMainScene,
'/game': _buildGameScene
}
@ -96,9 +96,9 @@ class GameDemoState extends State<GameDemo> {
}
Widget _buildMainScene(RouteArguments args) {
return new Stack([
return new Stack(<Widget>[
new SpriteWidget(new MainScreenBackground(), SpriteBoxTransformMode.fixedWidth),
new Column([
new Column(<Widget>[
new TextureButton(
onPressed: () {
_game = new GameDemoNode(
@ -106,8 +106,8 @@ class GameDemoState extends State<GameDemo> {
_spriteSheet,
_spriteSheetUI,
_sounds,
(lastScore) {
setState(() {_lastScore = lastScore;});
(int lastScore) {
setState(() { _lastScore = lastScore; });
args.navigator.pop();
}
);
@ -141,7 +141,7 @@ class TextureButton extends StatefulComponent {
this.height: 128.0
}) : super(key: key);
final Function onPressed;
final GestureTapCallback onPressed;
final Texture texture;
final Texture textureDown;
final double width;

View File

@ -3,26 +3,26 @@ part of game;
class PlayerState extends Node {
PlayerState(this._sheetUI, this._sheetGame) {
// Score display
_sprtBgScore = new Sprite(_sheetUI["scoreboard.png"]);
_sprtBgScore.pivot = new Point(1.0, 0.0);
_sprtBgScore.scale = 0.35;
_sprtBgScore.position = new Point(240.0, 10.0);
addChild(_sprtBgScore);
_spriteBackgroundScore = new Sprite(_sheetUI["scoreboard.png"]);
_spriteBackgroundScore.pivot = new Point(1.0, 0.0);
_spriteBackgroundScore.scale = 0.35;
_spriteBackgroundScore.position = new Point(240.0, 10.0);
addChild(_spriteBackgroundScore);
_scoreDisplay = new ScoreDisplay(_sheetUI);
_scoreDisplay.position = new Point(-13.0, 49.0);
_sprtBgScore.addChild(_scoreDisplay);
_spriteBackgroundScore.addChild(_scoreDisplay);
// Coin display
_sprtBgCoins = new Sprite(_sheetUI["coinboard.png"]);
_sprtBgCoins.pivot = new Point(1.0, 0.0);
_sprtBgCoins.scale = 0.35;
_sprtBgCoins.position = new Point(105.0, 10.0);
addChild(_sprtBgCoins);
_spriteBackgroundCoins = new Sprite(_sheetUI["coinboard.png"]);
_spriteBackgroundCoins.pivot = new Point(1.0, 0.0);
_spriteBackgroundCoins.scale = 0.35;
_spriteBackgroundCoins.position = new Point(105.0, 10.0);
addChild(_spriteBackgroundCoins);
_coinDisplay = new ScoreDisplay(_sheetUI);
_coinDisplay.position = new Point(-13.0, 49.0);
_sprtBgCoins.addChild(_coinDisplay);
_spriteBackgroundCoins.addChild(_coinDisplay);
}
final SpriteSheet _sheetUI;
@ -38,16 +38,16 @@ class PlayerState extends Node {
EnemyBoss boss;
Sprite _sprtBgScore;
Sprite _spriteBackgroundScore;
ScoreDisplay _scoreDisplay;
Sprite _sprtBgCoins;
Sprite _spriteBackgroundCoins;
ScoreDisplay _coinDisplay;
int get score => _scoreDisplay.score;
set score(int score) {
_scoreDisplay.score = score;
flashBgSprite(_sprtBgScore);
flashBackgroundSprite(_spriteBackgroundScore);
}
int get coins => _coinDisplay.score;
@ -59,26 +59,26 @@ class PlayerState extends Node {
Point middlePos = new Point((startPos.x + finalPos.x) / 2.0 + 50.0,
(startPos.y + finalPos.y) / 2.0);
List<Point> path = [startPos, middlePos, finalPos];
List<Point> path = <Point>[startPos, middlePos, finalPos];
Sprite sprt = new Sprite(_sheetGame["coin.png"]);
sprt.scale = 0.7;
Sprite sprite = new Sprite(_sheetGame["coin.png"]);
sprite.scale = 0.7;
ActionSpline spline = new ActionSpline((a) => sprt.position = a, path, 0.5);
ActionSpline spline = new ActionSpline((Point a) { sprite.position = a; }, path, 0.5);
spline.tension = 0.25;
ActionTween rotate = new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 0.5);
ActionTween scale = new ActionTween((a) => sprt.scale = a, 0.7, 1.2, 0.5);
ActionGroup group = new ActionGroup([spline, rotate, scale]);
sprt.actions.run(new ActionSequence([
ActionTween rotate = new ActionTween((double a) { sprite.rotation = a; }, 0.0, 360.0, 0.5);
ActionTween scale = new ActionTween((double a) { sprite.scale = a; }, 0.7, 1.2, 0.5);
ActionGroup group = new ActionGroup(<Action>[spline, rotate, scale]);
sprite.actions.run(new ActionSequence(<Action>[
group,
new ActionRemoveNode(sprt),
new ActionRemoveNode(sprite),
new ActionCallFunction(() {
_coinDisplay.score += 1;
flashBgSprite(_sprtBgCoins);
flashBackgroundSprite(_spriteBackgroundCoins);
})
]));
addChild(sprt);
addChild(sprite);
}
void activatePowerUp(PowerUpType type) {
@ -107,21 +107,25 @@ class PlayerState extends Node {
int _speedBoostFrames = 0;
bool get speedBoostActive => _speedBoostFrames > 0;
void flashBgSprite(Sprite sprt) {
sprt.actions.stopAll();
void flashBackgroundSprite(Sprite sprite) {
sprite.actions.stopAll();
ActionTween flash = new ActionTween(
(a) => sprt.colorOverlay = a,
(Color a) { sprite.colorOverlay = a; },
new Color(0x66ccfff0),
new Color(0x00ccfff0),
0.3);
sprt.actions.run(flash);
sprite.actions.run(flash);
}
void update(double dt) {
if (_shieldFrames > 0) _shieldFrames--;
if (_sideLaserFrames > 0) _sideLaserFrames--;
if (_speedLaserFrames > 0) _speedLaserFrames--;
if (_speedBoostFrames > 0) _speedBoostFrames--;
if (_shieldFrames > 0)
_shieldFrames--;
if (_sideLaserFrames > 0)
_sideLaserFrames--;
if (_speedLaserFrames > 0)
_speedLaserFrames--;
if (_speedBoostFrames > 0)
_speedBoostFrames--;
// Update speed
if (boss != null) {
@ -165,9 +169,9 @@ class ScoreDisplay extends Node {
double xPos = -37.0;
for (int i = scoreStr.length - 1; i >= 0; i--) {
String numStr = scoreStr.substring(i, i + 1);
Sprite numSprt = new Sprite(_sheetUI["number_$numStr.png"]);
numSprt.position = new Point(xPos, 0.0);
addChild(numSprt);
Sprite numSprite = new Sprite(_sheetUI["number_$numStr.png"]);
numSprite.position = new Point(xPos, 0.0);
addChild(numSprite);
xPos -= 37.0;
}
_dirtyScore = false;

View File

@ -1,25 +1,25 @@
part of game;
class RepeatedImage extends Node {
Sprite _sprt0;
Sprite _sprt1;
Sprite _sprite0;
Sprite _sprite1;
RepeatedImage(ui.Image image, [ui.TransferMode mode = null]) {
_sprt0 = new Sprite.fromImage(image);
_sprt0.size = new Size(1024.0, 1024.0);
_sprt0.pivot = Point.origin;
_sprt1 = new Sprite.fromImage(image);
_sprt1.size = new Size(1024.0, 1024.0);
_sprt1.pivot = Point.origin;
_sprt1.position = new Point(0.0, -1024.0);
_sprite0 = new Sprite.fromImage(image);
_sprite0.size = new Size(1024.0, 1024.0);
_sprite0.pivot = Point.origin;
_sprite1 = new Sprite.fromImage(image);
_sprite1.size = new Size(1024.0, 1024.0);
_sprite1.pivot = Point.origin;
_sprite1.position = new Point(0.0, -1024.0);
if (mode != null) {
_sprt0.transferMode = mode;
_sprt1.transferMode = mode;
_sprite0.transferMode = mode;
_sprite1.transferMode = mode;
}
addChild(_sprt0);
addChild(_sprt1);
addChild(_sprite0);
addChild(_sprite1);
}
void move(double dy) {

View File

@ -24,10 +24,10 @@ class StarField extends NodeWithSize {
}
void addStars() {
_starPositions = [];
_starScales = [];
_colors = [];
_rects = [];
_starPositions = <Point>[];
_starScales = <double>[];
_colors = <Color>[];
_rects = <Rect>[];
size = spriteBox.visibleArea.size;
_paddedSize = new Size(size.width + _padding * 2.0,
@ -48,7 +48,7 @@ class StarField extends NodeWithSize {
void paint(PaintingCanvas canvas) {
// Create a transform for each star
List<ui.RSTransform> transforms = [];
List<ui.RSTransform> transforms = <ui.RSTransform>[];
for (int i = 0; i < _numStars; i++) {
ui.RSTransform transform = new ui.RSTransform(
_starScales[i],

View File

@ -21,7 +21,7 @@ TestBedApp _app;
main() async {
_images = new ImageMap(_bundle);
await _images.load([
await _images.load(<String>[
'assets/sprites.png'
]);
@ -54,6 +54,5 @@ class TestBedApp extends MaterialApp {
}
class TestBed extends NodeWithSize {
TestBed() : super(new Size(1024.0, 1024.0)) {
}
TestBed() : super(new Size(1024.0, 1024.0));
}

View File

@ -25,7 +25,7 @@ final ThemeData _theme = new ThemeData(
main() async {
_images = new ImageMap(_bundle);
await _images.load([
await _images.load(<String>[
'assets/sprites.png'
]);
@ -35,7 +35,7 @@ main() async {
runApp(new MaterialApp(
title: 'Test drawAtlas',
theme: _theme,
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) {
return new SpriteWidget(
new TestDrawAtlas(),
@ -47,17 +47,16 @@ main() async {
}
class TestDrawAtlas extends NodeWithSize {
TestDrawAtlas() : super(new Size(1024.0, 1024.0)) {
}
TestDrawAtlas() : super(new Size(1024.0, 1024.0));
void paint(PaintingCanvas canvas) {
List<RSTransform> transforms = [
List<RSTransform> transforms = <RSTransform>[
new RSTransform(1.0, 0.0, 100.0, 100.0)
];
List<Rect> rects = [
List<Rect> rects = <Rect>[
_spriteSheet["ship.png"].frame
];
List<Color> colors = [
List<Color> colors = <Color>[
new Color(0xffffffff)
];

View File

@ -26,7 +26,7 @@ final ThemeData _theme = new ThemeData(
main() async {
_images = new ImageMap(_bundle);
await _images.load([
await _images.load(<String>[
'assets/sprites.png'
]);
@ -36,21 +36,19 @@ main() async {
runApp(new MaterialApp(
title: 'Test Sprite Performance',
theme: _theme,
routes: {
'/': (RouteArguments args) {
return new SpriteWidget(new TestPerformance());
}
routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new SpriteWidget(new TestPerformance())
}
));
}
class TestPerformance extends NodeWithSize {
TestPerformance() : super(new Size(1024.0, 1024.0));
final int numFramesPerTest = 100;
final int numTests = 5;
TestPerformance() : super(new Size(1024.0, 1024.0)) {
}
int test = 0;
int frame = 0;
int testStartTime;
@ -116,18 +114,18 @@ class TestPerformanceParticles extends PerformanceTest {
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
ParticleSystem particles = new ParticleSystem(
_spriteSheet["explosion_particle.png"],
rotateToMovement: true,
startRotation:90.0,
startRotationVar: 0.0,
endRotation: 90.0,
startSize: 0.3,
startSizeVar: 0.1,
endSize: 0.3,
endSizeVar: 0.1,
emissionRate:100.0,
greenVar: 127,
redVar: 127
_spriteSheet["explosion_particle.png"],
rotateToMovement: true,
startRotation:90.0,
startRotationVar: 0.0,
endRotation: 90.0,
startSize: 0.3,
startSizeVar: 0.1,
endSize: 0.3,
endSizeVar: 0.1,
emissionRate:100.0,
greenVar: 127,
redVar: 127
);
particles.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(particles);
@ -144,23 +142,22 @@ class TestPerformanceSprites extends PerformanceTest {
TestPerformanceSprites() {
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.scale = 1.0;
sprt.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprt);
//sprt.actions.run(new ActionRepeatForever(new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 1.0)));
Sprite sprite = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprite.scale = 1.0;
sprite.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprite);
}
}
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.position = new Point(512.0, 512.0);
addChild(sprt);
Sprite sprite = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprite.position = new Point(512.0, 512.0);
addChild(sprite);
}
void update(double dt) {
for (Sprite sprt in children) {
sprt.rotation += 1;
for (Node child in children) {
final Sprite sprite = child;
sprite.rotation += 1;
}
}
}
@ -173,23 +170,22 @@ class TestPerformanceSprites2 extends PerformanceTest {
TestPerformanceSprites2() {
for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) {
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.scale = 1.0;
sprt.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprt);
//sprt.actions.run(new ActionRepeatForever(new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 1.0)));
Sprite sprite = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprite.scale = 1.0;
sprite.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprite);
}
}
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.position = new Point(512.0, 512.0);
addChild(sprt);
Sprite sprite = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprite.position = new Point(512.0, 512.0);
addChild(sprite);
}
void update(double dt) {
for (Sprite sprt in children) {
sprt.rotation += 1;
for (Node child in children) {
final Sprite sprite = child;
sprite.rotation += 1;
}
}
}
@ -200,7 +196,7 @@ class TestPerformanceAtlas extends PerformanceTest {
final int grid = 100;
double rotation = 0.0;
List<Rect> rects = [];
List<Rect> rects = <Rect>[];
Paint cachedPaint = new Paint()
..filterQuality = ui.FilterQuality.low
..isAntiAlias = false;
@ -216,7 +212,7 @@ class TestPerformanceAtlas extends PerformanceTest {
void paint(PaintingCanvas canvas) {
// Setup transforms
List<ui.RSTransform> transforms = [];
List<ui.RSTransform> transforms = <ui.RSTransform>[];
for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) {
@ -253,7 +249,7 @@ class TestPerformanceAtlas2 extends PerformanceTest {
final int grid = 100;
double rotation = 0.0;
List<Rect> rects = [];
List<Rect> rects = <Rect>[];
Paint cachedPaint = new Paint()
..filterQuality = ui.FilterQuality.low
..isAntiAlias = false;
@ -269,7 +265,7 @@ class TestPerformanceAtlas2 extends PerformanceTest {
void paint(PaintingCanvas canvas) {
// Setup transforms
List<ui.RSTransform> transforms = [];
List<ui.RSTransform> transforms = <ui.RSTransform>[];
for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) {

View File

@ -15,10 +15,9 @@ void runTest() {
timeStart = new DateTime.now().millisecondsSinceEpoch;
// Create systems
List<TestParticleSystem> systems = [];
for (int i = 0; i < numSystems; i++) {
List<TestParticleSystem> systems = <TestParticleSystem>[];
for (int i = 0; i < numSystems; i++)
systems.add(new TestParticleSystem());
}
int timeAfterCreate = new DateTime.now().millisecondsSinceEpoch;
print("TIME creation ${(timeAfterCreate - timeStart) / 1000.0}");

View File

@ -21,7 +21,7 @@ SpriteSheet _spriteSheet;
main() async {
_images = new ImageMap(_bundle);
await _images.load([
await _images.load(<String>[
'assets/sprites.png'
]);
@ -34,7 +34,7 @@ main() async {
brightness: ThemeBrightness.light,
primarySwatch: Colors.purple
),
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) {
return new SpriteWidget(
new TestBed(),
@ -73,9 +73,9 @@ class TestBed extends NodeWithSize {
_world.addContactCallback(myCallback, "obstacle", "ship", PhysicsContactType.begin);
// Animate group
ActionSequence seq = new ActionSequence([
new ActionTween((a) => _group.position = a, new Point(-256.0, 0.0), new Point(256.0, 0.0), 1.0, Curves.easeInOut),
new ActionTween((a) => _group.position = a, new Point(256.0, 0.0), new Point(-256.0, 0.0), 1.0, Curves.easeInOut)
ActionSequence seq = new ActionSequence(<Action>[
new ActionTween((Point a) { _group.position = a; }, new Point(-256.0, 0.0), new Point(256.0, 0.0), 1.0, Curves.easeInOut),
new ActionTween((Point a) { _group.position = a; }, new Point(256.0, 0.0), new Point(-256.0, 0.0), 1.0, Curves.easeInOut)
]);
_group.actions.run(new ActionRepeatForever(seq));
@ -115,7 +115,7 @@ class TestBed extends NodeWithSize {
shipB.opacity = 0.3;
shipB.position = new Point(40.0, 0.0);
shipB.size = new Size(64.0, 64.0);
shipB.physicsBody = new PhysicsBody(new PhysicsShapePolygon([new Point(-25.0, -25.0), new Point(25.0, -25.0), new Point(25.0, 25.0), new Point(-25.0, 25.0)]),
shipB.physicsBody = new PhysicsBody(new PhysicsShapePolygon(<Point>[new Point(-25.0, -25.0), new Point(25.0, -25.0), new Point(25.0, 25.0), new Point(-25.0, 25.0)]),
friction: 0.5,
restitution: 0.5,
tag: "ship"

View File

@ -30,8 +30,8 @@ const List<Color> textColors = const <Color>[
const Color(0xFF000000),
];
final List<TextStyle> textStyles = textColors.map((color) {
return new TextStyle(color: color, fontWeight: bold, textAlign: TextAlign.center);
final List<TextStyle> textStyles = textColors.map((Color color) {
return new TextStyle(color: color, fontWeight: bold, textAlign: TextAlign.center);
}).toList();
enum CellState { covered, exploded, cleared, flagged, shown }
@ -64,10 +64,10 @@ class MineDiggerState extends State<MineDigger> {
hasWon = false;
detectedCount = 0;
// Initialize matrices.
cells = new List<List>.generate(rows, (int row) {
cells = new List<List<bool>>.generate(rows, (int row) {
return new List<bool>.filled(cols, false);
});
uiState = new List<List>.generate(rows, (int row) {
uiState = new List<List<CellState>>.generate(rows, (int row) {
return new List<CellState>.filled(cols, CellState.covered);
});
// Place the mines.

View File

@ -26,13 +26,14 @@ ui.Picture paint(ui.Rect paintBounds) {
canvas.rotate(math.PI/4.0);
ui.Gradient yellowBlue = new ui.Gradient.linear(
[new ui.Point(-radius, -radius), new ui.Point(0.0, 0.0)],
[const ui.Color(0xFFFFFF00), const ui.Color(0xFF0000FF)]);
<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);
new ui.Paint()..shader = yellowBlue);
// Scale x and y by 0.5.
var scaleMatrix = new Float64List.fromList([
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,
@ -45,35 +46,47 @@ ui.Picture paint(ui.Rect paintBounds) {
canvas.restore();
canvas.translate(0.0, 50.0);
var 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,
[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));
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);

View File

@ -7,34 +7,34 @@ import 'package:flutter/rendering.dart';
import 'lib/solid_color_box.dart';
void main() {
var table = new RenderFlex(direction: FlexDirection.vertical);
RenderFlex table = new RenderFlex(direction: FlexDirection.vertical);
for(FlexAlignItems alignItems in FlexAlignItems.values) {
for (FlexAlignItems alignItems in FlexAlignItems.values) {
TextStyle style = const TextStyle(color: const Color(0xFF000000));
RenderParagraph paragraph = new RenderParagraph(new StyledTextSpan(style, [new PlainTextSpan("${alignItems}")]));
RenderParagraph paragraph = new RenderParagraph(new StyledTextSpan(style, <TextSpan>[new PlainTextSpan("$alignItems")]));
table.add(new RenderPadding(child: paragraph, padding: new EdgeDims.only(top: 20.0)));
var row = new RenderFlex(alignItems: alignItems, textBaseline: TextBaseline.alphabetic);
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, [new PlainTextSpan('foo foo foo')]))
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, [new PlainTextSpan('foo foo foo')]))
child: new RenderParagraph(new StyledTextSpan(style, <TextSpan>[new PlainTextSpan('foo foo foo')]))
));
var subrow = new RenderFlex(alignItems: alignItems, textBaseline: TextBaseline.alphabetic);
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, [new PlainTextSpan('foo foo foo foo')]))
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);
row.parentData.flex = 1;
final FlexParentData rowParentData = row.parentData;
rowParentData.flex = 1;
}
RenderDecoratedBox root = new RenderDecoratedBox(

View File

@ -12,7 +12,7 @@ RenderBox getBox(double lh) {
new TextStyle(
color: const Color(0xFF0000A0)
),
[
<TextSpan>[
new PlainTextSpan('test'),
new StyledTextSpan(
new TextStyle(
@ -20,7 +20,7 @@ RenderBox getBox(double lh) {
fontSize: 50.0,
height: lh
),
[new PlainTextSpan('مرحبا Hello')]
<TextSpan>[new PlainTextSpan('مرحبا Hello')]
)
]
)
@ -62,7 +62,7 @@ RenderBox getBox(double lh) {
}
void main() {
RenderBox root = new RenderFlex(children: [
RenderBox root = new RenderFlex(children: <RenderBox>[
new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 50.0)
),

View File

@ -7,8 +7,8 @@ import 'dart:ui' as ui;
import 'package:flutter/rendering.dart';
void main() {
var root = new RenderFlex(
children: [
RenderFlex root = new RenderFlex(
children: <RenderBox>[
new RenderPadding(
padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox(

View File

@ -46,7 +46,8 @@ RenderBox buildFlexExample() {
);
flexRoot.add(decoratedRow);
decoratedRow.parentData.flex = 3;
final FlexParentData decoratedRowParentData = decoratedRow.parentData;
decoratedRowParentData.flex = 3;
return root;
}

View File

@ -33,7 +33,7 @@ class RenderImageGrow extends RenderImage {
RenderImageGrow image;
Map<int, Touch> touches = new Map();
final Map<int, Touch> touches = <int, Touch>{};
void handleEvent(event) {
if (event is ui.PointerEvent) {
if (event.type == 'pointermove')
@ -64,8 +64,7 @@ void main() {
image.image = dartLogo;
});
var padding = new RenderPadding(padding: const EdgeDims.all(10.0), child: image);
row.add(padding);
row.add(new RenderPadding(padding: const EdgeDims.all(10.0), child: image));
RenderFlex column = new RenderFlex(direction: FlexDirection.vertical);
@ -79,13 +78,14 @@ porchetta bacon kevin meatball meatloaf pig beef ribs chicken. Brisket ribeye
andouille leberkas capicola meatloaf. Chicken pig ball tip pork picanha bresaola
alcatra. Pork pork belly alcatra, flank chuck drumstick biltong doner jowl.
Pancetta meatball tongue tenderloin rump tail jowl boudin.""";
var text = new StyledTextSpan(
new TextStyle(color: const Color(0xFF009900)),
[new PlainTextSpan(meatyString)]);
padding = new RenderPadding(
padding: const EdgeDims.all(10.0),
child: new RenderParagraph(text));
column.add(padding);
TextSpan text = new StyledTextSpan(
new TextStyle(color: const Color(0xFF009900)),
<TextSpan>[new PlainTextSpan(meatyString)]
);
column.add(new RenderPadding(
padding: const EdgeDims.all(10.0),
child: new RenderParagraph(text)
));
// Bottom cell
addFlexChildSolidColor(column, const Color(0xFF0081C6), flex: 2);

View File

@ -14,15 +14,16 @@ void main() {
var table = new RenderFlex(direction: FlexDirection.vertical);
void addRow(FlexJustifyContent justify) {
RenderParagraph paragraph = new RenderParagraph(new StyledTextSpan(style, [new PlainTextSpan("${justify}")]));
RenderParagraph paragraph = new RenderParagraph(new StyledTextSpan(style, <TextSpan>[new PlainTextSpan("$justify")]));
table.add(new RenderPadding(child: paragraph, padding: new EdgeDims.only(top: 20.0)));
var row = new RenderFlex(direction: FlexDirection.horizontal);
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);
row.parentData.flex = 1;
final FlexParentData rowParentData = row.parentData;
rowParentData.flex = 1;
}
addRow(FlexJustifyContent.start);

View File

@ -19,7 +19,7 @@ Color randomColor() {
}
RenderBox buildGridExample() {
List<RenderBox> children = new List.generate(30, (_) => new RenderSolidColorBox(randomColor()));
List<RenderBox> children = new List<RenderBox>.generate(30, (_) => new RenderSolidColorBox(randomColor()));
return new RenderGrid(children: children, maxChildExtent: 100.0);
}

View File

@ -14,9 +14,11 @@ void main() {
child: flexRoot
);
FlexParentData childParentData;
RenderObject child = new RenderSolidColorBox(const Color(0xFFFFFF00));
flexRoot.add(child);
FlexParentData childParentData = child.parentData;
childParentData = child.parentData;
childParentData.flex = 2;
// The internet is a beautiful place. https://baconipsum.com/
@ -26,9 +28,10 @@ andouille leberkas capicola meatloaf. Chicken pig ball tip pork picanha bresaola
alcatra. Pork pork belly alcatra, flank chuck drumstick biltong doner jowl.
Pancetta meatball tongue tenderloin rump tail jowl boudin.""";
var text = new StyledTextSpan(
new TextStyle(color: const Color(0xFF009900)),
[new PlainTextSpan(meatyString)]);
StyledTextSpan text = new StyledTextSpan(
new TextStyle(color: const Color(0xFF009900)),
<TextSpan>[new PlainTextSpan(meatyString)]
);
child = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)),
child: new RenderParagraph(text)

View File

@ -12,7 +12,7 @@ void main() {
decoration: new BoxDecoration(
gradient: new RadialGradient(
center: Point.origin, radius: 500.0,
colors: [Colors.yellow[500], Colors.blue[500]]),
colors: <Color>[Colors.yellow[500], Colors.blue[500]]),
boxShadow: shadows[3])
);
var paddedBox = new RenderPadding(

View File

@ -24,7 +24,7 @@ void main() {
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF))
);
RenderAutoLayout root = new RenderAutoLayout(children: [c1, c2, c3, c4]);
RenderAutoLayout root = new RenderAutoLayout(children: <RenderBox>[c1, c2, c3, c4]);
AutoLayoutParentData p1 = c1.parentData;
AutoLayoutParentData p2 = c2.parentData;

View File

@ -7,7 +7,7 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/gestures.dart';
// Material design colors. :p
List<Color> kColors = [
List<Color> kColors = <Color>[
Colors.teal[500],
Colors.amber[500],
Colors.purple[500],
@ -34,9 +34,7 @@ class Dot {
}
class RenderTouchDemo extends RenderBox {
Map<int, Dot> dots = new Map();
RenderTouchDemo();
final Map<int, Dot> dots = <int, Dot>{};
void handleEvent(InputEvent event, BoxHitTestEntry entry) {
if (event is PointerInputEvent) {
@ -49,7 +47,7 @@ class RenderTouchDemo extends RenderBox {
dots.remove(event.pointer);
break;
case 'pointercancel':
dots = new Map();
dots.clear();
break;
case 'pointermove':
dots[event.pointer].update(event);
@ -74,14 +72,15 @@ class RenderTouchDemo extends RenderBox {
}
void main() {
var paragraph = new RenderParagraph(new PlainTextSpan("Touch me!"));
var stack = new RenderStack(children: [
RenderParagraph paragraph = new RenderParagraph(new PlainTextSpan("Touch me!"));
RenderStack stack = new RenderStack(children: <RenderBox>[
new RenderTouchDemo(),
paragraph,
]);
// Prevent the RenderParagraph from filling the whole screen so
// that it doesn't eat events.
paragraph.parentData..top = 40.0
..left = 20.0;
final StackParentData paragraphParentData = paragraph.parentData;
paragraphParentData..top = 40.0
..left = 20.0;
new FlutterBinding(root: stack);
}

View File

@ -8,7 +8,7 @@ enum _MenuItems { autorefresh, autorefreshCheckbox, add, remove }
const double _kMenuMargin = 16.0; // 24.0 on tablet
Future showStockMenu({BuildContext context, bool autorefresh, ValueChanged onAutorefreshChanged }) async {
Future showStockMenu({BuildContext context, bool autorefresh, ValueChanged<bool> onAutorefreshChanged }) async {
switch (await showMenu(
context: context,
position: new MenuPosition(

View File

@ -48,13 +48,19 @@ class CardCollectionState extends State<CardCollection> {
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.generate(cardHeights.length, (i) => new CardModel(i, cardHeights[i]));
_cardModels = new List<CardModel>.generate(
cardHeights.length,
(int i) => new CardModel(i, cardHeights[i])
);
}
void _initFixedSizedCardModels() {
const int cardCount = 27;
const double cardHeight = 100.0;
_cardModels = new List.generate(cardCount, (i) => new CardModel(i, cardHeight));
_cardModels = new List<CardModel>.generate(
cardCount,
(int i) => new CardModel(i, cardHeight)
);
}
void _initCardModels() {
@ -72,7 +78,7 @@ class CardCollectionState extends State<CardCollection> {
double _variableSizeToSnapOffset(double scrollOffset) {
double cumulativeHeight = 0.0;
double margins = 8.0;
List<double> cumulativeHeights = _cardModels.map((card) {
List<double> cumulativeHeights = _cardModels.map((CardModel card) {
cumulativeHeight += card.height + margins;
return cumulativeHeight;
})
@ -112,7 +118,7 @@ class CardCollectionState extends State<CardCollection> {
context: context,
child: new IconTheme(
data: const IconThemeData(color: IconThemeColor.black),
child: new Block([
child: new Block(<Widget>[
new DrawerHeader(child: new Text('Options')),
buildDrawerCheckbox("Snap fling scrolls to center", _snapToCenter, _toggleSnapToCenter),
buildDrawerCheckbox("Fixed size cards", _fixedSizeCards, _toggleFixedSizeCards),
@ -168,10 +174,10 @@ class CardCollectionState extends State<CardCollection> {
Navigator.of(context).pop();
}
Widget buildDrawerCheckbox(String label, bool value, Function callback) {
Widget buildDrawerCheckbox(String label, bool value, void callback()) {
return new DrawerItem(
onPressed: callback,
child: new Row([
child: new Row(<Widget>[
new Flexible(child: new Text(label)),
new Checkbox(value: value, onChanged: (_) { callback(); })
])
@ -182,7 +188,7 @@ class CardCollectionState extends State<CardCollection> {
return new DrawerItem(
icon: icon,
onPressed: () { onChanged(itemValue); },
child: new Row([
child: new Row(<Widget>[
new Flexible(child: new Text(label)),
new Radio(
value: itemValue,
@ -197,7 +203,7 @@ class CardCollectionState extends State<CardCollection> {
return new ToolBar(
left: new IconButton(icon: "navigation/menu", onPressed: _showDrawer),
center: new Text('Swipe Away'),
right: [
right: <Widget>[
new Text(_dismissDirectionText(_dismissDirection))
]
);
@ -210,7 +216,7 @@ class CardCollectionState extends State<CardCollection> {
CardModel cardModel = _cardModels[index];
Widget card = new Dismissable(
direction: _dismissDirection,
onResized: () { _invalidator([index]); },
onResized: () { _invalidator(<int>[index]); },
onDismissed: () { dismissCard(cardModel); },
child: new Card(
color: Theme.of(context).primarySwatch[cardModel.color],
@ -272,7 +278,7 @@ class CardCollectionState extends State<CardCollection> {
child: new Container(
height: cardModel.height,
decoration: new BoxDecoration(backgroundColor: Theme.of(context).primaryColor),
child: new Row([
child: new Row(<Widget>[
leftArrowIcon,
new Flexible(child: new Text(backgroundMessage, style: backgroundTextStyle)),
rightArrowIcon
@ -285,7 +291,7 @@ class CardCollectionState extends State<CardCollection> {
return new IconTheme(
key: cardModel.key,
data: const IconThemeData(color: IconThemeColor.white),
child: new Stack([background, card])
child: new Stack(<Widget>[background, card])
);
}
@ -299,8 +305,8 @@ class CardCollectionState extends State<CardCollection> {
return new LinearGradient(
begin: Point.origin,
end: new Point(0.0, bounds.height),
colors: [const Color(0x00FFFFFF), const Color(0xFFFFFFFF)],
stops: [0.1, 0.35]
colors: <Color>[const Color(0x00FFFFFF), const Color(0xFFFFFFFF)],
stops: <double>[0.1, 0.35]
)
.createShader();
}
@ -327,8 +333,8 @@ class CardCollectionState extends State<CardCollection> {
}
if (_sunshine)
cardCollection = new Stack([
new Column([new NetworkImage(src: _sunshineURL)]),
cardCollection = new Stack(<Widget>[
new Column(<Widget>[new NetworkImage(src: _sunshineURL)]),
new ShaderMask(child: cardCollection, shaderCallback: _createShader)
]);
@ -351,7 +357,7 @@ class CardCollectionState extends State<CardCollection> {
)
)
);
body = new Stack([body, indicator]);
body = new Stack(<Widget>[body, indicator]);
}
return new Theme(
@ -369,7 +375,7 @@ class CardCollectionState extends State<CardCollection> {
void main() {
runApp(new MaterialApp(
title: 'Cards',
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new CardCollection(),
}
));

View File

@ -6,7 +6,7 @@ import 'package:flutter/material.dart';
class ContainerApp extends StatelessComponent {
Widget build(BuildContext context) {
return new Column([
return new Column(<Widget>[
new Container(
padding: new EdgeDims.all(10.0),
margin: new EdgeDims.all(10.0),
@ -20,7 +20,7 @@ class ContainerApp extends StatelessComponent {
new Container(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFF00)),
padding: new EdgeDims.symmetric(horizontal: 50.0, vertical: 75.0),
child: new Row([
child: new Row(<Widget>[
new RaisedButton(
child: new Text('PRESS ME'),
onPressed: () => print("Hello World")

View File

@ -31,11 +31,11 @@ class DatePickerDemoState extends State<DatePickerDemo> {
brightness: ThemeBrightness.light,
primarySwatch: Colors.teal
),
child: new Stack([
child: new Stack(<Widget>[
new Scaffold(
toolBar: new ToolBar(center: new Text("Date Picker")),
body: new Row(
[new Text(_dateTime.toString())],
<Widget>[new Text(_dateTime.toString())],
alignItems: FlexAlignItems.end,
justifyContent: FlexJustifyContent.center
)
@ -48,7 +48,7 @@ class DatePickerDemoState extends State<DatePickerDemo> {
onChanged: _handleDateChanged
),
contentPadding: EdgeDims.zero,
actions: [
actions: <Widget>[
new FlatButton(
child: new Text('CANCEL')
),

View File

@ -105,8 +105,8 @@ class DragAndDropAppState extends State<DragAndDropApp> {
),
body: new DefaultTextStyle(
style: Theme.of(context).text.body1.copyWith(textAlign: TextAlign.center),
child: new Column([
new Flexible(child: new Row([
child: new Column(<Widget>[
new Flexible(child: new Row(<Widget>[
new ExampleDragSource(navigator: config.navigator, name: 'Orange', color: const Color(0xFFFF9000)),
new ExampleDragSource(navigator: config.navigator, name: 'Teal', color: const Color(0xFF00FFFF)),
new ExampleDragSource(navigator: config.navigator, name: 'Yellow', color: const Color(0xFFFFF000)),
@ -114,7 +114,7 @@ class DragAndDropAppState extends State<DragAndDropApp> {
alignItems: FlexAlignItems.center,
justifyContent: FlexJustifyContent.spaceAround
)),
new Flexible(child: new Row([
new Flexible(child: new Row(<Widget>[
new Flexible(child: new ExampleDragTarget()),
new Flexible(child: new ExampleDragTarget()),
new Flexible(child: new ExampleDragTarget()),
@ -129,7 +129,7 @@ class DragAndDropAppState extends State<DragAndDropApp> {
void main() {
runApp(new MaterialApp(
title: 'Drag and Drop Flutter Demo',
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new DragAndDropApp(navigator: args.navigator)
}
));

View File

@ -13,7 +13,7 @@ class DropdownDemo extends StatefulComponent {
class DropdownDemoState extends State<DropdownDemo> {
String _value = "Free";
List <DropdownMenuItem> _buildItems() {
List<DropdownMenuItem> _buildItems() {
return ["One", "Two", "Free", "Four"].map((String value) {
return new DropdownMenuItem<String>(value: value, child: new Text(value));
})
@ -24,7 +24,7 @@ class DropdownDemoState extends State<DropdownDemo> {
Widget dropdown = new DropdownButton<String>(
items: _buildItems(),
value: _value,
onChanged: (dynamic newValue) {
onChanged: (String newValue) {
setState(() {
if (newValue != null)
_value = newValue;
@ -50,7 +50,7 @@ void main() {
primarySwatch: Colors.blue,
accentColor: Colors.redAccent[200]
),
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new DropdownDemo(),
}
));

View File

@ -23,7 +23,7 @@ class Circle extends StatelessComponent {
class HorizontalScrollingApp extends StatelessComponent {
Widget build(BuildContext context) {
List<Widget> circles = [
List<Widget> circles = <Widget>[
new Circle(margin: new EdgeDims.only(left: 10.0)),
new Circle(),
new Circle(),

View File

@ -19,10 +19,10 @@ class IndexedStackDemoState extends State<IndexedStackDemo> {
});
}
List <PopupMenuItem> _buildMenu() {
List<PopupMenuItem> _buildMenu() {
TextStyle style = const TextStyle(fontSize: 18.0, fontWeight: bold);
String pad = '';
return new List.generate(_itemCount, (int i) {
return new List<PopupMenuItem>.generate(_itemCount, (int i) {
pad += '-';
return new PopupMenuItem(value: i, child: new Text('$pad Hello World $i $pad', style: style));
});
@ -30,7 +30,7 @@ class IndexedStackDemoState extends State<IndexedStackDemo> {
Widget build(BuildContext context) {
List <PopupMenuItem> items = _buildMenu();
IndexedStack indexedStack = new IndexedStack(items, index: _itemIndex, horizontalAlignment: 0.5);
IndexedStack indexedStack = new IndexedStack(items, index: _itemIndex, alignment: const FractionalOffset(0.5, 0.0));
return new Scaffold(
toolBar: new ToolBar(center: new Text('IndexedStackDemo Demo')),
@ -56,7 +56,7 @@ void main() {
primarySwatch: Colors.blue,
accentColor: Colors.redAccent[200]
),
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new IndexedStackDemo(),
}
));

View File

@ -8,7 +8,7 @@ final Map<String, RouteBuilder> routes = <String, RouteBuilder>{
'/': (RouteArguments args) => new Container(
padding: const EdgeDims.all(30.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFFCCCCCC)),
child: new Column([
child: new Column(<Widget>[
new Text("You are at home"),
new RaisedButton(
child: new Text('GO SHOPPING'),
@ -24,7 +24,7 @@ final Map<String, RouteBuilder> routes = <String, RouteBuilder>{
'/shopping': (RouteArguments args) => new Container(
padding: const EdgeDims.all(20.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFFBF5FFF)),
child: new Column([
child: new Column(<Widget>[
new Text("Village Shop"),
new RaisedButton(
child: new Text('RETURN HOME'),
@ -40,7 +40,7 @@ final Map<String, RouteBuilder> routes = <String, RouteBuilder>{
'/adventure': (RouteArguments args) => new Container(
padding: const EdgeDims.all(20.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFFDC143C)),
child: new Column([
child: new Column(<Widget>[
new Text("Monster's Lair"),
new RaisedButton(
child: new Text('RUN!!!'),

View File

@ -86,7 +86,7 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> {
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.generate(cardHeights.length, (i) {
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);
});
@ -121,7 +121,7 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> {
CardModel cardModel = cardModels[index];
return new Listener(
key: cardModel.key,
onPointerDown: (e) { return handlePointerDown(cardModel.targetKey, e); },
onPointerDown: (PointerInputEvent e) { return handlePointerDown(cardModel.targetKey, e); },
child: new Card(
key: cardModel.targetKey,
color: cardModel.color,
@ -162,7 +162,7 @@ void main() {
accentColor: Colors.redAccent[200]
),
title: 'Cards',
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new OverlayGeometryApp()
}
));

View File

@ -27,7 +27,7 @@ class PageableListAppState extends State<PageableListApp> {
.map((args) => new Size(args[0], args[1]))
.toList();
cardModels = new List.generate(cardSizes.length, (i) {
cardModels = new List<CardModel>.generate(cardSizes.length, (int i) {
Color color = Color.lerp(Colors.red[300], Colors.blue[900], i / cardSizes.length);
return new CardModel(i, cardSizes[i], color);
});
@ -86,7 +86,7 @@ class PageableListAppState extends State<PageableListApp> {
void _showDrawer() {
showDrawer(
context: context,
child: new Block([
child: new Block(<Widget>[
new DrawerHeader(child: new Text('Options')),
new DrawerItem(
icon: 'navigation/more_horiz',
@ -102,7 +102,7 @@ class PageableListAppState extends State<PageableListApp> {
),
new DrawerItem(
onPressed: toggleItemsWrap,
child: new Row([
child: new Row(<Widget>[
new Flexible(child: new Text('Scrolling wraps around')),
new Checkbox(value: itemsWrap)
])
@ -115,7 +115,7 @@ class PageableListAppState extends State<PageableListApp> {
return new ToolBar(
left: new IconButton(icon: "navigation/menu", onPressed: _showDrawer),
center: new Text('PageableList'),
right: [
right: <Widget>[
new Text(scrollDirection == ScrollDirection.horizontal ? "horizontal" : "vertical")
]
);
@ -156,7 +156,7 @@ void main() {
primarySwatch: Colors.blue,
accentColor: Colors.redAccent[200]
),
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new PageableListApp(),
}
));

View File

@ -18,11 +18,12 @@ const String frogs = "http://soundbible.com/grab.php?id=2033&type=wav";
const String rattle = "http://soundbible.com/grab.php?id=2037&type=wav";
const String iLoveYou = "http://soundbible.com/grab.php?id=2045&type=wav";
class Key {
Key(this.color, this.soundUrl);
class PianoKey {
PianoKey(this.color, this.soundUrl);
final Color color;
final String soundUrl;
final MediaPlayerProxy player = new MediaPlayerProxy.unbound();
bool get isPlayerOpen => player.impl.isOpen;
@ -51,13 +52,13 @@ class Key {
}
class PianoApp extends StatelessComponent {
final List<Key> keys = [
new Key(Colors.red[500], chimes),
new Key(Colors.orange[500], chainsaw),
new Key(Colors.yellow[500], stag),
new Key(Colors.green[500], frogs),
new Key(Colors.blue[500], rattle),
new Key(Colors.purple[500], iLoveYou),
final List<PianoKey> keys = <PianoKey>[
new PianoKey(Colors.red[500], chimes),
new PianoKey(Colors.orange[500], chainsaw),
new PianoKey(Colors.yellow[500], stag),
new PianoKey(Colors.green[500], frogs),
new PianoKey(Colors.blue[500], rattle),
new PianoKey(Colors.purple[500], iLoveYou),
];
Future connect() {
@ -68,10 +69,9 @@ class PianoApp extends StatelessComponent {
MediaServiceProxy mediaService = new MediaServiceProxy.unbound();
try {
shell.requestService(null, mediaService);
List<Future> pending = [];
for (Key key in keys) {
List<Future<MediaPlayerPrepareResponseParams>> pending = <Future<MediaPlayerPrepareResponseParams>>[];
for (PianoKey key in keys)
pending.add(key.load(mediaService));
}
await Future.wait(pending);
} finally {
mediaService.close();
@ -79,8 +79,8 @@ class PianoApp extends StatelessComponent {
}
Widget build(BuildContext context) {
List<Widget> children = [];
for (Key key in keys) {
List<Widget> children = <Widget>[];
for (PianoKey key in keys) {
children.add(new Flexible(
child: new Listener(
child: new Container(
@ -99,7 +99,7 @@ Widget statusBox(Widget child) {
const darkGray = const Color(0xff222222);
return new Center(
child: new Container(
decoration: const BoxDecoration(boxShadow: const [
decoration: const BoxDecoration(boxShadow: const <BoxShadow>[
const BoxShadow(
color: mediumGray, offset: const Offset(6.0, 6.0), blur: 5.0)
], backgroundColor: darkGray),

View File

@ -71,7 +71,7 @@ class ProgressIndicatorAppState extends State<ProgressIndicatorApp> {
];
return new Column(
indicators
.map((c) => new Container(child: c, margin: const EdgeDims.symmetric(vertical: 15.0, horizontal: 20.0)))
.map((Widget c) => new Container(child: c, margin: const EdgeDims.symmetric(vertical: 15.0, horizontal: 20.0)))
.toList(),
justifyContent: FlexJustifyContent.center
);
@ -83,7 +83,7 @@ class ProgressIndicatorAppState extends State<ProgressIndicatorApp> {
child: new Container(
padding: const EdgeDims.symmetric(vertical: 12.0, horizontal: 8.0),
child: new BuilderTransition(
variables: [valueAnimation.variable],
variables: <AnimatedValue<double>>[valueAnimation.variable],
performance: valueAnimation.view,
builder: buildIndicators
)

View File

@ -47,7 +47,7 @@ class ScaleAppState extends State<ScaleApp> {
double radius = size.width / 2.0 * _zoom;
Gradient gradient = new RadialGradient(
center: center, radius: radius,
colors: [Colors.blue[200], Colors.blue[800]]
colors: <Color>[Colors.blue[200], Colors.blue[800]]
);
Paint paint = new Paint()
..shader = gradient.createShader();

View File

@ -60,7 +60,7 @@ void main() {
primarySwatch: Colors.blue,
accentColor: Colors.redAccent[200]
),
routes: {
routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new ScrollbarApp(),
}
));

View File

@ -6,7 +6,7 @@ import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
final List<Map<int, Color>> _kColors = [
final List<Map<int, Color>> _kColors = <Map<int, Color>>[
Colors.amber,
Colors.yellow,
Colors.blue,
@ -42,7 +42,7 @@ class CardTransition extends StatelessComponent {
return new BuilderTransition(
performance: performance,
variables: [x, opacity, scale],
variables: <AnimatedValue<double>>[x, opacity, scale],
builder: (BuildContext context) {
Matrix4 transform = new Matrix4.identity()
..translate(x.value)

View File

@ -5,6 +5,8 @@
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();
}
@ -19,7 +21,7 @@ class StyledTextAppState extends State<StyledTextApp> {
.toList();
}
Function toText;
TextTransformer toText;
// From https://en.wikiquote.org/wiki/2001:_A_Space_Odyssey_(film)
final String dialogText = '''
@ -74,10 +76,10 @@ HAL: This mission is too important for me to allow you to jeopardize it.''';
Widget build(BuildContext context) {
List<Widget> lines = nameLines
.map((nameAndText) => Function.apply(toText, nameAndText))
.map((List<String> nameAndText) => Function.apply(toText, nameAndText))
.toList();
List<Widget> children = [];
List<Widget> children = <Widget>[];
for (Widget line in lines) {
children.add(line);
if (line != lines.last) {

View File

@ -19,7 +19,7 @@ class TabbedNavigatorAppState extends State<TabbedNavigatorApp> {
views: views,
selectedIndex: selectedIndices[n],
isScrollable: isScrollable,
onChanged: (tabIndex) {
onChanged: (int tabIndex) {
setState(() { selectedIndices[n] = tabIndex; } );
}
);
@ -46,7 +46,7 @@ class TabbedNavigatorAppState extends State<TabbedNavigatorApp> {
Iterable<TabNavigatorView> views = ["event", "home", "android", "alarm", "face", "language"]
.map((icon_name) {
return new TabNavigatorView(
label: new TabLabel(icon: "action/${icon_name}"),
label: new TabLabel(icon: "action/$icon_name"),
builder: (BuildContext context) => _buildContent(icon_name)
);
});

View File

@ -35,7 +35,7 @@ class Checkbox extends StatelessComponent {
const Checkbox({Key key, this.value, this.onChanged}) : super(key: key);
final bool value;
final ValueChanged onChanged;
final ValueChanged<bool> onChanged;
Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context);
@ -67,7 +67,7 @@ class _CheckboxWrapper extends LeafRenderObjectWidget {
}
final bool value;
final ValueChanged onChanged;
final ValueChanged<bool> onChanged;
final Color uncheckedColor;
final Color accentColor;
@ -91,7 +91,7 @@ class _RenderCheckbox extends RenderToggleable {
bool value,
Color uncheckedColor,
Color accentColor,
ValueChanged onChanged
ValueChanged<bool> onChanged
}): _uncheckedColor = uncheckedColor,
_accentColor = accentColor,
super(

View File

@ -368,7 +368,7 @@ class _YearPickerState extends ScrollableWidgetListState<YearPicker> {
List<Widget> buildItems(BuildContext context, int start, int count) {
TextStyle style = Theme.of(context).text.body1.copyWith(color: Colors.black54);
List<Widget> items = new List<Widget>();
for(int i = start; i < start + count; i++) {
for (int i = start; i < start + count; i++) {
int year = config.firstDate.year + i;
String label = year.toString();
Widget item = new InkWell(

View File

@ -203,7 +203,7 @@ class DropdownButton<T> extends StatelessComponent {
final List<DropdownMenuItem<T>> items;
final T value;
final ValueChanged onChanged;
final ValueChanged<T> onChanged;
final int level;
void _showDropdown(BuildContext context, int selectedIndex, GlobalKey indexedStackKey) {
@ -217,7 +217,7 @@ class DropdownButton<T> extends StatelessComponent {
rect: rect,
level: level
));
completer.future.then((dynamic newValue) {
completer.future.then((T newValue) {
if (onChanged != null)
onChanged(newValue);
});

View File

@ -32,7 +32,7 @@ class Switch extends StatelessComponent {
: super(key: key);
final bool value;
final ValueChanged onChanged;
final ValueChanged<bool> onChanged;
Widget build(BuildContext context) {
return new _SwitchWrapper(
@ -49,7 +49,7 @@ class _SwitchWrapper extends LeafRenderObjectWidget {
final bool value;
final Color thumbColor;
final ValueChanged onChanged;
final ValueChanged<bool> onChanged;
_RenderSwitch createRenderObject() => new _RenderSwitch(
value: value,
@ -68,7 +68,7 @@ class _RenderSwitch extends RenderToggleable {
_RenderSwitch({
bool value,
Color thumbColor: _kThumbOffColor,
ValueChanged onChanged
ValueChanged<bool> onChanged
}) : _thumbColor = thumbColor,
super(value: value, onChanged: onChanged, size: _kSwitchSize);

View File

@ -10,7 +10,7 @@ import 'box.dart';
import 'object.dart';
import 'proxy_box.dart';
typedef void ValueChanged(bool value);
typedef void ValueChanged<T>(T value);
const Duration _kToggleDuration = const Duration(milliseconds: 200);
@ -19,7 +19,7 @@ const Duration _kToggleDuration = const Duration(milliseconds: 200);
// ValueChanged on a tap gesture and driving a changed animation. Subclasses are
// responsible for painting.
abstract class RenderToggleable extends RenderConstrainedBox {
RenderToggleable({bool value, Size size, ValueChanged onChanged})
RenderToggleable({bool value, Size size, ValueChanged<bool> onChanged})
: _value = value,
_onChanged = onChanged,
super(additionalConstraints: new BoxConstraints.tight(size)) {
@ -70,9 +70,9 @@ abstract class RenderToggleable extends RenderConstrainedBox {
performance.play(value ? AnimationDirection.forward : AnimationDirection.reverse);
}
ValueChanged get onChanged => _onChanged;
ValueChanged _onChanged;
void set onChanged(ValueChanged onChanged) {
ValueChanged<bool> get onChanged => _onChanged;
ValueChanged<bool> _onChanged;
void set onChanged(ValueChanged<bool> onChanged) {
_onChanged = onChanged;
}
}

View File

@ -37,6 +37,8 @@ abstract class Action {
double get duration => 0.0;
}
typedef void SetterCallback(dynamic value);
/// The abstract class for an action that changes properties over a time
/// interval, optionally using an easing curve.
abstract class ActionInterval extends Action {
@ -351,17 +353,6 @@ class ActionRemoveNode extends ActionInstant {
/// type [Point], [Size], [Rect], [double], or [Color].
class ActionTween extends ActionInterval {
/// The setter method used to set the property being animated.
final Function setter;
/// The start value of the animation.
final startVal;
/// The end value of the animation.
final endVal;
var _delta;
/// Creates a new tween action. The [setter] will be called to update the
/// animated property from [startVal] to [endVal] over the [duration] time in
/// seconds. Optionally an animation [curve] can be passed in for easing the
@ -381,6 +372,17 @@ class ActionTween extends ActionInterval {
_computeDelta();
}
/// The setter method used to set the property being animated.
final SetterCallback setter;
/// The start value of the animation.
final dynamic startVal;
/// The end value of the animation.
final dynamic endVal;
dynamic _delta;
void _computeDelta() {
if (startVal is Point) {
// Point
@ -474,7 +476,7 @@ class ActionTween extends ActionInterval {
/// itself is typically a property of a [Node] and powered by the [SpriteBox].
class ActionController {
List<Action> _actions = [];
List<Action> _actions = <Action>[];
/// Creates a new [ActionController]. However, for most uses a reference to
/// an [ActionController] is acquired through the [Node.actions] property.

View File

@ -17,6 +17,8 @@ Point _cardinalSplineAt(Point p0, Point p1, Point p2, Point p3, double tension,
return new Point(x, y);
}
typedef void PointSetterCallback(Point value);
/// The spline action is used to animate a point along a spline definied by
/// a set of points.
class ActionSpline extends ActionInterval {
@ -30,7 +32,7 @@ class ActionSpline extends ActionInterval {
}
/// The callback used to update a point when the action is run.
final Function setter;
final PointSetterCallback setter;
/// A list of points that define the spline.
final List<Point> points;

View File

@ -21,8 +21,8 @@ class ColorSequence {
/// Creates a new color sequence from a start and an end color.
ColorSequence.fromStartAndEndColor(Color start, Color end) {
colors = [start, end];
colorStops = [0.0, 1.0];
colors = <Color>[start, end];
colorStops = <double>[0.0, 1.0];
}
/// Creates a new color sequence by copying an existing sequence.

View File

@ -30,14 +30,18 @@ class EffectLine extends Node {
this.simplify: true,
ColorSequence colorSequence
}) {
if (points == null) this.points = [];
else this.points = points;
if (points == null)
this.points = <Point>[];
else
this.points = points;
_colorSequence = colorSequence;
if (_colorSequence == null)
if (_colorSequence == null) {
_colorSequence = new ColorSequence.fromStartAndEndColor(
new Color(0xffffffff),
new Color(0xffffffff));
new Color(0xffffffff)
);
}
_offset = scrollStart;
@ -65,7 +69,7 @@ class EffectLine extends Node {
set points(List<Point> points) {
_points = points;
_pointAges = [];
_pointAges = <double>[];
for (int i = 0; i < _points.length; i++) {
_pointAges.add(0.0);
}
@ -125,7 +129,7 @@ class EffectLine extends Node {
// Calculate colors
List<double> stops = _painter.calculatedTextureStops;
List<Color> colors = [];
List<Color> colors = <Color>[];
for (int i = 0; i < stops.length; i++) {
double stop = stops[i];
Color color = _colorSequence.colorAtPosition(stop);
@ -143,7 +147,7 @@ class EffectLine extends Node {
_painter.colors = colors;
// Calculate widths
List<double> widths = [];
List<double> widths = <double>[];
for (int i = 0; i < stops.length; i++) {
double stop = stops[i];
double growth = math.max(widthGrowthSpeed * _pointAges[i], 0.0);

View File

@ -36,7 +36,7 @@ class Label extends Node {
void paint(PaintingCanvas canvas) {
if (_painter == null) {
PlainTextSpan textSpan = new PlainTextSpan(_text);
StyledTextSpan styledTextSpan = new StyledTextSpan(_textStyle, [textSpan]);
StyledTextSpan styledTextSpan = new StyledTextSpan(_textStyle, <TextSpan>[textSpan]);
_painter = new TextPainter(styledTextSpan);
_painter.maxWidth = double.INFINITY;

View File

@ -19,7 +19,7 @@ class Layer extends Node with SpritePaint {
/// if it is known.
///
/// var myLayer = new Layer();
Layer([Rect this.layerRect = null]);
Layer([this.layerRect = null]);
Paint _cachedPaint = new Paint()
..filterQuality = ui.FilterQuality.low

View File

@ -61,7 +61,7 @@ class Node {
bool handleMultiplePointers = false;
int _handlingPointer;
List<Node>_children = [];
List<Node> _children = <Node>[];
ActionController _actions;
@ -104,9 +104,8 @@ class Node {
/// Creates a new [Node] without any transformation.
///
/// var myNode = new Node();
Node() {
}
/// Node myNode = new Node();
Node();
// Property setters and getters
@ -115,7 +114,7 @@ class Node {
/// For most applications it's not necessary to access the [SpriteBox] directly.
///
/// // Get the transformMode of the sprite box
/// var transformMode = myNode.spriteBox.transformMode;
/// SpriteBoxTransformMode transformMode = myNode.spriteBox.transformMode;
SpriteBox get spriteBox => _spriteBox;
/// The parent of this node, or null if it doesn't have a parent.
@ -450,7 +449,7 @@ class Node {
child._parent = null;
child._spriteBox = null;
}
_children = [];
_children = <Node>[];
_childrenNeedSorting = false;
if (_spriteBox != null) _spriteBox._deregisterNode(null);
}

View File

@ -21,8 +21,9 @@ class NodeWithSize extends Node {
/// The default [size] is zero and the default [pivot] point is the origin. Subclasses may change the default values.
///
/// var myNodeWithSize = new NodeWithSize(new Size(1024.0, 1024.0));
NodeWithSize(Size this.size) {
if (size == null) size = Size.zero;
NodeWithSize(this.size) {
if (size == null)
size = Size.zero;
pivot = Point.origin;
}

View File

@ -359,9 +359,9 @@ class ParticleSystem extends Node {
void paint(PaintingCanvas canvas) {
List<ui.RSTransform> transforms = [];
List<Rect> rects = [];
List<Color> colors = [];
List<ui.RSTransform> transforms = <ui.RSTransform>[];
List<Rect> rects = <Rect>[];
List<Color> colors = <Color>[];
_paint.transferMode = transferMode;

View File

@ -237,7 +237,7 @@ class PhysicsBody {
box2d.Body _body;
List<PhysicsJoint> _joints = [];
List<PhysicsJoint> _joints = <PhysicsJoint>[];
bool _attached = false;
@ -355,8 +355,8 @@ class PhysicsBody {
fixtureDef.isSensor = isSensor;
// Get shapes
List<box2d.Shape> b2Shapes = [];
List<PhysicsShape> physicsShapes = [];
List<box2d.Shape> b2Shapes = <box2d.Shape>[];
List<PhysicsShape> physicsShapes = <PhysicsShape>[];
_addB2Shapes(physicsNode, shape, b2Shapes, physicsShapes);
// Create fixtures

View File

@ -41,7 +41,7 @@ class PhysicsShapePolygon extends PhysicsShape {
final List<Point> points;
box2d.Shape _createB2Shape(PhysicsWorld node, double scale) {
List<Vector2> vectors = [];
List<Vector2> vectors = <Vector2>[];
for (Point point in points) {
Vector2 vec = new Vector2(
scale * point.x / node.b2WorldToNodeConversionFactor,
@ -91,7 +91,7 @@ class PhysicsShapeChain extends PhysicsShape {
final bool loop;
box2d.Shape _createB2Shape(PhysicsWorld node, double scale) {
List<Vector2> vectors = [];
List<Vector2> vectors = <Vector2>[];
for (Point point in points) {
Vector2 vec = new Vector2(
scale * point.x / node.b2WorldToNodeConversionFactor,

View File

@ -39,11 +39,11 @@ class PhysicsWorld extends Node {
_ContactHandler _contactHandler;
List<PhysicsJoint> _joints = [];
List<PhysicsJoint> _joints = <PhysicsJoint>[];
List<box2d.Body> _bodiesScheduledForDestruction = [];
List<box2d.Body> _bodiesScheduledForDestruction = <box2d.Body>[];
List<PhysicsBody> _bodiesScheduledForUpdate = [];
List<PhysicsBody> _bodiesScheduledForUpdate = <PhysicsBody>[];
_PhysicsDebugDraw _debugDraw;
@ -272,7 +272,7 @@ class _ContactHandler extends box2d.ContactListener {
PhysicsWorld physicsNode;
List<_ContactCallbackInfo> callbackInfos = [];
List<_ContactCallbackInfo> callbackInfos = <_ContactCallbackInfo>[];
void addContactCallback(PhysicsContactCallback callback, Object tagA, Object tagB, PhysicsContactType type) {
callbackInfos.add(new _ContactCallbackInfo(callback, tagA, tagB, type));
@ -324,7 +324,7 @@ class _ContactHandler extends box2d.ContactListener {
box2d.WorldManifold manifold = new box2d.WorldManifold();
b2Contact.getWorldManifold(manifold);
touchingNormal = new Offset(manifold.normal.x, manifold.normal.y);
touchingPoints = [];
touchingPoints = <Point>[];
for (Vector2 vec in manifold.points) {
touchingPoints.add(new Point(
vec.x * physicsNode.b2WorldToNodeConversionFactor,

View File

@ -59,10 +59,10 @@ class SoundEffectPlayer {
}
MediaServiceProxy _mediaService;
List<SoundEffectStream> _soundEffectStreams = [];
List<SoundEffectStream> _soundEffectStreams = <SoundEffectStream>[];
// TODO: This should no longer be needed when moving to SoundPool backing
Map<SoundEffect,MediaPlayerProxy> _mediaPlayers = {};
Map<SoundEffect,MediaPlayerProxy> _mediaPlayers = <SoundEffect, MediaPlayerProxy>{};
Future _prepare(SoundEffectStream playingSound) async {
await playingSound._player.ptr.prepare(playingSound.sound._data);
@ -133,7 +133,7 @@ class SoundEffectPlayer {
for (SoundEffectStream playingSound in _soundEffectStreams) {
playingSound._player.ptr.pause();
}
_soundEffectStreams = [];
_soundEffectStreams = <SoundEffectStream>[];
}
}
@ -154,7 +154,7 @@ class SoundTrack {
SoundTrackPlayer _sharedSoundTrackPlayer;
class SoundTrackPlayer {
List<SoundTrack> _soundTracks = [];
List<SoundTrack> _soundTracks = <SoundTrack>[];
static sharedInstance() {
if (_sharedSoundTrackPlayer == null) {

View File

@ -18,7 +18,7 @@ enum SoundEventMinimumOverlapPolicy {
class SoundEvent {
SoundEvent(SoundEffect effect) {
effects = [effect];
effects = <SoundEffect>[effect];
}
SoundEvent.withList(this.effects);
@ -61,7 +61,7 @@ class SoundManager {
new Timer.periodic(new Duration(milliseconds:10), _update);
}
Map<SoundEvent, List<_PlayingSoundEvent>> _playingEvents = {};
Map<SoundEvent, List<_PlayingSoundEvent>> _playingEvents = <SoundEvent, List<_PlayingSoundEvent>>{};
SoundTrack _backgroundMusicTrack;
SoundEffectPlayer _effectPlayer = SoundEffectPlayer.sharedInstance();
@ -75,7 +75,7 @@ class SoundManager {
void playEvent(SoundEvent evt, [double volume = 1.0, double pitch = 1.0, double pan = 0.0]) {
List<_PlayingSoundEvent> playingList = _playingEvents[evt];
if (playingList == null) playingList = [];
if (playingList == null) playingList = <_PlayingSoundEvent>[];
// Check simultaneousLimit
if (evt.simultaneousLimit != 0 && evt.simultaneousLimit >= playingList.length) {
@ -131,13 +131,13 @@ class SoundManager {
}
void stopAllEvents([double fadeDuration]) {
for (List<_PlayingSoundEvent> playingList in _playingEvents) {
for (List<_PlayingSoundEvent> playingList in _playingEvents.values) {
for (_PlayingSoundEvent playing in playingList) {
if (fadeDuration > 0.0) {
// Fade out and stop
ActionTween fadeOut = new ActionTween((a) => playing.stream.volume = a, playing.stream.volume, 0.0, fadeDuration);
ActionCallFunction stop = new ActionCallFunction(() { _effectPlayer.stop(playing.stream); });
ActionSequence seq = new ActionSequence([fadeOut, stop]);
ActionSequence seq = new ActionSequence(<Action>[fadeOut, stop]);
actions.run(seq);
}
else {
@ -175,7 +175,7 @@ class SoundManager {
} else {
ActionTween fadeOut = new ActionTween((a) => _backgroundMusicTrack.volume = a, _backgroundMusicTrack.volume, 0.0, fadeOutDuration);
ActionCallFunction stop = new ActionCallFunction(() { _trackPlayer.stop(_backgroundMusicTrack); });
ActionSequence seq = new ActionSequence([fadeOut, stop]);
ActionSequence seq = new ActionSequence(<Action>[fadeOut, stop]);
actions.run(seq);
}
} else {
@ -190,7 +190,7 @@ class SoundManager {
ActionCallFunction fadeInCall = new ActionCallFunction(() {
_fadeInTrack(track, fadeInDuration);
});
ActionSequence seq = new ActionSequence([delay, fadeInCall]);
ActionSequence seq = new ActionSequence(<Action>[delay, fadeInCall]);
actions.run(seq);
}
}
@ -216,7 +216,7 @@ class SoundManager {
ActionCallFunction stopCall = new ActionCallFunction(() {
_trackPlayer.stop(_backgroundMusicTrack);
});
ActionSequence seq = new ActionSequence([fadeOut, stopCall]);
ActionSequence seq = new ActionSequence(<Action>[fadeOut, stopCall]);
actions.run(seq);
}

View File

@ -196,12 +196,12 @@ class SpriteBox extends RenderBox {
if (event.type == 'pointerdown') {
// Build list of event targets
if (_eventTargets == null) {
_eventTargets = [];
_eventTargets = <Node>[];
_addEventTargets(_rootNode, _eventTargets);
}
// Find the once that are hit by the pointer
List<Node> nodeTargets = [];
List<Node> nodeTargets = <Node>[];
for (int i = _eventTargets.length - 1; i >= 0; i--) {
Node node = _eventTargets[i];
@ -393,8 +393,8 @@ class SpriteBox extends RenderBox {
}
void _rebuildActionControllersAndPhysicsNodes() {
_actionControllers = [];
_physicsNodes = [];
_actionControllers = <ActionController>[];
_physicsNodes = <PhysicsWorld>[];
_addActionControllersAndPhysicsNodes(_rootNode);
}
@ -429,7 +429,7 @@ class SpriteBox extends RenderBox {
void _callConstraintsPreUpdate(double dt) {
if (_constrainedNodes == null) {
_constrainedNodes = [];
_constrainedNodes = <Node>[];
_addConstrainedNodes(_rootNode, _constrainedNodes);
}
@ -442,7 +442,7 @@ class SpriteBox extends RenderBox {
void _callConstraintsConstrain(double dt) {
if (_constrainedNodes == null) {
_constrainedNodes = [];
_constrainedNodes = <Node>[];
_addConstrainedNodes(_rootNode, _constrainedNodes);
}
@ -481,7 +481,7 @@ class SpriteBox extends RenderBox {
List<Node> findNodesAtPosition(Point position) {
assert(position != null);
List<Node> nodes = [];
List<Node> nodes = <Node>[];
// Traverse the render tree and find objects at the position
_addNodesAtPosition(_rootNode, position, nodes);

View File

@ -9,7 +9,7 @@ part of flutter_sprites;
class SpriteSheet {
ui.Image _image;
Map<String, Texture> _textures = new Map();
Map<String, Texture> _textures = new Map<String, Texture>();
/// Creates a new sprite sheet from an [_image] and a sprite sheet [jsonDefinition].
///

View File

@ -4,6 +4,23 @@ part of flutter_sprites;
///
/// Normally you get a reference to a texture from a [SpriteSheet], but you can also create one from an [Image].
class Texture {
/// Creates a new texture from an [Image] object.
///
/// var myTexture = new Texture(myImage);
Texture(ui.Image image) :
size = new Size(image.width.toDouble(), image.height.toDouble()),
image = image,
trimmed = false,
rotated = false,
frame = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
spriteSourceSize = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
pivot = new Point(0.5, 0.5);
Texture._fromSpriteFrame(this.image, this.name, this.size, this.rotated, this.trimmed, this.frame,
this.spriteSourceSize, this.pivot);
/// The image that this texture is a part of.
///
/// var textureImage = myTexture.image;
@ -48,23 +65,6 @@ class Texture {
/// myTexture.pivot = new Point(0.5, 0.5);
Point pivot;
/// Creates a new texture from an [Image] object.
///
/// var myTexture = new Texture(myImage);
Texture(ui.Image image) :
size = new Size(image.width.toDouble(), image.height.toDouble()),
image = image,
trimmed = false,
rotated = false,
frame = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
spriteSourceSize = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
pivot = new Point(0.5, 0.5);
Texture._fromSpriteFrame(this.image, this.name, this.size, this.rotated, this.trimmed, this.frame,
this.spriteSourceSize, this.pivot) {
}
Texture textureFromRect(Rect rect, [String name = null]) {
assert(rect != null);
assert(!rotated);

View File

@ -92,15 +92,15 @@ class TexturedLinePainter {
_cachedPaint.transferMode = transferMode;
// Calculate normals
List<Vector2> vectors = [];
List<Vector2> vectors = <Vector2>[];
for (Point pt in _points) {
vectors.add(new Vector2(pt.x, pt.y));
}
List<Vector2> miters = _computeMiterList(vectors, false);
List<Point> vertices = [];
List<int> indicies = [];
List<Color> verticeColors = [];
List<Point> vertices = <Point>[];
List<int> indicies = <int>[];
List<Color> verticeColors = <Color>[];
List<Point> textureCoordinates;
double textureTop;
double textureBottom;
@ -121,7 +121,7 @@ class TexturedLinePainter {
// Setup for calculating texture coordinates
textureTop = texture.frame.top;
textureBottom = texture.frame.bottom;
textureCoordinates = [];
textureCoordinates = <Point>[];
// Use correct stops
if (textureStops != null) {
@ -150,8 +150,8 @@ class TexturedLinePainter {
int lastIndex1 = (i - 1) * 2 + 1;
int currentIndex0 = i * 2;
int currentIndex1 = i * 2 + 1;
indicies.addAll([lastIndex0, lastIndex1, currentIndex0]);
indicies.addAll([lastIndex1, currentIndex1, currentIndex0]);
indicies.addAll(<int>[lastIndex0, lastIndex1, currentIndex0]);
indicies.addAll(<int>[lastIndex1, currentIndex1, currentIndex0]);
// Add colors
verticeColors.add(colors[i]);
@ -209,7 +209,7 @@ class TexturedLinePainter {
}
void _calculateTextureStops() {
List<double> stops = [];
List<double> stops = <double>[];
double length = 0.0;
// Add first stop
@ -262,7 +262,7 @@ Vector2 _vectorDirection(Vector2 a, Vector2 b) {
}
List<Vector2> _computeMiterList(List<Vector2> points, bool closed) {
List<Vector2> out = [];
List<Vector2> out = <Vector2>[];
Vector2 curNormal = null;
if (closed) {

View File

@ -39,7 +39,7 @@ class VirtualJoystick extends NodeWithSize {
else if (event.type == "pointerup" || event.type == "pointercancel") {
_pointerDownAt = null;
_value = Point.origin;
ActionTween moveToCenter = new ActionTween((a) => _handlePos = a, _handlePos, _center, 0.4, elasticOut);
ActionTween moveToCenter = new ActionTween((a) => _handlePos = a, _handlePos, _center, 0.4, Curves.elasticOut);
actions.run(moveToCenter);
_isDown = false;
} else if (event.type == "pointermove") {