Commit a6c473ea authored by Hixie's avatar Hixie

Strong modeify the examples

This makes skyanalyzer also check the examples, and fixes everything it
found there.
parent 1dbf9bc8
...@@ -17,7 +17,7 @@ class Field extends StatelessComponent { ...@@ -17,7 +17,7 @@ class Field extends StatelessComponent {
final String placeholder; final String placeholder;
Widget build(BuildContext context) { Widget build(BuildContext context) {
return new Row([ return new Row(<Widget>[
new Padding( new Padding(
padding: const EdgeDims.symmetric(horizontal: 16.0), padding: const EdgeDims.symmetric(horizontal: 16.0),
child: new Icon(type: icon, size: 24) child: new Icon(type: icon, size: 24)
...@@ -37,7 +37,7 @@ class AddressBookHome extends StatelessComponent { ...@@ -37,7 +37,7 @@ class AddressBookHome extends StatelessComponent {
Widget buildToolBar(BuildContext context) { Widget buildToolBar(BuildContext context) {
return new ToolBar( return new ToolBar(
left: new IconButton(icon: "navigation/arrow_back"), 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 { ...@@ -56,7 +56,7 @@ class AddressBookHome extends StatelessComponent {
static final GlobalKey noteKey = new GlobalKey(label: 'note field'); static final GlobalKey noteKey = new GlobalKey(label: 'note field');
Widget buildBody(BuildContext context) { Widget buildBody(BuildContext context) {
return new Block([ return new Block(<Widget>[
new AspectRatio( new AspectRatio(
aspectRatio: 16.0 / 9.0, aspectRatio: 16.0 / 9.0,
child: new Container( child: new Container(
......
...@@ -10,61 +10,59 @@ class DateUtils { ...@@ -10,61 +10,59 @@ class DateUtils {
static const YESTERDAY = 'Yesterday'; static const YESTERDAY = 'Yesterday';
static const MS_IN_WEEK = static const MS_IN_WEEK = DateTime.DAYS_PER_WEEK * Duration.MILLISECONDS_PER_DAY;
DateTime.DAYS_PER_WEEK * Duration.MILLISECONDS_PER_DAY;
// TODO(jmesserly): locale specific date format // TODO(jmesserly): locale specific date format
static String _twoDigits(int n) { static String _twoDigits(int n) {
if (n >= 10) return "${n}"; if (n >= 10)
return "0${n}"; 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) { static String toHourMinutesString(Duration duration) {
assert(duration.inDays == 0); assert(duration.inDays == 0);
int hours = duration.inHours; int hours = duration.inHours;
String a; String a;
if (hours >= 12) { if (hours >= 12) {
a = 'pm'; a = 'pm';
if (hours != 12) { if (hours != 12)
hours -= 12; hours -= 12;
}
} else { } else {
a = 'am'; a = 'am';
if (hours == 0) { if (hours == 0)
hours += 12; hours += 12;
}
} }
String twoDigits(int n) { String twoDigits(int n) {
if (n >= 10) return "${n}"; if (n >= 10)
return "0${n}"; return '$n';
return '0$n';
} }
String mm = String mm = twoDigits(duration.inMinutes.remainder(Duration.MINUTES_PER_HOUR));
twoDigits(duration.inMinutes.remainder(Duration.MINUTES_PER_HOUR)); return '$hours:$mm $a';
return "${hours}:${mm} ${a}";
} }
/** /// A date/time formatter that takes into account the current date/time:
* 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 today, just show the time /// - if it's from yesterday, just show 'Yesterday'
* - if it's from yesterday, just show 'Yesterday' /// - if it's from the same week, just show the weekday
* - if it's from the same week, just show the weekday /// - otherwise, show just the date
* - otherwise, show just the date
*/
static String toRecentTimeString(DateTime then) { static String toRecentTimeString(DateTime then) {
bool datesAreEqual(DateTime d1, DateTime d2) { bool datesAreEqual(DateTime d1, DateTime d2) {
return (d1.year == d2.year) && (d1.month == d2.month) && return (d1.year == d2.year) &&
(d1.day == d2.day); (d1.month == d2.month) &&
(d1.day == d2.day);
} }
final now = new DateTime.now(); final now = new DateTime.now();
if (datesAreEqual(then, now)) { if (datesAreEqual(then, now)) {
return toHourMinutesString(new Duration( return toHourMinutesString(new Duration(
days: 0, days: 0,
hours: then.hour, hours: then.hour,
minutes: then.minute, minutes: then.minute,
seconds: then.second, seconds: then.second,
milliseconds: then.millisecond)); milliseconds: then.millisecond)
);
} }
final today = new DateTime(now.year, now.month, now.day, 0, 0, 0, 0); final today = new DateTime(now.year, now.month, now.day, 0, 0, 0, 0);
...@@ -76,7 +74,7 @@ class DateUtils { ...@@ -76,7 +74,7 @@ class DateUtils {
} else { } else {
String twoDigitMonth = _twoDigits(then.month); String twoDigitMonth = _twoDigits(then.month);
String twoDigitDay = _twoDigits(then.day); String twoDigitDay = _twoDigits(then.day);
return "${then.year}-${twoDigitMonth}-${twoDigitDay}"; return '${then.year}-$twoDigitMonth-$twoDigitDay';
} }
} }
...@@ -84,6 +82,6 @@ class DateUtils { ...@@ -84,6 +82,6 @@ class DateUtils {
// TODO(jmesserly): locale specific date format // TODO(jmesserly): locale specific date format
String twoDigitMonth = _twoDigits(then.month); String twoDigitMonth = _twoDigits(then.month);
String twoDigitDay = _twoDigits(then.day); String twoDigitDay = _twoDigits(then.day);
return "${then.year}-${twoDigitMonth}-${twoDigitDay}"; return '${then.year}-$twoDigitMonth-$twoDigitDay';
} }
} }
...@@ -18,7 +18,7 @@ class FitnessItemList extends StatelessComponent { ...@@ -18,7 +18,7 @@ class FitnessItemList extends StatelessComponent {
padding: const EdgeDims.all(4.0), padding: const EdgeDims.all(4.0),
items: items, items: items,
itemExtent: kFitnessItemHeight, 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> { ...@@ -68,7 +68,7 @@ class FeedFragmentState extends State<FeedFragment> {
void _showDrawer() { void _showDrawer() {
showDrawer( showDrawer(
context: context, context: context,
child: new Block([ child: new Block(<Widget>[
new DrawerHeader(child: new Text('Fitness')), new DrawerHeader(child: new Text('Fitness')),
new DrawerItem( new DrawerItem(
icon: 'action/view_list', icon: 'action/view_list',
...@@ -120,7 +120,7 @@ class FeedFragmentState extends State<FeedFragment> { ...@@ -120,7 +120,7 @@ class FeedFragmentState extends State<FeedFragment> {
context: context, context: context,
placeholderKey: _snackBarPlaceholderKey, placeholderKey: _snackBarPlaceholderKey,
content: new Text("Item deleted."), content: new Text("Item deleted."),
actions: [new SnackBarAction(label: "UNDO", onPressed: () { actions: <SnackBarAction>[new SnackBarAction(label: "UNDO", onPressed: () {
config.onItemCreated(item); config.onItemCreated(item);
config.navigator.pop(); config.navigator.pop();
})] })]
...@@ -172,7 +172,7 @@ class FeedFragmentState extends State<FeedFragment> { ...@@ -172,7 +172,7 @@ class FeedFragmentState extends State<FeedFragment> {
return new Container(); return new Container();
if (config.userData.items.length == 0) { if (config.userData.items.length == 0) {
return new Row( 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 justifyContent: FlexJustifyContent.center
); );
} }
...@@ -225,7 +225,7 @@ class AddItemDialog extends StatefulComponent { ...@@ -225,7 +225,7 @@ class AddItemDialog extends StatefulComponent {
class AddItemDialogState extends State<AddItemDialog> { class AddItemDialogState extends State<AddItemDialog> {
// TODO(jackson): Internationalize // TODO(jackson): Internationalize
static final Map<String, String> _labels = { static final Map<String, String> _labels = <String, String>{
'/measurements/new': 'Measure', '/measurements/new': 'Measure',
'/meals/new': 'Eat', '/meals/new': 'Eat',
}; };
...@@ -239,9 +239,9 @@ class AddItemDialogState extends State<AddItemDialog> { ...@@ -239,9 +239,9 @@ class AddItemDialogState extends State<AddItemDialog> {
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
List<Widget> menuItems = []; List<Widget> menuItems = <Widget>[];
for(String routeName in _labels.keys) { for (String routeName in _labels.keys) {
menuItems.add(new DialogMenuItem([ menuItems.add(new DialogMenuItem(<Widget>[
new Flexible(child: new Text(_labels[routeName])), new Flexible(child: new Text(_labels[routeName])),
new Radio(value: routeName, groupValue: _addItemRoute, onChanged: _handleAddItemRouteChanged), new Radio(value: routeName, groupValue: _addItemRoute, onChanged: _handleAddItemRouteChanged),
], onPressed: () => _handleAddItemRouteChanged(routeName))); ], onPressed: () => _handleAddItemRouteChanged(routeName)));
...@@ -252,7 +252,7 @@ class AddItemDialogState extends State<AddItemDialog> { ...@@ -252,7 +252,7 @@ class AddItemDialogState extends State<AddItemDialog> {
onDismiss: () { onDismiss: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
actions: [ actions: <Widget>[
new FlatButton( new FlatButton(
child: new Text('CANCEL'), child: new Text('CANCEL'),
onPressed: () { onPressed: () {
......
...@@ -29,7 +29,7 @@ abstract class UserData { ...@@ -29,7 +29,7 @@ abstract class UserData {
class UserDataImpl extends UserData { class UserDataImpl extends UserData {
UserDataImpl(); UserDataImpl();
List<FitnessItem> _items = []; List<FitnessItem> _items = <FitnessItem>[];
BackupMode _backupMode; BackupMode _backupMode;
BackupMode get backupMode => _backupMode; BackupMode get backupMode => _backupMode;
...@@ -46,7 +46,7 @@ class UserDataImpl extends UserData { ...@@ -46,7 +46,7 @@ class UserDataImpl extends UserData {
List<FitnessItem> get items => _items; List<FitnessItem> get items => _items;
void sort() { 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) { void add(FitnessItem item) {
...@@ -69,14 +69,14 @@ class UserDataImpl extends UserData { ...@@ -69,14 +69,14 @@ class UserDataImpl extends UserData {
return mode.toString() == json['backupMode']; return mode.toString() == json['backupMode'];
}); });
} catch(e) { } catch(e) {
print("Failed to load backup mode: ${e}"); print("Failed to load backup mode: $e");
} }
_goalWeight = json['goalWeight']; _goalWeight = json['goalWeight'];
} }
Map toJson() { Map toJson() {
Map json = new Map(); 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['backupMode'] = _backupMode.toString();
json['goalWeight'] = _goalWeight; json['goalWeight'] = _goalWeight;
return json; return json;
...@@ -132,7 +132,7 @@ class FitnessAppState extends State<FitnessApp> { ...@@ -132,7 +132,7 @@ class FitnessAppState extends State<FitnessApp> {
accentColor: Colors.pinkAccent[200] accentColor: Colors.pinkAccent[200]
), ),
title: 'Fitness', title: 'Fitness',
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) { '/': (RouteArguments args) {
return new FeedFragment( return new FeedFragment(
navigator: args.navigator, navigator: args.navigator,
......
...@@ -20,7 +20,7 @@ class MealRow extends FitnessItemRow { ...@@ -20,7 +20,7 @@ class MealRow extends FitnessItemRow {
Widget buildContent(BuildContext context) { Widget buildContent(BuildContext context) {
Meal meal = item; Meal meal = item;
List<Widget> children = [ List<Widget> children = <Widget>[
new Flexible( new Flexible(
child: new Text( child: new Text(
meal.description, meal.description,
...@@ -65,7 +65,7 @@ class MealFragmentState extends State<MealFragment> { ...@@ -65,7 +65,7 @@ class MealFragmentState extends State<MealFragment> {
icon: "navigation/close", icon: "navigation/close",
onPressed: config.navigator.pop), onPressed: config.navigator.pop),
center: new Text('New Meal'), center: new Text('New Meal'),
right: [ right: <Widget>[
// TODO(abarth): Should this be a FlatButton? // TODO(abarth): Should this be a FlatButton?
new InkWell( new InkWell(
onTap: _handleSave, onTap: _handleSave,
...@@ -85,10 +85,11 @@ class MealFragmentState extends State<MealFragment> { ...@@ -85,10 +85,11 @@ class MealFragmentState extends State<MealFragment> {
Widget buildBody() { Widget buildBody() {
Meal meal = new Meal(when: new DateTime.now()); 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( return new ScrollableViewport(
child: new Container( child: new Container(
padding: const EdgeDims.all(20.0), padding: const EdgeDims.all(20.0),
child: new BlockBody([ child: new BlockBody(<Widget>[
new Text(meal.displayDate), new Text(meal.displayDate),
new Input( new Input(
key: descriptionKey, key: descriptionKey,
......
...@@ -6,7 +6,7 @@ part of fitness; ...@@ -6,7 +6,7 @@ part of fitness;
class Measurement extends FitnessItem { class Measurement extends FitnessItem {
Measurement({ DateTime when, this.weight }) : super(when: when); 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; final double weight;
...@@ -32,7 +32,7 @@ class MeasurementRow extends FitnessItemRow { ...@@ -32,7 +32,7 @@ class MeasurementRow extends FitnessItemRow {
Widget buildContent(BuildContext context) { Widget buildContent(BuildContext context) {
Measurement measurement = item; Measurement measurement = item;
List<Widget> children = [ List<Widget> children = <Widget>[
new Flexible( new Flexible(
child: new Text( child: new Text(
measurement.displayWeight, measurement.displayWeight,
...@@ -85,7 +85,7 @@ class MeasurementDateDialogState extends State<MeasurementDateDialog> { ...@@ -85,7 +85,7 @@ class MeasurementDateDialogState extends State<MeasurementDateDialog> {
onChanged: _handleDateChanged onChanged: _handleDateChanged
), ),
contentPadding: EdgeDims.zero, contentPadding: EdgeDims.zero,
actions: [ actions: <Widget>[
new FlatButton( new FlatButton(
child: new Text('CANCEL'), child: new Text('CANCEL'),
onPressed: () { onPressed: () {
...@@ -140,7 +140,7 @@ class MeasurementFragmentState extends State<MeasurementFragment> { ...@@ -140,7 +140,7 @@ class MeasurementFragmentState extends State<MeasurementFragment> {
icon: "navigation/close", icon: "navigation/close",
onPressed: config.navigator.pop), onPressed: config.navigator.pop),
center: new Text('New Measurement'), center: new Text('New Measurement'),
right: [ right: <Widget>[
// TODO(abarth): Should this be a FlatButton? // TODO(abarth): Should this be a FlatButton?
new InkWell( new InkWell(
onTap: _handleSave, onTap: _handleSave,
...@@ -175,12 +175,12 @@ class MeasurementFragmentState extends State<MeasurementFragment> { ...@@ -175,12 +175,12 @@ class MeasurementFragmentState extends State<MeasurementFragment> {
// TODO(jackson): Revisit the layout of this pane to be more maintainable // TODO(jackson): Revisit the layout of this pane to be more maintainable
return new Container( return new Container(
padding: const EdgeDims.all(20.0), padding: const EdgeDims.all(20.0),
child: new Column([ child: new Column(<Widget>[
new GestureDetector( new GestureDetector(
onTap: _handleDatePressed, onTap: _handleDatePressed,
child: new Container( child: new Container(
height: 50.0, height: 50.0,
child: new Column([ child: new Column(<Widget>[
new Text('Measurement Date'), new Text('Measurement Date'),
new Text(measurement.displayDate, style: Theme.of(context).text.caption), new Text(measurement.displayDate, style: Theme.of(context).text.caption),
], alignItems: FlexAlignItems.start) ], alignItems: FlexAlignItems.start)
......
...@@ -74,7 +74,7 @@ class SettingsFragmentState extends State<SettingsFragment> { ...@@ -74,7 +74,7 @@ class SettingsFragmentState extends State<SettingsFragment> {
onDismiss: () { onDismiss: () {
Navigator.of(context).pop(); Navigator.of(context).pop();
}, },
actions: [ actions: <Widget>[
new FlatButton( new FlatButton(
child: new Text('CANCEL'), child: new Text('CANCEL'),
onPressed: () { onPressed: () {
...@@ -94,20 +94,21 @@ class SettingsFragmentState extends State<SettingsFragment> { ...@@ -94,20 +94,21 @@ class SettingsFragmentState extends State<SettingsFragment> {
} }
Widget buildSettingsPane(BuildContext context) { Widget buildSettingsPane(BuildContext context) {
// TODO(ianh): Make Block capable of doing this
return new ScrollableViewport( return new ScrollableViewport(
child: new Container( child: new Container(
padding: const EdgeDims.symmetric(vertical: 20.0), padding: const EdgeDims.symmetric(vertical: 20.0),
child: new BlockBody([ child: new BlockBody(<Widget>[
new DrawerItem( new DrawerItem(
onPressed: () { _handleBackupChanged(!(config.userData.backupMode == BackupMode.enabled)); }, 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 Flexible(child: new Text('Back up data to the cloud')),
new Switch(value: config.userData.backupMode == BackupMode.enabled, onChanged: _handleBackupChanged), new Switch(value: config.userData.backupMode == BackupMode.enabled, onChanged: _handleBackupChanged),
]) ])
), ),
new DrawerItem( new DrawerItem(
onPressed: () => _handleGoalWeightPressed(), onPressed: () => _handleGoalWeightPressed(),
child: new Column([ child: new Column(<Widget>[
new Text('Goal Weight'), new Text('Goal Weight'),
new Text(goalWeightText, style: Theme.of(context).text.caption), new Text(goalWeightText, style: Theme.of(context).text.caption),
], ],
......
...@@ -18,7 +18,7 @@ SpriteSheet _spriteSheet; ...@@ -18,7 +18,7 @@ SpriteSheet _spriteSheet;
main() async { main() async {
_images = new ImageMap(_bundle); _images = new ImageMap(_bundle);
await _images.load([ await _images.load(<String>[
'assets/checker.png', 'assets/checker.png',
'assets/line_effects.png' 'assets/line_effects.png'
]); ]);
...@@ -45,7 +45,7 @@ class TestAppState extends State<TestApp> { ...@@ -45,7 +45,7 @@ class TestAppState extends State<TestApp> {
TestBed _testBed; TestBed _testBed;
int _selectedLine = 0; int _selectedLine = 0;
List<String> _labelTexts = [ List<String> _labelTexts = <String>[
"Colored", "Colored",
"Smoke", "Smoke",
"Electric", "Electric",
...@@ -56,14 +56,14 @@ class TestAppState extends State<TestApp> { ...@@ -56,14 +56,14 @@ class TestAppState extends State<TestApp> {
return new MaterialApp( return new MaterialApp(
title: 'EffectLine Demo', title: 'EffectLine Demo',
theme: _theme, theme: _theme,
routes: { routes: <String, RouteBuilder>{
'/': _buildColumn '/': _buildColumn
} }
); );
} }
Column _buildColumn(RouteArguments args) { Column _buildColumn(RouteArguments args) {
return new Column([ return new Column(<Widget>[
new Flexible(child: _buildSpriteWidget()), new Flexible(child: _buildSpriteWidget()),
_buildTabBar() _buildTabBar()
]); ]);
...@@ -82,10 +82,9 @@ class TestAppState extends State<TestApp> { ...@@ -82,10 +82,9 @@ class TestAppState extends State<TestApp> {
} }
List<TabLabel> _buildTabLabels() { List<TabLabel> _buildTabLabels() {
List<TabLabel> labels = []; List<TabLabel> labels = <TabLabel>[];
for(String text in _labelTexts) { for (String text in _labelTexts)
labels.add(new TabLabel(text: text)); labels.add(new TabLabel(text: text));
}
return labels; return labels;
} }
...@@ -168,7 +167,8 @@ class TestBed extends NodeWithSize { ...@@ -168,7 +167,8 @@ class TestBed extends NodeWithSize {
} }
bool handleEvent(SpriteBoxEvent event) { bool handleEvent(SpriteBoxEvent event) {
if (event.type == "pointerdown") _line.points = []; if (event.type == "pointerdown")
_line.points = <Point>[];
if (event.type == "pointerdown" || event.type == "pointermove") { if (event.type == "pointerdown" || event.type == "pointermove") {
Point pos = convertPointToNodeSpace(event.boxPosition); Point pos = convertPointToNodeSpace(event.boxPosition);
......
part of game; part of game;
typedef void PointSetterCallback(Point value);
class ActionCircularMove extends ActionInterval { class ActionCircularMove extends ActionInterval {
ActionCircularMove(this.setter, this.center, this.radius, this.startAngle, this.clockWise, double duration) : super (duration); 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 Point center;
final double radius; final double radius;
final double startAngle; final double startAngle;
...@@ -21,7 +23,7 @@ class ActionCircularMove extends ActionInterval { ...@@ -21,7 +23,7 @@ class ActionCircularMove extends ActionInterval {
class ActionOscillate extends ActionInterval { class ActionOscillate extends ActionInterval {
ActionOscillate(this.setter, this.center, this.radius, double duration) : super(duration); ActionOscillate(this.setter, this.center, this.radius, double duration) : super(duration);
final Function setter; final PointSetterCallback setter;
final Point center; final Point center;
final double radius; final double radius;
......
...@@ -31,7 +31,7 @@ class ExplosionBig extends Explosion { ...@@ -31,7 +31,7 @@ class ExplosionBig extends Explosion {
ParticleSystem particlesFire = new ParticleSystem( ParticleSystem particlesFire = new ParticleSystem(
sheet["fire_particle.png"], 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, numParticlesToEmit: 25,
emissionRate: 1000.0, emissionRate: 1000.0,
startSize: 0.5, startSize: 0.5,
...@@ -48,32 +48,32 @@ class ExplosionBig extends Explosion { ...@@ -48,32 +48,32 @@ class ExplosionBig extends Explosion {
addChild(particlesFire); addChild(particlesFire);
// Add ring // Add ring
Sprite sprtRing = new Sprite(sheet["explosion_ring.png"]); Sprite spriteRing = new Sprite(sheet["explosion_ring.png"]);
sprtRing.transferMode = ui.TransferMode.plus; spriteRing.transferMode = ui.TransferMode.plus;
addChild(sprtRing); addChild(spriteRing);
Action scale = new ActionTween( (a) => sprtRing.scale = a, 0.2, 1.0, 0.75); Action scale = new ActionTween((double a) { spriteRing.scale = a; }, 0.2, 1.0, 0.75);
Action scaleAndRemove = new ActionSequence([scale, new ActionRemoveNode(sprtRing)]); Action scaleAndRemove = new ActionSequence(<Action>[scale, new ActionRemoveNode(spriteRing)]);
Action fade = new ActionTween( (a) => sprtRing.opacity = a, 1.0, 0.0, 0.75); Action fade = new ActionTween((double a) { spriteRing.opacity = a; }, 1.0, 0.0, 0.75);
actions.run(scaleAndRemove); actions.run(scaleAndRemove);
actions.run(fade); actions.run(fade);
// Add streaks // Add streaks
for (int i = 0; i < 5; i++) { for (int i = 0; i < 5; i++) {
Sprite sprtFlare = new Sprite(sheet["explosion_flare.png"]); Sprite spriteFlare = new Sprite(sheet["explosion_flare.png"]);
sprtFlare.pivot = new Point(0.3, 1.0); spriteFlare.pivot = new Point(0.3, 1.0);
sprtFlare.scaleX = 0.3; spriteFlare.scaleX = 0.3;
sprtFlare.transferMode = ui.TransferMode.plus; spriteFlare.transferMode = ui.TransferMode.plus;
sprtFlare.rotation = randomDouble() * 360.0; spriteFlare.rotation = randomDouble() * 360.0;
addChild(sprtFlare); addChild(spriteFlare);
double multiplier = randomDouble() * 0.3 + 1.0; double multiplier = randomDouble() * 0.3 + 1.0;
Action scale = new ActionTween( (a) => sprtFlare.scaleY = a, 0.3 * multiplier, 0.8, 0.75 * multiplier); Action scale = new ActionTween((double a) { spriteFlare.scaleY = a; }, 0.3 * multiplier, 0.8, 0.75 * multiplier);
Action scaleAndRemove = new ActionSequence([scale, new ActionRemoveNode(sprtFlare)]); Action scaleAndRemove = new ActionSequence(<Action>[scale, new ActionRemoveNode(spriteFlare)]);
Action fadeIn = new ActionTween( (a) => sprtFlare.opacity = a, 0.0, 1.0, 0.25 * multiplier); Action fadeIn = new ActionTween((double a) { spriteFlare.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 fadeOut = new ActionTween((double a) { spriteFlare.opacity = a; }, 1.0, 0.0, 0.5 * multiplier);
Action fadeInOut = new ActionSequence([fadeIn, fadeOut]); Action fadeInOut = new ActionSequence(<Action>[fadeIn, fadeOut]);
actions.run(scaleAndRemove); actions.run(scaleAndRemove);
actions.run(fadeInOut); actions.run(fadeInOut);
} }
...@@ -96,14 +96,14 @@ class ExplosionMini extends Explosion { ...@@ -96,14 +96,14 @@ class ExplosionMini extends Explosion {
rotationEnd = -rotationEnd; 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); 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); 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); actions.run(seq);
} }
} }
...@@ -2,8 +2,8 @@ part of game; ...@@ -2,8 +2,8 @@ part of game;
class Flash extends NodeWithSize { class Flash extends NodeWithSize {
Flash(Size size, this.duration) : super(size) { Flash(Size size, this.duration) : super(size) {
ActionTween fade = new ActionTween((a) => _opacity = a, 1.0, 0.0, duration); ActionTween fade = new ActionTween((double a) { _opacity = a; }, 1.0, 0.0, duration);
ActionSequence seq = new ActionSequence([fade, new ActionRemoveNode(this)]); ActionSequence seq = new ActionSequence(<Action>[fade, new ActionRemoveNode(this)]);
actions.run(seq); actions.run(seq);
} }
......
...@@ -8,6 +8,8 @@ final int _chunksPerLevel = 9; ...@@ -8,6 +8,8 @@ final int _chunksPerLevel = 9;
final bool _drawDebug = false; final bool _drawDebug = false;
typedef void GameOverCallback(int score);
class GameDemoNode extends NodeWithSize { class GameDemoNode extends NodeWithSize {
GameDemoNode( GameDemoNode(
...@@ -66,7 +68,7 @@ class GameDemoNode extends NodeWithSize { ...@@ -66,7 +68,7 @@ class GameDemoNode extends NodeWithSize {
SoundEffectPlayer _effectPlayer = SoundEffectPlayer.sharedInstance(); SoundEffectPlayer _effectPlayer = SoundEffectPlayer.sharedInstance();
// Callback // Callback
Function _gameOverCallback; GameOverCallback _gameOverCallback;
// Game screen nodes // Game screen nodes
Node _gameScreen; Node _gameScreen;
...@@ -133,12 +135,12 @@ class GameDemoNode extends NodeWithSize { ...@@ -133,12 +135,12 @@ class GameDemoNode extends NodeWithSize {
if (_gameOver) return; if (_gameOver) return;
// Check for collisions between lasers and objects that can take damage // Check for collisions between lasers and objects that can take damage
List<Laser> lasers = []; List<Laser> lasers = <Laser>[];
for (Node node in _level.children) { for (Node node in _level.children) {
if (node is Laser) lasers.add(node); if (node is Laser) lasers.add(node);
} }
List<GameObject> damageables = []; List<GameObject> damageables = <GameObject>[];
for (Node node in _level.children) { for (Node node in _level.children) {
if (node is GameObject && node.canBeDamaged) damageables.add(node); if (node is GameObject && node.canBeDamaged) damageables.add(node);
} }
...@@ -154,7 +156,7 @@ class GameDemoNode extends NodeWithSize { ...@@ -154,7 +156,7 @@ class GameDemoNode extends NodeWithSize {
} }
// Check for collsions between ship and objects that can damage the ship // 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) { for (Node node in nodes) {
if (node is GameObject && node.canDamageShip) { if (node is GameObject && node.canDamageShip) {
if (node.collidingWith(_level.ship)) { if (node.collidingWith(_level.ship)) {
......
This diff is collapsed.
...@@ -23,7 +23,7 @@ final AssetBundle _bundle = _initBundle(); ...@@ -23,7 +23,7 @@ final AssetBundle _bundle = _initBundle();
ImageMap _imageMap; ImageMap _imageMap;
SpriteSheet _spriteSheet; SpriteSheet _spriteSheet;
SpriteSheet _spriteSheetUI; SpriteSheet _spriteSheetUI;
Map<String,SoundEffect> _sounds = {}; Map<String, SoundEffect> _sounds = <String, SoundEffect>{};
main() async { main() async {
_imageMap = new ImageMap(_bundle); _imageMap = new ImageMap(_bundle);
...@@ -31,7 +31,7 @@ main() async { ...@@ -31,7 +31,7 @@ main() async {
// Use a list to wait on all loads in parallel just before starting the app. // Use a list to wait on all loads in parallel just before starting the app.
List loads = []; List loads = [];
loads.add(_imageMap.load([ loads.add(_imageMap.load(<String>[
'assets/nebula.png', 'assets/nebula.png',
'assets/sprites.png', 'assets/sprites.png',
'assets/starfield.png', 'assets/starfield.png',
...@@ -84,7 +84,7 @@ class GameDemoState extends State<GameDemo> { ...@@ -84,7 +84,7 @@ class GameDemoState extends State<GameDemo> {
return new MaterialApp( return new MaterialApp(
title: 'Asteroids', title: 'Asteroids',
theme: _theme, theme: _theme,
routes: { routes: <String, RouteBuilder>{
'/': _buildMainScene, '/': _buildMainScene,
'/game': _buildGameScene '/game': _buildGameScene
} }
...@@ -96,9 +96,9 @@ class GameDemoState extends State<GameDemo> { ...@@ -96,9 +96,9 @@ class GameDemoState extends State<GameDemo> {
} }
Widget _buildMainScene(RouteArguments args) { Widget _buildMainScene(RouteArguments args) {
return new Stack([ return new Stack(<Widget>[
new SpriteWidget(new MainScreenBackground(), SpriteBoxTransformMode.fixedWidth), new SpriteWidget(new MainScreenBackground(), SpriteBoxTransformMode.fixedWidth),
new Column([ new Column(<Widget>[
new TextureButton( new TextureButton(
onPressed: () { onPressed: () {
_game = new GameDemoNode( _game = new GameDemoNode(
...@@ -106,8 +106,8 @@ class GameDemoState extends State<GameDemo> { ...@@ -106,8 +106,8 @@ class GameDemoState extends State<GameDemo> {
_spriteSheet, _spriteSheet,
_spriteSheetUI, _spriteSheetUI,
_sounds, _sounds,
(lastScore) { (int lastScore) {
setState(() {_lastScore = lastScore;}); setState(() { _lastScore = lastScore; });
args.navigator.pop(); args.navigator.pop();
} }
); );
...@@ -141,7 +141,7 @@ class TextureButton extends StatefulComponent { ...@@ -141,7 +141,7 @@ class TextureButton extends StatefulComponent {
this.height: 128.0 this.height: 128.0
}) : super(key: key); }) : super(key: key);
final Function onPressed; final GestureTapCallback onPressed;
final Texture texture; final Texture texture;
final Texture textureDown; final Texture textureDown;
final double width; final double width;
......
...@@ -3,26 +3,26 @@ part of game; ...@@ -3,26 +3,26 @@ part of game;
class PlayerState extends Node { class PlayerState extends Node {
PlayerState(this._sheetUI, this._sheetGame) { PlayerState(this._sheetUI, this._sheetGame) {
// Score display // Score display
_sprtBgScore = new Sprite(_sheetUI["scoreboard.png"]); _spriteBackgroundScore = new Sprite(_sheetUI["scoreboard.png"]);
_sprtBgScore.pivot = new Point(1.0, 0.0); _spriteBackgroundScore.pivot = new Point(1.0, 0.0);
_sprtBgScore.scale = 0.35; _spriteBackgroundScore.scale = 0.35;
_sprtBgScore.position = new Point(240.0, 10.0); _spriteBackgroundScore.position = new Point(240.0, 10.0);
addChild(_sprtBgScore); addChild(_spriteBackgroundScore);
_scoreDisplay = new ScoreDisplay(_sheetUI); _scoreDisplay = new ScoreDisplay(_sheetUI);
_scoreDisplay.position = new Point(-13.0, 49.0); _scoreDisplay.position = new Point(-13.0, 49.0);
_sprtBgScore.addChild(_scoreDisplay); _spriteBackgroundScore.addChild(_scoreDisplay);
// Coin display // Coin display
_sprtBgCoins = new Sprite(_sheetUI["coinboard.png"]); _spriteBackgroundCoins = new Sprite(_sheetUI["coinboard.png"]);
_sprtBgCoins.pivot = new Point(1.0, 0.0); _spriteBackgroundCoins.pivot = new Point(1.0, 0.0);
_sprtBgCoins.scale = 0.35; _spriteBackgroundCoins.scale = 0.35;
_sprtBgCoins.position = new Point(105.0, 10.0); _spriteBackgroundCoins.position = new Point(105.0, 10.0);
addChild(_sprtBgCoins); addChild(_spriteBackgroundCoins);
_coinDisplay = new ScoreDisplay(_sheetUI); _coinDisplay = new ScoreDisplay(_sheetUI);
_coinDisplay.position = new Point(-13.0, 49.0); _coinDisplay.position = new Point(-13.0, 49.0);
_sprtBgCoins.addChild(_coinDisplay); _spriteBackgroundCoins.addChild(_coinDisplay);
} }
final SpriteSheet _sheetUI; final SpriteSheet _sheetUI;
...@@ -38,16 +38,16 @@ class PlayerState extends Node { ...@@ -38,16 +38,16 @@ class PlayerState extends Node {
EnemyBoss boss; EnemyBoss boss;
Sprite _sprtBgScore; Sprite _spriteBackgroundScore;
ScoreDisplay _scoreDisplay; ScoreDisplay _scoreDisplay;
Sprite _sprtBgCoins; Sprite _spriteBackgroundCoins;
ScoreDisplay _coinDisplay; ScoreDisplay _coinDisplay;
int get score => _scoreDisplay.score; int get score => _scoreDisplay.score;
set score(int score) { set score(int score) {
_scoreDisplay.score = score; _scoreDisplay.score = score;
flashBgSprite(_sprtBgScore); flashBackgroundSprite(_spriteBackgroundScore);
} }
int get coins => _coinDisplay.score; int get coins => _coinDisplay.score;
...@@ -59,26 +59,26 @@ class PlayerState extends Node { ...@@ -59,26 +59,26 @@ class PlayerState extends Node {
Point middlePos = new Point((startPos.x + finalPos.x) / 2.0 + 50.0, Point middlePos = new Point((startPos.x + finalPos.x) / 2.0 + 50.0,
(startPos.y + finalPos.y) / 2.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"]); Sprite sprite = new Sprite(_sheetGame["coin.png"]);
sprt.scale = 0.7; 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; spline.tension = 0.25;
ActionTween rotate = new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 0.5); ActionTween rotate = new ActionTween((double a) { sprite.rotation = a; }, 0.0, 360.0, 0.5);
ActionTween scale = new ActionTween((a) => sprt.scale = a, 0.7, 1.2, 0.5); ActionTween scale = new ActionTween((double a) { sprite.scale = a; }, 0.7, 1.2, 0.5);
ActionGroup group = new ActionGroup([spline, rotate, scale]); ActionGroup group = new ActionGroup(<Action>[spline, rotate, scale]);
sprt.actions.run(new ActionSequence([ sprite.actions.run(new ActionSequence(<Action>[
group, group,
new ActionRemoveNode(sprt), new ActionRemoveNode(sprite),
new ActionCallFunction(() { new ActionCallFunction(() {
_coinDisplay.score += 1; _coinDisplay.score += 1;
flashBgSprite(_sprtBgCoins); flashBackgroundSprite(_spriteBackgroundCoins);
}) })
])); ]));
addChild(sprt); addChild(sprite);
} }
void activatePowerUp(PowerUpType type) { void activatePowerUp(PowerUpType type) {
...@@ -107,21 +107,25 @@ class PlayerState extends Node { ...@@ -107,21 +107,25 @@ class PlayerState extends Node {
int _speedBoostFrames = 0; int _speedBoostFrames = 0;
bool get speedBoostActive => _speedBoostFrames > 0; bool get speedBoostActive => _speedBoostFrames > 0;
void flashBgSprite(Sprite sprt) { void flashBackgroundSprite(Sprite sprite) {
sprt.actions.stopAll(); sprite.actions.stopAll();
ActionTween flash = new ActionTween( ActionTween flash = new ActionTween(
(a) => sprt.colorOverlay = a, (Color a) { sprite.colorOverlay = a; },
new Color(0x66ccfff0), new Color(0x66ccfff0),
new Color(0x00ccfff0), new Color(0x00ccfff0),
0.3); 0.3);
sprt.actions.run(flash); sprite.actions.run(flash);
} }
void update(double dt) { void update(double dt) {
if (_shieldFrames > 0) _shieldFrames--; if (_shieldFrames > 0)
if (_sideLaserFrames > 0) _sideLaserFrames--; _shieldFrames--;
if (_speedLaserFrames > 0) _speedLaserFrames--; if (_sideLaserFrames > 0)
if (_speedBoostFrames > 0) _speedBoostFrames--; _sideLaserFrames--;
if (_speedLaserFrames > 0)
_speedLaserFrames--;
if (_speedBoostFrames > 0)
_speedBoostFrames--;
// Update speed // Update speed
if (boss != null) { if (boss != null) {
...@@ -165,9 +169,9 @@ class ScoreDisplay extends Node { ...@@ -165,9 +169,9 @@ class ScoreDisplay extends Node {
double xPos = -37.0; double xPos = -37.0;
for (int i = scoreStr.length - 1; i >= 0; i--) { for (int i = scoreStr.length - 1; i >= 0; i--) {
String numStr = scoreStr.substring(i, i + 1); String numStr = scoreStr.substring(i, i + 1);
Sprite numSprt = new Sprite(_sheetUI["number_$numStr.png"]); Sprite numSprite = new Sprite(_sheetUI["number_$numStr.png"]);
numSprt.position = new Point(xPos, 0.0); numSprite.position = new Point(xPos, 0.0);
addChild(numSprt); addChild(numSprite);
xPos -= 37.0; xPos -= 37.0;
} }
_dirtyScore = false; _dirtyScore = false;
......
part of game; part of game;
class RepeatedImage extends Node { class RepeatedImage extends Node {
Sprite _sprt0; Sprite _sprite0;
Sprite _sprt1; Sprite _sprite1;
RepeatedImage(ui.Image image, [ui.TransferMode mode = null]) { RepeatedImage(ui.Image image, [ui.TransferMode mode = null]) {
_sprt0 = new Sprite.fromImage(image); _sprite0 = new Sprite.fromImage(image);
_sprt0.size = new Size(1024.0, 1024.0); _sprite0.size = new Size(1024.0, 1024.0);
_sprt0.pivot = Point.origin; _sprite0.pivot = Point.origin;
_sprt1 = new Sprite.fromImage(image); _sprite1 = new Sprite.fromImage(image);
_sprt1.size = new Size(1024.0, 1024.0); _sprite1.size = new Size(1024.0, 1024.0);
_sprt1.pivot = Point.origin; _sprite1.pivot = Point.origin;
_sprt1.position = new Point(0.0, -1024.0); _sprite1.position = new Point(0.0, -1024.0);
if (mode != null) { if (mode != null) {
_sprt0.transferMode = mode; _sprite0.transferMode = mode;
_sprt1.transferMode = mode; _sprite1.transferMode = mode;
} }
addChild(_sprt0); addChild(_sprite0);
addChild(_sprt1); addChild(_sprite1);
} }
void move(double dy) { void move(double dy) {
......
...@@ -24,10 +24,10 @@ class StarField extends NodeWithSize { ...@@ -24,10 +24,10 @@ class StarField extends NodeWithSize {
} }
void addStars() { void addStars() {
_starPositions = []; _starPositions = <Point>[];
_starScales = []; _starScales = <double>[];
_colors = []; _colors = <Color>[];
_rects = []; _rects = <Rect>[];
size = spriteBox.visibleArea.size; size = spriteBox.visibleArea.size;
_paddedSize = new Size(size.width + _padding * 2.0, _paddedSize = new Size(size.width + _padding * 2.0,
...@@ -48,7 +48,7 @@ class StarField extends NodeWithSize { ...@@ -48,7 +48,7 @@ class StarField extends NodeWithSize {
void paint(PaintingCanvas canvas) { void paint(PaintingCanvas canvas) {
// Create a transform for each star // Create a transform for each star
List<ui.RSTransform> transforms = []; List<ui.RSTransform> transforms = <ui.RSTransform>[];
for (int i = 0; i < _numStars; i++) { for (int i = 0; i < _numStars; i++) {
ui.RSTransform transform = new ui.RSTransform( ui.RSTransform transform = new ui.RSTransform(
_starScales[i], _starScales[i],
......
...@@ -21,7 +21,7 @@ TestBedApp _app; ...@@ -21,7 +21,7 @@ TestBedApp _app;
main() async { main() async {
_images = new ImageMap(_bundle); _images = new ImageMap(_bundle);
await _images.load([ await _images.load(<String>[
'assets/sprites.png' 'assets/sprites.png'
]); ]);
...@@ -54,6 +54,5 @@ class TestBedApp extends MaterialApp { ...@@ -54,6 +54,5 @@ class TestBedApp extends MaterialApp {
} }
class TestBed extends NodeWithSize { class TestBed extends NodeWithSize {
TestBed() : super(new Size(1024.0, 1024.0)) { TestBed() : super(new Size(1024.0, 1024.0));
}
} }
...@@ -25,7 +25,7 @@ final ThemeData _theme = new ThemeData( ...@@ -25,7 +25,7 @@ final ThemeData _theme = new ThemeData(
main() async { main() async {
_images = new ImageMap(_bundle); _images = new ImageMap(_bundle);
await _images.load([ await _images.load(<String>[
'assets/sprites.png' 'assets/sprites.png'
]); ]);
...@@ -35,7 +35,7 @@ main() async { ...@@ -35,7 +35,7 @@ main() async {
runApp(new MaterialApp( runApp(new MaterialApp(
title: 'Test drawAtlas', title: 'Test drawAtlas',
theme: _theme, theme: _theme,
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) { '/': (RouteArguments args) {
return new SpriteWidget( return new SpriteWidget(
new TestDrawAtlas(), new TestDrawAtlas(),
...@@ -47,17 +47,16 @@ main() async { ...@@ -47,17 +47,16 @@ main() async {
} }
class TestDrawAtlas extends NodeWithSize { class TestDrawAtlas extends NodeWithSize {
TestDrawAtlas() : super(new Size(1024.0, 1024.0)) { TestDrawAtlas() : super(new Size(1024.0, 1024.0));
}
void paint(PaintingCanvas canvas) { void paint(PaintingCanvas canvas) {
List<RSTransform> transforms = [ List<RSTransform> transforms = <RSTransform>[
new RSTransform(1.0, 0.0, 100.0, 100.0) new RSTransform(1.0, 0.0, 100.0, 100.0)
]; ];
List<Rect> rects = [ List<Rect> rects = <Rect>[
_spriteSheet["ship.png"].frame _spriteSheet["ship.png"].frame
]; ];
List<Color> colors = [ List<Color> colors = <Color>[
new Color(0xffffffff) new Color(0xffffffff)
]; ];
......
...@@ -26,7 +26,7 @@ final ThemeData _theme = new ThemeData( ...@@ -26,7 +26,7 @@ final ThemeData _theme = new ThemeData(
main() async { main() async {
_images = new ImageMap(_bundle); _images = new ImageMap(_bundle);
await _images.load([ await _images.load(<String>[
'assets/sprites.png' 'assets/sprites.png'
]); ]);
...@@ -36,21 +36,19 @@ main() async { ...@@ -36,21 +36,19 @@ main() async {
runApp(new MaterialApp( runApp(new MaterialApp(
title: 'Test Sprite Performance', title: 'Test Sprite Performance',
theme: _theme, theme: _theme,
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) { '/': (RouteArguments args) => new SpriteWidget(new TestPerformance())
return new SpriteWidget(new TestPerformance());
}
} }
)); ));
} }
class TestPerformance extends NodeWithSize { class TestPerformance extends NodeWithSize {
TestPerformance() : super(new Size(1024.0, 1024.0));
final int numFramesPerTest = 100; final int numFramesPerTest = 100;
final int numTests = 5; final int numTests = 5;
TestPerformance() : super(new Size(1024.0, 1024.0)) {
}
int test = 0; int test = 0;
int frame = 0; int frame = 0;
int testStartTime; int testStartTime;
...@@ -116,18 +114,18 @@ class TestPerformanceParticles extends PerformanceTest { ...@@ -116,18 +114,18 @@ class TestPerformanceParticles extends PerformanceTest {
for (int x = 0; x < grid; x++) { for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) { for (int y = 0; y < grid; y++) {
ParticleSystem particles = new ParticleSystem( ParticleSystem particles = new ParticleSystem(
_spriteSheet["explosion_particle.png"], _spriteSheet["explosion_particle.png"],
rotateToMovement: true, rotateToMovement: true,
startRotation:90.0, startRotation:90.0,
startRotationVar: 0.0, startRotationVar: 0.0,
endRotation: 90.0, endRotation: 90.0,
startSize: 0.3, startSize: 0.3,
startSizeVar: 0.1, startSizeVar: 0.1,
endSize: 0.3, endSize: 0.3,
endSizeVar: 0.1, endSizeVar: 0.1,
emissionRate:100.0, emissionRate:100.0,
greenVar: 127, greenVar: 127,
redVar: 127 redVar: 127
); );
particles.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1)); particles.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(particles); addChild(particles);
...@@ -144,23 +142,22 @@ class TestPerformanceSprites extends PerformanceTest { ...@@ -144,23 +142,22 @@ class TestPerformanceSprites extends PerformanceTest {
TestPerformanceSprites() { TestPerformanceSprites() {
for (int x = 0; x < grid; x++) { for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) { for (int y = 0; y < grid; y++) {
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]); Sprite sprite = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.scale = 1.0; sprite.scale = 1.0;
sprt.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1)); sprite.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprt); addChild(sprite);
//sprt.actions.run(new ActionRepeatForever(new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 1.0)));
} }
} }
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]); Sprite sprite = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.position = new Point(512.0, 512.0); sprite.position = new Point(512.0, 512.0);
addChild(sprt); addChild(sprite);
} }
void update(double dt) { void update(double dt) {
for (Sprite sprt in children) { for (Node child in children) {
sprt.rotation += 1; final Sprite sprite = child;
sprite.rotation += 1;
} }
} }
} }
...@@ -173,23 +170,22 @@ class TestPerformanceSprites2 extends PerformanceTest { ...@@ -173,23 +170,22 @@ class TestPerformanceSprites2 extends PerformanceTest {
TestPerformanceSprites2() { TestPerformanceSprites2() {
for (int x = 12; x < grid - 12; x++) { for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) { for (int y = 0; y < grid; y++) {
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]); Sprite sprite = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.scale = 1.0; sprite.scale = 1.0;
sprt.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1)); sprite.position = new Point(x * 1024.0 / (grid - 1), y * 1024.0 / (grid - 1));
addChild(sprt); addChild(sprite);
//sprt.actions.run(new ActionRepeatForever(new ActionTween((a) => sprt.rotation = a, 0.0, 360.0, 1.0)));
} }
} }
Sprite sprt = new Sprite(_spriteSheet["asteroid_big_1.png"]); Sprite sprite = new Sprite(_spriteSheet["asteroid_big_1.png"]);
sprt.position = new Point(512.0, 512.0); sprite.position = new Point(512.0, 512.0);
addChild(sprt); addChild(sprite);
} }
void update(double dt) { void update(double dt) {
for (Sprite sprt in children) { for (Node child in children) {
sprt.rotation += 1; final Sprite sprite = child;
sprite.rotation += 1;
} }
} }
} }
...@@ -200,7 +196,7 @@ class TestPerformanceAtlas extends PerformanceTest { ...@@ -200,7 +196,7 @@ class TestPerformanceAtlas extends PerformanceTest {
final int grid = 100; final int grid = 100;
double rotation = 0.0; double rotation = 0.0;
List<Rect> rects = []; List<Rect> rects = <Rect>[];
Paint cachedPaint = new Paint() Paint cachedPaint = new Paint()
..filterQuality = ui.FilterQuality.low ..filterQuality = ui.FilterQuality.low
..isAntiAlias = false; ..isAntiAlias = false;
...@@ -216,7 +212,7 @@ class TestPerformanceAtlas extends PerformanceTest { ...@@ -216,7 +212,7 @@ class TestPerformanceAtlas extends PerformanceTest {
void paint(PaintingCanvas canvas) { void paint(PaintingCanvas canvas) {
// Setup transforms // Setup transforms
List<ui.RSTransform> transforms = []; List<ui.RSTransform> transforms = <ui.RSTransform>[];
for (int x = 0; x < grid; x++) { for (int x = 0; x < grid; x++) {
for (int y = 0; y < grid; y++) { for (int y = 0; y < grid; y++) {
...@@ -253,7 +249,7 @@ class TestPerformanceAtlas2 extends PerformanceTest { ...@@ -253,7 +249,7 @@ class TestPerformanceAtlas2 extends PerformanceTest {
final int grid = 100; final int grid = 100;
double rotation = 0.0; double rotation = 0.0;
List<Rect> rects = []; List<Rect> rects = <Rect>[];
Paint cachedPaint = new Paint() Paint cachedPaint = new Paint()
..filterQuality = ui.FilterQuality.low ..filterQuality = ui.FilterQuality.low
..isAntiAlias = false; ..isAntiAlias = false;
...@@ -269,7 +265,7 @@ class TestPerformanceAtlas2 extends PerformanceTest { ...@@ -269,7 +265,7 @@ class TestPerformanceAtlas2 extends PerformanceTest {
void paint(PaintingCanvas canvas) { void paint(PaintingCanvas canvas) {
// Setup transforms // Setup transforms
List<ui.RSTransform> transforms = []; List<ui.RSTransform> transforms = <ui.RSTransform>[];
for (int x = 12; x < grid - 12; x++) { for (int x = 12; x < grid - 12; x++) {
for (int y = 0; y < grid; y++) { for (int y = 0; y < grid; y++) {
......
...@@ -15,10 +15,9 @@ void runTest() { ...@@ -15,10 +15,9 @@ void runTest() {
timeStart = new DateTime.now().millisecondsSinceEpoch; timeStart = new DateTime.now().millisecondsSinceEpoch;
// Create systems // Create systems
List<TestParticleSystem> systems = []; List<TestParticleSystem> systems = <TestParticleSystem>[];
for (int i = 0; i < numSystems; i++) { for (int i = 0; i < numSystems; i++)
systems.add(new TestParticleSystem()); systems.add(new TestParticleSystem());
}
int timeAfterCreate = new DateTime.now().millisecondsSinceEpoch; int timeAfterCreate = new DateTime.now().millisecondsSinceEpoch;
print("TIME creation ${(timeAfterCreate - timeStart) / 1000.0}"); print("TIME creation ${(timeAfterCreate - timeStart) / 1000.0}");
......
...@@ -21,7 +21,7 @@ SpriteSheet _spriteSheet; ...@@ -21,7 +21,7 @@ SpriteSheet _spriteSheet;
main() async { main() async {
_images = new ImageMap(_bundle); _images = new ImageMap(_bundle);
await _images.load([ await _images.load(<String>[
'assets/sprites.png' 'assets/sprites.png'
]); ]);
...@@ -34,7 +34,7 @@ main() async { ...@@ -34,7 +34,7 @@ main() async {
brightness: ThemeBrightness.light, brightness: ThemeBrightness.light,
primarySwatch: Colors.purple primarySwatch: Colors.purple
), ),
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) { '/': (RouteArguments args) {
return new SpriteWidget( return new SpriteWidget(
new TestBed(), new TestBed(),
...@@ -73,9 +73,9 @@ class TestBed extends NodeWithSize { ...@@ -73,9 +73,9 @@ class TestBed extends NodeWithSize {
_world.addContactCallback(myCallback, "obstacle", "ship", PhysicsContactType.begin); _world.addContactCallback(myCallback, "obstacle", "ship", PhysicsContactType.begin);
// Animate group // Animate group
ActionSequence seq = new ActionSequence([ ActionSequence seq = new ActionSequence(<Action>[
new ActionTween((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),
new ActionTween((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)); _group.actions.run(new ActionRepeatForever(seq));
...@@ -115,7 +115,7 @@ class TestBed extends NodeWithSize { ...@@ -115,7 +115,7 @@ class TestBed extends NodeWithSize {
shipB.opacity = 0.3; shipB.opacity = 0.3;
shipB.position = new Point(40.0, 0.0); shipB.position = new Point(40.0, 0.0);
shipB.size = new Size(64.0, 64.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, friction: 0.5,
restitution: 0.5, restitution: 0.5,
tag: "ship" tag: "ship"
......
...@@ -30,8 +30,8 @@ const List<Color> textColors = const <Color>[ ...@@ -30,8 +30,8 @@ const List<Color> textColors = const <Color>[
const Color(0xFF000000), const Color(0xFF000000),
]; ];
final List<TextStyle> textStyles = textColors.map((color) { final List<TextStyle> textStyles = textColors.map((Color color) {
return new TextStyle(color: color, fontWeight: bold, textAlign: TextAlign.center); return new TextStyle(color: color, fontWeight: bold, textAlign: TextAlign.center);
}).toList(); }).toList();
enum CellState { covered, exploded, cleared, flagged, shown } enum CellState { covered, exploded, cleared, flagged, shown }
...@@ -64,10 +64,10 @@ class MineDiggerState extends State<MineDigger> { ...@@ -64,10 +64,10 @@ class MineDiggerState extends State<MineDigger> {
hasWon = false; hasWon = false;
detectedCount = 0; detectedCount = 0;
// Initialize matrices. // 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); 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); return new List<CellState>.filled(cols, CellState.covered);
}); });
// Place the mines. // Place the mines.
......
...@@ -26,13 +26,14 @@ ui.Picture paint(ui.Rect paintBounds) { ...@@ -26,13 +26,14 @@ ui.Picture paint(ui.Rect paintBounds) {
canvas.rotate(math.PI/4.0); canvas.rotate(math.PI/4.0);
ui.Gradient yellowBlue = new ui.Gradient.linear( ui.Gradient yellowBlue = new ui.Gradient.linear(
[new ui.Point(-radius, -radius), new ui.Point(0.0, 0.0)], <ui.Point>[new ui.Point(-radius, -radius), new ui.Point(0.0, 0.0)],
[const ui.Color(0xFFFFFF00), const ui.Color(0xFF0000FF)]); <ui.Color>[const ui.Color(0xFFFFFF00), const ui.Color(0xFF0000FF)]
);
canvas.drawRect(new ui.Rect.fromLTRB(-radius, -radius, radius, radius), 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. // 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.5, 0.0, 0.0, 0.0,
0.0, 0.5, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0,
...@@ -45,35 +46,47 @@ ui.Picture paint(ui.Rect paintBounds) { ...@@ -45,35 +46,47 @@ ui.Picture paint(ui.Rect paintBounds) {
canvas.restore(); canvas.restore();
canvas.translate(0.0, 50.0); canvas.translate(0.0, 50.0);
var builder = new ui.LayerDrawLooperBuilder() ui.LayerDrawLooperBuilder builder = new ui.LayerDrawLooperBuilder()
..addLayerOnTop( ..addLayerOnTop(
new ui.DrawLooperLayerInfo() new ui.DrawLooperLayerInfo()
..setOffset(const ui.Offset(150.0, 0.0)) ..setOffset(const ui.Offset(150.0, 0.0))
..setColorMode(ui.TransferMode.src) ..setColorMode(ui.TransferMode.src)
..setPaintBits(ui.PaintBits.all), ..setPaintBits(ui.PaintBits.all),
new ui.Paint() new ui.Paint()
..color = const ui.Color.fromARGB(128, 255, 255, 0) ..color = const ui.Color.fromARGB(128, 255, 255, 0)
..colorFilter = new ui.ColorFilter.mode( ..colorFilter = new ui.ColorFilter.mode(
const ui.Color.fromARGB(128, 0, 0, 255), ui.TransferMode.srcIn) const ui.Color.fromARGB(128, 0, 0, 255),
..maskFilter = new ui.MaskFilter.blur( ui.TransferMode.srcIn
ui.BlurStyle.normal, 3.0, highQuality: true)) )
..addLayerOnTop( ..maskFilter = new ui.MaskFilter.blur(
new ui.DrawLooperLayerInfo() ui.BlurStyle.normal, 3.0, highQuality: true
..setOffset(const ui.Offset(75.0, 75.0)) )
..setColorMode(ui.TransferMode.src) )
..setPaintBits(ui.PaintBits.shader), ..addLayerOnTop(
new ui.Paint() new ui.DrawLooperLayerInfo()
..shader = new ui.Gradient.radial( ..setOffset(const ui.Offset(75.0, 75.0))
new ui.Point(0.0, 0.0), radius/3.0, ..setColorMode(ui.TransferMode.src)
[const ui.Color(0xFFFFFF00), const ui.Color(0xFFFF0000)], ..setPaintBits(ui.PaintBits.shader),
null, ui.TileMode.mirror) new ui.Paint()
// Since we're don't set ui.PaintBits.maskFilter, this has no effect. ..shader = new ui.Gradient.radial(
..maskFilter = new ui.MaskFilter.blur( new ui.Point(0.0, 0.0), radius/3.0,
ui.BlurStyle.normal, 50.0, highQuality: true)) <ui.Color>[
..addLayerOnTop( const ui.Color(0xFFFFFF00),
new ui.DrawLooperLayerInfo()..setOffset(const ui.Offset(225.0, 75.0)), const ui.Color(0xFFFF0000)
// Since this layer uses a DST color mode, this has no effect. ],
new ui.Paint()..color = const ui.Color.fromARGB(128, 255, 0, 0)); 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(); paint.drawLooper = builder.build();
canvas.drawCircle(ui.Point.origin, radius, paint); canvas.drawCircle(ui.Point.origin, radius, paint);
......
...@@ -7,34 +7,34 @@ import 'package:flutter/rendering.dart'; ...@@ -7,34 +7,34 @@ import 'package:flutter/rendering.dart';
import 'lib/solid_color_box.dart'; import 'lib/solid_color_box.dart';
void main() { 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)); 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))); 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)); style = new TextStyle(fontSize: 15.0, color: const Color(0xFF000000));
row.add(new RenderDecoratedBox( row.add(new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0x7FFFCCCC)), 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)); style = new TextStyle(fontSize: 10.0, color: const Color(0xFF000000));
row.add(new RenderDecoratedBox( row.add(new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0x7FCCFFCC)), 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)); style = new TextStyle(fontSize: 25.0, color: const Color(0xFF000000));
subrow.add(new RenderDecoratedBox( subrow.add(new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0x7FCCCCFF)), 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))); subrow.add(new RenderSolidColorBox(const Color(0x7FCCFFFF), desiredSize: new Size(30.0, 40.0)));
row.add(subrow); row.add(subrow);
table.add(row); table.add(row);
row.parentData.flex = 1; final FlexParentData rowParentData = row.parentData;
rowParentData.flex = 1;
} }
RenderDecoratedBox root = new RenderDecoratedBox( RenderDecoratedBox root = new RenderDecoratedBox(
......
...@@ -12,7 +12,7 @@ RenderBox getBox(double lh) { ...@@ -12,7 +12,7 @@ RenderBox getBox(double lh) {
new TextStyle( new TextStyle(
color: const Color(0xFF0000A0) color: const Color(0xFF0000A0)
), ),
[ <TextSpan>[
new PlainTextSpan('test'), new PlainTextSpan('test'),
new StyledTextSpan( new StyledTextSpan(
new TextStyle( new TextStyle(
...@@ -20,7 +20,7 @@ RenderBox getBox(double lh) { ...@@ -20,7 +20,7 @@ RenderBox getBox(double lh) {
fontSize: 50.0, fontSize: 50.0,
height: lh height: lh
), ),
[new PlainTextSpan('مرحبا Hello')] <TextSpan>[new PlainTextSpan('مرحبا Hello')]
) )
] ]
) )
...@@ -62,7 +62,7 @@ RenderBox getBox(double lh) { ...@@ -62,7 +62,7 @@ RenderBox getBox(double lh) {
} }
void main() { void main() {
RenderBox root = new RenderFlex(children: [ RenderBox root = new RenderFlex(children: <RenderBox>[
new RenderConstrainedBox( new RenderConstrainedBox(
additionalConstraints: new BoxConstraints.tightFor(height: 50.0) additionalConstraints: new BoxConstraints.tightFor(height: 50.0)
), ),
......
...@@ -7,8 +7,8 @@ import 'dart:ui' as ui; ...@@ -7,8 +7,8 @@ import 'dart:ui' as ui;
import 'package:flutter/rendering.dart'; import 'package:flutter/rendering.dart';
void main() { void main() {
var root = new RenderFlex( RenderFlex root = new RenderFlex(
children: [ children: <RenderBox>[
new RenderPadding( new RenderPadding(
padding: new EdgeDims.all(10.0), padding: new EdgeDims.all(10.0),
child: new RenderConstrainedBox( child: new RenderConstrainedBox(
......
...@@ -46,7 +46,8 @@ RenderBox buildFlexExample() { ...@@ -46,7 +46,8 @@ RenderBox buildFlexExample() {
); );
flexRoot.add(decoratedRow); flexRoot.add(decoratedRow);
decoratedRow.parentData.flex = 3; final FlexParentData decoratedRowParentData = decoratedRow.parentData;
decoratedRowParentData.flex = 3;
return root; return root;
} }
......
...@@ -33,7 +33,7 @@ class RenderImageGrow extends RenderImage { ...@@ -33,7 +33,7 @@ class RenderImageGrow extends RenderImage {
RenderImageGrow image; RenderImageGrow image;
Map<int, Touch> touches = new Map(); final Map<int, Touch> touches = <int, Touch>{};
void handleEvent(event) { void handleEvent(event) {
if (event is ui.PointerEvent) { if (event is ui.PointerEvent) {
if (event.type == 'pointermove') if (event.type == 'pointermove')
...@@ -64,8 +64,7 @@ void main() { ...@@ -64,8 +64,7 @@ void main() {
image.image = dartLogo; image.image = dartLogo;
}); });
var padding = new RenderPadding(padding: const EdgeDims.all(10.0), child: image); row.add(new RenderPadding(padding: const EdgeDims.all(10.0), child: image));
row.add(padding);
RenderFlex column = new RenderFlex(direction: FlexDirection.vertical); RenderFlex column = new RenderFlex(direction: FlexDirection.vertical);
...@@ -79,13 +78,14 @@ porchetta bacon kevin meatball meatloaf pig beef ribs chicken. Brisket ribeye ...@@ -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 andouille leberkas capicola meatloaf. Chicken pig ball tip pork picanha bresaola
alcatra. Pork pork belly alcatra, flank chuck drumstick biltong doner jowl. alcatra. Pork pork belly alcatra, flank chuck drumstick biltong doner jowl.
Pancetta meatball tongue tenderloin rump tail jowl boudin."""; Pancetta meatball tongue tenderloin rump tail jowl boudin.""";
var text = new StyledTextSpan( TextSpan text = new StyledTextSpan(
new TextStyle(color: const Color(0xFF009900)), new TextStyle(color: const Color(0xFF009900)),
[new PlainTextSpan(meatyString)]); <TextSpan>[new PlainTextSpan(meatyString)]
padding = new RenderPadding( );
padding: const EdgeDims.all(10.0), column.add(new RenderPadding(
child: new RenderParagraph(text)); padding: const EdgeDims.all(10.0),
column.add(padding); child: new RenderParagraph(text)
));
// Bottom cell // Bottom cell
addFlexChildSolidColor(column, const Color(0xFF0081C6), flex: 2); addFlexChildSolidColor(column, const Color(0xFF0081C6), flex: 2);
......
...@@ -14,15 +14,16 @@ void main() { ...@@ -14,15 +14,16 @@ void main() {
var table = new RenderFlex(direction: FlexDirection.vertical); var table = new RenderFlex(direction: FlexDirection.vertical);
void addRow(FlexJustifyContent justify) { 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))); 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(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(0xFFCCFFCC), desiredSize: new Size(64.0, 60.0)));
row.add(new RenderSolidColorBox(const Color(0xFFCCCCFF), desiredSize: new Size(160.0, 60.0))); row.add(new RenderSolidColorBox(const Color(0xFFCCCCFF), desiredSize: new Size(160.0, 60.0)));
row.justifyContent = justify; row.justifyContent = justify;
table.add(row); table.add(row);
row.parentData.flex = 1; final FlexParentData rowParentData = row.parentData;
rowParentData.flex = 1;
} }
addRow(FlexJustifyContent.start); addRow(FlexJustifyContent.start);
......
...@@ -19,7 +19,7 @@ Color randomColor() { ...@@ -19,7 +19,7 @@ Color randomColor() {
} }
RenderBox buildGridExample() { 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); return new RenderGrid(children: children, maxChildExtent: 100.0);
} }
......
...@@ -14,9 +14,11 @@ void main() { ...@@ -14,9 +14,11 @@ void main() {
child: flexRoot child: flexRoot
); );
FlexParentData childParentData;
RenderObject child = new RenderSolidColorBox(const Color(0xFFFFFF00)); RenderObject child = new RenderSolidColorBox(const Color(0xFFFFFF00));
flexRoot.add(child); flexRoot.add(child);
FlexParentData childParentData = child.parentData; childParentData = child.parentData;
childParentData.flex = 2; childParentData.flex = 2;
// The internet is a beautiful place. https://baconipsum.com/ // The internet is a beautiful place. https://baconipsum.com/
...@@ -26,9 +28,10 @@ andouille leberkas capicola meatloaf. Chicken pig ball tip pork picanha bresaola ...@@ -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. alcatra. Pork pork belly alcatra, flank chuck drumstick biltong doner jowl.
Pancetta meatball tongue tenderloin rump tail jowl boudin."""; Pancetta meatball tongue tenderloin rump tail jowl boudin.""";
var text = new StyledTextSpan( StyledTextSpan text = new StyledTextSpan(
new TextStyle(color: const Color(0xFF009900)), new TextStyle(color: const Color(0xFF009900)),
[new PlainTextSpan(meatyString)]); <TextSpan>[new PlainTextSpan(meatyString)]
);
child = new RenderDecoratedBox( child = new RenderDecoratedBox(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)), decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)),
child: new RenderParagraph(text) child: new RenderParagraph(text)
......
...@@ -12,7 +12,7 @@ void main() { ...@@ -12,7 +12,7 @@ void main() {
decoration: new BoxDecoration( decoration: new BoxDecoration(
gradient: new RadialGradient( gradient: new RadialGradient(
center: Point.origin, radius: 500.0, center: Point.origin, radius: 500.0,
colors: [Colors.yellow[500], Colors.blue[500]]), colors: <Color>[Colors.yellow[500], Colors.blue[500]]),
boxShadow: shadows[3]) boxShadow: shadows[3])
); );
var paddedBox = new RenderPadding( var paddedBox = new RenderPadding(
......
...@@ -24,7 +24,7 @@ void main() { ...@@ -24,7 +24,7 @@ void main() {
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFFFF)) 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 p1 = c1.parentData;
AutoLayoutParentData p2 = c2.parentData; AutoLayoutParentData p2 = c2.parentData;
......
...@@ -7,7 +7,7 @@ import 'package:flutter/rendering.dart'; ...@@ -7,7 +7,7 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/gestures.dart'; import 'package:flutter/gestures.dart';
// Material design colors. :p // Material design colors. :p
List<Color> kColors = [ List<Color> kColors = <Color>[
Colors.teal[500], Colors.teal[500],
Colors.amber[500], Colors.amber[500],
Colors.purple[500], Colors.purple[500],
...@@ -34,9 +34,7 @@ class Dot { ...@@ -34,9 +34,7 @@ class Dot {
} }
class RenderTouchDemo extends RenderBox { class RenderTouchDemo extends RenderBox {
Map<int, Dot> dots = new Map(); final Map<int, Dot> dots = <int, Dot>{};
RenderTouchDemo();
void handleEvent(InputEvent event, BoxHitTestEntry entry) { void handleEvent(InputEvent event, BoxHitTestEntry entry) {
if (event is PointerInputEvent) { if (event is PointerInputEvent) {
...@@ -49,7 +47,7 @@ class RenderTouchDemo extends RenderBox { ...@@ -49,7 +47,7 @@ class RenderTouchDemo extends RenderBox {
dots.remove(event.pointer); dots.remove(event.pointer);
break; break;
case 'pointercancel': case 'pointercancel':
dots = new Map(); dots.clear();
break; break;
case 'pointermove': case 'pointermove':
dots[event.pointer].update(event); dots[event.pointer].update(event);
...@@ -74,14 +72,15 @@ class RenderTouchDemo extends RenderBox { ...@@ -74,14 +72,15 @@ class RenderTouchDemo extends RenderBox {
} }
void main() { void main() {
var paragraph = new RenderParagraph(new PlainTextSpan("Touch me!")); RenderParagraph paragraph = new RenderParagraph(new PlainTextSpan("Touch me!"));
var stack = new RenderStack(children: [ RenderStack stack = new RenderStack(children: <RenderBox>[
new RenderTouchDemo(), new RenderTouchDemo(),
paragraph, paragraph,
]); ]);
// Prevent the RenderParagraph from filling the whole screen so // Prevent the RenderParagraph from filling the whole screen so
// that it doesn't eat events. // that it doesn't eat events.
paragraph.parentData..top = 40.0 final StackParentData paragraphParentData = paragraph.parentData;
..left = 20.0; paragraphParentData..top = 40.0
..left = 20.0;
new FlutterBinding(root: stack); new FlutterBinding(root: stack);
} }
...@@ -8,7 +8,7 @@ enum _MenuItems { autorefresh, autorefreshCheckbox, add, remove } ...@@ -8,7 +8,7 @@ enum _MenuItems { autorefresh, autorefreshCheckbox, add, remove }
const double _kMenuMargin = 16.0; // 24.0 on tablet 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( switch (await showMenu(
context: context, context: context,
position: new MenuPosition( position: new MenuPosition(
......
...@@ -48,13 +48,19 @@ class CardCollectionState extends State<CardCollection> { ...@@ -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,
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() { void _initFixedSizedCardModels() {
const int cardCount = 27; const int cardCount = 27;
const double cardHeight = 100.0; 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() { void _initCardModels() {
...@@ -72,7 +78,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -72,7 +78,7 @@ class CardCollectionState extends State<CardCollection> {
double _variableSizeToSnapOffset(double scrollOffset) { double _variableSizeToSnapOffset(double scrollOffset) {
double cumulativeHeight = 0.0; double cumulativeHeight = 0.0;
double margins = 8.0; double margins = 8.0;
List<double> cumulativeHeights = _cardModels.map((card) { List<double> cumulativeHeights = _cardModels.map((CardModel card) {
cumulativeHeight += card.height + margins; cumulativeHeight += card.height + margins;
return cumulativeHeight; return cumulativeHeight;
}) })
...@@ -112,7 +118,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -112,7 +118,7 @@ class CardCollectionState extends State<CardCollection> {
context: context, context: context,
child: new IconTheme( child: new IconTheme(
data: const IconThemeData(color: IconThemeColor.black), data: const IconThemeData(color: IconThemeColor.black),
child: new Block([ child: new Block(<Widget>[
new DrawerHeader(child: new Text('Options')), new DrawerHeader(child: new Text('Options')),
buildDrawerCheckbox("Snap fling scrolls to center", _snapToCenter, _toggleSnapToCenter), buildDrawerCheckbox("Snap fling scrolls to center", _snapToCenter, _toggleSnapToCenter),
buildDrawerCheckbox("Fixed size cards", _fixedSizeCards, _toggleFixedSizeCards), buildDrawerCheckbox("Fixed size cards", _fixedSizeCards, _toggleFixedSizeCards),
...@@ -168,10 +174,10 @@ class CardCollectionState extends State<CardCollection> { ...@@ -168,10 +174,10 @@ class CardCollectionState extends State<CardCollection> {
Navigator.of(context).pop(); Navigator.of(context).pop();
} }
Widget buildDrawerCheckbox(String label, bool value, Function callback) { Widget buildDrawerCheckbox(String label, bool value, void callback()) {
return new DrawerItem( return new DrawerItem(
onPressed: callback, onPressed: callback,
child: new Row([ child: new Row(<Widget>[
new Flexible(child: new Text(label)), new Flexible(child: new Text(label)),
new Checkbox(value: value, onChanged: (_) { callback(); }) new Checkbox(value: value, onChanged: (_) { callback(); })
]) ])
...@@ -182,7 +188,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -182,7 +188,7 @@ class CardCollectionState extends State<CardCollection> {
return new DrawerItem( return new DrawerItem(
icon: icon, icon: icon,
onPressed: () { onChanged(itemValue); }, onPressed: () { onChanged(itemValue); },
child: new Row([ child: new Row(<Widget>[
new Flexible(child: new Text(label)), new Flexible(child: new Text(label)),
new Radio( new Radio(
value: itemValue, value: itemValue,
...@@ -197,7 +203,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -197,7 +203,7 @@ class CardCollectionState extends State<CardCollection> {
return new ToolBar( return new ToolBar(
left: new IconButton(icon: "navigation/menu", onPressed: _showDrawer), left: new IconButton(icon: "navigation/menu", onPressed: _showDrawer),
center: new Text('Swipe Away'), center: new Text('Swipe Away'),
right: [ right: <Widget>[
new Text(_dismissDirectionText(_dismissDirection)) new Text(_dismissDirectionText(_dismissDirection))
] ]
); );
...@@ -210,7 +216,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -210,7 +216,7 @@ class CardCollectionState extends State<CardCollection> {
CardModel cardModel = _cardModels[index]; CardModel cardModel = _cardModels[index];
Widget card = new Dismissable( Widget card = new Dismissable(
direction: _dismissDirection, direction: _dismissDirection,
onResized: () { _invalidator([index]); }, onResized: () { _invalidator(<int>[index]); },
onDismissed: () { dismissCard(cardModel); }, onDismissed: () { dismissCard(cardModel); },
child: new Card( child: new Card(
color: Theme.of(context).primarySwatch[cardModel.color], color: Theme.of(context).primarySwatch[cardModel.color],
...@@ -272,7 +278,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -272,7 +278,7 @@ class CardCollectionState extends State<CardCollection> {
child: new Container( child: new Container(
height: cardModel.height, height: cardModel.height,
decoration: new BoxDecoration(backgroundColor: Theme.of(context).primaryColor), decoration: new BoxDecoration(backgroundColor: Theme.of(context).primaryColor),
child: new Row([ child: new Row(<Widget>[
leftArrowIcon, leftArrowIcon,
new Flexible(child: new Text(backgroundMessage, style: backgroundTextStyle)), new Flexible(child: new Text(backgroundMessage, style: backgroundTextStyle)),
rightArrowIcon rightArrowIcon
...@@ -285,7 +291,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -285,7 +291,7 @@ class CardCollectionState extends State<CardCollection> {
return new IconTheme( return new IconTheme(
key: cardModel.key, key: cardModel.key,
data: const IconThemeData(color: IconThemeColor.white), 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> { ...@@ -299,8 +305,8 @@ class CardCollectionState extends State<CardCollection> {
return new LinearGradient( return new LinearGradient(
begin: Point.origin, begin: Point.origin,
end: new Point(0.0, bounds.height), end: new Point(0.0, bounds.height),
colors: [const Color(0x00FFFFFF), const Color(0xFFFFFFFF)], colors: <Color>[const Color(0x00FFFFFF), const Color(0xFFFFFFFF)],
stops: [0.1, 0.35] stops: <double>[0.1, 0.35]
) )
.createShader(); .createShader();
} }
...@@ -327,8 +333,8 @@ class CardCollectionState extends State<CardCollection> { ...@@ -327,8 +333,8 @@ class CardCollectionState extends State<CardCollection> {
} }
if (_sunshine) if (_sunshine)
cardCollection = new Stack([ cardCollection = new Stack(<Widget>[
new Column([new NetworkImage(src: _sunshineURL)]), new Column(<Widget>[new NetworkImage(src: _sunshineURL)]),
new ShaderMask(child: cardCollection, shaderCallback: _createShader) new ShaderMask(child: cardCollection, shaderCallback: _createShader)
]); ]);
...@@ -351,7 +357,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -351,7 +357,7 @@ class CardCollectionState extends State<CardCollection> {
) )
) )
); );
body = new Stack([body, indicator]); body = new Stack(<Widget>[body, indicator]);
} }
return new Theme( return new Theme(
...@@ -369,7 +375,7 @@ class CardCollectionState extends State<CardCollection> { ...@@ -369,7 +375,7 @@ class CardCollectionState extends State<CardCollection> {
void main() { void main() {
runApp(new MaterialApp( runApp(new MaterialApp(
title: 'Cards', title: 'Cards',
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new CardCollection(), '/': (RouteArguments args) => new CardCollection(),
} }
)); ));
......
...@@ -6,7 +6,7 @@ import 'package:flutter/material.dart'; ...@@ -6,7 +6,7 @@ import 'package:flutter/material.dart';
class ContainerApp extends StatelessComponent { class ContainerApp extends StatelessComponent {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return new Column([ return new Column(<Widget>[
new Container( new Container(
padding: new EdgeDims.all(10.0), padding: new EdgeDims.all(10.0),
margin: new EdgeDims.all(10.0), margin: new EdgeDims.all(10.0),
...@@ -20,7 +20,7 @@ class ContainerApp extends StatelessComponent { ...@@ -20,7 +20,7 @@ class ContainerApp extends StatelessComponent {
new Container( new Container(
decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFF00)), decoration: new BoxDecoration(backgroundColor: const Color(0xFFFFFF00)),
padding: new EdgeDims.symmetric(horizontal: 50.0, vertical: 75.0), padding: new EdgeDims.symmetric(horizontal: 50.0, vertical: 75.0),
child: new Row([ child: new Row(<Widget>[
new RaisedButton( new RaisedButton(
child: new Text('PRESS ME'), child: new Text('PRESS ME'),
onPressed: () => print("Hello World") onPressed: () => print("Hello World")
......
...@@ -31,11 +31,11 @@ class DatePickerDemoState extends State<DatePickerDemo> { ...@@ -31,11 +31,11 @@ class DatePickerDemoState extends State<DatePickerDemo> {
brightness: ThemeBrightness.light, brightness: ThemeBrightness.light,
primarySwatch: Colors.teal primarySwatch: Colors.teal
), ),
child: new Stack([ child: new Stack(<Widget>[
new Scaffold( new Scaffold(
toolBar: new ToolBar(center: new Text("Date Picker")), toolBar: new ToolBar(center: new Text("Date Picker")),
body: new Row( body: new Row(
[new Text(_dateTime.toString())], <Widget>[new Text(_dateTime.toString())],
alignItems: FlexAlignItems.end, alignItems: FlexAlignItems.end,
justifyContent: FlexJustifyContent.center justifyContent: FlexJustifyContent.center
) )
...@@ -48,7 +48,7 @@ class DatePickerDemoState extends State<DatePickerDemo> { ...@@ -48,7 +48,7 @@ class DatePickerDemoState extends State<DatePickerDemo> {
onChanged: _handleDateChanged onChanged: _handleDateChanged
), ),
contentPadding: EdgeDims.zero, contentPadding: EdgeDims.zero,
actions: [ actions: <Widget>[
new FlatButton( new FlatButton(
child: new Text('CANCEL') child: new Text('CANCEL')
), ),
......
...@@ -105,8 +105,8 @@ class DragAndDropAppState extends State<DragAndDropApp> { ...@@ -105,8 +105,8 @@ class DragAndDropAppState extends State<DragAndDropApp> {
), ),
body: new DefaultTextStyle( body: new DefaultTextStyle(
style: Theme.of(context).text.body1.copyWith(textAlign: TextAlign.center), style: Theme.of(context).text.body1.copyWith(textAlign: TextAlign.center),
child: new Column([ child: new Column(<Widget>[
new Flexible(child: new Row([ new Flexible(child: new Row(<Widget>[
new ExampleDragSource(navigator: config.navigator, name: 'Orange', color: const Color(0xFFFF9000)), 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: 'Teal', color: const Color(0xFF00FFFF)),
new ExampleDragSource(navigator: config.navigator, name: 'Yellow', color: const Color(0xFFFFF000)), new ExampleDragSource(navigator: config.navigator, name: 'Yellow', color: const Color(0xFFFFF000)),
...@@ -114,7 +114,7 @@ class DragAndDropAppState extends State<DragAndDropApp> { ...@@ -114,7 +114,7 @@ class DragAndDropAppState extends State<DragAndDropApp> {
alignItems: FlexAlignItems.center, alignItems: FlexAlignItems.center,
justifyContent: FlexJustifyContent.spaceAround 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()), new Flexible(child: new ExampleDragTarget()),
new Flexible(child: new ExampleDragTarget()), new Flexible(child: new ExampleDragTarget()),
...@@ -129,7 +129,7 @@ class DragAndDropAppState extends State<DragAndDropApp> { ...@@ -129,7 +129,7 @@ class DragAndDropAppState extends State<DragAndDropApp> {
void main() { void main() {
runApp(new MaterialApp( runApp(new MaterialApp(
title: 'Drag and Drop Flutter Demo', title: 'Drag and Drop Flutter Demo',
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new DragAndDropApp(navigator: args.navigator) '/': (RouteArguments args) => new DragAndDropApp(navigator: args.navigator)
} }
)); ));
......
...@@ -13,7 +13,7 @@ class DropdownDemo extends StatefulComponent { ...@@ -13,7 +13,7 @@ class DropdownDemo extends StatefulComponent {
class DropdownDemoState extends State<DropdownDemo> { class DropdownDemoState extends State<DropdownDemo> {
String _value = "Free"; String _value = "Free";
List <DropdownMenuItem> _buildItems() { List<DropdownMenuItem> _buildItems() {
return ["One", "Two", "Free", "Four"].map((String value) { return ["One", "Two", "Free", "Four"].map((String value) {
return new DropdownMenuItem<String>(value: value, child: new Text(value)); return new DropdownMenuItem<String>(value: value, child: new Text(value));
}) })
...@@ -24,7 +24,7 @@ class DropdownDemoState extends State<DropdownDemo> { ...@@ -24,7 +24,7 @@ class DropdownDemoState extends State<DropdownDemo> {
Widget dropdown = new DropdownButton<String>( Widget dropdown = new DropdownButton<String>(
items: _buildItems(), items: _buildItems(),
value: _value, value: _value,
onChanged: (dynamic newValue) { onChanged: (String newValue) {
setState(() { setState(() {
if (newValue != null) if (newValue != null)
_value = newValue; _value = newValue;
...@@ -50,7 +50,7 @@ void main() { ...@@ -50,7 +50,7 @@ void main() {
primarySwatch: Colors.blue, primarySwatch: Colors.blue,
accentColor: Colors.redAccent[200] accentColor: Colors.redAccent[200]
), ),
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new DropdownDemo(), '/': (RouteArguments args) => new DropdownDemo(),
} }
)); ));
......
...@@ -23,7 +23,7 @@ class Circle extends StatelessComponent { ...@@ -23,7 +23,7 @@ class Circle extends StatelessComponent {
class HorizontalScrollingApp extends StatelessComponent { class HorizontalScrollingApp extends StatelessComponent {
Widget build(BuildContext context) { Widget build(BuildContext context) {
List<Widget> circles = [ List<Widget> circles = <Widget>[
new Circle(margin: new EdgeDims.only(left: 10.0)), new Circle(margin: new EdgeDims.only(left: 10.0)),
new Circle(), new Circle(),
new Circle(), new Circle(),
......
...@@ -19,10 +19,10 @@ class IndexedStackDemoState extends State<IndexedStackDemo> { ...@@ -19,10 +19,10 @@ class IndexedStackDemoState extends State<IndexedStackDemo> {
}); });
} }
List <PopupMenuItem> _buildMenu() { List<PopupMenuItem> _buildMenu() {
TextStyle style = const TextStyle(fontSize: 18.0, fontWeight: bold); TextStyle style = const TextStyle(fontSize: 18.0, fontWeight: bold);
String pad = ''; String pad = '';
return new List.generate(_itemCount, (int i) { return new List<PopupMenuItem>.generate(_itemCount, (int i) {
pad += '-'; pad += '-';
return new PopupMenuItem(value: i, child: new Text('$pad Hello World $i $pad', style: style)); return new PopupMenuItem(value: i, child: new Text('$pad Hello World $i $pad', style: style));
}); });
...@@ -30,7 +30,7 @@ class IndexedStackDemoState extends State<IndexedStackDemo> { ...@@ -30,7 +30,7 @@ class IndexedStackDemoState extends State<IndexedStackDemo> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
List <PopupMenuItem> items = _buildMenu(); 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( return new Scaffold(
toolBar: new ToolBar(center: new Text('IndexedStackDemo Demo')), toolBar: new ToolBar(center: new Text('IndexedStackDemo Demo')),
...@@ -56,7 +56,7 @@ void main() { ...@@ -56,7 +56,7 @@ void main() {
primarySwatch: Colors.blue, primarySwatch: Colors.blue,
accentColor: Colors.redAccent[200] accentColor: Colors.redAccent[200]
), ),
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new IndexedStackDemo(), '/': (RouteArguments args) => new IndexedStackDemo(),
} }
)); ));
......
...@@ -8,7 +8,7 @@ final Map<String, RouteBuilder> routes = <String, RouteBuilder>{ ...@@ -8,7 +8,7 @@ final Map<String, RouteBuilder> routes = <String, RouteBuilder>{
'/': (RouteArguments args) => new Container( '/': (RouteArguments args) => new Container(
padding: const EdgeDims.all(30.0), padding: const EdgeDims.all(30.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFFCCCCCC)), decoration: new BoxDecoration(backgroundColor: const Color(0xFFCCCCCC)),
child: new Column([ child: new Column(<Widget>[
new Text("You are at home"), new Text("You are at home"),
new RaisedButton( new RaisedButton(
child: new Text('GO SHOPPING'), child: new Text('GO SHOPPING'),
...@@ -24,7 +24,7 @@ final Map<String, RouteBuilder> routes = <String, RouteBuilder>{ ...@@ -24,7 +24,7 @@ final Map<String, RouteBuilder> routes = <String, RouteBuilder>{
'/shopping': (RouteArguments args) => new Container( '/shopping': (RouteArguments args) => new Container(
padding: const EdgeDims.all(20.0), padding: const EdgeDims.all(20.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFFBF5FFF)), decoration: new BoxDecoration(backgroundColor: const Color(0xFFBF5FFF)),
child: new Column([ child: new Column(<Widget>[
new Text("Village Shop"), new Text("Village Shop"),
new RaisedButton( new RaisedButton(
child: new Text('RETURN HOME'), child: new Text('RETURN HOME'),
...@@ -40,7 +40,7 @@ final Map<String, RouteBuilder> routes = <String, RouteBuilder>{ ...@@ -40,7 +40,7 @@ final Map<String, RouteBuilder> routes = <String, RouteBuilder>{
'/adventure': (RouteArguments args) => new Container( '/adventure': (RouteArguments args) => new Container(
padding: const EdgeDims.all(20.0), padding: const EdgeDims.all(20.0),
decoration: new BoxDecoration(backgroundColor: const Color(0xFFDC143C)), decoration: new BoxDecoration(backgroundColor: const Color(0xFFDC143C)),
child: new Column([ child: new Column(<Widget>[
new Text("Monster's Lair"), new Text("Monster's Lair"),
new RaisedButton( new RaisedButton(
child: new Text('RUN!!!'), child: new Text('RUN!!!'),
......
...@@ -86,7 +86,7 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> { ...@@ -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,
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); Color color = Color.lerp(Colors.red[300], Colors.blue[900], i / cardHeights.length);
return new CardModel(i, cardHeights[i], color); return new CardModel(i, cardHeights[i], color);
}); });
...@@ -121,7 +121,7 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> { ...@@ -121,7 +121,7 @@ class OverlayGeometryAppState extends State<OverlayGeometryApp> {
CardModel cardModel = cardModels[index]; CardModel cardModel = cardModels[index];
return new Listener( return new Listener(
key: cardModel.key, key: cardModel.key,
onPointerDown: (e) { return handlePointerDown(cardModel.targetKey, e); }, onPointerDown: (PointerInputEvent e) { return handlePointerDown(cardModel.targetKey, e); },
child: new Card( child: new Card(
key: cardModel.targetKey, key: cardModel.targetKey,
color: cardModel.color, color: cardModel.color,
...@@ -162,7 +162,7 @@ void main() { ...@@ -162,7 +162,7 @@ void main() {
accentColor: Colors.redAccent[200] accentColor: Colors.redAccent[200]
), ),
title: 'Cards', title: 'Cards',
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new OverlayGeometryApp() '/': (RouteArguments args) => new OverlayGeometryApp()
} }
)); ));
......
...@@ -27,7 +27,7 @@ class PageableListAppState extends State<PageableListApp> { ...@@ -27,7 +27,7 @@ class PageableListAppState extends State<PageableListApp> {
.map((args) => new Size(args[0], args[1])) .map((args) => new Size(args[0], args[1]))
.toList(); .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); Color color = Color.lerp(Colors.red[300], Colors.blue[900], i / cardSizes.length);
return new CardModel(i, cardSizes[i], color); return new CardModel(i, cardSizes[i], color);
}); });
...@@ -86,7 +86,7 @@ class PageableListAppState extends State<PageableListApp> { ...@@ -86,7 +86,7 @@ class PageableListAppState extends State<PageableListApp> {
void _showDrawer() { void _showDrawer() {
showDrawer( showDrawer(
context: context, context: context,
child: new Block([ child: new Block(<Widget>[
new DrawerHeader(child: new Text('Options')), new DrawerHeader(child: new Text('Options')),
new DrawerItem( new DrawerItem(
icon: 'navigation/more_horiz', icon: 'navigation/more_horiz',
...@@ -102,7 +102,7 @@ class PageableListAppState extends State<PageableListApp> { ...@@ -102,7 +102,7 @@ class PageableListAppState extends State<PageableListApp> {
), ),
new DrawerItem( new DrawerItem(
onPressed: toggleItemsWrap, onPressed: toggleItemsWrap,
child: new Row([ child: new Row(<Widget>[
new Flexible(child: new Text('Scrolling wraps around')), new Flexible(child: new Text('Scrolling wraps around')),
new Checkbox(value: itemsWrap) new Checkbox(value: itemsWrap)
]) ])
...@@ -115,7 +115,7 @@ class PageableListAppState extends State<PageableListApp> { ...@@ -115,7 +115,7 @@ class PageableListAppState extends State<PageableListApp> {
return new ToolBar( return new ToolBar(
left: new IconButton(icon: "navigation/menu", onPressed: _showDrawer), left: new IconButton(icon: "navigation/menu", onPressed: _showDrawer),
center: new Text('PageableList'), center: new Text('PageableList'),
right: [ right: <Widget>[
new Text(scrollDirection == ScrollDirection.horizontal ? "horizontal" : "vertical") new Text(scrollDirection == ScrollDirection.horizontal ? "horizontal" : "vertical")
] ]
); );
...@@ -156,7 +156,7 @@ void main() { ...@@ -156,7 +156,7 @@ void main() {
primarySwatch: Colors.blue, primarySwatch: Colors.blue,
accentColor: Colors.redAccent[200] accentColor: Colors.redAccent[200]
), ),
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new PageableListApp(), '/': (RouteArguments args) => new PageableListApp(),
} }
)); ));
......
...@@ -18,11 +18,12 @@ const String frogs = "http://soundbible.com/grab.php?id=2033&type=wav"; ...@@ -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 rattle = "http://soundbible.com/grab.php?id=2037&type=wav";
const String iLoveYou = "http://soundbible.com/grab.php?id=2045&type=wav"; const String iLoveYou = "http://soundbible.com/grab.php?id=2045&type=wav";
class Key { class PianoKey {
Key(this.color, this.soundUrl); PianoKey(this.color, this.soundUrl);
final Color color; final Color color;
final String soundUrl; final String soundUrl;
final MediaPlayerProxy player = new MediaPlayerProxy.unbound(); final MediaPlayerProxy player = new MediaPlayerProxy.unbound();
bool get isPlayerOpen => player.impl.isOpen; bool get isPlayerOpen => player.impl.isOpen;
...@@ -51,13 +52,13 @@ class Key { ...@@ -51,13 +52,13 @@ class Key {
} }
class PianoApp extends StatelessComponent { class PianoApp extends StatelessComponent {
final List<Key> keys = [ final List<PianoKey> keys = <PianoKey>[
new Key(Colors.red[500], chimes), new PianoKey(Colors.red[500], chimes),
new Key(Colors.orange[500], chainsaw), new PianoKey(Colors.orange[500], chainsaw),
new Key(Colors.yellow[500], stag), new PianoKey(Colors.yellow[500], stag),
new Key(Colors.green[500], frogs), new PianoKey(Colors.green[500], frogs),
new Key(Colors.blue[500], rattle), new PianoKey(Colors.blue[500], rattle),
new Key(Colors.purple[500], iLoveYou), new PianoKey(Colors.purple[500], iLoveYou),
]; ];
Future connect() { Future connect() {
...@@ -68,10 +69,9 @@ class PianoApp extends StatelessComponent { ...@@ -68,10 +69,9 @@ class PianoApp extends StatelessComponent {
MediaServiceProxy mediaService = new MediaServiceProxy.unbound(); MediaServiceProxy mediaService = new MediaServiceProxy.unbound();
try { try {
shell.requestService(null, mediaService); shell.requestService(null, mediaService);
List<Future> pending = []; List<Future<MediaPlayerPrepareResponseParams>> pending = <Future<MediaPlayerPrepareResponseParams>>[];
for (Key key in keys) { for (PianoKey key in keys)
pending.add(key.load(mediaService)); pending.add(key.load(mediaService));
}
await Future.wait(pending); await Future.wait(pending);
} finally { } finally {
mediaService.close(); mediaService.close();
...@@ -79,8 +79,8 @@ class PianoApp extends StatelessComponent { ...@@ -79,8 +79,8 @@ class PianoApp extends StatelessComponent {
} }
Widget build(BuildContext context) { Widget build(BuildContext context) {
List<Widget> children = []; List<Widget> children = <Widget>[];
for (Key key in keys) { for (PianoKey key in keys) {
children.add(new Flexible( children.add(new Flexible(
child: new Listener( child: new Listener(
child: new Container( child: new Container(
...@@ -99,7 +99,7 @@ Widget statusBox(Widget child) { ...@@ -99,7 +99,7 @@ Widget statusBox(Widget child) {
const darkGray = const Color(0xff222222); const darkGray = const Color(0xff222222);
return new Center( return new Center(
child: new Container( child: new Container(
decoration: const BoxDecoration(boxShadow: const [ decoration: const BoxDecoration(boxShadow: const <BoxShadow>[
const BoxShadow( const BoxShadow(
color: mediumGray, offset: const Offset(6.0, 6.0), blur: 5.0) color: mediumGray, offset: const Offset(6.0, 6.0), blur: 5.0)
], backgroundColor: darkGray), ], backgroundColor: darkGray),
......
...@@ -71,7 +71,7 @@ class ProgressIndicatorAppState extends State<ProgressIndicatorApp> { ...@@ -71,7 +71,7 @@ class ProgressIndicatorAppState extends State<ProgressIndicatorApp> {
]; ];
return new Column( return new Column(
indicators 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(), .toList(),
justifyContent: FlexJustifyContent.center justifyContent: FlexJustifyContent.center
); );
...@@ -83,7 +83,7 @@ class ProgressIndicatorAppState extends State<ProgressIndicatorApp> { ...@@ -83,7 +83,7 @@ class ProgressIndicatorAppState extends State<ProgressIndicatorApp> {
child: new Container( child: new Container(
padding: const EdgeDims.symmetric(vertical: 12.0, horizontal: 8.0), padding: const EdgeDims.symmetric(vertical: 12.0, horizontal: 8.0),
child: new BuilderTransition( child: new BuilderTransition(
variables: [valueAnimation.variable], variables: <AnimatedValue<double>>[valueAnimation.variable],
performance: valueAnimation.view, performance: valueAnimation.view,
builder: buildIndicators builder: buildIndicators
) )
......
...@@ -47,7 +47,7 @@ class ScaleAppState extends State<ScaleApp> { ...@@ -47,7 +47,7 @@ class ScaleAppState extends State<ScaleApp> {
double radius = size.width / 2.0 * _zoom; double radius = size.width / 2.0 * _zoom;
Gradient gradient = new RadialGradient( Gradient gradient = new RadialGradient(
center: center, radius: radius, center: center, radius: radius,
colors: [Colors.blue[200], Colors.blue[800]] colors: <Color>[Colors.blue[200], Colors.blue[800]]
); );
Paint paint = new Paint() Paint paint = new Paint()
..shader = gradient.createShader(); ..shader = gradient.createShader();
......
...@@ -60,7 +60,7 @@ void main() { ...@@ -60,7 +60,7 @@ void main() {
primarySwatch: Colors.blue, primarySwatch: Colors.blue,
accentColor: Colors.redAccent[200] accentColor: Colors.redAccent[200]
), ),
routes: { routes: <String, RouteBuilder>{
'/': (RouteArguments args) => new ScrollbarApp(), '/': (RouteArguments args) => new ScrollbarApp(),
} }
)); ));
......
...@@ -6,7 +6,7 @@ import 'package:flutter/animation.dart'; ...@@ -6,7 +6,7 @@ import 'package:flutter/animation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart'; import 'package:flutter/rendering.dart';
final List<Map<int, Color>> _kColors = [ final List<Map<int, Color>> _kColors = <Map<int, Color>>[
Colors.amber, Colors.amber,
Colors.yellow, Colors.yellow,
Colors.blue, Colors.blue,
...@@ -42,7 +42,7 @@ class CardTransition extends StatelessComponent { ...@@ -42,7 +42,7 @@ class CardTransition extends StatelessComponent {
return new BuilderTransition( return new BuilderTransition(
performance: performance, performance: performance,
variables: [x, opacity, scale], variables: <AnimatedValue<double>>[x, opacity, scale],
builder: (BuildContext context) { builder: (BuildContext context) {
Matrix4 transform = new Matrix4.identity() Matrix4 transform = new Matrix4.identity()
..translate(x.value) ..translate(x.value)
......
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart'; import 'package:flutter/rendering.dart';
typedef Widget TextTransformer(String name, String text);
class StyledTextApp extends StatefulComponent { class StyledTextApp extends StatefulComponent {
StyledTextAppState createState() => new StyledTextAppState(); StyledTextAppState createState() => new StyledTextAppState();
} }
...@@ -19,7 +21,7 @@ class StyledTextAppState extends State<StyledTextApp> { ...@@ -19,7 +21,7 @@ class StyledTextAppState extends State<StyledTextApp> {
.toList(); .toList();
} }
Function toText; TextTransformer toText;
// From https://en.wikiquote.org/wiki/2001:_A_Space_Odyssey_(film) // From https://en.wikiquote.org/wiki/2001:_A_Space_Odyssey_(film)
final String dialogText = ''' final String dialogText = '''
...@@ -74,10 +76,10 @@ HAL: This mission is too important for me to allow you to jeopardize it.'''; ...@@ -74,10 +76,10 @@ HAL: This mission is too important for me to allow you to jeopardize it.''';
Widget build(BuildContext context) { Widget build(BuildContext context) {
List<Widget> lines = nameLines List<Widget> lines = nameLines
.map((nameAndText) => Function.apply(toText, nameAndText)) .map((List<String> nameAndText) => Function.apply(toText, nameAndText))
.toList(); .toList();
List<Widget> children = []; List<Widget> children = <Widget>[];
for (Widget line in lines) { for (Widget line in lines) {
children.add(line); children.add(line);
if (line != lines.last) { if (line != lines.last) {
......
...@@ -19,7 +19,7 @@ class TabbedNavigatorAppState extends State<TabbedNavigatorApp> { ...@@ -19,7 +19,7 @@ class TabbedNavigatorAppState extends State<TabbedNavigatorApp> {
views: views, views: views,
selectedIndex: selectedIndices[n], selectedIndex: selectedIndices[n],
isScrollable: isScrollable, isScrollable: isScrollable,
onChanged: (tabIndex) { onChanged: (int tabIndex) {
setState(() { selectedIndices[n] = tabIndex; } ); setState(() { selectedIndices[n] = tabIndex; } );
} }
); );
...@@ -46,7 +46,7 @@ class TabbedNavigatorAppState extends State<TabbedNavigatorApp> { ...@@ -46,7 +46,7 @@ class TabbedNavigatorAppState extends State<TabbedNavigatorApp> {
Iterable<TabNavigatorView> views = ["event", "home", "android", "alarm", "face", "language"] Iterable<TabNavigatorView> views = ["event", "home", "android", "alarm", "face", "language"]
.map((icon_name) { .map((icon_name) {
return new TabNavigatorView( return new TabNavigatorView(
label: new TabLabel(icon: "action/${icon_name}"), label: new TabLabel(icon: "action/$icon_name"),
builder: (BuildContext context) => _buildContent(icon_name) builder: (BuildContext context) => _buildContent(icon_name)
); );
}); });
......
...@@ -35,7 +35,7 @@ class Checkbox extends StatelessComponent { ...@@ -35,7 +35,7 @@ class Checkbox extends StatelessComponent {
const Checkbox({Key key, this.value, this.onChanged}) : super(key: key); const Checkbox({Key key, this.value, this.onChanged}) : super(key: key);
final bool value; final bool value;
final ValueChanged onChanged; final ValueChanged<bool> onChanged;
Widget build(BuildContext context) { Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context); ThemeData themeData = Theme.of(context);
...@@ -67,7 +67,7 @@ class _CheckboxWrapper extends LeafRenderObjectWidget { ...@@ -67,7 +67,7 @@ class _CheckboxWrapper extends LeafRenderObjectWidget {
} }
final bool value; final bool value;
final ValueChanged onChanged; final ValueChanged<bool> onChanged;
final Color uncheckedColor; final Color uncheckedColor;
final Color accentColor; final Color accentColor;
...@@ -91,7 +91,7 @@ class _RenderCheckbox extends RenderToggleable { ...@@ -91,7 +91,7 @@ class _RenderCheckbox extends RenderToggleable {
bool value, bool value,
Color uncheckedColor, Color uncheckedColor,
Color accentColor, Color accentColor,
ValueChanged onChanged ValueChanged<bool> onChanged
}): _uncheckedColor = uncheckedColor, }): _uncheckedColor = uncheckedColor,
_accentColor = accentColor, _accentColor = accentColor,
super( super(
......
...@@ -368,7 +368,7 @@ class _YearPickerState extends ScrollableWidgetListState<YearPicker> { ...@@ -368,7 +368,7 @@ class _YearPickerState extends ScrollableWidgetListState<YearPicker> {
List<Widget> buildItems(BuildContext context, int start, int count) { List<Widget> buildItems(BuildContext context, int start, int count) {
TextStyle style = Theme.of(context).text.body1.copyWith(color: Colors.black54); TextStyle style = Theme.of(context).text.body1.copyWith(color: Colors.black54);
List<Widget> items = new List<Widget>(); 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; int year = config.firstDate.year + i;
String label = year.toString(); String label = year.toString();
Widget item = new InkWell( Widget item = new InkWell(
......
...@@ -203,7 +203,7 @@ class DropdownButton<T> extends StatelessComponent { ...@@ -203,7 +203,7 @@ class DropdownButton<T> extends StatelessComponent {
final List<DropdownMenuItem<T>> items; final List<DropdownMenuItem<T>> items;
final T value; final T value;
final ValueChanged onChanged; final ValueChanged<T> onChanged;
final int level; final int level;
void _showDropdown(BuildContext context, int selectedIndex, GlobalKey indexedStackKey) { void _showDropdown(BuildContext context, int selectedIndex, GlobalKey indexedStackKey) {
...@@ -217,7 +217,7 @@ class DropdownButton<T> extends StatelessComponent { ...@@ -217,7 +217,7 @@ class DropdownButton<T> extends StatelessComponent {
rect: rect, rect: rect,
level: level level: level
)); ));
completer.future.then((dynamic newValue) { completer.future.then((T newValue) {
if (onChanged != null) if (onChanged != null)
onChanged(newValue); onChanged(newValue);
}); });
......
...@@ -32,7 +32,7 @@ class Switch extends StatelessComponent { ...@@ -32,7 +32,7 @@ class Switch extends StatelessComponent {
: super(key: key); : super(key: key);
final bool value; final bool value;
final ValueChanged onChanged; final ValueChanged<bool> onChanged;
Widget build(BuildContext context) { Widget build(BuildContext context) {
return new _SwitchWrapper( return new _SwitchWrapper(
...@@ -49,7 +49,7 @@ class _SwitchWrapper extends LeafRenderObjectWidget { ...@@ -49,7 +49,7 @@ class _SwitchWrapper extends LeafRenderObjectWidget {
final bool value; final bool value;
final Color thumbColor; final Color thumbColor;
final ValueChanged onChanged; final ValueChanged<bool> onChanged;
_RenderSwitch createRenderObject() => new _RenderSwitch( _RenderSwitch createRenderObject() => new _RenderSwitch(
value: value, value: value,
...@@ -68,7 +68,7 @@ class _RenderSwitch extends RenderToggleable { ...@@ -68,7 +68,7 @@ class _RenderSwitch extends RenderToggleable {
_RenderSwitch({ _RenderSwitch({
bool value, bool value,
Color thumbColor: _kThumbOffColor, Color thumbColor: _kThumbOffColor,
ValueChanged onChanged ValueChanged<bool> onChanged
}) : _thumbColor = thumbColor, }) : _thumbColor = thumbColor,
super(value: value, onChanged: onChanged, size: _kSwitchSize); super(value: value, onChanged: onChanged, size: _kSwitchSize);
......
...@@ -10,7 +10,7 @@ import 'box.dart'; ...@@ -10,7 +10,7 @@ import 'box.dart';
import 'object.dart'; import 'object.dart';
import 'proxy_box.dart'; import 'proxy_box.dart';
typedef void ValueChanged(bool value); typedef void ValueChanged<T>(T value);
const Duration _kToggleDuration = const Duration(milliseconds: 200); const Duration _kToggleDuration = const Duration(milliseconds: 200);
...@@ -19,7 +19,7 @@ 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 // ValueChanged on a tap gesture and driving a changed animation. Subclasses are
// responsible for painting. // responsible for painting.
abstract class RenderToggleable extends RenderConstrainedBox { abstract class RenderToggleable extends RenderConstrainedBox {
RenderToggleable({bool value, Size size, ValueChanged onChanged}) RenderToggleable({bool value, Size size, ValueChanged<bool> onChanged})
: _value = value, : _value = value,
_onChanged = onChanged, _onChanged = onChanged,
super(additionalConstraints: new BoxConstraints.tight(size)) { super(additionalConstraints: new BoxConstraints.tight(size)) {
...@@ -70,9 +70,9 @@ abstract class RenderToggleable extends RenderConstrainedBox { ...@@ -70,9 +70,9 @@ abstract class RenderToggleable extends RenderConstrainedBox {
performance.play(value ? AnimationDirection.forward : AnimationDirection.reverse); performance.play(value ? AnimationDirection.forward : AnimationDirection.reverse);
} }
ValueChanged get onChanged => _onChanged; ValueChanged<bool> get onChanged => _onChanged;
ValueChanged _onChanged; ValueChanged<bool> _onChanged;
void set onChanged(ValueChanged onChanged) { void set onChanged(ValueChanged<bool> onChanged) {
_onChanged = onChanged; _onChanged = onChanged;
} }
} }
...@@ -37,6 +37,8 @@ abstract class Action { ...@@ -37,6 +37,8 @@ abstract class Action {
double get duration => 0.0; double get duration => 0.0;
} }
typedef void SetterCallback(dynamic value);
/// The abstract class for an action that changes properties over a time /// The abstract class for an action that changes properties over a time
/// interval, optionally using an easing curve. /// interval, optionally using an easing curve.
abstract class ActionInterval extends Action { abstract class ActionInterval extends Action {
...@@ -351,17 +353,6 @@ class ActionRemoveNode extends ActionInstant { ...@@ -351,17 +353,6 @@ class ActionRemoveNode extends ActionInstant {
/// type [Point], [Size], [Rect], [double], or [Color]. /// type [Point], [Size], [Rect], [double], or [Color].
class ActionTween extends ActionInterval { 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 /// Creates a new tween action. The [setter] will be called to update the
/// animated property from [startVal] to [endVal] over the [duration] time in /// animated property from [startVal] to [endVal] over the [duration] time in
/// seconds. Optionally an animation [curve] can be passed in for easing the /// seconds. Optionally an animation [curve] can be passed in for easing the
...@@ -381,6 +372,17 @@ class ActionTween extends ActionInterval { ...@@ -381,6 +372,17 @@ class ActionTween extends ActionInterval {
_computeDelta(); _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() { void _computeDelta() {
if (startVal is Point) { if (startVal is Point) {
// Point // Point
...@@ -474,7 +476,7 @@ class ActionTween extends ActionInterval { ...@@ -474,7 +476,7 @@ class ActionTween extends ActionInterval {
/// itself is typically a property of a [Node] and powered by the [SpriteBox]. /// itself is typically a property of a [Node] and powered by the [SpriteBox].
class ActionController { class ActionController {
List<Action> _actions = []; List<Action> _actions = <Action>[];
/// Creates a new [ActionController]. However, for most uses a reference to /// Creates a new [ActionController]. However, for most uses a reference to
/// an [ActionController] is acquired through the [Node.actions] property. /// an [ActionController] is acquired through the [Node.actions] property.
......
...@@ -17,6 +17,8 @@ Point _cardinalSplineAt(Point p0, Point p1, Point p2, Point p3, double tension, ...@@ -17,6 +17,8 @@ Point _cardinalSplineAt(Point p0, Point p1, Point p2, Point p3, double tension,
return new Point(x, y); return new Point(x, y);
} }
typedef void PointSetterCallback(Point value);
/// The spline action is used to animate a point along a spline definied by /// The spline action is used to animate a point along a spline definied by
/// a set of points. /// a set of points.
class ActionSpline extends ActionInterval { class ActionSpline extends ActionInterval {
...@@ -30,7 +32,7 @@ class ActionSpline extends ActionInterval { ...@@ -30,7 +32,7 @@ class ActionSpline extends ActionInterval {
} }
/// The callback used to update a point when the action is run. /// 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. /// A list of points that define the spline.
final List<Point> points; final List<Point> points;
......
...@@ -21,8 +21,8 @@ class ColorSequence { ...@@ -21,8 +21,8 @@ class ColorSequence {
/// Creates a new color sequence from a start and an end color. /// Creates a new color sequence from a start and an end color.
ColorSequence.fromStartAndEndColor(Color start, Color end) { ColorSequence.fromStartAndEndColor(Color start, Color end) {
colors = [start, end]; colors = <Color>[start, end];
colorStops = [0.0, 1.0]; colorStops = <double>[0.0, 1.0];
} }
/// Creates a new color sequence by copying an existing sequence. /// Creates a new color sequence by copying an existing sequence.
......
...@@ -30,14 +30,18 @@ class EffectLine extends Node { ...@@ -30,14 +30,18 @@ class EffectLine extends Node {
this.simplify: true, this.simplify: true,
ColorSequence colorSequence ColorSequence colorSequence
}) { }) {
if (points == null) this.points = []; if (points == null)
else this.points = points; this.points = <Point>[];
else
this.points = points;
_colorSequence = colorSequence; _colorSequence = colorSequence;
if (_colorSequence == null) if (_colorSequence == null) {
_colorSequence = new ColorSequence.fromStartAndEndColor( _colorSequence = new ColorSequence.fromStartAndEndColor(
new Color(0xffffffff), new Color(0xffffffff),
new Color(0xffffffff)); new Color(0xffffffff)
);
}
_offset = scrollStart; _offset = scrollStart;
...@@ -65,7 +69,7 @@ class EffectLine extends Node { ...@@ -65,7 +69,7 @@ class EffectLine extends Node {
set points(List<Point> points) { set points(List<Point> points) {
_points = points; _points = points;
_pointAges = []; _pointAges = <double>[];
for (int i = 0; i < _points.length; i++) { for (int i = 0; i < _points.length; i++) {
_pointAges.add(0.0); _pointAges.add(0.0);
} }
...@@ -125,7 +129,7 @@ class EffectLine extends Node { ...@@ -125,7 +129,7 @@ class EffectLine extends Node {
// Calculate colors // Calculate colors
List<double> stops = _painter.calculatedTextureStops; List<double> stops = _painter.calculatedTextureStops;
List<Color> colors = []; List<Color> colors = <Color>[];
for (int i = 0; i < stops.length; i++) { for (int i = 0; i < stops.length; i++) {
double stop = stops[i]; double stop = stops[i];
Color color = _colorSequence.colorAtPosition(stop); Color color = _colorSequence.colorAtPosition(stop);
...@@ -143,7 +147,7 @@ class EffectLine extends Node { ...@@ -143,7 +147,7 @@ class EffectLine extends Node {
_painter.colors = colors; _painter.colors = colors;
// Calculate widths // Calculate widths
List<double> widths = []; List<double> widths = <double>[];
for (int i = 0; i < stops.length; i++) { for (int i = 0; i < stops.length; i++) {
double stop = stops[i]; double stop = stops[i];
double growth = math.max(widthGrowthSpeed * _pointAges[i], 0.0); double growth = math.max(widthGrowthSpeed * _pointAges[i], 0.0);
......
...@@ -36,7 +36,7 @@ class Label extends Node { ...@@ -36,7 +36,7 @@ class Label extends Node {
void paint(PaintingCanvas canvas) { void paint(PaintingCanvas canvas) {
if (_painter == null) { if (_painter == null) {
PlainTextSpan textSpan = new PlainTextSpan(_text); PlainTextSpan textSpan = new PlainTextSpan(_text);
StyledTextSpan styledTextSpan = new StyledTextSpan(_textStyle, [textSpan]); StyledTextSpan styledTextSpan = new StyledTextSpan(_textStyle, <TextSpan>[textSpan]);
_painter = new TextPainter(styledTextSpan); _painter = new TextPainter(styledTextSpan);
_painter.maxWidth = double.INFINITY; _painter.maxWidth = double.INFINITY;
......
...@@ -19,7 +19,7 @@ class Layer extends Node with SpritePaint { ...@@ -19,7 +19,7 @@ class Layer extends Node with SpritePaint {
/// if it is known. /// if it is known.
/// ///
/// var myLayer = new Layer(); /// var myLayer = new Layer();
Layer([Rect this.layerRect = null]); Layer([this.layerRect = null]);
Paint _cachedPaint = new Paint() Paint _cachedPaint = new Paint()
..filterQuality = ui.FilterQuality.low ..filterQuality = ui.FilterQuality.low
......
...@@ -61,7 +61,7 @@ class Node { ...@@ -61,7 +61,7 @@ class Node {
bool handleMultiplePointers = false; bool handleMultiplePointers = false;
int _handlingPointer; int _handlingPointer;
List<Node>_children = []; List<Node> _children = <Node>[];
ActionController _actions; ActionController _actions;
...@@ -104,9 +104,8 @@ class Node { ...@@ -104,9 +104,8 @@ class Node {
/// Creates a new [Node] without any transformation. /// Creates a new [Node] without any transformation.
/// ///
/// var myNode = new Node(); /// Node myNode = new Node();
Node() { Node();
}
// Property setters and getters // Property setters and getters
...@@ -115,7 +114,7 @@ class Node { ...@@ -115,7 +114,7 @@ class Node {
/// For most applications it's not necessary to access the [SpriteBox] directly. /// For most applications it's not necessary to access the [SpriteBox] directly.
/// ///
/// // Get the transformMode of the sprite box /// // Get the transformMode of the sprite box
/// var transformMode = myNode.spriteBox.transformMode; /// SpriteBoxTransformMode transformMode = myNode.spriteBox.transformMode;
SpriteBox get spriteBox => _spriteBox; SpriteBox get spriteBox => _spriteBox;
/// The parent of this node, or null if it doesn't have a parent. /// The parent of this node, or null if it doesn't have a parent.
...@@ -450,7 +449,7 @@ class Node { ...@@ -450,7 +449,7 @@ class Node {
child._parent = null; child._parent = null;
child._spriteBox = null; child._spriteBox = null;
} }
_children = []; _children = <Node>[];
_childrenNeedSorting = false; _childrenNeedSorting = false;
if (_spriteBox != null) _spriteBox._deregisterNode(null); if (_spriteBox != null) _spriteBox._deregisterNode(null);
} }
......
...@@ -21,8 +21,9 @@ class NodeWithSize extends Node { ...@@ -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. /// 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)); /// var myNodeWithSize = new NodeWithSize(new Size(1024.0, 1024.0));
NodeWithSize(Size this.size) { NodeWithSize(this.size) {
if (size == null) size = Size.zero; if (size == null)
size = Size.zero;
pivot = Point.origin; pivot = Point.origin;
} }
......
...@@ -359,9 +359,9 @@ class ParticleSystem extends Node { ...@@ -359,9 +359,9 @@ class ParticleSystem extends Node {
void paint(PaintingCanvas canvas) { void paint(PaintingCanvas canvas) {
List<ui.RSTransform> transforms = []; List<ui.RSTransform> transforms = <ui.RSTransform>[];
List<Rect> rects = []; List<Rect> rects = <Rect>[];
List<Color> colors = []; List<Color> colors = <Color>[];
_paint.transferMode = transferMode; _paint.transferMode = transferMode;
......
...@@ -237,7 +237,7 @@ class PhysicsBody { ...@@ -237,7 +237,7 @@ class PhysicsBody {
box2d.Body _body; box2d.Body _body;
List<PhysicsJoint> _joints = []; List<PhysicsJoint> _joints = <PhysicsJoint>[];
bool _attached = false; bool _attached = false;
...@@ -355,8 +355,8 @@ class PhysicsBody { ...@@ -355,8 +355,8 @@ class PhysicsBody {
fixtureDef.isSensor = isSensor; fixtureDef.isSensor = isSensor;
// Get shapes // Get shapes
List<box2d.Shape> b2Shapes = []; List<box2d.Shape> b2Shapes = <box2d.Shape>[];
List<PhysicsShape> physicsShapes = []; List<PhysicsShape> physicsShapes = <PhysicsShape>[];
_addB2Shapes(physicsNode, shape, b2Shapes, physicsShapes); _addB2Shapes(physicsNode, shape, b2Shapes, physicsShapes);
// Create fixtures // Create fixtures
......
...@@ -41,7 +41,7 @@ class PhysicsShapePolygon extends PhysicsShape { ...@@ -41,7 +41,7 @@ class PhysicsShapePolygon extends PhysicsShape {
final List<Point> points; final List<Point> points;
box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { box2d.Shape _createB2Shape(PhysicsWorld node, double scale) {
List<Vector2> vectors = []; List<Vector2> vectors = <Vector2>[];
for (Point point in points) { for (Point point in points) {
Vector2 vec = new Vector2( Vector2 vec = new Vector2(
scale * point.x / node.b2WorldToNodeConversionFactor, scale * point.x / node.b2WorldToNodeConversionFactor,
...@@ -91,7 +91,7 @@ class PhysicsShapeChain extends PhysicsShape { ...@@ -91,7 +91,7 @@ class PhysicsShapeChain extends PhysicsShape {
final bool loop; final bool loop;
box2d.Shape _createB2Shape(PhysicsWorld node, double scale) { box2d.Shape _createB2Shape(PhysicsWorld node, double scale) {
List<Vector2> vectors = []; List<Vector2> vectors = <Vector2>[];
for (Point point in points) { for (Point point in points) {
Vector2 vec = new Vector2( Vector2 vec = new Vector2(
scale * point.x / node.b2WorldToNodeConversionFactor, scale * point.x / node.b2WorldToNodeConversionFactor,
......
...@@ -39,11 +39,11 @@ class PhysicsWorld extends Node { ...@@ -39,11 +39,11 @@ class PhysicsWorld extends Node {
_ContactHandler _contactHandler; _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; _PhysicsDebugDraw _debugDraw;
...@@ -272,7 +272,7 @@ class _ContactHandler extends box2d.ContactListener { ...@@ -272,7 +272,7 @@ class _ContactHandler extends box2d.ContactListener {
PhysicsWorld physicsNode; PhysicsWorld physicsNode;
List<_ContactCallbackInfo> callbackInfos = []; List<_ContactCallbackInfo> callbackInfos = <_ContactCallbackInfo>[];
void addContactCallback(PhysicsContactCallback callback, Object tagA, Object tagB, PhysicsContactType type) { void addContactCallback(PhysicsContactCallback callback, Object tagA, Object tagB, PhysicsContactType type) {
callbackInfos.add(new _ContactCallbackInfo(callback, tagA, tagB, type)); callbackInfos.add(new _ContactCallbackInfo(callback, tagA, tagB, type));
...@@ -324,7 +324,7 @@ class _ContactHandler extends box2d.ContactListener { ...@@ -324,7 +324,7 @@ class _ContactHandler extends box2d.ContactListener {
box2d.WorldManifold manifold = new box2d.WorldManifold(); box2d.WorldManifold manifold = new box2d.WorldManifold();
b2Contact.getWorldManifold(manifold); b2Contact.getWorldManifold(manifold);
touchingNormal = new Offset(manifold.normal.x, manifold.normal.y); touchingNormal = new Offset(manifold.normal.x, manifold.normal.y);
touchingPoints = []; touchingPoints = <Point>[];
for (Vector2 vec in manifold.points) { for (Vector2 vec in manifold.points) {
touchingPoints.add(new Point( touchingPoints.add(new Point(
vec.x * physicsNode.b2WorldToNodeConversionFactor, vec.x * physicsNode.b2WorldToNodeConversionFactor,
......
...@@ -59,10 +59,10 @@ class SoundEffectPlayer { ...@@ -59,10 +59,10 @@ class SoundEffectPlayer {
} }
MediaServiceProxy _mediaService; MediaServiceProxy _mediaService;
List<SoundEffectStream> _soundEffectStreams = []; List<SoundEffectStream> _soundEffectStreams = <SoundEffectStream>[];
// TODO: This should no longer be needed when moving to SoundPool backing // 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 { Future _prepare(SoundEffectStream playingSound) async {
await playingSound._player.ptr.prepare(playingSound.sound._data); await playingSound._player.ptr.prepare(playingSound.sound._data);
...@@ -133,7 +133,7 @@ class SoundEffectPlayer { ...@@ -133,7 +133,7 @@ class SoundEffectPlayer {
for (SoundEffectStream playingSound in _soundEffectStreams) { for (SoundEffectStream playingSound in _soundEffectStreams) {
playingSound._player.ptr.pause(); playingSound._player.ptr.pause();
} }
_soundEffectStreams = []; _soundEffectStreams = <SoundEffectStream>[];
} }
} }
...@@ -154,7 +154,7 @@ class SoundTrack { ...@@ -154,7 +154,7 @@ class SoundTrack {
SoundTrackPlayer _sharedSoundTrackPlayer; SoundTrackPlayer _sharedSoundTrackPlayer;
class SoundTrackPlayer { class SoundTrackPlayer {
List<SoundTrack> _soundTracks = []; List<SoundTrack> _soundTracks = <SoundTrack>[];
static sharedInstance() { static sharedInstance() {
if (_sharedSoundTrackPlayer == null) { if (_sharedSoundTrackPlayer == null) {
......
...@@ -18,7 +18,7 @@ enum SoundEventMinimumOverlapPolicy { ...@@ -18,7 +18,7 @@ enum SoundEventMinimumOverlapPolicy {
class SoundEvent { class SoundEvent {
SoundEvent(SoundEffect effect) { SoundEvent(SoundEffect effect) {
effects = [effect]; effects = <SoundEffect>[effect];
} }
SoundEvent.withList(this.effects); SoundEvent.withList(this.effects);
...@@ -61,7 +61,7 @@ class SoundManager { ...@@ -61,7 +61,7 @@ class SoundManager {
new Timer.periodic(new Duration(milliseconds:10), _update); new Timer.periodic(new Duration(milliseconds:10), _update);
} }
Map<SoundEvent, List<_PlayingSoundEvent>> _playingEvents = {}; Map<SoundEvent, List<_PlayingSoundEvent>> _playingEvents = <SoundEvent, List<_PlayingSoundEvent>>{};
SoundTrack _backgroundMusicTrack; SoundTrack _backgroundMusicTrack;
SoundEffectPlayer _effectPlayer = SoundEffectPlayer.sharedInstance(); SoundEffectPlayer _effectPlayer = SoundEffectPlayer.sharedInstance();
...@@ -75,7 +75,7 @@ class SoundManager { ...@@ -75,7 +75,7 @@ class SoundManager {
void playEvent(SoundEvent evt, [double volume = 1.0, double pitch = 1.0, double pan = 0.0]) { void playEvent(SoundEvent evt, [double volume = 1.0, double pitch = 1.0, double pan = 0.0]) {
List<_PlayingSoundEvent> playingList = _playingEvents[evt]; List<_PlayingSoundEvent> playingList = _playingEvents[evt];
if (playingList == null) playingList = []; if (playingList == null) playingList = <_PlayingSoundEvent>[];
// Check simultaneousLimit // Check simultaneousLimit
if (evt.simultaneousLimit != 0 && evt.simultaneousLimit >= playingList.length) { if (evt.simultaneousLimit != 0 && evt.simultaneousLimit >= playingList.length) {
...@@ -131,13 +131,13 @@ class SoundManager { ...@@ -131,13 +131,13 @@ class SoundManager {
} }
void stopAllEvents([double fadeDuration]) { void stopAllEvents([double fadeDuration]) {
for (List<_PlayingSoundEvent> playingList in _playingEvents) { for (List<_PlayingSoundEvent> playingList in _playingEvents.values) {
for (_PlayingSoundEvent playing in playingList) { for (_PlayingSoundEvent playing in playingList) {
if (fadeDuration > 0.0) { if (fadeDuration > 0.0) {
// Fade out and stop // Fade out and stop
ActionTween fadeOut = new ActionTween((a) => playing.stream.volume = a, playing.stream.volume, 0.0, fadeDuration); ActionTween fadeOut = new ActionTween((a) => playing.stream.volume = a, playing.stream.volume, 0.0, fadeDuration);
ActionCallFunction stop = new ActionCallFunction(() { _effectPlayer.stop(playing.stream); }); ActionCallFunction stop = new ActionCallFunction(() { _effectPlayer.stop(playing.stream); });
ActionSequence seq = new ActionSequence([fadeOut, stop]); ActionSequence seq = new ActionSequence(<Action>[fadeOut, stop]);
actions.run(seq); actions.run(seq);
} }
else { else {
...@@ -175,7 +175,7 @@ class SoundManager { ...@@ -175,7 +175,7 @@ class SoundManager {
} else { } else {
ActionTween fadeOut = new ActionTween((a) => _backgroundMusicTrack.volume = a, _backgroundMusicTrack.volume, 0.0, fadeOutDuration); ActionTween fadeOut = new ActionTween((a) => _backgroundMusicTrack.volume = a, _backgroundMusicTrack.volume, 0.0, fadeOutDuration);
ActionCallFunction stop = new ActionCallFunction(() { _trackPlayer.stop(_backgroundMusicTrack); }); ActionCallFunction stop = new ActionCallFunction(() { _trackPlayer.stop(_backgroundMusicTrack); });
ActionSequence seq = new ActionSequence([fadeOut, stop]); ActionSequence seq = new ActionSequence(<Action>[fadeOut, stop]);
actions.run(seq); actions.run(seq);
} }
} else { } else {
...@@ -190,7 +190,7 @@ class SoundManager { ...@@ -190,7 +190,7 @@ class SoundManager {
ActionCallFunction fadeInCall = new ActionCallFunction(() { ActionCallFunction fadeInCall = new ActionCallFunction(() {
_fadeInTrack(track, fadeInDuration); _fadeInTrack(track, fadeInDuration);
}); });
ActionSequence seq = new ActionSequence([delay, fadeInCall]); ActionSequence seq = new ActionSequence(<Action>[delay, fadeInCall]);
actions.run(seq); actions.run(seq);
} }
} }
...@@ -216,7 +216,7 @@ class SoundManager { ...@@ -216,7 +216,7 @@ class SoundManager {
ActionCallFunction stopCall = new ActionCallFunction(() { ActionCallFunction stopCall = new ActionCallFunction(() {
_trackPlayer.stop(_backgroundMusicTrack); _trackPlayer.stop(_backgroundMusicTrack);
}); });
ActionSequence seq = new ActionSequence([fadeOut, stopCall]); ActionSequence seq = new ActionSequence(<Action>[fadeOut, stopCall]);
actions.run(seq); actions.run(seq);
} }
......
...@@ -196,12 +196,12 @@ class SpriteBox extends RenderBox { ...@@ -196,12 +196,12 @@ class SpriteBox extends RenderBox {
if (event.type == 'pointerdown') { if (event.type == 'pointerdown') {
// Build list of event targets // Build list of event targets
if (_eventTargets == null) { if (_eventTargets == null) {
_eventTargets = []; _eventTargets = <Node>[];
_addEventTargets(_rootNode, _eventTargets); _addEventTargets(_rootNode, _eventTargets);
} }
// Find the once that are hit by the pointer // 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--) { for (int i = _eventTargets.length - 1; i >= 0; i--) {
Node node = _eventTargets[i]; Node node = _eventTargets[i];
...@@ -393,8 +393,8 @@ class SpriteBox extends RenderBox { ...@@ -393,8 +393,8 @@ class SpriteBox extends RenderBox {
} }
void _rebuildActionControllersAndPhysicsNodes() { void _rebuildActionControllersAndPhysicsNodes() {
_actionControllers = []; _actionControllers = <ActionController>[];
_physicsNodes = []; _physicsNodes = <PhysicsWorld>[];
_addActionControllersAndPhysicsNodes(_rootNode); _addActionControllersAndPhysicsNodes(_rootNode);
} }
...@@ -429,7 +429,7 @@ class SpriteBox extends RenderBox { ...@@ -429,7 +429,7 @@ class SpriteBox extends RenderBox {
void _callConstraintsPreUpdate(double dt) { void _callConstraintsPreUpdate(double dt) {
if (_constrainedNodes == null) { if (_constrainedNodes == null) {
_constrainedNodes = []; _constrainedNodes = <Node>[];
_addConstrainedNodes(_rootNode, _constrainedNodes); _addConstrainedNodes(_rootNode, _constrainedNodes);
} }
...@@ -442,7 +442,7 @@ class SpriteBox extends RenderBox { ...@@ -442,7 +442,7 @@ class SpriteBox extends RenderBox {
void _callConstraintsConstrain(double dt) { void _callConstraintsConstrain(double dt) {
if (_constrainedNodes == null) { if (_constrainedNodes == null) {
_constrainedNodes = []; _constrainedNodes = <Node>[];
_addConstrainedNodes(_rootNode, _constrainedNodes); _addConstrainedNodes(_rootNode, _constrainedNodes);
} }
...@@ -481,7 +481,7 @@ class SpriteBox extends RenderBox { ...@@ -481,7 +481,7 @@ class SpriteBox extends RenderBox {
List<Node> findNodesAtPosition(Point position) { List<Node> findNodesAtPosition(Point position) {
assert(position != null); assert(position != null);
List<Node> nodes = []; List<Node> nodes = <Node>[];
// Traverse the render tree and find objects at the position // Traverse the render tree and find objects at the position
_addNodesAtPosition(_rootNode, position, nodes); _addNodesAtPosition(_rootNode, position, nodes);
......
...@@ -9,7 +9,7 @@ part of flutter_sprites; ...@@ -9,7 +9,7 @@ part of flutter_sprites;
class SpriteSheet { class SpriteSheet {
ui.Image _image; 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]. /// Creates a new sprite sheet from an [_image] and a sprite sheet [jsonDefinition].
/// ///
......
...@@ -4,6 +4,23 @@ part of flutter_sprites; ...@@ -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]. /// Normally you get a reference to a texture from a [SpriteSheet], but you can also create one from an [Image].
class Texture { 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. /// The image that this texture is a part of.
/// ///
/// var textureImage = myTexture.image; /// var textureImage = myTexture.image;
...@@ -48,23 +65,6 @@ class Texture { ...@@ -48,23 +65,6 @@ class Texture {
/// myTexture.pivot = new Point(0.5, 0.5); /// myTexture.pivot = new Point(0.5, 0.5);
Point pivot; 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]) { Texture textureFromRect(Rect rect, [String name = null]) {
assert(rect != null); assert(rect != null);
assert(!rotated); assert(!rotated);
......
...@@ -92,15 +92,15 @@ class TexturedLinePainter { ...@@ -92,15 +92,15 @@ class TexturedLinePainter {
_cachedPaint.transferMode = transferMode; _cachedPaint.transferMode = transferMode;
// Calculate normals // Calculate normals
List<Vector2> vectors = []; List<Vector2> vectors = <Vector2>[];
for (Point pt in _points) { for (Point pt in _points) {
vectors.add(new Vector2(pt.x, pt.y)); vectors.add(new Vector2(pt.x, pt.y));
} }
List<Vector2> miters = _computeMiterList(vectors, false); List<Vector2> miters = _computeMiterList(vectors, false);
List<Point> vertices = []; List<Point> vertices = <Point>[];
List<int> indicies = []; List<int> indicies = <int>[];
List<Color> verticeColors = []; List<Color> verticeColors = <Color>[];
List<Point> textureCoordinates; List<Point> textureCoordinates;
double textureTop; double textureTop;
double textureBottom; double textureBottom;
...@@ -121,7 +121,7 @@ class TexturedLinePainter { ...@@ -121,7 +121,7 @@ class TexturedLinePainter {
// Setup for calculating texture coordinates // Setup for calculating texture coordinates
textureTop = texture.frame.top; textureTop = texture.frame.top;
textureBottom = texture.frame.bottom; textureBottom = texture.frame.bottom;
textureCoordinates = []; textureCoordinates = <Point>[];
// Use correct stops // Use correct stops
if (textureStops != null) { if (textureStops != null) {
...@@ -150,8 +150,8 @@ class TexturedLinePainter { ...@@ -150,8 +150,8 @@ class TexturedLinePainter {
int lastIndex1 = (i - 1) * 2 + 1; int lastIndex1 = (i - 1) * 2 + 1;
int currentIndex0 = i * 2; int currentIndex0 = i * 2;
int currentIndex1 = i * 2 + 1; int currentIndex1 = i * 2 + 1;
indicies.addAll([lastIndex0, lastIndex1, currentIndex0]); indicies.addAll(<int>[lastIndex0, lastIndex1, currentIndex0]);
indicies.addAll([lastIndex1, currentIndex1, currentIndex0]); indicies.addAll(<int>[lastIndex1, currentIndex1, currentIndex0]);
// Add colors // Add colors
verticeColors.add(colors[i]); verticeColors.add(colors[i]);
...@@ -209,7 +209,7 @@ class TexturedLinePainter { ...@@ -209,7 +209,7 @@ class TexturedLinePainter {
} }
void _calculateTextureStops() { void _calculateTextureStops() {
List<double> stops = []; List<double> stops = <double>[];
double length = 0.0; double length = 0.0;
// Add first stop // Add first stop
...@@ -262,7 +262,7 @@ Vector2 _vectorDirection(Vector2 a, Vector2 b) { ...@@ -262,7 +262,7 @@ Vector2 _vectorDirection(Vector2 a, Vector2 b) {
} }
List<Vector2> _computeMiterList(List<Vector2> points, bool closed) { List<Vector2> _computeMiterList(List<Vector2> points, bool closed) {
List<Vector2> out = []; List<Vector2> out = <Vector2>[];
Vector2 curNormal = null; Vector2 curNormal = null;
if (closed) { if (closed) {
......
...@@ -39,7 +39,7 @@ class VirtualJoystick extends NodeWithSize { ...@@ -39,7 +39,7 @@ class VirtualJoystick extends NodeWithSize {
else if (event.type == "pointerup" || event.type == "pointercancel") { else if (event.type == "pointerup" || event.type == "pointercancel") {
_pointerDownAt = null; _pointerDownAt = null;
_value = Point.origin; _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); actions.run(moveToCenter);
_isDown = false; _isDown = false;
} else if (event.type == "pointermove") { } else if (event.type == "pointermove") {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment