Declare locals final where not reassigned (#8564)

Covers lib/ in package:flutter.
This commit is contained in:
Chris Bracken 2017-03-03 17:42:23 -08:00 committed by GitHub
parent 8738eb97bc
commit 27e8cc3797
141 changed files with 734 additions and 734 deletions

View File

@ -146,7 +146,7 @@ class AnimationController extends Animation<double>
/// Recreates the [Ticker] with the new [TickerProvider]. /// Recreates the [Ticker] with the new [TickerProvider].
void resync(TickerProvider vsync) { void resync(TickerProvider vsync) {
Ticker oldTicker = _ticker; final Ticker oldTicker = _ticker;
_ticker = vsync.createTicker(_tick); _ticker = vsync.createTicker(_tick);
_ticker.absorbTicker(oldTicker); _ticker.absorbTicker(oldTicker);
} }
@ -279,8 +279,8 @@ class AnimationController extends Animation<double>
} }
return true; return true;
}); });
double range = upperBound - lowerBound; final double range = upperBound - lowerBound;
double remainingFraction = range.isFinite ? (target - _value).abs() / range : 1.0; final double remainingFraction = range.isFinite ? (target - _value).abs() / range : 1.0;
simulationDuration = this.duration * remainingFraction; simulationDuration = this.duration * remainingFraction;
} }
stop(); stop();
@ -326,7 +326,7 @@ class AnimationController extends Animation<double>
_direction = velocity < 0.0 ? _AnimationDirection.reverse : _AnimationDirection.forward; _direction = velocity < 0.0 ? _AnimationDirection.reverse : _AnimationDirection.forward;
final double target = velocity < 0.0 ? lowerBound - _kFlingTolerance.distance final double target = velocity < 0.0 ? lowerBound - _kFlingTolerance.distance
: upperBound + _kFlingTolerance.distance; : upperBound + _kFlingTolerance.distance;
Simulation simulation = new SpringSimulation(_kFlingSpringDescription, value, target, velocity) final Simulation simulation = new SpringSimulation(_kFlingSpringDescription, value, target, velocity)
..tolerance = _kFlingTolerance; ..tolerance = _kFlingTolerance;
return animateWith(simulation); return animateWith(simulation);
} }
@ -343,7 +343,7 @@ class AnimationController extends Animation<double>
_simulation = simulation; _simulation = simulation;
_lastElapsedDuration = Duration.ZERO; _lastElapsedDuration = Duration.ZERO;
_value = simulation.x(0.0).clamp(lowerBound, upperBound); _value = simulation.x(0.0).clamp(lowerBound, upperBound);
Future<Null> result = _ticker.start(); final Future<Null> result = _ticker.start();
_status = (_direction == _AnimationDirection.forward) ? _status = (_direction == _AnimationDirection.forward) ?
AnimationStatus.forward : AnimationStatus.forward :
AnimationStatus.reverse; AnimationStatus.reverse;
@ -381,7 +381,7 @@ class AnimationController extends Animation<double>
AnimationStatus _lastReportedStatus = AnimationStatus.dismissed; AnimationStatus _lastReportedStatus = AnimationStatus.dismissed;
void _checkStatusChanged() { void _checkStatusChanged() {
AnimationStatus newStatus = status; final AnimationStatus newStatus = status;
if (_lastReportedStatus != newStatus) { if (_lastReportedStatus != newStatus) {
_lastReportedStatus = newStatus; _lastReportedStatus = newStatus;
notifyStatusListeners(newStatus); notifyStatusListeners(newStatus);
@ -390,7 +390,7 @@ class AnimationController extends Animation<double>
void _tick(Duration elapsed) { void _tick(Duration elapsed) {
_lastElapsedDuration = elapsed; _lastElapsedDuration = elapsed;
double elapsedInSeconds = elapsed.inMicroseconds.toDouble() / Duration.MICROSECONDS_PER_SECOND; final double elapsedInSeconds = elapsed.inMicroseconds.toDouble() / Duration.MICROSECONDS_PER_SECOND;
assert(elapsedInSeconds >= 0.0); assert(elapsedInSeconds >= 0.0);
_value = _simulation.x(elapsedInSeconds).clamp(lowerBound, upperBound); _value = _simulation.x(elapsedInSeconds).clamp(lowerBound, upperBound);
if (_simulation.isDone(elapsedInSeconds)) { if (_simulation.isDone(elapsedInSeconds)) {
@ -405,10 +405,10 @@ class AnimationController extends Animation<double>
@override @override
String toStringDetails() { String toStringDetails() {
String paused = isAnimating ? '' : '; paused'; final String paused = isAnimating ? '' : '; paused';
String ticker = _ticker == null ? '; DISPOSED' : (_ticker.muted ? '; silenced' : ''); final String ticker = _ticker == null ? '; DISPOSED' : (_ticker.muted ? '; silenced' : '');
String label = debugLabel == null ? '' : '; for $debugLabel'; final String label = debugLabel == null ? '' : '; for $debugLabel';
String more = '${super.toStringDetails()} ${value.toStringAsFixed(3)}'; final String more = '${super.toStringDetails()} ${value.toStringAsFixed(3)}';
return '$more$paused$ticker$label'; return '$more$paused$ticker$label';
} }
} }
@ -428,7 +428,7 @@ class _InterpolationSimulation extends Simulation {
@override @override
double x(double timeInSeconds) { double x(double timeInSeconds) {
double t = (timeInSeconds / _durationInSeconds).clamp(0.0, 1.0); final double t = (timeInSeconds / _durationInSeconds).clamp(0.0, 1.0);
if (t == 0.0) if (t == 0.0)
return _begin; return _begin;
else if (t == 1.0) else if (t == 1.0)
@ -439,7 +439,7 @@ class _InterpolationSimulation extends Simulation {
@override @override
double dx(double timeInSeconds) { double dx(double timeInSeconds) {
double epsilon = tolerance.time; final double epsilon = tolerance.time;
return (x(timeInSeconds + epsilon) - x(timeInSeconds - epsilon)) / (2 * epsilon); return (x(timeInSeconds + epsilon) - x(timeInSeconds - epsilon)) / (2 * epsilon);
} }

View File

@ -384,9 +384,9 @@ class CurvedAnimation extends Animation<double> with AnimationWithParentMixin<do
@override @override
double get value { double get value {
Curve activeCurve = _useForwardCurve ? curve : reverseCurve; final Curve activeCurve = _useForwardCurve ? curve : reverseCurve;
double t = parent.value; final double t = parent.value;
if (activeCurve == null) if (activeCurve == null)
return t; return t;
if (t == 0.0 || t == 1.0) { if (t == 0.0 || t == 1.0) {
@ -501,7 +501,7 @@ class TrainHoppingAnimation extends Animation<double>
_statusChangeHandler(_currentTrain.status); _statusChangeHandler(_currentTrain.status);
} }
} }
double newValue = value; final double newValue = value;
if (newValue != _lastValue) { if (newValue != _lastValue) {
notifyListeners(); notifyListeners();
_lastValue = newValue; _lastValue = newValue;

View File

@ -190,8 +190,8 @@ class Cubic extends Curve {
double start = 0.0; double start = 0.0;
double end = 1.0; double end = 1.0;
while (true) { while (true) {
double midpoint = (start + end) / 2; final double midpoint = (start + end) / 2;
double estimate = _evaluateCubic(a, c, midpoint); final double estimate = _evaluateCubic(a, c, midpoint);
if ((t - estimate).abs() < _kCubicErrorBound) if ((t - estimate).abs() < _kCubicErrorBound)
return _evaluateCubic(b, d, midpoint); return _evaluateCubic(b, d, midpoint);
if (estimate < t) if (estimate < t)
@ -326,7 +326,7 @@ class ElasticInCurve extends Curve {
@override @override
double transform(double t) { double transform(double t) {
assert(t >= 0.0 && t <= 1.0); assert(t >= 0.0 && t <= 1.0);
double s = period / 4.0; final double s = period / 4.0;
t = t - 1.0; t = t - 1.0;
return -math.pow(2.0, 10.0 * t) * math.sin((t - s) * (math.PI * 2.0) / period); return -math.pow(2.0, 10.0 * t) * math.sin((t - s) * (math.PI * 2.0) / period);
} }
@ -350,7 +350,7 @@ class ElasticOutCurve extends Curve {
@override @override
double transform(double t) { double transform(double t) {
assert(t >= 0.0 && t <= 1.0); assert(t >= 0.0 && t <= 1.0);
double s = period / 4.0; final double s = period / 4.0;
return math.pow(2.0, -10 * t) * math.sin((t - s) * (math.PI * 2.0) / period) + 1.0; return math.pow(2.0, -10 * t) * math.sin((t - s) * (math.PI * 2.0) / period) + 1.0;
} }
@ -373,7 +373,7 @@ class ElasticInOutCurve extends Curve {
@override @override
double transform(double t) { double transform(double t) {
assert(t >= 0.0 && t <= 1.0); assert(t >= 0.0 && t <= 1.0);
double s = period / 4.0; final double s = period / 4.0;
t = 2.0 * t - 1.0; t = 2.0 * t - 1.0;
if (t < 0.0) if (t < 0.0)
return -0.5 * math.pow(2.0, 10.0 * t) * math.sin((t - s) * (math.PI * 2.0) / period); return -0.5 * math.pow(2.0, 10.0 * t) * math.sin((t - s) * (math.PI * 2.0) / period);

View File

@ -60,7 +60,7 @@ class _ChainedEvaluation<T> extends Animatable<T> {
@override @override
T evaluate(Animation<double> animation) { T evaluate(Animation<double> animation) {
double value = _parent.evaluate(animation); final double value = _parent.evaluate(animation);
return _evaluatable.evaluate(new AlwaysStoppedAnimation<double>(value)); return _evaluatable.evaluate(new AlwaysStoppedAnimation<double>(value));
} }
@ -240,7 +240,7 @@ class CurveTween extends Animatable<double> {
@override @override
double evaluate(Animation<double> animation) { double evaluate(Animation<double> animation) {
double t = animation.value; final double t = animation.value;
if (t == 0.0 || t == 1.0) { if (t == 0.0 || t == 1.0) {
assert(curve.transform(t).round() == t); assert(curve.transform(t).round() == t);
return t; return t;

View File

@ -21,7 +21,7 @@ class CupertinoThumbPainter {
void paint(Canvas canvas, Rect rect) { void paint(Canvas canvas, Rect rect) {
final RRect rrect = new RRect.fromRectAndRadius(rect, new Radius.circular(rect.shortestSide / 2.0)); final RRect rrect = new RRect.fromRectAndRadius(rect, new Radius.circular(rect.shortestSide / 2.0));
Paint paint = new Paint() final Paint paint = new Paint()
..color = shadowColor ..color = shadowColor
..maskFilter = _kShadowMaskFilter; ..maskFilter = _kShadowMaskFilter;
canvas.drawRRect(rrect, paint); canvas.drawRRect(rrect, paint);

View File

@ -214,7 +214,7 @@ class FlutterError extends AssertionError {
if ((details.exception is AssertionError) && (details.exception is! FlutterError)) { if ((details.exception is AssertionError) && (details.exception is! FlutterError)) {
bool ourFault = true; bool ourFault = true;
if (stackLines != null) { if (stackLines != null) {
List<String> stackList = stackLines.take(2).toList(); final List<String> stackList = stackLines.take(2).toList();
if (stackList.length >= 2) { if (stackList.length >= 2) {
final RegExp throwPattern = new RegExp(r'^#0 +_AssertionError._throwNew \(dart:.+\)$'); final RegExp throwPattern = new RegExp(r'^#0 +_AssertionError._throwNew \(dart:.+\)$');
final RegExp assertPattern = new RegExp(r'^#1 +[^(]+ \((.+?):([0-9]+)(?::[0-9]+)?\)$'); final RegExp assertPattern = new RegExp(r'^#1 +[^(]+ \((.+?):([0-9]+)(?::[0-9]+)?\)$');
@ -247,7 +247,7 @@ class FlutterError extends AssertionError {
debugPrint(line, wrapWidth: _kWrapWidth); debugPrint(line, wrapWidth: _kWrapWidth);
} }
if (details.informationCollector != null) { if (details.informationCollector != null) {
StringBuffer information = new StringBuffer(); final StringBuffer information = new StringBuffer();
details.informationCollector(information); details.informationCollector(information);
debugPrint('\n$information', wrapWidth: _kWrapWidth); debugPrint('\n$information', wrapWidth: _kWrapWidth);
} }
@ -285,11 +285,11 @@ class FlutterError extends AssertionError {
final List<String> result = <String>[]; final List<String> result = <String>[];
final List<String> skipped = <String>[]; final List<String> skipped = <String>[];
for (String line in frames) { for (String line in frames) {
Match match = stackParser.firstMatch(line); final Match match = stackParser.firstMatch(line);
if (match != null) { if (match != null) {
assert(match.groupCount == 2); assert(match.groupCount == 2);
if (filteredPackages.contains(match.group(2))) { if (filteredPackages.contains(match.group(2))) {
Match packageMatch = packageParser.firstMatch(match.group(2)); final Match packageMatch = packageParser.firstMatch(match.group(2));
if (packageMatch != null && packageMatch.group(1) == 'package') { if (packageMatch != null && packageMatch.group(1) == 'package') {
skipped.add('package ${packageMatch.group(2)}'); // avoid "package package:foo" skipped.add('package ${packageMatch.group(2)}'); // avoid "package package:foo"
} else { } else {
@ -307,7 +307,7 @@ class FlutterError extends AssertionError {
if (skipped.length == 1) { if (skipped.length == 1) {
result.add('(elided one frame from ${skipped.single})'); result.add('(elided one frame from ${skipped.single})');
} else if (skipped.length > 1) { } else if (skipped.length > 1) {
List<String> where = new Set<String>.from(skipped).toList()..sort(); final List<String> where = new Set<String>.from(skipped).toList()..sort();
if (where.length > 1) if (where.length > 1)
where[where.length - 1] = 'and ${where.last}'; where[where.length - 1] = 'and ${where.last}';
if (where.length > 2) { if (where.length > 2) {

View File

@ -132,7 +132,7 @@ class LicenseEntryWithLineBreaks extends LicenseEntry {
int currentLineIndent = 0; int currentLineIndent = 0;
int currentParagraphIndentation; int currentParagraphIndentation;
_LicenseEntryWithLineBreaksParserState state = _LicenseEntryWithLineBreaksParserState.beforeParagraph; _LicenseEntryWithLineBreaksParserState state = _LicenseEntryWithLineBreaksParserState.beforeParagraph;
List<String> lines = <String>[]; final List<String> lines = <String>[];
void addLine() { void addLine() {
assert(lineStart < currentPosition); assert(lineStart < currentPosition);

View File

@ -64,7 +64,7 @@ void _debugPrintTask() {
_debugPrintedCharacters = 0; _debugPrintedCharacters = 0;
} }
while (_debugPrintedCharacters < _kDebugPrintCapacity && _debugPrintBuffer.isNotEmpty) { while (_debugPrintedCharacters < _kDebugPrintCapacity && _debugPrintBuffer.isNotEmpty) {
String line = _debugPrintBuffer.removeFirst(); final String line = _debugPrintBuffer.removeFirst();
_debugPrintedCharacters += line.length; // TODO(ianh): Use the UTF-8 byte length instead _debugPrintedCharacters += line.length; // TODO(ianh): Use the UTF-8 byte length instead
print(line); print(line);
} }
@ -108,8 +108,8 @@ Iterable<String> debugWordWrap(String message, int width, { String wrapIndent: '
yield message; yield message;
return; return;
} }
Match prefixMatch = _indentPattern.matchAsPrefix(message); final Match prefixMatch = _indentPattern.matchAsPrefix(message);
String prefix = wrapIndent + ' ' * prefixMatch.group(0).length; final String prefix = wrapIndent + ' ' * prefixMatch.group(0).length;
int start = 0; int start = 0;
int startForLengthCalculations = 0; int startForLengthCalculations = 0;
bool addPrefix = false; bool addPrefix = false;

View File

@ -35,7 +35,7 @@ class SynchronousFuture<T> implements Future<T> {
@override @override
Future<E> then<E>(dynamic f(T value), { Function onError }) { Future<E> then<E>(dynamic f(T value), { Function onError }) {
dynamic result = f(_value); final dynamic result = f(_value);
if (result is Future<E>) if (result is Future<E>)
return result; return result;
return new SynchronousFuture<E>(result); return new SynchronousFuture<E>(result);
@ -49,7 +49,7 @@ class SynchronousFuture<T> implements Future<T> {
@override @override
Future<T> whenComplete(dynamic action()) { Future<T> whenComplete(dynamic action()) {
try { try {
dynamic result = action(); final dynamic result = action();
if (result is Future) if (result is Future)
return result.then<T>((dynamic value) => _value); return result.then<T>((dynamic value) => _value);
return this; return this;

View File

@ -75,7 +75,7 @@ class GestureArenaManager {
/// Adds a new member (e.g., gesture recognizer) to the arena. /// Adds a new member (e.g., gesture recognizer) to the arena.
GestureArenaEntry add(int pointer, GestureArenaMember member) { GestureArenaEntry add(int pointer, GestureArenaMember member) {
_GestureArena state = _arenas.putIfAbsent(pointer, () => new _GestureArena()); final _GestureArena state = _arenas.putIfAbsent(pointer, () => new _GestureArena());
state.add(member); state.add(member);
return new GestureArenaEntry._(this, pointer, member); return new GestureArenaEntry._(this, pointer, member);
} }
@ -84,7 +84,7 @@ class GestureArenaManager {
/// ///
/// Called after the framework has finished dispatching the pointer down event. /// Called after the framework has finished dispatching the pointer down event.
void close(int pointer) { void close(int pointer) {
_GestureArena state = _arenas[pointer]; final _GestureArena state = _arenas[pointer];
if (state == null) if (state == null)
return; // This arena either never existed or has been resolved. return; // This arena either never existed or has been resolved.
state.isOpen = false; state.isOpen = false;
@ -105,7 +105,7 @@ class GestureArenaManager {
/// * [hold] /// * [hold]
/// * [release] /// * [release]
void sweep(int pointer) { void sweep(int pointer) {
_GestureArena state = _arenas[pointer]; final _GestureArena state = _arenas[pointer];
if (state == null) if (state == null)
return; // This arena either never existed or has been resolved. return; // This arena either never existed or has been resolved.
assert(!state.isOpen); assert(!state.isOpen);
@ -136,7 +136,7 @@ class GestureArenaManager {
/// * [sweep] /// * [sweep]
/// * [release] /// * [release]
void hold(int pointer) { void hold(int pointer) {
_GestureArena state = _arenas[pointer]; final _GestureArena state = _arenas[pointer];
if (state == null) if (state == null)
return; // This arena either never existed or has been resolved. return; // This arena either never existed or has been resolved.
state.isHeld = true; state.isHeld = true;
@ -152,7 +152,7 @@ class GestureArenaManager {
/// * [sweep] /// * [sweep]
/// * [hold] /// * [hold]
void release(int pointer) { void release(int pointer) {
_GestureArena state = _arenas[pointer]; final _GestureArena state = _arenas[pointer];
if (state == null) if (state == null)
return; // This arena either never existed or has been resolved. return; // This arena either never existed or has been resolved.
state.isHeld = false; state.isHeld = false;
@ -184,7 +184,7 @@ class GestureArenaManager {
} }
void _resolve(int pointer, GestureArenaMember member, GestureDisposition disposition) { void _resolve(int pointer, GestureArenaMember member, GestureDisposition disposition) {
_GestureArena state = _arenas[pointer]; final _GestureArena state = _arenas[pointer];
if (state == null) if (state == null)
return; // This arena has already resolved. return; // This arena has already resolved.
assert(state.members.contains(member)); assert(state.members.contains(member));

View File

@ -53,7 +53,7 @@ class PointerEventConverter {
switch (datum.change) { switch (datum.change) {
case ui.PointerChange.add: case ui.PointerChange.add:
assert(!_pointers.containsKey(datum.device)); assert(!_pointers.containsKey(datum.device));
_PointerState state = _ensureStateForPointer(datum, position); final _PointerState state = _ensureStateForPointer(datum, position);
assert(state.lastPosition == position); assert(state.lastPosition == position);
yield new PointerAddedEvent( yield new PointerAddedEvent(
timeStamp: timeStamp, timeStamp: timeStamp,
@ -73,7 +73,7 @@ class PointerEventConverter {
break; break;
case ui.PointerChange.hover: case ui.PointerChange.hover:
final bool alreadyAdded = _pointers.containsKey(datum.device); final bool alreadyAdded = _pointers.containsKey(datum.device);
_PointerState state = _ensureStateForPointer(datum, position); final _PointerState state = _ensureStateForPointer(datum, position);
assert(!state.down); assert(!state.down);
if (!alreadyAdded) { if (!alreadyAdded) {
assert(state.lastPosition == position); assert(state.lastPosition == position);
@ -93,7 +93,7 @@ class PointerEventConverter {
tilt: datum.tilt tilt: datum.tilt
); );
} }
Offset offset = position - state.lastPosition; final Offset offset = position - state.lastPosition;
state.lastPosition = position; state.lastPosition = position;
yield new PointerHoverEvent( yield new PointerHoverEvent(
timeStamp: timeStamp, timeStamp: timeStamp,
@ -118,7 +118,7 @@ class PointerEventConverter {
break; break;
case ui.PointerChange.down: case ui.PointerChange.down:
final bool alreadyAdded = _pointers.containsKey(datum.device); final bool alreadyAdded = _pointers.containsKey(datum.device);
_PointerState state = _ensureStateForPointer(datum, position); final _PointerState state = _ensureStateForPointer(datum, position);
assert(!state.down); assert(!state.down);
if (!alreadyAdded) { if (!alreadyAdded) {
assert(state.lastPosition == position); assert(state.lastPosition == position);
@ -142,7 +142,7 @@ class PointerEventConverter {
// Not all sources of pointer packets respect the invariant that // Not all sources of pointer packets respect the invariant that
// they hover the pointer to the down location before sending the // they hover the pointer to the down location before sending the
// down event. We restore the invariant here for our clients. // down event. We restore the invariant here for our clients.
Offset offset = position - state.lastPosition; final Offset offset = position - state.lastPosition;
state.lastPosition = position; state.lastPosition = position;
yield new PointerHoverEvent( yield new PointerHoverEvent(
timeStamp: timeStamp, timeStamp: timeStamp,
@ -192,9 +192,9 @@ class PointerEventConverter {
// start sending us ADDED and REMOVED data points. // start sending us ADDED and REMOVED data points.
// See also: https://github.com/flutter/flutter/issues/720 // See also: https://github.com/flutter/flutter/issues/720
assert(_pointers.containsKey(datum.device)); assert(_pointers.containsKey(datum.device));
_PointerState state = _pointers[datum.device]; final _PointerState state = _pointers[datum.device];
assert(state.down); assert(state.down);
Offset offset = position - state.lastPosition; final Offset offset = position - state.lastPosition;
state.lastPosition = position; state.lastPosition = position;
yield new PointerMoveEvent( yield new PointerMoveEvent(
timeStamp: timeStamp, timeStamp: timeStamp,
@ -220,7 +220,7 @@ class PointerEventConverter {
case ui.PointerChange.up: case ui.PointerChange.up:
case ui.PointerChange.cancel: case ui.PointerChange.cancel:
assert(_pointers.containsKey(datum.device)); assert(_pointers.containsKey(datum.device));
_PointerState state = _pointers[datum.device]; final _PointerState state = _pointers[datum.device];
assert(state.down); assert(state.down);
if (position != state.lastPosition) { if (position != state.lastPosition) {
// Not all sources of pointer packets respect the invariant that // Not all sources of pointer packets respect the invariant that
@ -228,7 +228,7 @@ class PointerEventConverter {
// event. For example, in the iOS simulator, of you drag outside the // event. For example, in the iOS simulator, of you drag outside the
// window, you'll get a stream of pointers that violates that // window, you'll get a stream of pointers that violates that
// invariant. We restore the invariant here for our clients. // invariant. We restore the invariant here for our clients.
Offset offset = position - state.lastPosition; final Offset offset = position - state.lastPosition;
state.lastPosition = position; state.lastPosition = position;
yield new PointerMoveEvent( yield new PointerMoveEvent(
timeStamp: timeStamp, timeStamp: timeStamp,
@ -293,7 +293,7 @@ class PointerEventConverter {
break; break;
case ui.PointerChange.remove: case ui.PointerChange.remove:
assert(_pointers.containsKey(datum.device)); assert(_pointers.containsKey(datum.device));
_PointerState state = _pointers[datum.device]; final _PointerState state = _pointers[datum.device];
if (state.down) { if (state.down) {
yield new PointerCancelEvent( yield new PointerCancelEvent(
timeStamp: timeStamp, timeStamp: timeStamp,

View File

@ -283,10 +283,10 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer {
void handleEvent(PointerEvent event) { void handleEvent(PointerEvent event) {
assert(_state != _DragState.ready); assert(_state != _DragState.ready);
if (event is PointerMoveEvent) { if (event is PointerMoveEvent) {
VelocityTracker tracker = _velocityTrackers[event.pointer]; final VelocityTracker tracker = _velocityTrackers[event.pointer];
assert(tracker != null); assert(tracker != null);
tracker.addPosition(event.timeStamp, event.position); tracker.addPosition(event.timeStamp, event.position);
Offset delta = event.delta; final Offset delta = event.delta;
if (_state == _DragState.accepted) { if (_state == _DragState.accepted) {
if (onUpdate != null) { if (onUpdate != null) {
invokeCallback<Null>('onUpdate', () => onUpdate(new DragUpdateDetails( // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504 invokeCallback<Null>('onUpdate', () => onUpdate(new DragUpdateDetails( // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
@ -308,7 +308,7 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer {
void acceptGesture(int pointer) { void acceptGesture(int pointer) {
if (_state != _DragState.accepted) { if (_state != _DragState.accepted) {
_state = _DragState.accepted; _state = _DragState.accepted;
Offset delta = _pendingDragOffset; final Offset delta = _pendingDragOffset;
_pendingDragOffset = Offset.zero; _pendingDragOffset = Offset.zero;
if (onStart != null) { if (onStart != null) {
invokeCallback<Null>('onStart', () => onStart(new DragStartDetails( // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504 invokeCallback<Null>('onStart', () => onStart(new DragStartDetails( // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
@ -339,10 +339,10 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer {
invokeCallback<Null>('onCancel', onCancel); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504 invokeCallback<Null>('onCancel', onCancel); // ignore: STRONG_MODE_INVALID_CAST_FUNCTION_EXPR, https://github.com/dart-lang/sdk/issues/27504
return; return;
} }
bool wasAccepted = (_state == _DragState.accepted); final bool wasAccepted = (_state == _DragState.accepted);
_state = _DragState.ready; _state = _DragState.ready;
if (wasAccepted && onEnd != null) { if (wasAccepted && onEnd != null) {
VelocityTracker tracker = _velocityTrackers[pointer]; final VelocityTracker tracker = _velocityTrackers[pointer];
assert(tracker != null); assert(tracker != null);
Velocity velocity = tracker.getVelocity(); Velocity velocity = tracker.getVelocity();

View File

@ -94,14 +94,14 @@ class LeastSquaresSolver {
if (degree > x.length) // Not enough data to fit a curve. if (degree > x.length) // Not enough data to fit a curve.
return null; return null;
PolynomialFit result = new PolynomialFit(degree); final PolynomialFit result = new PolynomialFit(degree);
// Shorthands for the purpose of notation equivalence to original C++ code. // Shorthands for the purpose of notation equivalence to original C++ code.
final int m = x.length; final int m = x.length;
final int n = degree + 1; final int n = degree + 1;
// Expand the X vector to a matrix A, pre-multiplied by the weights. // Expand the X vector to a matrix A, pre-multiplied by the weights.
_Matrix a = new _Matrix(n, m); final _Matrix a = new _Matrix(n, m);
for (int h = 0; h < m; h += 1) { for (int h = 0; h < m; h += 1) {
a.set(0, h, w[h]); a.set(0, h, w[h]);
for (int i = 1; i < n; i += 1) for (int i = 1; i < n; i += 1)
@ -111,25 +111,25 @@ class LeastSquaresSolver {
// Apply the Gram-Schmidt process to A to obtain its QR decomposition. // Apply the Gram-Schmidt process to A to obtain its QR decomposition.
// Orthonormal basis, column-major ordVectorer. // Orthonormal basis, column-major ordVectorer.
_Matrix q = new _Matrix(n, m); final _Matrix q = new _Matrix(n, m);
// Upper triangular matrix, row-major order. // Upper triangular matrix, row-major order.
_Matrix r = new _Matrix(n, n); final _Matrix r = new _Matrix(n, n);
for (int j = 0; j < n; j += 1) { for (int j = 0; j < n; j += 1) {
for (int h = 0; h < m; h += 1) for (int h = 0; h < m; h += 1)
q.set(j, h, a.get(j, h)); q.set(j, h, a.get(j, h));
for (int i = 0; i < j; i += 1) { for (int i = 0; i < j; i += 1) {
double dot = q.getRow(j) * q.getRow(i); final double dot = q.getRow(j) * q.getRow(i);
for (int h = 0; h < m; h += 1) for (int h = 0; h < m; h += 1)
q.set(j, h, q.get(j, h) - dot * q.get(i, h)); q.set(j, h, q.get(j, h) - dot * q.get(i, h));
} }
double norm = q.getRow(j).norm(); final double norm = q.getRow(j).norm();
if (norm < 0.000001) { if (norm < 0.000001) {
// Vectors are linearly dependent or zero so no solution. // Vectors are linearly dependent or zero so no solution.
return null; return null;
} }
double inverseNorm = 1.0 / norm; final double inverseNorm = 1.0 / norm;
for (int h = 0; h < m; h += 1) for (int h = 0; h < m; h += 1)
q.set(j, h, q.get(j, h) * inverseNorm); q.set(j, h, q.get(j, h) * inverseNorm);
for (int i = 0; i < n; i += 1) for (int i = 0; i < n; i += 1)
@ -138,7 +138,7 @@ class LeastSquaresSolver {
// Solve R B = Qt W Y to find B. This is easy because R is upper triangular. // Solve R B = Qt W Y to find B. This is easy because R is upper triangular.
// We just work from bottom-right to top-left calculating B's coefficients. // We just work from bottom-right to top-left calculating B's coefficients.
_Vector wy = new _Vector(m); final _Vector wy = new _Vector(m);
for (int h = 0; h < m; h += 1) for (int h = 0; h < m; h += 1)
wy[h] = y[h] * w[h]; wy[h] = y[h] * w[h];
for (int i = n - 1; i >= 0; i -= 1) { for (int i = n - 1; i >= 0; i -= 1) {

View File

@ -206,7 +206,7 @@ abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> exten
assert(event.pointer != null); assert(event.pointer != null);
assert(event.position != null); assert(event.position != null);
assert(!_pointers.containsKey(event.pointer)); assert(!_pointers.containsKey(event.pointer));
T state = createNewPointerState(event); final T state = createNewPointerState(event);
_pointers[event.pointer] = state; _pointers[event.pointer] = state;
GestureBinding.instance.pointerRouter.addRoute(event.pointer, _handleEvent); GestureBinding.instance.pointerRouter.addRoute(event.pointer, _handleEvent);
state._setArenaEntry(GestureBinding.instance.gestureArena.add(event.pointer, this)); state._setArenaEntry(GestureBinding.instance.gestureArena.add(event.pointer, this));
@ -223,7 +223,7 @@ abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> exten
assert(event.timeStamp != null); assert(event.timeStamp != null);
assert(event.position != null); assert(event.position != null);
assert(_pointers.containsKey(event.pointer)); assert(_pointers.containsKey(event.pointer));
T state = _pointers[event.pointer]; final T state = _pointers[event.pointer];
if (event is PointerMoveEvent) { if (event is PointerMoveEvent) {
state._move(event); state._move(event);
// We might be disposed here. // We might be disposed here.
@ -248,7 +248,7 @@ abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> exten
@override @override
void acceptGesture(int pointer) { void acceptGesture(int pointer) {
assert(_pointers != null); assert(_pointers != null);
T state = _pointers[pointer]; final T state = _pointers[pointer];
if (state == null) if (state == null)
return; // We might already have canceled this drag if the up comes before the accept. return; // We might already have canceled this drag if the up comes before the accept.
state.accepted((Point initialPosition) => _startDrag(initialPosition, pointer)); state.accepted((Point initialPosition) => _startDrag(initialPosition, pointer));
@ -256,7 +256,7 @@ abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> exten
Drag _startDrag(Point initialPosition, int pointer) { Drag _startDrag(Point initialPosition, int pointer) {
assert(_pointers != null); assert(_pointers != null);
T state = _pointers[pointer]; final T state = _pointers[pointer];
assert(state != null); assert(state != null);
assert(state._pendingDelta != null); assert(state._pendingDelta != null);
Drag drag; Drag drag;
@ -274,7 +274,7 @@ abstract class MultiDragGestureRecognizer<T extends MultiDragPointerState> exten
void rejectGesture(int pointer) { void rejectGesture(int pointer) {
assert(_pointers != null); assert(_pointers != null);
if (_pointers.containsKey(pointer)) { if (_pointers.containsKey(pointer)) {
T state = _pointers[pointer]; final T state = _pointers[pointer];
assert(state != null); assert(state != null);
state.rejected(); state.rejected();
_removeState(pointer); _removeState(pointer);

View File

@ -60,7 +60,7 @@ class _TapTracker {
} }
bool isWithinTolerance(PointerEvent event, double tolerance) { bool isWithinTolerance(PointerEvent event, double tolerance) {
Offset offset = event.position - _initialPosition; final Offset offset = event.position - _initialPosition;
return offset.distance <= tolerance; return offset.distance <= tolerance;
} }
} }
@ -103,7 +103,7 @@ class DoubleTapGestureRecognizer extends GestureRecognizer {
!_firstTap.isWithinTolerance(event, kDoubleTapSlop)) !_firstTap.isWithinTolerance(event, kDoubleTapSlop))
return; return;
_stopDoubleTapTimer(); _stopDoubleTapTimer();
_TapTracker tracker = new _TapTracker( final _TapTracker tracker = new _TapTracker(
event: event, event: event,
entry: GestureBinding.instance.gestureArena.add(event.pointer, this) entry: GestureBinding.instance.gestureArena.add(event.pointer, this)
); );
@ -112,7 +112,7 @@ class DoubleTapGestureRecognizer extends GestureRecognizer {
} }
void _handleEvent(PointerEvent event) { void _handleEvent(PointerEvent event) {
_TapTracker tracker = _trackers[event.pointer]; final _TapTracker tracker = _trackers[event.pointer];
assert(tracker != null); assert(tracker != null);
if (event is PointerUpEvent) { if (event is PointerUpEvent) {
if (_firstTap == null) if (_firstTap == null)
@ -166,7 +166,7 @@ class DoubleTapGestureRecognizer extends GestureRecognizer {
if (_firstTap != null) { if (_firstTap != null) {
// Note, order is important below in order for the resolve -> reject logic // Note, order is important below in order for the resolve -> reject logic
// to work properly. // to work properly.
_TapTracker tracker = _firstTap; final _TapTracker tracker = _firstTap;
_firstTap = null; _firstTap = null;
_reject(tracker); _reject(tracker);
GestureBinding.instance.gestureArena.release(tracker.pointer); GestureBinding.instance.gestureArena.release(tracker.pointer);
@ -196,7 +196,7 @@ class DoubleTapGestureRecognizer extends GestureRecognizer {
} }
void _clearTrackers() { void _clearTrackers() {
List<_TapTracker> localTrackers = new List<_TapTracker>.from(_trackers.values); final List<_TapTracker> localTrackers = new List<_TapTracker>.from(_trackers.values);
for (_TapTracker tracker in localTrackers) for (_TapTracker tracker in localTrackers)
_reject(tracker); _reject(tracker);
assert(_trackers.isEmpty); assert(_trackers.isEmpty);

View File

@ -24,7 +24,7 @@ class PointerRouter {
/// Routes added reentrantly within [PointerRouter.route] will take effect when /// Routes added reentrantly within [PointerRouter.route] will take effect when
/// routing the next event. /// routing the next event.
void addRoute(int pointer, PointerRoute route) { void addRoute(int pointer, PointerRoute route) {
LinkedHashSet<PointerRoute> routes = _routeMap.putIfAbsent(pointer, () => new LinkedHashSet<PointerRoute>()); final LinkedHashSet<PointerRoute> routes = _routeMap.putIfAbsent(pointer, () => new LinkedHashSet<PointerRoute>());
assert(!routes.contains(route)); assert(!routes.contains(route));
routes.add(route); routes.add(route);
} }
@ -38,7 +38,7 @@ class PointerRouter {
/// immediately. /// immediately.
void removeRoute(int pointer, PointerRoute route) { void removeRoute(int pointer, PointerRoute route) {
assert(_routeMap.containsKey(pointer)); assert(_routeMap.containsKey(pointer));
LinkedHashSet<PointerRoute> routes = _routeMap[pointer]; final LinkedHashSet<PointerRoute> routes = _routeMap[pointer];
assert(routes.contains(route)); assert(routes.contains(route));
routes.remove(route); routes.remove(route);
if (routes.isEmpty) if (routes.isEmpty)
@ -93,8 +93,8 @@ class PointerRouter {
/// Routes are called in the order in which they were added to the /// Routes are called in the order in which they were added to the
/// PointerRouter object. /// PointerRouter object.
void route(PointerEvent event) { void route(PointerEvent event) {
LinkedHashSet<PointerRoute> routes = _routeMap[event.pointer]; final LinkedHashSet<PointerRoute> routes = _routeMap[event.pointer];
List<PointerRoute> globalRoutes = new List<PointerRoute>.from(_globalRoutes); final List<PointerRoute> globalRoutes = new List<PointerRoute>.from(_globalRoutes);
if (routes != null) { if (routes != null) {
for (PointerRoute route in new List<PointerRoute>.from(routes)) { for (PointerRoute route in new List<PointerRoute>.from(routes)) {
if (routes.contains(route)) if (routes.contains(route))

View File

@ -113,7 +113,7 @@ abstract class OneSequenceGestureRecognizer extends GestureRecognizer {
@protected @protected
@mustCallSuper @mustCallSuper
void resolve(GestureDisposition disposition) { void resolve(GestureDisposition disposition) {
List<GestureArenaEntry> localEntries = new List<GestureArenaEntry>.from(_entries.values); final List<GestureArenaEntry> localEntries = new List<GestureArenaEntry>.from(_entries.values);
_entries.clear(); _entries.clear();
for (GestureArenaEntry entry in localEntries) for (GestureArenaEntry entry in localEntries)
entry.resolve(disposition); entry.resolve(disposition);
@ -303,7 +303,7 @@ abstract class PrimaryPointerGestureRecognizer extends OneSequenceGestureRecogni
} }
double _getDistance(PointerEvent event) { double _getDistance(PointerEvent event) {
Offset offset = event.position - initialPosition; final Offset offset = event.position - initialPosition;
return offset.distance; return offset.distance;
} }

View File

@ -136,7 +136,7 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer {
assert(_state != ScaleState.ready); assert(_state != ScaleState.ready);
bool configChanged = false; bool configChanged = false;
if (event is PointerMoveEvent) { if (event is PointerMoveEvent) {
VelocityTracker tracker = _velocityTrackers[event.pointer]; final VelocityTracker tracker = _velocityTrackers[event.pointer];
assert(tracker != null); assert(tracker != null);
tracker.addPosition(event.timeStamp, event.position); tracker.addPosition(event.timeStamp, event.position);
_pointerLocations[event.pointer] = event.position; _pointerLocations[event.pointer] = event.position;
@ -154,7 +154,7 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer {
} }
void _update(bool configChanged, int pointer) { void _update(bool configChanged, int pointer) {
int count = _pointerLocations.keys.length; final int count = _pointerLocations.keys.length;
// Compute the focal point // Compute the focal point
Point focalPoint = Point.origin; Point focalPoint = Point.origin;
@ -172,7 +172,7 @@ class ScaleGestureRecognizer extends OneSequenceGestureRecognizer {
_initialSpan = _currentSpan; _initialSpan = _currentSpan;
if (_state == ScaleState.started) { if (_state == ScaleState.started) {
if (onEnd != null) { if (onEnd != null) {
VelocityTracker tracker = _velocityTrackers[pointer]; final VelocityTracker tracker = _velocityTrackers[pointer];
assert(tracker != null); assert(tracker != null);
Velocity velocity = tracker.getVelocity(); Velocity velocity = tracker.getVelocity();

View File

@ -52,7 +52,7 @@ class _CombiningGestureArenaMember extends GestureArenaMember {
void _close() { void _close() {
assert(!_resolved); assert(!_resolved);
_resolved = true; _resolved = true;
_CombiningGestureArenaMember combiner = _owner._combiners.remove(_pointer); final _CombiningGestureArenaMember combiner = _owner._combiners.remove(_pointer);
assert(combiner == this); assert(combiner == this);
} }
@ -100,7 +100,7 @@ class GestureArenaTeam {
/// To assign a gesture recognizer to a team, see /// To assign a gesture recognizer to a team, see
/// [OneSequenceGestureRecognizer.team]. /// [OneSequenceGestureRecognizer.team].
GestureArenaEntry add(int pointer, GestureArenaMember member) { GestureArenaEntry add(int pointer, GestureArenaMember member) {
_CombiningGestureArenaMember combiner = _combiners.putIfAbsent( final _CombiningGestureArenaMember combiner = _combiners.putIfAbsent(
pointer, () => new _CombiningGestureArenaMember(this, pointer)); pointer, () => new _CombiningGestureArenaMember(this, pointer));
return combiner._add(pointer, member); return combiner._add(pointer, member);
} }

View File

@ -63,30 +63,30 @@ class _LeastSquaresVelocityTrackerStrategy extends _VelocityTrackerStrategy {
@override @override
_Estimate getEstimate() { _Estimate getEstimate() {
// Iterate over movement samples in reverse time order and collect samples. // Iterate over movement samples in reverse time order and collect samples.
List<double> x = new List<double>(); final List<double> x = new List<double>();
List<double> y = new List<double>(); final List<double> y = new List<double>();
List<double> w = new List<double>(); final List<double> w = new List<double>();
List<double> time = new List<double>(); final List<double> time = new List<double>();
int m = 0; int m = 0;
int index = _index; int index = _index;
_Movement newestMovement = _movements[index]; final _Movement newestMovement = _movements[index];
_Movement previousMovement = newestMovement; _Movement previousMovement = newestMovement;
if (newestMovement == null) if (newestMovement == null)
return null; return null;
do { do {
_Movement movement = _movements[index]; final _Movement movement = _movements[index];
if (movement == null) if (movement == null)
break; break;
double age = (newestMovement.eventTime - movement.eventTime).inMilliseconds.toDouble(); final double age = (newestMovement.eventTime - movement.eventTime).inMilliseconds.toDouble();
double delta = (movement.eventTime - previousMovement.eventTime).inMilliseconds.abs().toDouble(); final double delta = (movement.eventTime - previousMovement.eventTime).inMilliseconds.abs().toDouble();
previousMovement = movement; previousMovement = movement;
if (age > kHorizonMilliseconds || delta > kAssumePointerMoveStoppedMilliseconds) if (age > kHorizonMilliseconds || delta > kAssumePointerMoveStoppedMilliseconds)
break; break;
Point position = movement.position; final Point position = movement.position;
x.add(position.x); x.add(position.x);
y.add(position.y); y.add(position.y);
w.add(1.0); w.add(1.0);
@ -102,11 +102,11 @@ class _LeastSquaresVelocityTrackerStrategy extends _VelocityTrackerStrategy {
n = m - 1; n = m - 1;
if (n >= 1) { if (n >= 1) {
LeastSquaresSolver xSolver = new LeastSquaresSolver(time, x, w); final LeastSquaresSolver xSolver = new LeastSquaresSolver(time, x, w);
PolynomialFit xFit = xSolver.solve(n); final PolynomialFit xFit = xSolver.solve(n);
if (xFit != null) { if (xFit != null) {
LeastSquaresSolver ySolver = new LeastSquaresSolver(time, y, w); final LeastSquaresSolver ySolver = new LeastSquaresSolver(time, y, w);
PolynomialFit yFit = ySolver.solve(n); final PolynomialFit yFit = ySolver.solve(n);
if (yFit != null) { if (yFit != null) {
return new _Estimate( return new _Estimate(
xCoefficients: xFit.coefficients, xCoefficients: xFit.coefficients,
@ -223,7 +223,7 @@ class VelocityTracker {
/// getVelocity() will return null if no estimate is available or if /// getVelocity() will return null if no estimate is available or if
/// the velocity is zero. /// the velocity is zero.
Velocity getVelocity() { Velocity getVelocity() {
_Estimate estimate = _strategy.getEstimate(); final _Estimate estimate = _strategy.getEstimate();
if (estimate != null && estimate.degree >= 1) { if (estimate != null && estimate.degree >= 1) {
return new Velocity( return new Velocity(
pixelsPerSecond: new Offset( // convert from pixels/ms to pixels/s pixelsPerSecond: new Offset( // convert from pixels/ms to pixels/s

View File

@ -460,7 +460,7 @@ class _LicensePageState extends State<LicensePage> {
} }
String _defaultApplicationName(BuildContext context) { String _defaultApplicationName(BuildContext context) {
Title ancestorTitle = context.ancestorWidgetOfExactType(Title); final Title ancestorTitle = context.ancestorWidgetOfExactType(Title);
return ancestorTitle?.title ?? Platform.resolvedExecutable.split(Platform.pathSeparator).last; return ancestorTitle?.title ?? Platform.resolvedExecutable.split(Platform.pathSeparator).last;
} }

View File

@ -209,7 +209,7 @@ class _MaterialAppState extends State<MaterialApp> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ThemeData theme = config.theme ?? new ThemeData.fallback(); final ThemeData theme = config.theme ?? new ThemeData.fallback();
Widget result = new AnimatedTheme( Widget result = new AnimatedTheme(
data: theme, data: theme,
isMaterialAppTheme: true, isMaterialAppTheme: true,

View File

@ -337,7 +337,7 @@ class _AppBarState extends State<AppBar> {
@override @override
void dependenciesChanged() { void dependenciesChanged() {
super.dependenciesChanged(); super.dependenciesChanged();
ScaffoldState scaffold = Scaffold.of(context); final ScaffoldState scaffold = Scaffold.of(context);
_hasDrawer = scaffold?.hasDrawer ?? false; _hasDrawer = scaffold?.hasDrawer ?? false;
_canPop = ModalRoute.of(context)?.canPop ?? false; _canPop = ModalRoute.of(context)?.canPop ?? false;
} }
@ -354,7 +354,7 @@ class _AppBarState extends State<AppBar> {
TextStyle centerStyle = config.textTheme?.title ?? themeData.primaryTextTheme.title; TextStyle centerStyle = config.textTheme?.title ?? themeData.primaryTextTheme.title;
TextStyle sideStyle = config.textTheme?.body1 ?? themeData.primaryTextTheme.body1; TextStyle sideStyle = config.textTheme?.body1 ?? themeData.primaryTextTheme.body1;
Brightness brightness = config.brightness ?? themeData.primaryColorBrightness; final Brightness brightness = config.brightness ?? themeData.primaryColorBrightness;
SystemChrome.setSystemUIOverlayStyle(brightness == Brightness.dark SystemChrome.setSystemUIOverlayStyle(brightness == Brightness.dark
? SystemUiOverlayStyle.light ? SystemUiOverlayStyle.light
: SystemUiOverlayStyle.dark); : SystemUiOverlayStyle.dark);
@ -419,7 +419,7 @@ class _AppBarState extends State<AppBar> {
); );
} }
Widget toolbar = new Padding( final Widget toolbar = new Padding(
padding: const EdgeInsets.only(right: 4.0), padding: const EdgeInsets.only(right: 4.0),
child: new CustomMultiChildLayout( child: new CustomMultiChildLayout(
delegate: new _ToolbarLayout( delegate: new _ToolbarLayout(

View File

@ -167,7 +167,7 @@ T _maxBy<T>(Iterable<T> input, _KeyFunc<T> keyFunc) {
T maxValue; T maxValue;
dynamic maxKey; dynamic maxKey;
for (T value in input) { for (T value in input) {
dynamic key = keyFunc(value); final dynamic key = keyFunc(value);
if (maxKey == null || key > maxKey) { if (maxKey == null || key > maxKey) {
maxValue = value; maxValue = value;
maxKey = key; maxKey = key;

View File

@ -285,7 +285,7 @@ class BottomNavigationBarState extends State<BottomNavigationBar> with TickerPro
)..controller.addStatusListener((AnimationStatus status) { )..controller.addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.completed) { if (status == AnimationStatus.completed) {
setState(() { setState(() {
_Circle circle = _circles.removeFirst(); final _Circle circle = _circles.removeFirst();
_backgroundColor = circle.color; _backgroundColor = circle.color;
circle.dispose(); circle.dispose();
}); });
@ -575,8 +575,8 @@ class _RadialPainter extends CustomPainter {
final Paint paint = new Paint()..color = circle.color; final Paint paint = new Paint()..color = circle.color;
final Rect rect = new Rect.fromLTWH(0.0, 0.0, size.width, size.height); final Rect rect = new Rect.fromLTWH(0.0, 0.0, size.width, size.height);
canvas.clipRect(rect); canvas.clipRect(rect);
double navWidth = math.min(bottomNavMaxWidth, size.width); final double navWidth = math.min(bottomNavMaxWidth, size.width);
Point center = new Point( final Point center = new Point(
(size.width - navWidth) / 2.0 + circle.offset.dx * navWidth, (size.width - navWidth) / 2.0 + circle.offset.dx * navWidth,
circle.offset.dy * size.height circle.offset.dy * size.height
); );

View File

@ -109,7 +109,7 @@ class _BottomSheetState extends State<BottomSheet> {
if (_dismissUnderway) if (_dismissUnderway)
return; return;
if (details.velocity.pixelsPerSecond.dy > _kMinFlingVelocity) { if (details.velocity.pixelsPerSecond.dy > _kMinFlingVelocity) {
double flingVelocity = -details.velocity.pixelsPerSecond.dy / _childHeight; final double flingVelocity = -details.velocity.pixelsPerSecond.dy / _childHeight;
if (config.animationController.value > 0.0) if (config.animationController.value > 0.0)
config.animationController.fling(velocity: flingVelocity); config.animationController.fling(velocity: flingVelocity);
if (flingVelocity < 0.0) if (flingVelocity < 0.0)

View File

@ -100,7 +100,7 @@ class ButtonTheme extends InheritedWidget {
/// ButtonTheme theme = ButtonTheme.of(context); /// ButtonTheme theme = ButtonTheme.of(context);
/// ``` /// ```
static ButtonTheme of(BuildContext context) { static ButtonTheme of(BuildContext context) {
ButtonTheme result = context.inheritFromWidgetOfExactType(ButtonTheme); final ButtonTheme result = context.inheritFromWidgetOfExactType(ButtonTheme);
return result ?? const ButtonTheme(); return result ?? const ButtonTheme();
} }

View File

@ -91,7 +91,7 @@ class _CheckboxState extends State<Checkbox> with TickerProviderStateMixin {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context)); assert(debugCheckHasMaterial(context));
ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
return new _CheckboxRenderObjectWidget( return new _CheckboxRenderObjectWidget(
value: config.value, value: config.value,
activeColor: config.activeColor ?? themeData.accentColor, activeColor: config.activeColor ?? themeData.accentColor,
@ -174,40 +174,40 @@ class _RenderCheckbox extends RenderToggleable {
paintRadialReaction(canvas, offset, size.center(Point.origin)); paintRadialReaction(canvas, offset, size.center(Point.origin));
double t = position.value; final double t = position.value;
Color borderColor = inactiveColor; Color borderColor = inactiveColor;
if (onChanged != null) if (onChanged != null)
borderColor = t >= 0.25 ? activeColor : Color.lerp(inactiveColor, activeColor, t * 4.0); borderColor = t >= 0.25 ? activeColor : Color.lerp(inactiveColor, activeColor, t * 4.0);
Paint paint = new Paint() final Paint paint = new Paint()
..color = borderColor; ..color = borderColor;
double inset = 1.0 - (t - 0.5).abs() * 2.0; final double inset = 1.0 - (t - 0.5).abs() * 2.0;
double rectSize = _kEdgeSize - inset * _kStrokeWidth; final double rectSize = _kEdgeSize - inset * _kStrokeWidth;
Rect rect = new Rect.fromLTWH(offsetX + inset, offsetY + inset, rectSize, rectSize); final Rect rect = new Rect.fromLTWH(offsetX + inset, offsetY + inset, rectSize, rectSize);
RRect outer = new RRect.fromRectAndRadius(rect, _kEdgeRadius); final RRect outer = new RRect.fromRectAndRadius(rect, _kEdgeRadius);
if (t <= 0.5) { if (t <= 0.5) {
// Outline // Outline
RRect inner = outer.deflate(math.min(rectSize / 2.0, _kStrokeWidth + rectSize * t)); final RRect inner = outer.deflate(math.min(rectSize / 2.0, _kStrokeWidth + rectSize * t));
canvas.drawDRRect(outer, inner, paint); canvas.drawDRRect(outer, inner, paint);
} else { } else {
// Background // Background
canvas.drawRRect(outer, paint); canvas.drawRRect(outer, paint);
// White inner check // White inner check
double value = (t - 0.5) * 2.0; final double value = (t - 0.5) * 2.0;
paint paint
..color = const Color(0xFFFFFFFF) ..color = const Color(0xFFFFFFFF)
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = _kStrokeWidth; ..strokeWidth = _kStrokeWidth;
Path path = new Path(); final Path path = new Path();
Point start = const Point(_kEdgeSize * 0.15, _kEdgeSize * 0.45); final Point start = const Point(_kEdgeSize * 0.15, _kEdgeSize * 0.45);
Point mid = const Point(_kEdgeSize * 0.4, _kEdgeSize * 0.7); final Point mid = const Point(_kEdgeSize * 0.4, _kEdgeSize * 0.7);
Point end = const Point(_kEdgeSize * 0.85, _kEdgeSize * 0.25); final Point end = const Point(_kEdgeSize * 0.85, _kEdgeSize * 0.25);
Point drawStart = Point.lerp(start, mid, 1.0 - value); final Point drawStart = Point.lerp(start, mid, 1.0 - value);
Point drawEnd = Point.lerp(mid, end, value); final Point drawEnd = Point.lerp(mid, end, value);
path.moveTo(offsetX + drawStart.x, offsetY + drawStart.y); path.moveTo(offsetX + drawStart.x, offsetY + drawStart.y);
path.lineTo(offsetX + mid.x, offsetY + mid.y); path.lineTo(offsetX + mid.x, offsetY + mid.y);
path.lineTo(offsetX + drawEnd.x, offsetY + drawEnd.y); path.lineTo(offsetX + drawEnd.x, offsetY + drawEnd.y);

View File

@ -69,7 +69,7 @@ class Chip extends StatelessWidget {
double leftPadding = 12.0; double leftPadding = 12.0;
double rightPadding = 12.0; double rightPadding = 12.0;
List<Widget> children = <Widget>[]; final List<Widget> children = <Widget>[];
if (avatar != null) { if (avatar != null) {
leftPadding = 0.0; leftPadding = 0.0;

View File

@ -317,7 +317,7 @@ class DataTable extends StatelessWidget {
static int _initOnlyTextColumn(List<DataColumn> columns) { static int _initOnlyTextColumn(List<DataColumn> columns) {
int result; int result;
for (int index = 0; index < columns.length; index += 1) { for (int index = 0; index < columns.length; index += 1) {
DataColumn column = columns[index]; final DataColumn column = columns[index];
if (!column.numeric) { if (!column.numeric) {
if (result != null) if (result != null)
return null; return null;
@ -507,8 +507,8 @@ class DataTable extends StatelessWidget {
final bool showCheckboxColumn = rows.any((DataRow row) => row.onSelectChanged != null); final bool showCheckboxColumn = rows.any((DataRow row) => row.onSelectChanged != null);
final bool allChecked = showCheckboxColumn && !rows.any((DataRow row) => row.onSelectChanged != null && !row.selected); final bool allChecked = showCheckboxColumn && !rows.any((DataRow row) => row.onSelectChanged != null && !row.selected);
List<TableColumnWidth> tableColumns = new List<TableColumnWidth>(columns.length + (showCheckboxColumn ? 1 : 0)); final List<TableColumnWidth> tableColumns = new List<TableColumnWidth>(columns.length + (showCheckboxColumn ? 1 : 0));
List<TableRow> tableRows = new List<TableRow>.generate( final List<TableRow> tableRows = new List<TableRow>.generate(
rows.length + 1, // the +1 is for the header row rows.length + 1, // the +1 is for the header row
(int index) { (int index) {
return new TableRow( return new TableRow(
@ -544,7 +544,7 @@ class DataTable extends StatelessWidget {
} }
for (int dataColumnIndex = 0; dataColumnIndex < columns.length; dataColumnIndex += 1) { for (int dataColumnIndex = 0; dataColumnIndex < columns.length; dataColumnIndex += 1) {
DataColumn column = columns[dataColumnIndex]; final DataColumn column = columns[dataColumnIndex];
final EdgeInsets padding = new EdgeInsets.fromLTRB( final EdgeInsets padding = new EdgeInsets.fromLTRB(
dataColumnIndex == 0 ? showCheckboxColumn ? _kTablePadding / 2.0 : _kTablePadding : _kColumnSpacing / 2.0, dataColumnIndex == 0 ? showCheckboxColumn ? _kTablePadding / 2.0 : _kTablePadding : _kColumnSpacing / 2.0,
0.0, 0.0,
@ -568,7 +568,7 @@ class DataTable extends StatelessWidget {
); );
rowIndex = 1; rowIndex = 1;
for (DataRow row in rows) { for (DataRow row in rows) {
DataCell cell = row.cells[dataColumnIndex]; final DataCell cell = row.cells[dataColumnIndex];
tableRows[rowIndex].children[displayColumnIndex] = _buildDataCell( tableRows[rowIndex].children[displayColumnIndex] = _buildDataCell(
context: context, context: context,
padding: padding, padding: padding,
@ -629,22 +629,22 @@ class TableRowInkWell extends InkResponse {
return () { return () {
RenderObject cell = referenceBox; RenderObject cell = referenceBox;
AbstractNode table = cell.parent; AbstractNode table = cell.parent;
Matrix4 transform = new Matrix4.identity(); final Matrix4 transform = new Matrix4.identity();
while (table is RenderObject && table is! RenderTable) { while (table is RenderObject && table is! RenderTable) {
RenderTable parentBox = table; final RenderTable parentBox = table;
parentBox.applyPaintTransform(cell, transform); parentBox.applyPaintTransform(cell, transform);
assert(table == cell.parent); assert(table == cell.parent);
cell = table; cell = table;
table = table.parent; table = table.parent;
} }
if (table is RenderTable) { if (table is RenderTable) {
TableCellParentData cellParentData = cell.parentData; final TableCellParentData cellParentData = cell.parentData;
assert(cellParentData.y != null); assert(cellParentData.y != null);
Rect rect = table.getRowBox(cellParentData.y); final Rect rect = table.getRowBox(cellParentData.y);
// The rect is in the table's coordinate space. We need to change it to the // The rect is in the table's coordinate space. We need to change it to the
// TableRowInkWell's coordinate space. // TableRowInkWell's coordinate space.
table.applyPaintTransform(cell, transform); table.applyPaintTransform(cell, transform);
Offset offset = MatrixUtils.getAsTranslation(transform); final Offset offset = MatrixUtils.getAsTranslation(transform);
if (offset != null) if (offset != null)
return rect.shift(-offset); return rect.shift(-offset);
} }
@ -734,7 +734,7 @@ class _SortArrowState extends State<_SortArrow> with TickerProviderStateMixin {
void didUpdateConfig(_SortArrow oldConfig) { void didUpdateConfig(_SortArrow oldConfig) {
super.didUpdateConfig(oldConfig); super.didUpdateConfig(oldConfig);
bool skipArrow = false; bool skipArrow = false;
bool newDown = config.down != null ? config.down : _down; final bool newDown = config.down != null ? config.down : _down;
if (oldConfig.visible != config.visible) { if (oldConfig.visible != config.visible) {
if (config.visible && (_opacityController.status == AnimationStatus.dismissed)) { if (config.visible && (_opacityController.status == AnimationStatus.dismissed)) {
_orientationController.stop(); _orientationController.stop();

View File

@ -68,8 +68,8 @@ class _DatePickerHeader extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
TextTheme headerTextTheme = themeData.primaryTextTheme; final TextTheme headerTextTheme = themeData.primaryTextTheme;
Color dayColor; Color dayColor;
Color yearColor; Color yearColor;
switch(themeData.primaryColorBrightness) { switch(themeData.primaryColorBrightness) {
@ -82,8 +82,8 @@ class _DatePickerHeader extends StatelessWidget {
yearColor = mode == _DatePickerMode.year ? Colors.white : Colors.white70; yearColor = mode == _DatePickerMode.year ? Colors.white : Colors.white70;
break; break;
} }
TextStyle dayStyle = headerTextTheme.display1.copyWith(color: dayColor, height: 1.4); final TextStyle dayStyle = headerTextTheme.display1.copyWith(color: dayColor, height: 1.4);
TextStyle yearStyle = headerTextTheme.subhead.copyWith(color: yearColor, height: 1.4); final TextStyle yearStyle = headerTextTheme.subhead.copyWith(color: yearColor, height: 1.4);
Color backgroundColor; Color backgroundColor;
switch (themeData.brightness) { switch (themeData.brightness) {
@ -386,7 +386,7 @@ class _MonthPickerState extends State<MonthPicker> {
void _updateCurrentDate() { void _updateCurrentDate() {
_todayDate = new DateTime.now(); _todayDate = new DateTime.now();
DateTime tomorrow = new DateTime(_todayDate.year, _todayDate.month, _todayDate.day + 1); final DateTime tomorrow = new DateTime(_todayDate.year, _todayDate.month, _todayDate.day + 1);
Duration timeUntilTomorrow = tomorrow.difference(_todayDate); Duration timeUntilTomorrow = tomorrow.difference(_todayDate);
timeUntilTomorrow += const Duration(seconds: 1); // so we don't miss it by rounding timeUntilTomorrow += const Duration(seconds: 1); // so we don't miss it by rounding
if (_timer != null) if (_timer != null)
@ -668,13 +668,13 @@ class _DatePickerDialogState extends State<_DatePickerDialog> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Widget picker = new Flexible( final Widget picker = new Flexible(
child: new SizedBox( child: new SizedBox(
height: _kMaxDayPickerHeight, height: _kMaxDayPickerHeight,
child: _buildPicker(), child: _buildPicker(),
), ),
); );
Widget actions = new ButtonTheme.bar( final Widget actions = new ButtonTheme.bar(
child: new ButtonBar( child: new ButtonBar(
children: <Widget>[ children: <Widget>[
new FlatButton( new FlatButton(
@ -692,7 +692,7 @@ class _DatePickerDialogState extends State<_DatePickerDialog> {
return new Dialog( return new Dialog(
child: new OrientationBuilder( child: new OrientationBuilder(
builder: (BuildContext context, Orientation orientation) { builder: (BuildContext context, Orientation orientation) {
Widget header = new _DatePickerHeader( final Widget header = new _DatePickerHeader(
selectedDate: _selectedDate, selectedDate: _selectedDate,
mode: _mode, mode: _mode,
onModeChanged: _handleModeChanged, onModeChanged: _handleModeChanged,

View File

@ -22,7 +22,7 @@ import 'material.dart';
bool debugCheckHasMaterial(BuildContext context) { bool debugCheckHasMaterial(BuildContext context) {
assert(() { assert(() {
if (context.widget is! Material && context.ancestorWidgetOfExactType(Material) == null) { if (context.widget is! Material && context.ancestorWidgetOfExactType(Material) == null) {
Element element = context; final Element element = context;
throw new FlutterError( throw new FlutterError(
'No Material widget found.\n' 'No Material widget found.\n'
'${context.widget.runtimeType} widgets require a Material widget ancestor.\n' '${context.widget.runtimeType} widgets require a Material widget ancestor.\n'

View File

@ -148,7 +148,7 @@ class DrawerControllerState extends State<DrawerController> with SingleTickerPro
void _ensureHistoryEntry() { void _ensureHistoryEntry() {
if (_historyEntry == null) { if (_historyEntry == null) {
ModalRoute<dynamic> route = ModalRoute.of(context); final ModalRoute<dynamic> route = ModalRoute.of(context);
if (route != null) { if (route != null) {
_historyEntry = new LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved); _historyEntry = new LocalHistoryEntry(onRemove: _handleHistoryEntryRemoved);
route.addLocalHistoryEntry(_historyEntry); route.addLocalHistoryEntry(_historyEntry);
@ -196,7 +196,7 @@ class DrawerControllerState extends State<DrawerController> with SingleTickerPro
} }
double get _width { double get _width {
RenderBox drawerBox = _drawerKey.currentContext?.findRenderObject(); final RenderBox drawerBox = _drawerKey.currentContext?.findRenderObject();
if (drawerBox != null) if (drawerBox != null)
return drawerBox.size.width; return drawerBox.size.width;
return _kWidth; // drawer not being shown currently return _kWidth; // drawer not being shown currently

View File

@ -84,7 +84,7 @@ class DrawerItem extends StatelessWidget {
} }
TextStyle _getTextStyle(ThemeData themeData) { TextStyle _getTextStyle(ThemeData themeData) {
TextStyle result = themeData.textTheme.body2; final TextStyle result = themeData.textTheme.body2;
if (selected) { if (selected) {
switch (themeData.brightness) { switch (themeData.brightness) {
case Brightness.light: case Brightness.light:
@ -99,9 +99,9 @@ class DrawerItem extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context)); assert(debugCheckHasMaterial(context));
ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
List<Widget> children = <Widget>[]; final List<Widget> children = <Widget>[];
if (icon != null) { if (icon != null) {
children.add( children.add(
new Padding( new Padding(

View File

@ -114,7 +114,7 @@ class ExpansionPanelList extends StatelessWidget {
if (_isChildExpanded(i) && i != 0 && !_isChildExpanded(i - 1)) if (_isChildExpanded(i) && i != 0 && !_isChildExpanded(i - 1))
items.add(new MaterialGap(key: new ValueKey<int>(i * 2 - 1))); items.add(new MaterialGap(key: new ValueKey<int>(i * 2 - 1)));
Row header = new Row( final Row header = new Row(
children: <Widget>[ children: <Widget>[
new Expanded( new Expanded(
child: new AnimatedContainer( child: new AnimatedContainer(

View File

@ -94,7 +94,7 @@ class _FlexibleSpaceBarState extends State<FlexibleSpaceBar> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
_FlexibleSpaceBarSettings settings = context.inheritFromWidgetOfExactType(_FlexibleSpaceBarSettings); final _FlexibleSpaceBarSettings settings = context.inheritFromWidgetOfExactType(_FlexibleSpaceBarSettings);
assert(settings != null, 'A FlexibleSpaceBar must be wrapped in the widget returned by FlexibleSpaceBar.createSettings().'); assert(settings != null, 'A FlexibleSpaceBar must be wrapped in the widget returned by FlexibleSpaceBar.createSettings().');
final List<Widget> children = <Widget>[]; final List<Widget> children = <Widget>[];

View File

@ -73,8 +73,8 @@ class GridTileBar extends StatelessWidget {
if (leading != null) if (leading != null)
children.add(new Padding(padding: const EdgeInsets.only(right: 8.0), child: leading)); children.add(new Padding(padding: const EdgeInsets.only(right: 8.0), child: leading));
ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
ThemeData darkTheme = new ThemeData( final ThemeData darkTheme = new ThemeData(
brightness: Brightness.dark, brightness: Brightness.dark,
accentColor: theme.accentColor, accentColor: theme.accentColor,
accentColorBrightness: theme.accentColorBrightness accentColorBrightness: theme.accentColorBrightness

View File

@ -56,12 +56,12 @@ class IconTheme extends InheritedWidget {
/// IconThemeData theme = IconTheme.of(context); /// IconThemeData theme = IconTheme.of(context);
/// ``` /// ```
static IconThemeData of(BuildContext context) { static IconThemeData of(BuildContext context) {
IconThemeData iconThemeData = _getInheritedIconThemData(context); final IconThemeData iconThemeData = _getInheritedIconThemData(context);
return iconThemeData.isConcrete ? iconThemeData : const IconThemeData.fallback().merge(iconThemeData); return iconThemeData.isConcrete ? iconThemeData : const IconThemeData.fallback().merge(iconThemeData);
} }
static IconThemeData _getInheritedIconThemData(BuildContext context) { static IconThemeData _getInheritedIconThemData(BuildContext context) {
IconTheme iconTheme = context.inheritFromWidgetOfExactType(IconTheme); final IconTheme iconTheme = context.inheritFromWidgetOfExactType(IconTheme);
return iconTheme?.data ?? Theme.of(context).iconTheme; return iconTheme?.data ?? Theme.of(context).iconTheme;
} }

View File

@ -87,7 +87,7 @@ class IconThemeData {
@override @override
String toString() { String toString() {
List<String> result = <String>[]; final List<String> result = <String>[];
if (color != null) if (color != null)
result.add('color: $color'); result.add('color: $color');
if (_opacity != null) if (_opacity != null)

View File

@ -35,10 +35,10 @@ double _getTargetRadius(RenderBox referenceBox, bool containedInkWell, RectCallb
} }
double _getSplashRadiusForPoistionInSize(Size bounds, Point position) { double _getSplashRadiusForPoistionInSize(Size bounds, Point position) {
double d1 = (position - bounds.topLeft(Point.origin)).distance; final double d1 = (position - bounds.topLeft(Point.origin)).distance;
double d2 = (position - bounds.topRight(Point.origin)).distance; final double d2 = (position - bounds.topRight(Point.origin)).distance;
double d3 = (position - bounds.bottomLeft(Point.origin)).distance; final double d3 = (position - bounds.bottomLeft(Point.origin)).distance;
double d4 = (position - bounds.bottomRight(Point.origin)).distance; final double d4 = (position - bounds.bottomRight(Point.origin)).distance;
return math.max(math.max(d1, d2), math.max(d3, d4)).ceilToDouble(); return math.max(math.max(d1, d2), math.max(d3, d4)).ceilToDouble();
} }

View File

@ -157,7 +157,7 @@ class _InputFieldState extends State<InputField> {
]; ];
if (config.hintText != null && value.text.isEmpty) { if (config.hintText != null && value.text.isEmpty) {
TextStyle hintStyle = config.hintStyle ?? final TextStyle hintStyle = config.hintStyle ??
textStyle.copyWith(color: themeData.hintColor); textStyle.copyWith(color: themeData.hintColor);
stackChildren.add( stackChildren.add(
new Positioned( new Positioned(
@ -255,8 +255,8 @@ class _InputContainerState extends State<InputContainer> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context)); assert(debugCheckHasMaterial(context));
ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
String errorText = config.errorText; final String errorText = config.errorText;
final TextStyle textStyle = config.style ?? themeData.textTheme.subhead; final TextStyle textStyle = config.style ?? themeData.textTheme.subhead;
Color activeColor = themeData.hintColor; Color activeColor = themeData.hintColor;
@ -272,7 +272,7 @@ class _InputContainerState extends State<InputContainer> {
} }
double topPadding = config.isDense ? 12.0 : 16.0; double topPadding = config.isDense ? 12.0 : 16.0;
List<Widget> stackChildren = <Widget>[]; final List<Widget> stackChildren = <Widget>[];
// If we're not focused, there's not value, and labelText was provided, // If we're not focused, there's not value, and labelText was provided,
// then the label appears where the hint would. And we will not show // then the label appears where the hint would. And we will not show
@ -308,7 +308,7 @@ class _InputContainerState extends State<InputContainer> {
} }
if (config.hintText != null) { if (config.hintText != null) {
TextStyle hintStyle = textStyle.copyWith(color: themeData.hintColor); final TextStyle hintStyle = textStyle.copyWith(color: themeData.hintColor);
stackChildren.add( stackChildren.add(
new Positioned( new Positioned(
left: 0.0, left: 0.0,
@ -325,19 +325,19 @@ class _InputContainerState extends State<InputContainer> {
); );
} }
Color borderColor = errorText == null ? activeColor : themeData.errorColor; final Color borderColor = errorText == null ? activeColor : themeData.errorColor;
double bottomPadding = config.isDense ? 8.0 : 1.0; final double bottomPadding = config.isDense ? 8.0 : 1.0;
double bottomBorder = 2.0; final double bottomBorder = 2.0;
double bottomHeight = config.isDense ? 14.0 : 18.0; final double bottomHeight = config.isDense ? 14.0 : 18.0;
EdgeInsets padding = new EdgeInsets.only(top: topPadding, bottom: bottomPadding); final EdgeInsets padding = new EdgeInsets.only(top: topPadding, bottom: bottomPadding);
Border border = new Border( final Border border = new Border(
bottom: new BorderSide( bottom: new BorderSide(
color: borderColor, color: borderColor,
width: bottomBorder, width: bottomBorder,
) )
); );
EdgeInsets margin = new EdgeInsets.only(bottom: bottomHeight - (bottomPadding + bottomBorder)); final EdgeInsets margin = new EdgeInsets.only(bottom: bottomHeight - (bottomPadding + bottomBorder));
Widget divider; Widget divider;
if (!config.showDivider) { if (!config.showDivider) {
@ -361,7 +361,7 @@ class _InputContainerState extends State<InputContainer> {
stackChildren.add(divider); stackChildren.add(divider);
if (!config.isDense) { if (!config.isDense) {
TextStyle errorStyle = themeData.textTheme.caption.copyWith(color: themeData.errorColor); final TextStyle errorStyle = themeData.textTheme.caption.copyWith(color: themeData.errorColor);
stackChildren.add(new Positioned( stackChildren.add(new Positioned(
left: 0.0, left: 0.0,
bottom: 0.0, bottom: 0.0,
@ -372,8 +372,8 @@ class _InputContainerState extends State<InputContainer> {
Widget textField = new Stack(children: stackChildren); Widget textField = new Stack(children: stackChildren);
if (config.icon != null) { if (config.icon != null) {
double iconSize = config.isDense ? 18.0 : 24.0; final double iconSize = config.isDense ? 18.0 : 24.0;
double iconTop = topPadding + (textStyle.fontSize - iconSize) / 2.0; final double iconTop = topPadding + (textStyle.fontSize - iconSize) / 2.0;
textField = new Row( textField = new Row(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[ children: <Widget>[

View File

@ -203,10 +203,10 @@ class _MaterialState extends State<Material> with TickerProviderStateMixin {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Color backgroundColor = _getBackgroundColor(context); final Color backgroundColor = _getBackgroundColor(context);
assert(backgroundColor != null || config.type == MaterialType.transparency); assert(backgroundColor != null || config.type == MaterialType.transparency);
Widget contents = config.child; Widget contents = config.child;
BorderRadius radius = config.borderRadius ?? kMaterialEdges[config.type]; final BorderRadius radius = config.borderRadius ?? kMaterialEdges[config.type];
if (contents != null) { if (contents != null) {
contents = new AnimatedDefaultTextStyle( contents = new AnimatedDefaultTextStyle(
style: config.textStyle ?? Theme.of(context).textTheme.body1, style: config.textStyle ?? Theme.of(context).textTheme.body1,
@ -216,7 +216,7 @@ class _MaterialState extends State<Material> with TickerProviderStateMixin {
} }
contents = new NotificationListener<LayoutChangedNotification>( contents = new NotificationListener<LayoutChangedNotification>(
onNotification: (LayoutChangedNotification notification) { onNotification: (LayoutChangedNotification notification) {
_RenderInkFeatures renderer = _inkFeatureRenderer.currentContext.findRenderObject(); final _RenderInkFeatures renderer = _inkFeatureRenderer.currentContext.findRenderObject();
renderer._didChangeLayout(); renderer._didChangeLayout();
return true; return true;
}, },

View File

@ -239,7 +239,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
} }
void _removeChild(int index) { void _removeChild(int index) {
MergeableMaterialItem child = _children.removeAt(index); final MergeableMaterialItem child = _children.removeAt(index);
if (child is MaterialGap) if (child is MaterialGap)
_animationTuples[child.key] = null; _animationTuples[child.key] = null;
@ -316,7 +316,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
while (startOld < j) { while (startOld < j) {
if (_children[startOld] is MaterialGap) { if (_children[startOld] is MaterialGap) {
MaterialGap gap = _children[startOld]; final MaterialGap gap = _children[startOld];
gapSizeSum += gap.size; gapSizeSum += gap.size;
} }
@ -357,7 +357,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
for (int k = startNew; k < i; k += 1) { for (int k = startNew; k < i; k += 1) {
if (newChildren[k] is MaterialGap) { if (newChildren[k] is MaterialGap) {
MaterialGap gap = newChildren[k]; final MaterialGap gap = newChildren[k];
gapSizeSum += gap.size; gapSizeSum += gap.size;
} }
} }
@ -366,7 +366,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
// animate to their actual size. // animate to their actual size.
for (int k = startNew; k < i; k += 1) { for (int k = startNew; k < i; k += 1) {
if (newChildren[k] is MaterialGap) { if (newChildren[k] is MaterialGap) {
MaterialGap gap = newChildren[k]; final MaterialGap gap = newChildren[k];
_animationTuples[gap.key].gapStart = gapSize * gap.size / _animationTuples[gap.key].gapStart = gapSize * gap.size /
gapSizeSum; gapSizeSum;
@ -382,7 +382,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
_insertChild(startOld + k, newChildren[startNew + k]); _insertChild(startOld + k, newChildren[startNew + k]);
if (newChildren[startNew + k] is MaterialGap) { if (newChildren[startNew + k] is MaterialGap) {
MaterialGap gap = newChildren[startNew + k]; final MaterialGap gap = newChildren[startNew + k];
_animationTuples[gap.key].controller.forward(); _animationTuples[gap.key].controller.forward();
} }
} }
@ -397,7 +397,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
while (startOld < j) { while (startOld < j) {
if (_children[startOld] is MaterialGap) { if (_children[startOld] is MaterialGap) {
MaterialGap gap = _children[startOld]; final MaterialGap gap = _children[startOld];
gapSizeSum += gap.size; gapSizeSum += gap.size;
} }
@ -406,7 +406,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
} }
if (gapSizeSum != 0.0) { if (gapSizeSum != 0.0) {
MaterialGap gap = new MaterialGap( final MaterialGap gap = new MaterialGap(
key: new UniqueKey(), key: new UniqueKey(),
size: gapSizeSum size: gapSizeSum
); );
@ -420,7 +420,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
} }
} else if (oldLength == 1) { } else if (oldLength == 1) {
// Shrink gap. // Shrink gap.
MaterialGap gap = _children[startOld]; final MaterialGap gap = _children[startOld];
_animationTuples[gap.key].gapStart = 0.0; _animationTuples[gap.key].gapStart = 0.0;
_animationTuples[gap.key].controller.reverse(); _animationTuples[gap.key].controller.reverse();
} }
@ -487,7 +487,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
} }
double _getGapSize(int index) { double _getGapSize(int index) {
MaterialGap gap = _children[index]; final MaterialGap gap = _children[index];
return lerpDouble( return lerpDouble(
_animationTuples[gap.key].gapStart, _animationTuples[gap.key].gapStart,
@ -537,7 +537,7 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
) )
); );
} else { } else {
MaterialSlice slice = _children[i]; final MaterialSlice slice = _children[i];
Widget child = slice.child; Widget child = slice.child;
if (config.hasDividers) { if (config.hasDividers) {
@ -656,7 +656,7 @@ class _MergeableMaterialBlockBody extends BlockBody {
@override @override
void updateRenderObject(BuildContext context, RenderBlock renderObject) { void updateRenderObject(BuildContext context, RenderBlock renderObject) {
_MergeableMaterialRenderBlock materialRenderBlock = renderObject; final _MergeableMaterialRenderBlock materialRenderBlock = renderObject;
materialRenderBlock materialRenderBlock
..mainAxis = mainAxis ..mainAxis = mainAxis
..boxShadows = boxShadows; ..boxShadows = boxShadows;

View File

@ -250,7 +250,7 @@ class MaterialPageRoute<T> extends PageRoute<T> {
@override @override
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> forwardAnimation) { Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> forwardAnimation) {
Widget result = builder(context); final Widget result = builder(context);
assert(() { assert(() {
if (result == null) { if (result == null) {
throw new FlutterError( throw new FlutterError(

View File

@ -281,7 +281,7 @@ class PaginatedDataTableState extends State<PaginatedDataTable> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// TODO(ianh): This whole build function doesn't handle RTL yet. // TODO(ianh): This whole build function doesn't handle RTL yet.
ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
// HEADER // HEADER
final List<Widget> headerWidgets = <Widget>[]; final List<Widget> headerWidgets = <Widget>[];
double leftPadding = 24.0; double leftPadding = 24.0;
@ -318,7 +318,7 @@ class PaginatedDataTableState extends State<PaginatedDataTable> {
final TextStyle footerTextStyle = themeData.textTheme.caption; final TextStyle footerTextStyle = themeData.textTheme.caption;
final List<Widget> footerWidgets = <Widget>[]; final List<Widget> footerWidgets = <Widget>[];
if (config.onRowsPerPageChanged != null) { if (config.onRowsPerPageChanged != null) {
List<Widget> availableRowsPerPage = config.availableRowsPerPage final List<Widget> availableRowsPerPage = config.availableRowsPerPage
.where((int value) => value <= _rowCount) .where((int value) => value <= _rowCount)
.map<DropdownMenuItem<int>>((int value) { .map<DropdownMenuItem<int>>((int value) {
return new DropdownMenuItem<int>( return new DropdownMenuItem<int>(

View File

@ -262,13 +262,13 @@ class _PopupMenu<T> extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
double unit = 1.0 / (route.items.length + 1.5); // 1.0 for the width and 0.5 for the last item's fade. final double unit = 1.0 / (route.items.length + 1.5); // 1.0 for the width and 0.5 for the last item's fade.
List<Widget> children = <Widget>[]; final List<Widget> children = <Widget>[];
for (int i = 0; i < route.items.length; ++i) { for (int i = 0; i < route.items.length; ++i) {
final double start = (i + 1) * unit; final double start = (i + 1) * unit;
final double end = (start + 1.5 * unit).clamp(0.0, 1.0); final double end = (start + 1.5 * unit).clamp(0.0, 1.0);
CurvedAnimation opacity = new CurvedAnimation( final CurvedAnimation opacity = new CurvedAnimation(
parent: route.animation, parent: route.animation,
curve: new Interval(start, end) curve: new Interval(start, end)
); );
@ -289,7 +289,7 @@ class _PopupMenu<T> extends StatelessWidget {
final CurveTween width = new CurveTween(curve: new Interval(0.0, unit)); final CurveTween width = new CurveTween(curve: new Interval(0.0, unit));
final CurveTween height = new CurveTween(curve: new Interval(0.0, unit * route.items.length)); final CurveTween height = new CurveTween(curve: new Interval(0.0, unit * route.items.length));
Widget child = new ConstrainedBox( final Widget child = new ConstrainedBox(
constraints: const BoxConstraints( constraints: const BoxConstraints(
minWidth: _kMenuMinWidth, minWidth: _kMenuMinWidth,
maxWidth: _kMenuMaxWidth, maxWidth: _kMenuMaxWidth,

View File

@ -86,20 +86,20 @@ class _LinearProgressIndicatorPainter extends CustomPainter {
@override @override
void paint(Canvas canvas, Size size) { void paint(Canvas canvas, Size size) {
Paint paint = new Paint() final Paint paint = new Paint()
..color = backgroundColor ..color = backgroundColor
..style = PaintingStyle.fill; ..style = PaintingStyle.fill;
canvas.drawRect(Point.origin & size, paint); canvas.drawRect(Point.origin & size, paint);
paint.color = valueColor; paint.color = valueColor;
if (value != null) { if (value != null) {
double width = value.clamp(0.0, 1.0) * size.width; final double width = value.clamp(0.0, 1.0) * size.width;
canvas.drawRect(Point.origin & new Size(width, size.height), paint); canvas.drawRect(Point.origin & new Size(width, size.height), paint);
} else { } else {
double startX = size.width * (1.5 * animationValue - 0.5); final double startX = size.width * (1.5 * animationValue - 0.5);
double endX = startX + 0.5 * size.width; final double endX = startX + 0.5 * size.width;
double x = startX.clamp(0.0, size.width); final double x = startX.clamp(0.0, size.width);
double width = endX.clamp(0.0, size.width) - x; final double width = endX.clamp(0.0, size.width) - x;
canvas.drawRect(new Point(x, 0.0) & new Size(width, size.height), paint); canvas.drawRect(new Point(x, 0.0) & new Size(width, size.height), paint);
} }
} }
@ -236,7 +236,7 @@ class _CircularProgressIndicatorPainter extends CustomPainter {
@override @override
void paint(Canvas canvas, Size size) { void paint(Canvas canvas, Size size) {
Paint paint = new Paint() final Paint paint = new Paint()
..color = valueColor ..color = valueColor
..strokeWidth = strokeWidth ..strokeWidth = strokeWidth
..style = PaintingStyle.stroke; ..style = PaintingStyle.stroke;
@ -409,12 +409,12 @@ class _RefreshProgressIndicatorPainter extends _CircularProgressIndicatorPainter
final double innerRadius = radius - arrowheadRadius; final double innerRadius = radius - arrowheadRadius;
final double outerRadius = radius + arrowheadRadius; final double outerRadius = radius + arrowheadRadius;
Path path = new Path() final Path path = new Path()
..moveTo(radius + ux * innerRadius, radius + uy * innerRadius) ..moveTo(radius + ux * innerRadius, radius + uy * innerRadius)
..lineTo(radius + ux * outerRadius, radius + uy * outerRadius) ..lineTo(radius + ux * outerRadius, radius + uy * outerRadius)
..lineTo(arrowheadPointX, arrowheadPointY) ..lineTo(arrowheadPointX, arrowheadPointY)
..close(); ..close();
Paint paint = new Paint() final Paint paint = new Paint()
..color = valueColor ..color = valueColor
..strokeWidth = strokeWidth ..strokeWidth = strokeWidth
..style = PaintingStyle.fill; ..style = PaintingStyle.fill;

View File

@ -112,7 +112,7 @@ class _RadioState<T> extends State<Radio<T>> with TickerProviderStateMixin {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context)); assert(debugCheckHasMaterial(context));
ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
return new Semantics( return new Semantics(
checked: config.value == config.groupValue, checked: config.value == config.groupValue,
child: new _RadioRenderObjectWidget( child: new _RadioRenderObjectWidget(
@ -192,11 +192,11 @@ class _RenderRadio extends RenderToggleable {
paintRadialReaction(canvas, offset, const Point(kRadialReactionRadius, kRadialReactionRadius)); paintRadialReaction(canvas, offset, const Point(kRadialReactionRadius, kRadialReactionRadius));
Point center = (offset & size).center; final Point center = (offset & size).center;
Color radioColor = onChanged != null ? activeColor : inactiveColor; final Color radioColor = onChanged != null ? activeColor : inactiveColor;
// Outer circle // Outer circle
Paint paint = new Paint() final Paint paint = new Paint()
..color = Color.lerp(inactiveColor, radioColor, position.value) ..color = Color.lerp(inactiveColor, radioColor, position.value)
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 2.0; ..strokeWidth = 2.0;

View File

@ -112,7 +112,7 @@ class RaisedButton extends StatelessWidget {
} else { } else {
if (disabledColor != null) if (disabledColor != null)
return disabledColor; return disabledColor;
Brightness brightness = Theme.of(context).brightness; final Brightness brightness = Theme.of(context).brightness;
assert(brightness != null); assert(brightness != null);
switch (brightness) { switch (brightness) {
case Brightness.light: case Brightness.light:

View File

@ -303,7 +303,7 @@ class RefreshIndicatorState extends State<RefreshIndicator> with TickerProviderS
void _show() { void _show() {
assert(_mode != _RefreshIndicatorMode.refresh); assert(_mode != _RefreshIndicatorMode.refresh);
assert(_mode != _RefreshIndicatorMode.snap); assert(_mode != _RefreshIndicatorMode.snap);
Completer<Null> completer = new Completer<Null>(); final Completer<Null> completer = new Completer<Null>();
_pendingRefreshFuture = completer.future; _pendingRefreshFuture = completer.future;
_mode = _RefreshIndicatorMode.snap; _mode = _RefreshIndicatorMode.snap;
_positionController _positionController
@ -356,7 +356,7 @@ class RefreshIndicatorState extends State<RefreshIndicator> with TickerProviderS
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Widget child = new NotificationListener<ScrollNotification>( final Widget child = new NotificationListener<ScrollNotification>(
key: _key, key: _key,
onNotification: _handleScrollNotification, onNotification: _handleScrollNotification,
child: new NotificationListener<OverscrollIndicatorNotification>( child: new NotificationListener<OverscrollIndicatorNotification>(

View File

@ -469,10 +469,10 @@ class Scaffold extends StatefulWidget {
assert(registerForUpdates != null); assert(registerForUpdates != null);
assert(context != null); assert(context != null);
if (registerForUpdates) { if (registerForUpdates) {
_ScaffoldScope scaffold = context.inheritFromWidgetOfExactType(_ScaffoldScope); final _ScaffoldScope scaffold = context.inheritFromWidgetOfExactType(_ScaffoldScope);
return scaffold?.hasDrawer ?? false; return scaffold?.hasDrawer ?? false;
} else { } else {
ScaffoldState scaffold = context.ancestorStateOfType(const TypeMatcher<ScaffoldState>()); final ScaffoldState scaffold = context.ancestorStateOfType(const TypeMatcher<ScaffoldState>());
return scaffold?.hasDrawer ?? false; return scaffold?.hasDrawer ?? false;
} }
} }
@ -640,12 +640,12 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin {
_currentBottomSheet.close(); _currentBottomSheet.close();
assert(_currentBottomSheet == null); assert(_currentBottomSheet == null);
} }
Completer<T> completer = new Completer<T>(); final Completer<T> completer = new Completer<T>();
GlobalKey<_PersistentBottomSheetState> bottomSheetKey = new GlobalKey<_PersistentBottomSheetState>(); final GlobalKey<_PersistentBottomSheetState> bottomSheetKey = new GlobalKey<_PersistentBottomSheetState>();
AnimationController controller = BottomSheet.createAnimationController(this) final AnimationController controller = BottomSheet.createAnimationController(this)
..forward(); ..forward();
_PersistentBottomSheet bottomSheet; _PersistentBottomSheet bottomSheet;
LocalHistoryEntry entry = new LocalHistoryEntry( final LocalHistoryEntry entry = new LocalHistoryEntry(
onRemove: () { onRemove: () {
assert(_currentBottomSheet._widget == bottomSheet); assert(_currentBottomSheet._widget == bottomSheet);
assert(bottomSheetKey.currentState != null); assert(bottomSheetKey.currentState != null);
@ -758,7 +758,7 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
EdgeInsets padding = MediaQuery.of(context).padding; EdgeInsets padding = MediaQuery.of(context).padding;
ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
if (!config.resizeToAvoidBottomPadding) if (!config.resizeToAvoidBottomPadding)
padding = new EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0.0); padding = new EdgeInsets.fromLTRB(padding.left, padding.top, padding.right, 0.0);
@ -783,9 +783,9 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin {
if (config.appBar != null) { if (config.appBar != null) {
assert(config.appBar.primary || padding.top == 0.0, 'A non-primary AppBar was passed to a Scaffold but the MediaQuery in scope has top padding.'); assert(config.appBar.primary || padding.top == 0.0, 'A non-primary AppBar was passed to a Scaffold but the MediaQuery in scope has top padding.');
double topPadding = config.appBar.primary ? padding.top : 0.0; final double topPadding = config.appBar.primary ? padding.top : 0.0;
Widget appBar = config.appBar; Widget appBar = config.appBar;
double extent = config.appBar.minExtent + topPadding; final double extent = config.appBar.minExtent + topPadding;
if (config.appBar.flexibleSpace != null) { if (config.appBar.flexibleSpace != null) {
appBar = FlexibleSpaceBar.createSettings( appBar = FlexibleSpaceBar.createSettings(
currentExtent: extent, currentExtent: extent,
@ -838,7 +838,7 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin {
bottomSheets.addAll(_dismissedBottomSheets); bottomSheets.addAll(_dismissedBottomSheets);
if (_currentBottomSheet != null) if (_currentBottomSheet != null)
bottomSheets.add(_currentBottomSheet._widget); bottomSheets.add(_currentBottomSheet._widget);
Widget stack = new Stack( final Widget stack = new Stack(
children: bottomSheets, children: bottomSheets,
alignment: FractionalOffset.bottomCenter, alignment: FractionalOffset.bottomCenter,
); );

View File

@ -162,7 +162,7 @@ class _SliderState extends State<Slider> with TickerProviderStateMixin {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context)); assert(debugCheckHasMaterial(context));
ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
return new _SliderRenderObjectWidget( return new _SliderRenderObjectWidget(
value: (config.value - config.min) / (config.max - config.min), value: (config.value - config.min) / (config.max - config.min),
divisions: config.divisions, divisions: config.divisions,
@ -277,7 +277,7 @@ class _RenderSlider extends RenderConstrainedBox implements SemanticsActionHandl
super(additionalConstraints: _getAdditionalConstraints(label)) { super(additionalConstraints: _getAdditionalConstraints(label)) {
assert(value != null && value >= 0.0 && value <= 1.0); assert(value != null && value >= 0.0 && value <= 1.0);
this.label = label; this.label = label;
GestureArenaTeam team = new GestureArenaTeam(); final GestureArenaTeam team = new GestureArenaTeam();
_drag = new HorizontalDragGestureRecognizer() _drag = new HorizontalDragGestureRecognizer()
..team = team ..team = team
..onStart = _handleDragStart ..onStart = _handleDragStart
@ -501,14 +501,14 @@ class _RenderSlider extends RenderConstrainedBox implements SemanticsActionHandl
final double tipAttachment = _kLabelBalloonTipAttachmentRatio * radius; final double tipAttachment = _kLabelBalloonTipAttachmentRatio * radius;
canvas.drawCircle(center, radius, primaryPaint); canvas.drawCircle(center, radius, primaryPaint);
Path path = new Path() final Path path = new Path()
..moveTo(tip.x, tip.y) ..moveTo(tip.x, tip.y)
..lineTo(center.x - tipAttachment, center.y + tipAttachment) ..lineTo(center.x - tipAttachment, center.y + tipAttachment)
..lineTo(center.x + tipAttachment, center.y + tipAttachment) ..lineTo(center.x + tipAttachment, center.y + tipAttachment)
..close(); ..close();
canvas.drawPath(path, primaryPaint); canvas.drawPath(path, primaryPaint);
_labelPainter.layout(); _labelPainter.layout();
Offset labelOffset = new Offset( final Offset labelOffset = new Offset(
center.x - _labelPainter.width / 2.0, center.x - _labelPainter.width / 2.0,
center.y - _labelPainter.height / 2.0 center.y - _labelPainter.height / 2.0
); );

View File

@ -190,13 +190,13 @@ class SnackBar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
assert(animation != null); assert(animation != null);
ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
ThemeData darkTheme = new ThemeData( final ThemeData darkTheme = new ThemeData(
brightness: Brightness.dark, brightness: Brightness.dark,
accentColor: theme.accentColor, accentColor: theme.accentColor,
accentColorBrightness: theme.accentColorBrightness accentColorBrightness: theme.accentColorBrightness
); );
List<Widget> children = <Widget>[ final List<Widget> children = <Widget>[
const SizedBox(width: _kSnackBarPadding), const SizedBox(width: _kSnackBarPadding),
new Expanded( new Expanded(
child: new Container( child: new Container(
@ -217,8 +217,8 @@ class SnackBar extends StatelessWidget {
} else { } else {
children.add(const SizedBox(width: _kSnackBarPadding)); children.add(const SizedBox(width: _kSnackBarPadding));
} }
CurvedAnimation heightAnimation = new CurvedAnimation(parent: animation, curve: _snackBarHeightCurve); final CurvedAnimation heightAnimation = new CurvedAnimation(parent: animation, curve: _snackBarHeightCurve);
CurvedAnimation fadeAnimation = new CurvedAnimation(parent: animation, curve: _snackBarFadeCurve, reverseCurve: const Threshold(0.0)); final CurvedAnimation fadeAnimation = new CurvedAnimation(parent: animation, curve: _snackBarFadeCurve, reverseCurve: const Threshold(0.0));
return new ClipRect( return new ClipRect(
child: new AnimatedBuilder( child: new AnimatedBuilder(
animation: heightAnimation, animation: heightAnimation,

View File

@ -514,7 +514,7 @@ class _StepperState extends State<Stepper> with TickerProviderStateMixin {
} }
Widget _buildVertical() { Widget _buildVertical() {
List<Widget> children = <Widget>[]; final List<Widget> children = <Widget>[];
for (int i = 0; i < config.steps.length; i += 1) { for (int i = 0; i < config.steps.length; i += 1) {
children.add( children.add(

View File

@ -244,7 +244,7 @@ class DefaultTabController extends StatefulWidget {
/// TabController controller = DefaultTabBarController.of(context); /// TabController controller = DefaultTabBarController.of(context);
/// ``` /// ```
static TabController of(BuildContext context) { static TabController of(BuildContext context) {
_TabControllerScope scope = context.inheritFromWidgetOfExactType(_TabControllerScope); final _TabControllerScope scope = context.inheritFromWidgetOfExactType(_TabControllerScope);
return scope?.controller; return scope?.controller;
} }

View File

@ -431,7 +431,7 @@ class _TabBarState extends State<TabBar> {
int _currentIndex; int _currentIndex;
void _updateTabController() { void _updateTabController() {
TabController newController = config.controller ?? DefaultTabController.of(context); final TabController newController = config.controller ?? DefaultTabController.of(context);
if (newController == _controller) if (newController == _controller)
return; return;
@ -676,7 +676,7 @@ class _TabBarViewState extends State<TabBarView> {
int _warpUnderwayCount = 0; int _warpUnderwayCount = 0;
void _updateTabController() { void _updateTabController() {
TabController newController = config.controller ?? DefaultTabController.of(context); final TabController newController = config.controller ?? DefaultTabController.of(context);
if (newController == _controller) if (newController == _controller)
return; return;

View File

@ -24,7 +24,7 @@ class _TextSelectionToolbar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
List<Widget> items = <Widget>[]; final List<Widget> items = <Widget>[];
if (!value.selection.isCollapsed) { if (!value.selection.isCollapsed) {
items.add(new FlatButton(child: new Text('CUT'), onPressed: _handleCut)); items.add(new FlatButton(child: new Text('CUT'), onPressed: _handleCut));
@ -68,8 +68,8 @@ class _TextSelectionToolbar extends StatelessWidget {
} }
Future<Null> _handlePaste() async { Future<Null> _handlePaste() async {
InputValue value = this.value; // Snapshot the input before using `await`. final InputValue value = this.value; // Snapshot the input before using `await`.
ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain); final ClipboardData data = await Clipboard.getData(Clipboard.kTextPlain);
if (data != null) { if (data != null) {
delegate.inputValue = new InputValue( delegate.inputValue = new InputValue(
text: value.selection.textBefore(value.text) + data.text + value.selection.textAfter(value.text), text: value.selection.textBefore(value.text) + data.text + value.selection.textAfter(value.text),
@ -131,8 +131,8 @@ class _TextSelectionHandlePainter extends CustomPainter {
@override @override
void paint(Canvas canvas, Size size) { void paint(Canvas canvas, Size size) {
Paint paint = new Paint()..color = color; final Paint paint = new Paint()..color = color;
double radius = size.width/2.0; final double radius = size.width/2.0;
canvas.drawCircle(new Point(radius, radius), radius, paint); canvas.drawCircle(new Point(radius, radius), radius, paint);
canvas.drawRect(new Rect.fromLTWH(0.0, 0.0, radius, radius), paint); canvas.drawRect(new Rect.fromLTWH(0.0, 0.0, radius, radius), paint);
} }
@ -164,7 +164,7 @@ class _MaterialTextSelectionControls extends TextSelectionControls {
/// Builder for material-style text selection handles. /// Builder for material-style text selection handles.
@override @override
Widget buildHandle(BuildContext context, TextSelectionHandleType type) { Widget buildHandle(BuildContext context, TextSelectionHandleType type) {
Widget handle = new SizedBox( final Widget handle = new SizedBox(
width: _kHandleSize, width: _kHandleSize,
height: _kHandleSize, height: _kHandleSize,
child: new CustomPaint( child: new CustomPaint(

View File

@ -475,7 +475,7 @@ class ThemeData {
bool operator ==(Object other) { bool operator ==(Object other) {
if (other.runtimeType != runtimeType) if (other.runtimeType != runtimeType)
return false; return false;
ThemeData otherData = other; final ThemeData otherData = other;
return (otherData.brightness == brightness) && return (otherData.brightness == brightness) &&
(otherData.primaryColor == primaryColor) && (otherData.primaryColor == primaryColor) &&
(otherData.primaryColorBrightness == primaryColorBrightness) && (otherData.primaryColorBrightness == primaryColorBrightness) &&

View File

@ -230,7 +230,7 @@ class _TimePickerHeader extends StatelessWidget {
} }
void _handleChangeDayPeriod() { void _handleChangeDayPeriod() {
int newHour = (selectedTime.hour + _kHoursPerPeriod) % _kHoursPerDay; final int newHour = (selectedTime.hour + _kHoursPerPeriod) % _kHoursPerDay;
onChanged(selectedTime.replacing(hour: newHour)); onChanged(selectedTime.replacing(hour: newHour));
} }
@ -250,9 +250,9 @@ class _TimePickerHeader extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
TextTheme headerTextTheme = themeData.primaryTextTheme; final TextTheme headerTextTheme = themeData.primaryTextTheme;
TextStyle baseHeaderStyle = _getBaseHeaderStyle(headerTextTheme); final TextStyle baseHeaderStyle = _getBaseHeaderStyle(headerTextTheme);
Color activeColor; Color activeColor;
Color inactiveColor; Color inactiveColor;
switch(themeData.primaryColorBrightness) { switch(themeData.primaryColorBrightness) {
@ -276,20 +276,20 @@ class _TimePickerHeader extends StatelessWidget {
break; break;
} }
TextStyle activeStyle = baseHeaderStyle.copyWith(color: activeColor); final TextStyle activeStyle = baseHeaderStyle.copyWith(color: activeColor);
TextStyle inactiveStyle = baseHeaderStyle.copyWith(color: inactiveColor); final TextStyle inactiveStyle = baseHeaderStyle.copyWith(color: inactiveColor);
TextStyle hourStyle = mode == _TimePickerMode.hour ? activeStyle : inactiveStyle; final TextStyle hourStyle = mode == _TimePickerMode.hour ? activeStyle : inactiveStyle;
TextStyle minuteStyle = mode == _TimePickerMode.minute ? activeStyle : inactiveStyle; final TextStyle minuteStyle = mode == _TimePickerMode.minute ? activeStyle : inactiveStyle;
TextStyle amStyle = headerTextTheme.subhead.copyWith( final TextStyle amStyle = headerTextTheme.subhead.copyWith(
color: selectedTime.period == DayPeriod.am ? activeColor: inactiveColor color: selectedTime.period == DayPeriod.am ? activeColor: inactiveColor
); );
TextStyle pmStyle = headerTextTheme.subhead.copyWith( final TextStyle pmStyle = headerTextTheme.subhead.copyWith(
color: selectedTime.period == DayPeriod.pm ? activeColor: inactiveColor color: selectedTime.period == DayPeriod.pm ? activeColor: inactiveColor
); );
Widget dayPeriodPicker = new GestureDetector( final Widget dayPeriodPicker = new GestureDetector(
onTap: _handleChangeDayPeriod, onTap: _handleChangeDayPeriod,
behavior: HitTestBehavior.opaque, behavior: HitTestBehavior.opaque,
child: new Column( child: new Column(
@ -302,17 +302,17 @@ class _TimePickerHeader extends StatelessWidget {
) )
); );
Widget hour = new GestureDetector( final Widget hour = new GestureDetector(
onTap: () => _handleChangeMode(_TimePickerMode.hour), onTap: () => _handleChangeMode(_TimePickerMode.hour),
child: new Text(selectedTime.hourOfPeriodLabel, style: hourStyle), child: new Text(selectedTime.hourOfPeriodLabel, style: hourStyle),
); );
Widget minute = new GestureDetector( final Widget minute = new GestureDetector(
onTap: () => _handleChangeMode(_TimePickerMode.minute), onTap: () => _handleChangeMode(_TimePickerMode.minute),
child: new Text(selectedTime.minuteLabel, style: minuteStyle), child: new Text(selectedTime.minuteLabel, style: minuteStyle),
); );
Widget colon = new Text(':', style: inactiveStyle); final Widget colon = new Text(':', style: inactiveStyle);
EdgeInsets padding; EdgeInsets padding;
double height; double height;
@ -349,10 +349,10 @@ class _TimePickerHeader extends StatelessWidget {
} }
List<TextPainter> _initPainters(TextTheme textTheme, List<String> labels) { List<TextPainter> _initPainters(TextTheme textTheme, List<String> labels) {
TextStyle style = textTheme.subhead; final TextStyle style = textTheme.subhead;
List<TextPainter> painters = new List<TextPainter>(labels.length); final List<TextPainter> painters = new List<TextPainter>(labels.length);
for (int i = 0; i < painters.length; ++i) { for (int i = 0; i < painters.length; ++i) {
String label = labels[i]; final String label = labels[i];
// TODO(abarth): Handle textScaleFactor. // TODO(abarth): Handle textScaleFactor.
// https://github.com/flutter/flutter/issues/5939 // https://github.com/flutter/flutter/issues/5939
painters[i] = new TextPainter( painters[i] = new TextPainter(
@ -391,24 +391,24 @@ class _DialPainter extends CustomPainter {
@override @override
void paint(Canvas canvas, Size size) { void paint(Canvas canvas, Size size) {
double radius = size.shortestSide / 2.0; final double radius = size.shortestSide / 2.0;
Offset center = new Offset(size.width / 2.0, size.height / 2.0); final Offset center = new Offset(size.width / 2.0, size.height / 2.0);
Point centerPoint = center.toPoint(); final Point centerPoint = center.toPoint();
canvas.drawCircle(centerPoint, radius, new Paint()..color = backgroundColor); canvas.drawCircle(centerPoint, radius, new Paint()..color = backgroundColor);
const double labelPadding = 24.0; const double labelPadding = 24.0;
double labelRadius = radius - labelPadding; final double labelRadius = radius - labelPadding;
Offset getOffsetForTheta(double theta) { Offset getOffsetForTheta(double theta) {
return center + new Offset(labelRadius * math.cos(theta), return center + new Offset(labelRadius * math.cos(theta),
-labelRadius * math.sin(theta)); -labelRadius * math.sin(theta));
} }
void paintLabels(List<TextPainter> labels) { void paintLabels(List<TextPainter> labels) {
double labelThetaIncrement = -_kTwoPi / labels.length; final double labelThetaIncrement = -_kTwoPi / labels.length;
double labelTheta = math.PI / 2.0; double labelTheta = math.PI / 2.0;
for (TextPainter label in labels) { for (TextPainter label in labels) {
Offset labelOffset = new Offset(-label.width / 2.0, -label.height / 2.0); final Offset labelOffset = new Offset(-label.width / 2.0, -label.height / 2.0);
label.paint(canvas, getOffsetForTheta(labelTheta) + labelOffset); label.paint(canvas, getOffsetForTheta(labelTheta) + labelOffset);
labelTheta += labelThetaIncrement; labelTheta += labelThetaIncrement;
} }
@ -499,7 +499,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
} }
void _animateTo(double targetTheta) { void _animateTo(double targetTheta) {
double currentTheta = _theta.value; final double currentTheta = _theta.value;
double beginTheta = _nearest(targetTheta, currentTheta, currentTheta + _kTwoPi); double beginTheta = _nearest(targetTheta, currentTheta, currentTheta + _kTwoPi);
beginTheta = _nearest(targetTheta, beginTheta, currentTheta - _kTwoPi); beginTheta = _nearest(targetTheta, beginTheta, currentTheta - _kTwoPi);
_thetaTween _thetaTween
@ -511,16 +511,16 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
} }
double _getThetaForTime(TimeOfDay time) { double _getThetaForTime(TimeOfDay time) {
double fraction = (config.mode == _TimePickerMode.hour) ? final double fraction = (config.mode == _TimePickerMode.hour) ?
(time.hour / _kHoursPerPeriod) % _kHoursPerPeriod : (time.hour / _kHoursPerPeriod) % _kHoursPerPeriod :
(time.minute / _kMinutesPerHour) % _kMinutesPerHour; (time.minute / _kMinutesPerHour) % _kMinutesPerHour;
return (math.PI / 2.0 - fraction * _kTwoPi) % _kTwoPi; return (math.PI / 2.0 - fraction * _kTwoPi) % _kTwoPi;
} }
TimeOfDay _getTimeForTheta(double theta) { TimeOfDay _getTimeForTheta(double theta) {
double fraction = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1.0; final double fraction = (0.25 - (theta % _kTwoPi) / _kTwoPi) % 1.0;
if (config.mode == _TimePickerMode.hour) { if (config.mode == _TimePickerMode.hour) {
int hourOfPeriod = (fraction * _kHoursPerPeriod).round() % _kHoursPerPeriod; final int hourOfPeriod = (fraction * _kHoursPerPeriod).round() % _kHoursPerPeriod;
return config.selectedTime.replacing( return config.selectedTime.replacing(
hour: hourOfPeriod + config.selectedTime.periodOffset hour: hourOfPeriod + config.selectedTime.periodOffset
); );
@ -534,7 +534,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
void _notifyOnChangedIfNeeded() { void _notifyOnChangedIfNeeded() {
if (config.onChanged == null) if (config.onChanged == null)
return; return;
TimeOfDay current = _getTimeForTheta(_theta.value); final TimeOfDay current = _getTimeForTheta(_theta.value);
if (current != config.selectedTime) if (current != config.selectedTime)
config.onChanged(current); config.onChanged(current);
} }
@ -578,7 +578,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
Color backgroundColor; Color backgroundColor;
switch (themeData.brightness) { switch (themeData.brightness) {
@ -590,7 +590,7 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
break; break;
} }
ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
List<TextPainter> primaryLabels; List<TextPainter> primaryLabels;
List<TextPainter> secondaryLabels; List<TextPainter> secondaryLabels;
switch (config.mode) { switch (config.mode) {
@ -686,7 +686,7 @@ class _TimePickerDialogState extends State<_TimePickerDialog> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Widget picker = new Padding( final Widget picker = new Padding(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
child: new AspectRatio( child: new AspectRatio(
aspectRatio: 1.0, aspectRatio: 1.0,
@ -698,7 +698,7 @@ class _TimePickerDialogState extends State<_TimePickerDialog> {
) )
); );
Widget actions = new ButtonTheme.bar( final Widget actions = new ButtonTheme.bar(
child: new ButtonBar( child: new ButtonBar(
children: <Widget>[ children: <Widget>[
new FlatButton( new FlatButton(
@ -716,7 +716,7 @@ class _TimePickerDialogState extends State<_TimePickerDialog> {
return new Dialog( return new Dialog(
child: new OrientationBuilder( child: new OrientationBuilder(
builder: (BuildContext context, Orientation orientation) { builder: (BuildContext context, Orientation orientation) {
Widget header = new _TimePickerHeader( final Widget header = new _TimePickerHeader(
selectedTime: _selectedTime, selectedTime: _selectedTime,
mode: _mode, mode: _mode,
orientation: orientation, orientation: orientation,

View File

@ -275,9 +275,9 @@ abstract class RenderToggleable extends RenderConstrainedBox implements Semantic
void paintRadialReaction(Canvas canvas, Offset offset, Point origin) { void paintRadialReaction(Canvas canvas, Offset offset, Point origin) {
if (!_reaction.isDismissed) { if (!_reaction.isDismissed) {
// TODO(abarth): We should have a different reaction color when position is zero. // TODO(abarth): We should have a different reaction color when position is zero.
Paint reactionPaint = new Paint()..color = activeColor.withAlpha(kRadialReactionAlpha); final Paint reactionPaint = new Paint()..color = activeColor.withAlpha(kRadialReactionAlpha);
Point center = Point.lerp(_downPosition ?? origin, origin, _reaction.value); final Point center = Point.lerp(_downPosition ?? origin, origin, _reaction.value);
double radius = _kRadialReactionRadiusTween.evaluate(_reaction); final double radius = _kRadialReactionRadiusTween.evaluate(_reaction);
canvas.drawCircle(center + offset, radius, reactionPaint); canvas.drawCircle(center + offset, radius, reactionPaint);
} }
} }

View File

@ -213,7 +213,7 @@ class _TooltipPositionDelegate extends SingleChildLayoutDelegate {
else else
y = math.max(target.y - verticalOffset - childSize.height, _kScreenEdgeMargin); y = math.max(target.y - verticalOffset - childSize.height, _kScreenEdgeMargin);
// HORIZONTAL DIRECTION // HORIZONTAL DIRECTION
double normalizedTargetX = target.x.clamp(_kScreenEdgeMargin, size.width - _kScreenEdgeMargin); final double normalizedTargetX = target.x.clamp(_kScreenEdgeMargin, size.width - _kScreenEdgeMargin);
double x; double x;
if (normalizedTargetX < _kScreenEdgeMargin + childSize.width / 2.0) { if (normalizedTargetX < _kScreenEdgeMargin + childSize.width / 2.0) {
x = _kScreenEdgeMargin; x = _kScreenEdgeMargin;
@ -255,8 +255,8 @@ class _TooltipOverlay extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
ThemeData darkTheme = new ThemeData( final ThemeData darkTheme = new ThemeData(
brightness: Brightness.dark, brightness: Brightness.dark,
textTheme: theme.brightness == Brightness.dark ? theme.textTheme : theme.primaryTextTheme, textTheme: theme.brightness == Brightness.dark ? theme.textTheme : theme.primaryTextTheme,
platform: theme.platform, platform: theme.platform,

View File

@ -366,7 +366,7 @@ class Border {
assert(bottom != null); assert(bottom != null);
assert(left != null); assert(left != null);
Paint paint = new Paint() final Paint paint = new Paint()
..strokeWidth = 0.0; // used for hairline borders ..strokeWidth = 0.0; // used for hairline borders
Path path; Path path;
@ -450,29 +450,29 @@ class Border {
void _paintBorderWithRadius(Canvas canvas, Rect rect, void _paintBorderWithRadius(Canvas canvas, Rect rect,
BorderRadius borderRadius) { BorderRadius borderRadius) {
assert(isUniform); assert(isUniform);
Paint paint = new Paint() final Paint paint = new Paint()
..color = top.color; ..color = top.color;
RRect outer = borderRadius.toRRect(rect); final RRect outer = borderRadius.toRRect(rect);
double width = top.width; final double width = top.width;
if (width == 0.0) { if (width == 0.0) {
paint paint
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 0.0; ..strokeWidth = 0.0;
canvas.drawRRect(outer, paint); canvas.drawRRect(outer, paint);
} else { } else {
RRect inner = outer.deflate(width); final RRect inner = outer.deflate(width);
canvas.drawDRRect(outer, inner, paint); canvas.drawDRRect(outer, inner, paint);
} }
} }
void _paintBorderWithCircle(Canvas canvas, Rect rect) { void _paintBorderWithCircle(Canvas canvas, Rect rect) {
assert(isUniform); assert(isUniform);
double width = top.width; final double width = top.width;
Paint paint = new Paint() final Paint paint = new Paint()
..color = top.color ..color = top.color
..strokeWidth = width ..strokeWidth = width
..style = PaintingStyle.stroke; ..style = PaintingStyle.stroke;
double radius = (rect.shortestSide - width) / 2.0; final double radius = (rect.shortestSide - width) / 2.0;
canvas.drawCircle(rect.center, radius, paint); canvas.drawCircle(rect.center, radius, paint);
} }
@ -581,8 +581,8 @@ class BoxShadow {
a = new List<BoxShadow>(); a = new List<BoxShadow>();
if (b == null) if (b == null)
b = new List<BoxShadow>(); b = new List<BoxShadow>();
List<BoxShadow> result = new List<BoxShadow>(); final List<BoxShadow> result = new List<BoxShadow>();
int commonLength = math.min(a.length, b.length); final int commonLength = math.min(a.length, b.length);
for (int i = 0; i < commonLength; ++i) for (int i = 0; i < commonLength; ++i)
result.add(BoxShadow.lerp(a[i], b[i], t)); result.add(BoxShadow.lerp(a[i], b[i], t));
for (int i = commonLength; i < a.length; ++i) for (int i = commonLength; i < a.length; ++i)
@ -838,8 +838,8 @@ Iterable<Rect> _generateImageTileRects(Rect outputRect, Rect fundamentalRect, Im
int startY = 0; int startY = 0;
int stopX = 0; int stopX = 0;
int stopY = 0; int stopY = 0;
double strideX = fundamentalRect.width; final double strideX = fundamentalRect.width;
double strideY = fundamentalRect.height; final double strideY = fundamentalRect.height;
if (repeat == ImageRepeat.repeat || repeat == ImageRepeat.repeatX) { if (repeat == ImageRepeat.repeat || repeat == ImageRepeat.repeatX) {
startX = ((outputRect.left - fundamentalRect.left) / strideX).floor(); startX = ((outputRect.left - fundamentalRect.left) / strideX).floor();
@ -929,7 +929,7 @@ void paintImage({
// output rect with the image. // output rect with the image.
repeat = ImageRepeat.noRepeat; repeat = ImageRepeat.noRepeat;
} }
Paint paint = new Paint()..isAntiAlias = false; final Paint paint = new Paint()..isAntiAlias = false;
if (colorFilter != null) if (colorFilter != null)
paint.colorFilter = colorFilter; paint.colorFilter = colorFilter;
if (sourceSize != destinationSize) { if (sourceSize != destinationSize) {
@ -938,10 +938,10 @@ void paintImage({
// to nearest-neighbor. // to nearest-neighbor.
paint.filterQuality = FilterQuality.low; paint.filterQuality = FilterQuality.low;
} }
double dx = (outputSize.width - destinationSize.width) * (alignment?.dx ?? 0.5); final double dx = (outputSize.width - destinationSize.width) * (alignment?.dx ?? 0.5);
double dy = (outputSize.height - destinationSize.height) * (alignment?.dy ?? 0.5); final double dy = (outputSize.height - destinationSize.height) * (alignment?.dy ?? 0.5);
Point destinationPosition = rect.topLeft + new Offset(dx, dy); final Point destinationPosition = rect.topLeft + new Offset(dx, dy);
Rect destinationRect = destinationPosition & destinationSize; final Rect destinationRect = destinationPosition & destinationSize;
if (repeat != ImageRepeat.noRepeat) { if (repeat != ImageRepeat.noRepeat) {
canvas.save(); canvas.save();
canvas.clipRect(rect); canvas.clipRect(rect);
@ -1200,7 +1200,7 @@ class BoxDecoration extends Decoration {
/// span multiple lines, each prefixed by that argument. /// span multiple lines, each prefixed by that argument.
@override @override
String toString([String prefix = '', String indentPrefix]) { String toString([String prefix = '', String indentPrefix]) {
List<String> result = <String>[]; final List<String> result = <String>[];
if (backgroundColor != null) if (backgroundColor != null)
result.add('${prefix}backgroundColor: $backgroundColor'); result.add('${prefix}backgroundColor: $backgroundColor');
if (backgroundImage != null) if (backgroundImage != null)
@ -1236,14 +1236,14 @@ class BoxDecoration extends Decoration {
switch (shape) { switch (shape) {
case BoxShape.rectangle: case BoxShape.rectangle:
if (borderRadius != null) { if (borderRadius != null) {
RRect bounds = borderRadius.toRRect(Point.origin & size); final RRect bounds = borderRadius.toRRect(Point.origin & size);
return bounds.contains(position); return bounds.contains(position);
} }
return true; return true;
case BoxShape.circle: case BoxShape.circle:
// Circles are inscribed into our smallest dimension. // Circles are inscribed into our smallest dimension.
Point center = size.center(Point.origin); final Point center = size.center(Point.origin);
double distance = (position - center).distance; final double distance = (position - center).distance;
return distance <= math.min(size.width, size.height) / 2.0; return distance <= math.min(size.width, size.height) / 2.0;
} }
assert(shape != null); assert(shape != null);
@ -1272,7 +1272,7 @@ class _BoxDecorationPainter extends BoxPainter {
if (_cachedBackgroundPaint == null || if (_cachedBackgroundPaint == null ||
(_decoration.gradient == null && _rectForCachedBackgroundPaint != null) || (_decoration.gradient == null && _rectForCachedBackgroundPaint != null) ||
(_decoration.gradient != null && _rectForCachedBackgroundPaint != rect)) { (_decoration.gradient != null && _rectForCachedBackgroundPaint != rect)) {
Paint paint = new Paint(); final Paint paint = new Paint();
if (_decoration.backgroundColor != null) if (_decoration.backgroundColor != null)
paint.color = _decoration.backgroundColor; paint.color = _decoration.backgroundColor;
@ -1294,8 +1294,8 @@ class _BoxDecorationPainter extends BoxPainter {
switch (_decoration.shape) { switch (_decoration.shape) {
case BoxShape.circle: case BoxShape.circle:
assert(_decoration.borderRadius == null); assert(_decoration.borderRadius == null);
Point center = rect.center; final Point center = rect.center;
double radius = rect.shortestSide / 2.0; final double radius = rect.shortestSide / 2.0;
canvas.drawCircle(center, radius, paint); canvas.drawCircle(center, radius, paint);
break; break;
case BoxShape.rectangle: case BoxShape.rectangle:

View File

@ -384,7 +384,7 @@ class _FlutterLogoPainter extends BoxPainter {
@override @override
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
offset += _config.margin.topLeft; offset += _config.margin.topLeft;
Size canvasSize = _config.margin.deflateSize(configuration.size); final Size canvasSize = _config.margin.deflateSize(configuration.size);
Size logoSize; Size logoSize;
if (_config._position > 0.0) { if (_config._position > 0.0) {
// horizontal style // horizontal style

View File

@ -73,7 +73,7 @@ class TextRange {
return true; return true;
if (other is! TextRange) if (other is! TextRange)
return false; return false;
TextRange typedOther = other; final TextRange typedOther = other;
return typedOther.start == start return typedOther.start == start
&& typedOther.end == end; && typedOther.end == end;
} }
@ -181,7 +181,7 @@ class TextSelection extends TextRange {
return true; return true;
if (other is! TextSelection) if (other is! TextSelection)
return false; return false;
TextSelection typedOther = other; final TextSelection typedOther = other;
return typedOther.baseOffset == baseOffset return typedOther.baseOffset == baseOffset
&& typedOther.extentOffset == extentOffset && typedOther.extentOffset == extentOffset
&& typedOther.affinity == affinity && typedOther.affinity == affinity

View File

@ -137,7 +137,7 @@ class TextPainter {
double get preferredLineHeight { double get preferredLineHeight {
assert(text != null); assert(text != null);
if (_layoutTemplate == null) { if (_layoutTemplate == null) {
ui.ParagraphBuilder builder = new ui.ParagraphBuilder(new ui.ParagraphStyle()); final ui.ParagraphBuilder builder = new ui.ParagraphBuilder(new ui.ParagraphStyle());
if (text.style != null) if (text.style != null)
builder.pushStyle(text.style.getTextStyle(textScaleFactor: textScaleFactor)); builder.pushStyle(text.style.getTextStyle(textScaleFactor: textScaleFactor));
builder.addText(_kZeroWidthSpace); builder.addText(_kZeroWidthSpace);
@ -247,7 +247,7 @@ class TextPainter {
maxLines: maxLines, maxLines: maxLines,
ellipsis: ellipsis, ellipsis: ellipsis,
); );
ui.ParagraphBuilder builder = new ui.ParagraphBuilder(paragraphStyle); final ui.ParagraphBuilder builder = new ui.ParagraphBuilder(paragraphStyle);
_text.build(builder, textScaleFactor: textScaleFactor); _text.build(builder, textScaleFactor: textScaleFactor);
_paragraph = builder.build(); _paragraph = builder.build();
} }
@ -291,30 +291,30 @@ class TextPainter {
} }
Offset _getOffsetFromUpstream(int offset, Rect caretPrototype) { Offset _getOffsetFromUpstream(int offset, Rect caretPrototype) {
int prevCodeUnit = _text.codeUnitAt(offset - 1); final int prevCodeUnit = _text.codeUnitAt(offset - 1);
if (prevCodeUnit == null) if (prevCodeUnit == null)
return null; return null;
int prevRuneOffset = _isUtf16Surrogate(prevCodeUnit) ? offset - 2 : offset - 1; final int prevRuneOffset = _isUtf16Surrogate(prevCodeUnit) ? offset - 2 : offset - 1;
List<ui.TextBox> boxes = _paragraph.getBoxesForRange(prevRuneOffset, offset); final List<ui.TextBox> boxes = _paragraph.getBoxesForRange(prevRuneOffset, offset);
if (boxes.isEmpty) if (boxes.isEmpty)
return null; return null;
ui.TextBox box = boxes[0]; final ui.TextBox box = boxes[0];
double caretEnd = box.end; final double caretEnd = box.end;
double dx = box.direction == TextDirection.rtl ? caretEnd : caretEnd - caretPrototype.width; final double dx = box.direction == TextDirection.rtl ? caretEnd : caretEnd - caretPrototype.width;
return new Offset(dx, box.top); return new Offset(dx, box.top);
} }
Offset _getOffsetFromDownstream(int offset, Rect caretPrototype) { Offset _getOffsetFromDownstream(int offset, Rect caretPrototype) {
int nextCodeUnit = _text.codeUnitAt(offset + 1); final int nextCodeUnit = _text.codeUnitAt(offset + 1);
if (nextCodeUnit == null) if (nextCodeUnit == null)
return null; return null;
int nextRuneOffset = _isUtf16Surrogate(nextCodeUnit) ? offset + 2 : offset + 1; final int nextRuneOffset = _isUtf16Surrogate(nextCodeUnit) ? offset + 2 : offset + 1;
List<ui.TextBox> boxes = _paragraph.getBoxesForRange(offset, nextRuneOffset); final List<ui.TextBox> boxes = _paragraph.getBoxesForRange(offset, nextRuneOffset);
if (boxes.isEmpty) if (boxes.isEmpty)
return null; return null;
ui.TextBox box = boxes[0]; final ui.TextBox box = boxes[0];
double caretStart = box.start; final double caretStart = box.start;
double dx = box.direction == TextDirection.rtl ? caretStart - caretPrototype.width : caretStart; final double dx = box.direction == TextDirection.rtl ? caretStart - caretPrototype.width : caretStart;
return new Offset(dx, box.top); return new Offset(dx, box.top);
} }
@ -323,7 +323,7 @@ class TextPainter {
/// Valid only after [layout] has been called. /// Valid only after [layout] has been called.
Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) { Offset getOffsetForCaret(TextPosition position, Rect caretPrototype) {
assert(!_needsLayout); assert(!_needsLayout);
int offset = position.offset; final int offset = position.offset;
// TODO(abarth): Handle the directionality of the text painter itself. // TODO(abarth): Handle the directionality of the text painter itself.
const Offset emptyOffset = Offset.zero; const Offset emptyOffset = Offset.zero;
switch (position.affinity) { switch (position.affinity) {
@ -365,7 +365,7 @@ class TextPainter {
/// <http://www.unicode.org/reports/tr29/#Word_Boundaries>. /// <http://www.unicode.org/reports/tr29/#Word_Boundaries>.
TextRange getWordBoundary(TextPosition position) { TextRange getWordBoundary(TextPosition position) {
assert(!_needsLayout); assert(!_needsLayout);
List<int> indices = _paragraph.getWordBoundary(position.offset); final List<int> indices = _paragraph.getWordBoundary(position.offset);
return new TextRange(start: indices[0], end: indices[1]); return new TextRange(start: indices[0], end: indices[1]);
} }
} }

View File

@ -128,13 +128,13 @@ class TextSpan {
/// Returns the text span that contains the given position in the text. /// Returns the text span that contains the given position in the text.
TextSpan getSpanForPosition(TextPosition position) { TextSpan getSpanForPosition(TextPosition position) {
assert(debugAssertIsValid()); assert(debugAssertIsValid());
TextAffinity affinity = position.affinity; final TextAffinity affinity = position.affinity;
int targetOffset = position.offset; final int targetOffset = position.offset;
int offset = 0; int offset = 0;
TextSpan result; TextSpan result;
visitTextSpan((TextSpan span) { visitTextSpan((TextSpan span) {
assert(result == null); assert(result == null);
int endOffset = offset + span.text.length; final int endOffset = offset + span.text.length;
if (targetOffset == offset && affinity == TextAffinity.downstream || if (targetOffset == offset && affinity == TextAffinity.downstream ||
targetOffset > offset && targetOffset < endOffset || targetOffset > offset && targetOffset < endOffset ||
targetOffset == endOffset && affinity == TextAffinity.upstream) { targetOffset == endOffset && affinity == TextAffinity.upstream) {
@ -152,7 +152,7 @@ class TextSpan {
/// Styles are not honored in this process. /// Styles are not honored in this process.
String toPlainText() { String toPlainText() {
assert(debugAssertIsValid()); assert(debugAssertIsValid());
StringBuffer buffer = new StringBuffer(); final StringBuffer buffer = new StringBuffer();
visitTextSpan((TextSpan span) { visitTextSpan((TextSpan span) {
buffer.write(span.text); buffer.write(span.text);
return true; return true;
@ -180,9 +180,9 @@ class TextSpan {
@override @override
String toString([String prefix = '']) { String toString([String prefix = '']) {
StringBuffer buffer = new StringBuffer(); final StringBuffer buffer = new StringBuffer();
buffer.writeln('$prefix$runtimeType:'); buffer.writeln('$prefix$runtimeType:');
String indent = '$prefix '; final String indent = '$prefix ';
if (style != null) if (style != null)
buffer.writeln(style.toString(indent)); buffer.writeln(style.toString(indent));
if (text != null) if (text != null)

View File

@ -290,7 +290,7 @@ class TextStyle {
@override @override
String toString([String prefix = '']) { String toString([String prefix = '']) {
List<String> result = <String>[]; final List<String> result = <String>[];
result.add('${prefix}inherit: $inherit'); result.add('${prefix}inherit: $inherit');
if (color != null) if (color != null)
result.add('${prefix}color: $color'); result.add('${prefix}color: $color');

View File

@ -19,7 +19,7 @@ class MatrixUtils {
/// Otherwise, returns null. /// Otherwise, returns null.
static Offset getAsTranslation(Matrix4 transform) { static Offset getAsTranslation(Matrix4 transform) {
assert(transform != null); assert(transform != null);
Float64List values = transform.storage; final Float64List values = transform.storage;
// Values are stored in column-major order. // Values are stored in column-major order.
if (values[0] == 1.0 && // col 1 if (values[0] == 1.0 && // col 1
values[1] == 0.0 && values[1] == 0.0 &&
@ -95,8 +95,8 @@ class MatrixUtils {
/// This function assumes the given point has a z-coordinate of 0.0. The /// This function assumes the given point has a z-coordinate of 0.0. The
/// z-coordinate of the result is ignored. /// z-coordinate of the result is ignored.
static Point transformPoint(Matrix4 transform, Point point) { static Point transformPoint(Matrix4 transform, Point point) {
Vector3 position3 = new Vector3(point.x, point.y, 0.0); final Vector3 position3 = new Vector3(point.x, point.y, 0.0);
Vector3 transformed3 = transform.perspectiveTransform(position3); final Vector3 transformed3 = transform.perspectiveTransform(position3);
return new Point(transformed3.x, transformed3.y); return new Point(transformed3.x, transformed3.y);
} }
@ -107,10 +107,10 @@ class MatrixUtils {
/// The transformed rect is then projected back into the plane with z equals /// The transformed rect is then projected back into the plane with z equals
/// 0.0 before computing its bounding rect. /// 0.0 before computing its bounding rect.
static Rect transformRect(Matrix4 transform, Rect rect) { static Rect transformRect(Matrix4 transform, Rect rect) {
Point point1 = transformPoint(transform, rect.topLeft); final Point point1 = transformPoint(transform, rect.topLeft);
Point point2 = transformPoint(transform, rect.topRight); final Point point2 = transformPoint(transform, rect.topRight);
Point point3 = transformPoint(transform, rect.bottomLeft); final Point point3 = transformPoint(transform, rect.bottomLeft);
Point point4 = transformPoint(transform, rect.bottomRight); final Point point4 = transformPoint(transform, rect.bottomRight);
return new Rect.fromLTRB( return new Rect.fromLTRB(
_min4(point1.x, point2.x, point3.x, point4.x), _min4(point1.x, point2.x, point3.x, point4.x),
_min4(point1.y, point2.y, point3.y, point4.y), _min4(point1.y, point2.y, point3.y, point4.y),

View File

@ -153,7 +153,7 @@ abstract class _SpringSolution {
assert(spring.damping != null); assert(spring.damping != null);
assert(initialPosition != null); assert(initialPosition != null);
assert(initialVelocity != null); assert(initialVelocity != null);
double cmk = spring.damping * spring.damping - 4 * spring.mass * spring.springConstant; final double cmk = spring.damping * spring.damping - 4 * spring.mass * spring.springConstant;
if (cmk == 0.0) if (cmk == 0.0)
return new _CriticalSolution(spring, initialPosition, initialVelocity); return new _CriticalSolution(spring, initialPosition, initialVelocity);
if (cmk > 0.0) if (cmk > 0.0)

View File

@ -74,7 +74,7 @@ abstract class RendererBinding extends BindingBase implements SchedulerBinding,
name: 'repaintRainbow', name: 'repaintRainbow',
getter: () async => debugRepaintRainbowEnabled, getter: () async => debugRepaintRainbowEnabled,
setter: (bool value) { setter: (bool value) {
bool repaint = debugRepaintRainbowEnabled && !value; final bool repaint = debugRepaintRainbowEnabled && !value;
debugRepaintRainbowEnabled = value; debugRepaintRainbowEnabled = value;
if (repaint) if (repaint)
return _forceRepaint(); return _forceRepaint();

View File

@ -62,10 +62,10 @@ class RenderBlock extends RenderBox
} }
double get _mainAxisExtent { double get _mainAxisExtent {
RenderBox child = lastChild; final RenderBox child = lastChild;
if (child == null) if (child == null)
return 0.0; return 0.0;
BoxParentData parentData = child.parentData; final BoxParentData parentData = child.parentData;
assert(mainAxis != null); assert(mainAxis != null);
switch (mainAxis) { switch (mainAxis) {
case Axis.horizontal: case Axis.horizontal:
@ -122,7 +122,7 @@ class RenderBlock extends RenderBox
'This is relatively expensive, however.' // (that's why we don't do it automatically) 'This is relatively expensive, however.' // (that's why we don't do it automatically)
); );
}); });
BoxConstraints innerConstraints = _getInnerConstraints(constraints); final BoxConstraints innerConstraints = _getInnerConstraints(constraints);
double position = 0.0; double position = 0.0;
RenderBox child = firstChild; RenderBox child = firstChild;
while (child != null) { while (child != null) {

View File

@ -245,7 +245,7 @@ class BoxConstraints extends Constraints {
double height = size.height; double height = size.height;
assert(width > 0.0); assert(width > 0.0);
assert(height > 0.0); assert(height > 0.0);
double aspectRatio = width / height; final double aspectRatio = width / height;
if (width > maxWidth) { if (width > maxWidth) {
width = maxWidth; width = maxWidth;
@ -387,13 +387,13 @@ class BoxConstraints extends Constraints {
}) { }) {
assert(() { assert(() {
void throwError(String message) { void throwError(String message) {
StringBuffer information = new StringBuffer(); final StringBuffer information = new StringBuffer();
if (informationCollector != null) if (informationCollector != null)
informationCollector(information); informationCollector(information);
throw new FlutterError('$message\n${information}The offending constraints were:\n $this'); throw new FlutterError('$message\n${information}The offending constraints were:\n $this');
} }
if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) { if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) {
List<String> affectedFieldsList = <String>[]; final List<String> affectedFieldsList = <String>[];
if (minWidth.isNaN) if (minWidth.isNaN)
affectedFieldsList.add('minWidth'); affectedFieldsList.add('minWidth');
if (maxWidth.isNaN) if (maxWidth.isNaN)
@ -481,7 +481,7 @@ class BoxConstraints extends Constraints {
@override @override
String toString() { String toString() {
String annotation = isNormalized ? '' : '; NOT NORMALIZED'; final String annotation = isNormalized ? '' : '; NOT NORMALIZED';
if (minWidth == double.INFINITY && minHeight == double.INFINITY) if (minWidth == double.INFINITY && minHeight == double.INFINITY)
return 'BoxConstraints(biggest$annotation)'; return 'BoxConstraints(biggest$annotation)';
if (minWidth == 0 && maxWidth == double.INFINITY && if (minWidth == 0 && maxWidth == double.INFINITY &&
@ -1466,7 +1466,7 @@ abstract class RenderBox extends RenderObject {
return false; return false;
}); });
assert(_debugSetDoingBaseline(true)); assert(_debugSetDoingBaseline(true));
double result = getDistanceToActualBaseline(baseline); final double result = getDistanceToActualBaseline(baseline);
assert(_debugSetDoingBaseline(false)); assert(_debugSetDoingBaseline(false));
if (result == null && !onlyReal) if (result == null && !onlyReal)
return size.height; return size.height;
@ -1534,14 +1534,14 @@ abstract class RenderBox extends RenderObject {
} }
// verify that the size is not infinite // verify that the size is not infinite
if (_size.isInfinite) { if (_size.isInfinite) {
StringBuffer information = new StringBuffer(); final StringBuffer information = new StringBuffer();
if (!constraints.hasBoundedWidth) { if (!constraints.hasBoundedWidth) {
RenderBox node = this; RenderBox node = this;
while (!node.constraints.hasBoundedWidth && node.parent is RenderBox) while (!node.constraints.hasBoundedWidth && node.parent is RenderBox)
node = node.parent; node = node.parent;
information.writeln('The nearest ancestor providing an unbounded width constraint is:'); information.writeln('The nearest ancestor providing an unbounded width constraint is:');
information.writeln(' $node'); information.writeln(' $node');
List<String> description = <String>[]; final List<String> description = <String>[];
node.debugFillDescription(description); node.debugFillDescription(description);
for (String line in description) for (String line in description)
information.writeln(' $line'); information.writeln(' $line');
@ -1552,7 +1552,7 @@ abstract class RenderBox extends RenderObject {
node = node.parent; node = node.parent;
information.writeln('The nearest ancestor providing an unbounded height constraint is:'); information.writeln('The nearest ancestor providing an unbounded height constraint is:');
information.writeln(' $node'); information.writeln(' $node');
List<String> description = <String>[]; final List<String> description = <String>[];
node.debugFillDescription(description); node.debugFillDescription(description);
for (String line in description) for (String line in description)
information.writeln(' $line'); information.writeln(' $line');
@ -1584,7 +1584,7 @@ abstract class RenderBox extends RenderObject {
// verify that the intrinsics are sane // verify that the intrinsics are sane
assert(!RenderObject.debugCheckingIntrinsics); assert(!RenderObject.debugCheckingIntrinsics);
RenderObject.debugCheckingIntrinsics = true; RenderObject.debugCheckingIntrinsics = true;
StringBuffer failures = new StringBuffer(); final StringBuffer failures = new StringBuffer();
int failureCount = 0; int failureCount = 0;
double testIntrinsic(double function(double extent), String name, double constraint) { double testIntrinsic(double function(double extent), String name, double constraint) {
@ -1813,7 +1813,7 @@ abstract class RenderBox extends RenderObject {
/// object) instead of from the global coordinate system. /// object) instead of from the global coordinate system.
Point globalToLocal(Point point, { RenderObject ancestor }) { Point globalToLocal(Point point, { RenderObject ancestor }) {
final Matrix4 transform = getTransformTo(ancestor); final Matrix4 transform = getTransformTo(ancestor);
double det = transform.invert(); final double det = transform.invert();
if (det == 0.0) if (det == 0.0)
return Point.origin; return Point.origin;
return MatrixUtils.transformPoint(transform, point); return MatrixUtils.transformPoint(transform, point);
@ -1918,7 +1918,7 @@ abstract class RenderBox extends RenderObject {
@protected @protected
void debugPaintSize(PaintingContext context, Offset offset) { void debugPaintSize(PaintingContext context, Offset offset) {
assert(() { assert(() {
Paint paint = new Paint() final Paint paint = new Paint()
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 1.0 ..strokeWidth = 1.0
..color = debugPaintSizeColor; ..color = debugPaintSizeColor;
@ -1933,12 +1933,12 @@ abstract class RenderBox extends RenderObject {
@protected @protected
void debugPaintBaselines(PaintingContext context, Offset offset) { void debugPaintBaselines(PaintingContext context, Offset offset) {
assert(() { assert(() {
Paint paint = new Paint() final Paint paint = new Paint()
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 0.25; ..strokeWidth = 0.25;
Path path; Path path;
// ideographic baseline // ideographic baseline
double baselineI = getDistanceToBaseline(TextBaseline.ideographic, onlyReal: true); final double baselineI = getDistanceToBaseline(TextBaseline.ideographic, onlyReal: true);
if (baselineI != null) { if (baselineI != null) {
paint.color = debugPaintIdeographicBaselineColor; paint.color = debugPaintIdeographicBaselineColor;
path = new Path(); path = new Path();
@ -1947,7 +1947,7 @@ abstract class RenderBox extends RenderObject {
context.canvas.drawPath(path, paint); context.canvas.drawPath(path, paint);
} }
// alphabetic baseline // alphabetic baseline
double baselineA = getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true); final double baselineA = getDistanceToBaseline(TextBaseline.alphabetic, onlyReal: true);
if (baselineA != null) { if (baselineA != null) {
paint.color = debugPaintAlphabeticBaselineColor; paint.color = debugPaintAlphabeticBaselineColor;
path = new Path(); path = new Path();
@ -1970,7 +1970,7 @@ abstract class RenderBox extends RenderObject {
void debugPaintPointers(PaintingContext context, Offset offset) { void debugPaintPointers(PaintingContext context, Offset offset) {
assert(() { assert(() {
if (_debugActivePointers > 0) { if (_debugActivePointers > 0) {
Paint paint = new Paint() final Paint paint = new Paint()
..color = new Color(debugPaintPointersColorValue | ((0x04000000 * depth) & 0xFF000000)); ..color = new Color(debugPaintPointersColorValue | ((0x04000000 * depth) & 0xFF000000));
context.canvas.drawRect(offset & size, paint); context.canvas.drawRect(offset & size, paint);
} }
@ -2002,7 +2002,7 @@ abstract class RenderBoxContainerDefaultsMixin<ChildType extends RenderBox, Pare
ChildType child = firstChild; ChildType child = firstChild;
while (child != null) { while (child != null) {
final ParentDataType childParentData = child.parentData; final ParentDataType childParentData = child.parentData;
double result = child.getDistanceToActualBaseline(baseline); final double result = child.getDistanceToActualBaseline(baseline);
if (result != null) if (result != null)
return result + childParentData.offset.dy; return result + childParentData.offset.dy;
child = childParentData.nextSibling; child = childParentData.nextSibling;
@ -2042,7 +2042,7 @@ abstract class RenderBoxContainerDefaultsMixin<ChildType extends RenderBox, Pare
ChildType child = lastChild; ChildType child = lastChild;
while (child != null) { while (child != null) {
final ParentDataType childParentData = child.parentData; final ParentDataType childParentData = child.parentData;
Point transformed = new Point(position.x - childParentData.offset.dx, final Point transformed = new Point(position.x - childParentData.offset.dx,
position.y - childParentData.offset.dy); position.y - childParentData.offset.dy);
if (child.hitTest(result, position: transformed)) if (child.hitTest(result, position: transformed))
return true; return true;

View File

@ -117,7 +117,7 @@ bool debugProfilePaintsEnabled = false;
/// Returns a list of strings representing the given transform in a format useful for [RenderObject.debugFillDescription]. /// Returns a list of strings representing the given transform in a format useful for [RenderObject.debugFillDescription].
List<String> debugDescribeTransform(Matrix4 transform) { List<String> debugDescribeTransform(Matrix4 transform) {
List<String> matrix = transform.toString().split('\n').map((String s) => ' $s').toList(); final List<String> matrix = transform.toString().split('\n').map((String s) => ' $s').toList();
matrix.removeLast(); matrix.removeLast();
return matrix; return matrix;
} }

View File

@ -302,7 +302,7 @@ class RenderEditable extends RenderBox {
final Point globalPosition = _lastTapDownPosition; final Point globalPosition = _lastTapDownPosition;
_lastTapDownPosition = null; _lastTapDownPosition = null;
if (onSelectionChanged != null) { if (onSelectionChanged != null) {
TextPosition position = _textPainter.getPositionForOffset(globalToLocal(globalPosition).toOffset()); final TextPosition position = _textPainter.getPositionForOffset(globalToLocal(globalPosition).toOffset());
onSelectionChanged(new TextSelection.fromPosition(position), this, false); onSelectionChanged(new TextSelection.fromPosition(position), this, false);
} }
} }

View File

@ -43,7 +43,7 @@ class RenderErrorBox extends RenderBox {
// Generally, the much better way to draw text in a RenderObject is to // Generally, the much better way to draw text in a RenderObject is to
// use the TextPainter class. If you're looking for code to crib from, // use the TextPainter class. If you're looking for code to crib from,
// see the paragraph.dart file and the RenderParagraph class. // see the paragraph.dart file and the RenderParagraph class.
ui.ParagraphBuilder builder = new ui.ParagraphBuilder(paragraphStyle); final ui.ParagraphBuilder builder = new ui.ParagraphBuilder(paragraphStyle);
builder.pushStyle(textStyle); builder.pushStyle(textStyle);
builder.addText( builder.addText(
'$message$_kLine$message$_kLine$message$_kLine$message$_kLine$message$_kLine$message$_kLine' '$message$_kLine$message$_kLine$message$_kLine$message$_kLine$message$_kLine$message$_kLine'
@ -105,7 +105,7 @@ class RenderErrorBox extends RenderBox {
// See the comment in the RenderErrorBox constructor. This is not the // See the comment in the RenderErrorBox constructor. This is not the
// code you want to be copying and pasting. :-) // code you want to be copying and pasting. :-)
if (parent is RenderBox) { if (parent is RenderBox) {
RenderBox parentBox = parent; final RenderBox parentBox = parent;
width = parentBox.size.width; width = parentBox.size.width;
} else { } else {
width = size.width; width = size.width;

View File

@ -247,10 +247,10 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin<RenderBox, Fl
double maxFlexFractionSoFar = 0.0; double maxFlexFractionSoFar = 0.0;
RenderBox child = firstChild; RenderBox child = firstChild;
while (child != null) { while (child != null) {
int flex = _getFlex(child); final int flex = _getFlex(child);
totalFlex += flex; totalFlex += flex;
if (flex > 0) { if (flex > 0) {
double flexFraction = childSize(child, extent) / _getFlex(child); final double flexFraction = childSize(child, extent) / _getFlex(child);
maxFlexFractionSoFar = math.max(maxFlexFractionSoFar, flexFraction); maxFlexFractionSoFar = math.max(maxFlexFractionSoFar, flexFraction);
} else { } else {
inflexibleSpace += childSize(child, extent); inflexibleSpace += childSize(child, extent);
@ -267,13 +267,13 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin<RenderBox, Fl
// TODO(ianh): Support baseline alignment. // TODO(ianh): Support baseline alignment.
// Get inflexible space using the max intrinsic dimensions of fixed children in the main direction. // Get inflexible space using the max intrinsic dimensions of fixed children in the main direction.
double availableMainSpace = extent; final double availableMainSpace = extent;
int totalFlex = 0; int totalFlex = 0;
double inflexibleSpace = 0.0; double inflexibleSpace = 0.0;
double maxCrossSize = 0.0; double maxCrossSize = 0.0;
RenderBox child = firstChild; RenderBox child = firstChild;
while (child != null) { while (child != null) {
int flex = _getFlex(child); final int flex = _getFlex(child);
totalFlex += flex; totalFlex += flex;
double mainSize; double mainSize;
double crossSize; double crossSize;
@ -297,13 +297,13 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin<RenderBox, Fl
// Determine the spacePerFlex by allocating the remaining available space. // Determine the spacePerFlex by allocating the remaining available space.
// When you're overconstrained spacePerFlex can be negative. // When you're overconstrained spacePerFlex can be negative.
double spacePerFlex = math.max(0.0, final double spacePerFlex = math.max(0.0,
(availableMainSpace - inflexibleSpace) / totalFlex); (availableMainSpace - inflexibleSpace) / totalFlex);
// Size remaining (flexible) items, find the maximum cross size. // Size remaining (flexible) items, find the maximum cross size.
child = firstChild; child = firstChild;
while (child != null) { while (child != null) {
int flex = _getFlex(child); final int flex = _getFlex(child);
if (flex > 0) if (flex > 0)
maxCrossSize = math.max(maxCrossSize, childSize(child, spacePerFlex * flex)); maxCrossSize = math.max(maxCrossSize, childSize(child, spacePerFlex * flex));
final FlexParentData childParentData = child.parentData; final FlexParentData childParentData = child.parentData;
@ -404,7 +404,7 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin<RenderBox, Fl
'if it is in a $axis scrollable, it will try to shrink-wrap its children along the $axis ' 'if it is in a $axis scrollable, it will try to shrink-wrap its children along the $axis '
'axis. Setting a flex on a child (e.g. using a Flexible) indicates that the child is to ' 'axis. Setting a flex on a child (e.g. using a Flexible) indicates that the child is to '
'expand to fill the remaining space in the $axis direction.'; 'expand to fill the remaining space in the $axis direction.';
StringBuffer information = new StringBuffer(); final StringBuffer information = new StringBuffer();
RenderBox node = this; RenderBox node = this;
switch (_direction) { switch (_direction) {
case Axis.horizontal: case Axis.horizontal:
@ -423,7 +423,7 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin<RenderBox, Fl
if (node != null) { if (node != null) {
information.writeln('The nearest ancestor providing an unbounded width constraint is:'); information.writeln('The nearest ancestor providing an unbounded width constraint is:');
information.writeln(' $node'); information.writeln(' $node');
List<String> description = <String>[]; final List<String> description = <String>[];
node.debugFillDescription(description); node.debugFillDescription(description);
for (String line in description) for (String line in description)
information.writeln(' $line'); information.writeln(' $line');
@ -543,7 +543,7 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin<RenderBox, Fl
throw new FlutterError('To use FlexAlignItems.baseline, you must also specify which baseline to use using the "baseline" argument.'); throw new FlutterError('To use FlexAlignItems.baseline, you must also specify which baseline to use using the "baseline" argument.');
return true; return true;
}); });
double distance = child.getDistanceToBaseline(textBaseline, onlyReal: true); final double distance = child.getDistanceToBaseline(textBaseline, onlyReal: true);
if (distance != null) if (distance != null)
maxBaselineDistance = math.max(maxBaselineDistance, distance); maxBaselineDistance = math.max(maxBaselineDistance, distance);
} }
@ -638,7 +638,7 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin<RenderBox, Fl
childCrossPosition = 0.0; childCrossPosition = 0.0;
if (_direction == Axis.horizontal) { if (_direction == Axis.horizontal) {
assert(textBaseline != null); assert(textBaseline != null);
double distance = child.getDistanceToBaseline(textBaseline, onlyReal: true); final double distance = child.getDistanceToBaseline(textBaseline, onlyReal: true);
if (distance != null) if (distance != null)
childCrossPosition = maxBaselineDistance - distance; childCrossPosition = maxBaselineDistance - distance;
} }
@ -681,8 +681,8 @@ class RenderFlex extends RenderBox with ContainerRenderObjectMixin<RenderBox, Fl
// If you do want clipping, use a RenderClip (Clip in the // If you do want clipping, use a RenderClip (Clip in the
// Widgets library). // Widgets library).
Paint markerPaint = new Paint()..color = const Color(0xE0FF0000); final Paint markerPaint = new Paint()..color = const Color(0xE0FF0000);
Paint highlightPaint = new Paint()..color = const Color(0x7FFF0000); final Paint highlightPaint = new Paint()..color = const Color(0x7FFF0000);
const double kMarkerSize = 0.1; const double kMarkerSize = 0.1;
Rect markerRect, overflowRect; Rect markerRect, overflowRect;
switch(direction) { switch(direction) {

View File

@ -285,7 +285,7 @@ class RenderFlow extends RenderBox
RenderBox child = firstChild; RenderBox child = firstChild;
while (child != null) { while (child != null) {
_randomAccessChildren.add(child); _randomAccessChildren.add(child);
BoxConstraints innerConstraints = _delegate.getConstraintsForChild(i, constraints); final BoxConstraints innerConstraints = _delegate.getConstraintsForChild(i, constraints);
child.layout(innerConstraints, parentUsesSize: true); child.layout(innerConstraints, parentUsesSize: true);
final FlowParentData childParentData = child.parentData; final FlowParentData childParentData = child.parentData;
childParentData.offset = Offset.zero; childParentData.offset = Offset.zero;
@ -314,7 +314,7 @@ class RenderFlow extends RenderBox
@override @override
void paintChild(int i, { Matrix4 transform, double opacity: 1.0 }) { void paintChild(int i, { Matrix4 transform, double opacity: 1.0 }) {
transform ??= new Matrix4.identity(); transform ??= new Matrix4.identity();
RenderBox child = _randomAccessChildren[i]; final RenderBox child = _randomAccessChildren[i];
final FlowParentData childParentData = child.parentData; final FlowParentData childParentData = child.parentData;
assert(() { assert(() {
if (childParentData._transform != null) { if (childParentData._transform != null) {

View File

@ -84,11 +84,11 @@ abstract class Layer {
String result = '$prefixLineOne$this\n'; String result = '$prefixLineOne$this\n';
final String childrenDescription = debugDescribeChildren(prefixOtherLines); final String childrenDescription = debugDescribeChildren(prefixOtherLines);
final String descriptionPrefix = childrenDescription != '' ? '$prefixOtherLines \u2502 ' : '$prefixOtherLines '; final String descriptionPrefix = childrenDescription != '' ? '$prefixOtherLines \u2502 ' : '$prefixOtherLines ';
List<String> description = <String>[]; final List<String> description = <String>[];
debugFillDescription(description); debugFillDescription(description);
result += description.map((String description) => "$descriptionPrefix$description\n").join(); result += description.map((String description) => "$descriptionPrefix$description\n").join();
if (childrenDescription == '') { if (childrenDescription == '') {
String prefix = prefixOtherLines.trimRight(); final String prefix = prefixOtherLines.trimRight();
if (prefix != '') if (prefix != '')
result += '$prefix\n'; result += '$prefix\n';
} else { } else {
@ -258,7 +258,7 @@ class ContainerLayer extends Layer {
void removeAllChildren() { void removeAllChildren() {
Layer child = _firstChild; Layer child = _firstChild;
while (child != null) { while (child != null) {
Layer next = child.nextSibling; final Layer next = child.nextSibling;
child._previousSibling = null; child._previousSibling = null;
child._nextSibling = null; child._nextSibling = null;
child._parent = null; child._parent = null;

View File

@ -83,7 +83,7 @@ class PaintingContext {
child._layer.debugCreator = child.debugCreator ?? child.runtimeType; child._layer.debugCreator = child.debugCreator ?? child.runtimeType;
return true; return true;
}); });
PaintingContext childContext = new PaintingContext._(child._layer, child.paintBounds); final PaintingContext childContext = new PaintingContext._(child._layer, child.paintBounds);
child._paintWithContext(childContext, Offset.zero); child._paintWithContext(childContext, Offset.zero);
childContext._stopRecordingIfNeeded(); childContext._stopRecordingIfNeeded();
} }
@ -186,14 +186,14 @@ class PaintingContext {
return; return;
assert(() { assert(() {
if (debugRepaintRainbowEnabled) { if (debugRepaintRainbowEnabled) {
Paint paint = new Paint() final Paint paint = new Paint()
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 6.0 ..strokeWidth = 6.0
..color = debugCurrentRepaintColor.toColor(); ..color = debugCurrentRepaintColor.toColor();
canvas.drawRect(_paintBounds.deflate(3.0), paint); canvas.drawRect(_paintBounds.deflate(3.0), paint);
} }
if (debugPaintLayerBordersEnabled) { if (debugPaintLayerBordersEnabled) {
Paint paint = new Paint() final Paint paint = new Paint()
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 1.0 ..strokeWidth = 1.0
..color = debugPaintLayerBordersColor; ..color = debugPaintLayerBordersColor;
@ -582,14 +582,14 @@ class _SemanticsGeometry {
Matrix4 transform; Matrix4 transform;
void applyAncestorChain(List<RenderObject> ancestorChain) { void applyAncestorChain(List<RenderObject> ancestorChain) {
for (int index = ancestorChain.length-1; index > 0; index -= 1) { for (int index = ancestorChain.length-1; index > 0; index -= 1) {
RenderObject parent = ancestorChain[index]; final RenderObject parent = ancestorChain[index];
RenderObject child = ancestorChain[index-1]; final RenderObject child = ancestorChain[index-1];
clipRect = _intersectClipRect(parent.describeApproximatePaintClip(child)); clipRect = _intersectClipRect(parent.describeApproximatePaintClip(child));
if (clipRect != null) { if (clipRect != null) {
if (clipRect.isEmpty) { if (clipRect.isEmpty) {
clipRect = Rect.zero; clipRect = Rect.zero;
} else { } else {
Matrix4 clipTransform = new Matrix4.identity(); final Matrix4 clipTransform = new Matrix4.identity();
parent.applyPaintTransform(child, clipTransform); parent.applyPaintTransform(child, clipTransform);
clipRect = MatrixUtils.inverseTransformRect(clipTransform, clipRect); clipRect = MatrixUtils.inverseTransformRect(clipTransform, clipRect);
} }
@ -623,7 +623,7 @@ abstract class _SemanticsFragment {
assert(() { assert(() {
if (children == null) if (children == null)
return true; return true;
Set<_SemanticsFragment> seenChildren = new Set<_SemanticsFragment>(); final Set<_SemanticsFragment> seenChildren = new Set<_SemanticsFragment>();
for (_SemanticsFragment child in children) for (_SemanticsFragment child in children)
assert(seenChildren.add(child)); // check for duplicate adds assert(seenChildren.add(child)); // check for duplicate adds
return true; return true;
@ -663,7 +663,7 @@ class _CleanSemanticsFragment extends _SemanticsFragment {
Iterable<SemanticsNode> compile({ _SemanticsGeometry geometry, SemanticsNode currentSemantics, SemanticsNode parentSemantics }) sync* { Iterable<SemanticsNode> compile({ _SemanticsGeometry geometry, SemanticsNode currentSemantics, SemanticsNode parentSemantics }) sync* {
assert(!_debugCompiled); assert(!_debugCompiled);
assert(() { _debugCompiled = true; return true; }); assert(() { _debugCompiled = true; return true; });
SemanticsNode node = renderObjectOwner._semantics; final SemanticsNode node = renderObjectOwner._semantics;
assert(node != null); assert(node != null);
if (geometry != null) { if (geometry != null) {
geometry.applyAncestorChain(_ancestorChain); geometry.applyAncestorChain(_ancestorChain);
@ -688,7 +688,7 @@ abstract class _InterestingSemanticsFragment extends _SemanticsFragment {
Iterable<SemanticsNode> compile({ _SemanticsGeometry geometry, SemanticsNode currentSemantics, SemanticsNode parentSemantics }) sync* { Iterable<SemanticsNode> compile({ _SemanticsGeometry geometry, SemanticsNode currentSemantics, SemanticsNode parentSemantics }) sync* {
assert(!_debugCompiled); assert(!_debugCompiled);
assert(() { _debugCompiled = true; return true; }); assert(() { _debugCompiled = true; return true; });
SemanticsNode node = establishSemanticsNode(geometry, currentSemantics, parentSemantics); final SemanticsNode node = establishSemanticsNode(geometry, currentSemantics, parentSemantics);
if (annotator != null) if (annotator != null)
annotator(node); annotator(node);
for (_SemanticsFragment child in _children) { for (_SemanticsFragment child in _children) {
@ -726,7 +726,7 @@ class _RootSemanticsFragment extends _InterestingSemanticsFragment {
handler: renderObjectOwner is SemanticsActionHandler ? renderObjectOwner as dynamic : null, handler: renderObjectOwner is SemanticsActionHandler ? renderObjectOwner as dynamic : null,
owner: renderObjectOwner.owner.semanticsOwner owner: renderObjectOwner.owner.semanticsOwner
); );
SemanticsNode node = renderObjectOwner._semantics; final SemanticsNode node = renderObjectOwner._semantics;
assert(MatrixUtils.matrixEquals(node.transform, new Matrix4.identity())); assert(MatrixUtils.matrixEquals(node.transform, new Matrix4.identity()));
assert(!node.wasAffectedByClip); assert(!node.wasAffectedByClip);
node.rect = renderObjectOwner.semanticBounds; node.rect = renderObjectOwner.semanticBounds;
@ -751,7 +751,7 @@ class _ConcreteSemanticsFragment extends _InterestingSemanticsFragment {
renderObjectOwner._semantics ??= new SemanticsNode( renderObjectOwner._semantics ??= new SemanticsNode(
handler: renderObjectOwner is SemanticsActionHandler ? renderObjectOwner as dynamic : null handler: renderObjectOwner is SemanticsActionHandler ? renderObjectOwner as dynamic : null
); );
SemanticsNode node = renderObjectOwner._semantics; final SemanticsNode node = renderObjectOwner._semantics;
if (geometry != null) { if (geometry != null) {
geometry.applyAncestorChain(_ancestorChain); geometry.applyAncestorChain(_ancestorChain);
geometry.updateSemanticsNode(rendering: renderObjectOwner, semantics: node, parentSemantics: parentSemantics); geometry.updateSemanticsNode(rendering: renderObjectOwner, semantics: node, parentSemantics: parentSemantics);
@ -972,7 +972,7 @@ class PipelineOwner {
try { try {
// TODO(ianh): assert that we're not allowing previously dirty nodes to redirty themeselves // TODO(ianh): assert that we're not allowing previously dirty nodes to redirty themeselves
while (_nodesNeedingLayout.isNotEmpty) { while (_nodesNeedingLayout.isNotEmpty) {
List<RenderObject> dirtyNodes = _nodesNeedingLayout; final List<RenderObject> dirtyNodes = _nodesNeedingLayout;
_nodesNeedingLayout = <RenderObject>[]; _nodesNeedingLayout = <RenderObject>[];
for (RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => a.depth - b.depth)) { for (RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => a.depth - b.depth)) {
if (node._needsLayout && node.owner == this) if (node._needsLayout && node.owner == this)
@ -995,7 +995,7 @@ class PipelineOwner {
// See [RenderObject.invokeLayoutCallback]. // See [RenderObject.invokeLayoutCallback].
void _enableMutationsToDirtySubtrees(VoidCallback callback) { void _enableMutationsToDirtySubtrees(VoidCallback callback) {
assert(_debugDoingLayout); assert(_debugDoingLayout);
bool oldState = _debugAllowMutationsToDirtySubtrees; final bool oldState = _debugAllowMutationsToDirtySubtrees;
_debugAllowMutationsToDirtySubtrees = true; _debugAllowMutationsToDirtySubtrees = true;
try { try {
callback(); callback();
@ -1041,7 +1041,7 @@ class PipelineOwner {
Timeline.startSync('Paint'); Timeline.startSync('Paint');
_debugDoingPaint = true; _debugDoingPaint = true;
try { try {
List<RenderObject> dirtyNodes = _nodesNeedingPaint; final List<RenderObject> dirtyNodes = _nodesNeedingPaint;
_nodesNeedingPaint = <RenderObject>[]; _nodesNeedingPaint = <RenderObject>[];
// Sort the dirty nodes in reverse order (deepest first). // Sort the dirty nodes in reverse order (deepest first).
for (RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => b.depth - a.depth)) { for (RenderObject node in dirtyNodes..sort((RenderObject a, RenderObject b) => b.depth - a.depth)) {
@ -1337,7 +1337,7 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
informationCollector: (StringBuffer information) { informationCollector: (StringBuffer information) {
information.writeln('The following RenderObject was being processed when the exception was fired:'); information.writeln('The following RenderObject was being processed when the exception was fired:');
information.writeln(' ${toStringShallow('\n ')}'); information.writeln(' ${toStringShallow('\n ')}');
List<String> descendants = <String>[]; final List<String> descendants = <String>[];
const int maxDepth = 5; const int maxDepth = 5;
int depth = 0; int depth = 0;
const int maxLines = 25; const int maxLines = 25;
@ -1684,9 +1684,9 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
assert(constraints.debugAssertIsValid( assert(constraints.debugAssertIsValid(
isAppliedConstraint: true, isAppliedConstraint: true,
informationCollector: (StringBuffer information) { informationCollector: (StringBuffer information) {
List<String> stack = StackTrace.current.toString().split('\n'); final List<String> stack = StackTrace.current.toString().split('\n');
int targetFrame; int targetFrame;
Pattern layoutFramePattern = new RegExp(r'^#[0-9]+ +RenderObject.layout \('); final Pattern layoutFramePattern = new RegExp(r'^#[0-9]+ +RenderObject.layout \(');
for (int i = 0; i < stack.length; i += 1) { for (int i = 0; i < stack.length; i += 1) {
if (layoutFramePattern.matchAsPrefix(stack[i]) != null) { if (layoutFramePattern.matchAsPrefix(stack[i]) != null) {
targetFrame = i + 1; targetFrame = i + 1;
@ -1699,8 +1699,8 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
'function by the following function, which probably computed the ' 'function by the following function, which probably computed the '
'invalid constraints in question:' 'invalid constraints in question:'
); );
Pattern targetFramePattern = new RegExp(r'^#[0-9]+ +(.+)$'); final Pattern targetFramePattern = new RegExp(r'^#[0-9]+ +(.+)$');
Match targetFrameMatch = targetFramePattern.matchAsPrefix(stack[targetFrame]); final Match targetFrameMatch = targetFramePattern.matchAsPrefix(stack[targetFrame]);
if (targetFrameMatch != null && targetFrameMatch.groupCount > 0) { if (targetFrameMatch != null && targetFrameMatch.groupCount > 0) {
information.writeln(' ${targetFrameMatch.group(1)}'); information.writeln(' ${targetFrameMatch.group(1)}');
} else { } else {
@ -1729,7 +1729,7 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
// to itself, so it has the right internal debug values. // to itself, so it has the right internal debug values.
_debugDoingThisResize = sizedByParent; _debugDoingThisResize = sizedByParent;
_debugDoingThisLayout = !sizedByParent; _debugDoingThisLayout = !sizedByParent;
RenderObject debugPreviousActiveLayout = _debugActiveLayout; final RenderObject debugPreviousActiveLayout = _debugActiveLayout;
_debugActiveLayout = this; _debugActiveLayout = this;
debugResetSize(); debugResetSize();
_debugActiveLayout = debugPreviousActiveLayout; _debugActiveLayout = debugPreviousActiveLayout;
@ -2005,7 +2005,7 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
void _updateCompositingBits() { void _updateCompositingBits() {
if (!_needsCompositingBitsUpdate) if (!_needsCompositingBitsUpdate)
return; return;
bool oldNeedsCompositing = _needsCompositing; final bool oldNeedsCompositing = _needsCompositing;
visitChildren((RenderObject child) { visitChildren((RenderObject child) {
child._updateCompositingBits(); child._updateCompositingBits();
if (child.needsCompositing) if (child.needsCompositing)
@ -2317,9 +2317,9 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
try { try {
assert(_needsSemanticsUpdate); assert(_needsSemanticsUpdate);
assert(_semantics != null || parent is! RenderObject); assert(_semantics != null || parent is! RenderObject);
_SemanticsFragment fragment = _getSemanticsFragment(); final _SemanticsFragment fragment = _getSemanticsFragment();
assert(fragment is _InterestingSemanticsFragment); assert(fragment is _InterestingSemanticsFragment);
SemanticsNode node = fragment.compile(parentSemantics: _semantics?.parent).single; final SemanticsNode node = fragment.compile(parentSemantics: _semantics?.parent).single;
assert(node != null); assert(node != null);
assert(node == _semantics); assert(node == _semantics);
} catch (e, stack) { } catch (e, stack) {
@ -2342,7 +2342,7 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
child._needsSemanticsUpdate = true; child._needsSemanticsUpdate = true;
child._needsSemanticsGeometryUpdate = true; child._needsSemanticsGeometryUpdate = true;
} }
_SemanticsFragment fragment = child._getSemanticsFragment(); final _SemanticsFragment fragment = child._getSemanticsFragment();
if (fragment != null) { if (fragment != null) {
fragment.addAncestor(this); fragment.addAncestor(this);
children ??= <_SemanticsFragment>[]; children ??= <_SemanticsFragment>[];
@ -2352,7 +2352,7 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
}); });
_needsSemanticsUpdate = false; _needsSemanticsUpdate = false;
_needsSemanticsGeometryUpdate = false; _needsSemanticsGeometryUpdate = false;
SemanticsAnnotator annotator = semanticsAnnotator; final SemanticsAnnotator annotator = semanticsAnnotator;
if (parent is! RenderObject) if (parent is! RenderObject)
return new _RootSemanticsFragment(renderObjectOwner: this, annotator: annotator, children: children); return new _RootSemanticsFragment(renderObjectOwner: this, annotator: annotator, children: children);
if (isSemanticBoundary) if (isSemanticBoundary)
@ -2456,19 +2456,19 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
/// If the prefix argument is provided, then every line in the output /// If the prefix argument is provided, then every line in the output
/// will be prefixed by that string. /// will be prefixed by that string.
String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) { String toStringDeep([String prefixLineOne = '', String prefixOtherLines = '']) {
RenderObject debugPreviousActiveLayout = _debugActiveLayout; final RenderObject debugPreviousActiveLayout = _debugActiveLayout;
_debugActiveLayout = null; _debugActiveLayout = null;
String result = '$prefixLineOne$this\n'; String result = '$prefixLineOne$this\n';
final String childrenDescription = debugDescribeChildren(prefixOtherLines); final String childrenDescription = debugDescribeChildren(prefixOtherLines);
final String descriptionPrefix = childrenDescription != '' ? '$prefixOtherLines \u2502 ' : '$prefixOtherLines '; final String descriptionPrefix = childrenDescription != '' ? '$prefixOtherLines \u2502 ' : '$prefixOtherLines ';
List<String> description = <String>[]; final List<String> description = <String>[];
debugFillDescription(description); debugFillDescription(description);
result += description result += description
.expand((String description) => debugWordWrap(description, 65, wrapIndent: ' ')) .expand((String description) => debugWordWrap(description, 65, wrapIndent: ' '))
.map<String>((String line) => "$descriptionPrefix$line\n") .map<String>((String line) => "$descriptionPrefix$line\n")
.join(); .join();
if (childrenDescription == '') { if (childrenDescription == '') {
String prefix = prefixOtherLines.trimRight(); final String prefix = prefixOtherLines.trimRight();
if (prefix != '') if (prefix != '')
result += '$prefix\n'; result += '$prefix\n';
} else { } else {
@ -2484,11 +2484,11 @@ abstract class RenderObject extends AbstractNode implements HitTestTarget {
/// This includes the same information for this RenderObject as given by /// This includes the same information for this RenderObject as given by
/// [toStringDeep], but does not recurse to any children. /// [toStringDeep], but does not recurse to any children.
String toStringShallow([String joiner = '; ']) { String toStringShallow([String joiner = '; ']) {
RenderObject debugPreviousActiveLayout = _debugActiveLayout; final RenderObject debugPreviousActiveLayout = _debugActiveLayout;
_debugActiveLayout = null; _debugActiveLayout = null;
StringBuffer result = new StringBuffer(); final StringBuffer result = new StringBuffer();
result.write('${this}$joiner'); // TODO(ianh): https://github.com/dart-lang/sdk/issues/28206 result.write('${this}$joiner'); // TODO(ianh): https://github.com/dart-lang/sdk/issues/28206
List<String> description = <String>[]; final List<String> description = <String>[];
debugFillDescription(description); debugFillDescription(description);
result.write(description.join(joiner)); result.write(description.join(joiner));
_debugActiveLayout = debugPreviousActiveLayout; _debugActiveLayout = debugPreviousActiveLayout;
@ -2728,7 +2728,7 @@ abstract class ContainerRenderObjectMixin<ChildType extends RenderObject, Parent
ChildType child = _firstChild; ChildType child = _firstChild;
while (child != null) { while (child != null) {
final ParentDataType childParentData = child.parentData; final ParentDataType childParentData = child.parentData;
ChildType next = childParentData.nextSibling; final ChildType next = childParentData.nextSibling;
childParentData.previousSibling = null; childParentData.previousSibling = null;
childParentData.nextSibling = null; childParentData.nextSibling = null;
dropChild(child); dropChild(child);

View File

@ -126,7 +126,7 @@ class RenderParagraph extends RenderBox {
} }
void _layoutText({ double minWidth: 0.0, double maxWidth: double.INFINITY }) { void _layoutText({ double minWidth: 0.0, double maxWidth: double.INFINITY }) {
bool wrap = _softWrap || (_overflow == TextOverflow.ellipsis && maxLines == null); final bool wrap = _softWrap || (_overflow == TextOverflow.ellipsis && maxLines == null);
_textPainter.layout(minWidth: minWidth, maxWidth: wrap ? maxWidth : double.INFINITY); _textPainter.layout(minWidth: minWidth, maxWidth: wrap ? maxWidth : double.INFINITY);
} }
@ -179,9 +179,9 @@ class RenderParagraph extends RenderBox {
if (event is! PointerDownEvent) if (event is! PointerDownEvent)
return; return;
_layoutTextWithConstraints(constraints); _layoutTextWithConstraints(constraints);
Offset offset = entry.localPosition.toOffset(); final Offset offset = entry.localPosition.toOffset();
TextPosition position = _textPainter.getPositionForOffset(offset); final TextPosition position = _textPainter.getPositionForOffset(offset);
TextSpan span = _textPainter.text.getSpanForPosition(position); final TextSpan span = _textPainter.text.getSpanForPosition(position);
span?.recognizer?.addPointer(event); span?.recognizer?.addPointer(event);
} }
@ -212,7 +212,7 @@ class RenderParagraph extends RenderBox {
_overflowShader = null; _overflowShader = null;
break; break;
case TextOverflow.fade: case TextOverflow.fade:
TextPainter fadeSizePainter = new TextPainter( final TextPainter fadeSizePainter = new TextPainter(
text: new TextSpan(style: _textPainter.text.style, text: '\u2026'), text: new TextSpan(style: _textPainter.text.style, text: '\u2026'),
textScaleFactor: textScaleFactor textScaleFactor: textScaleFactor
)..layout(); )..layout();
@ -256,7 +256,7 @@ class RenderParagraph extends RenderBox {
assert(() { assert(() {
if (debugRepaintTextRainbowEnabled) { if (debugRepaintTextRainbowEnabled) {
Paint paint = new Paint() final Paint paint = new Paint()
..color = debugCurrentRepaintColor.toColor(); ..color = debugCurrentRepaintColor.toColor();
canvas.drawRect(offset & size, paint); canvas.drawRect(offset & size, paint);
} }
@ -275,7 +275,7 @@ class RenderParagraph extends RenderBox {
if (_hasVisualOverflow) { if (_hasVisualOverflow) {
if (_overflowShader != null) { if (_overflowShader != null) {
canvas.translate(offset.dx, offset.dy); canvas.translate(offset.dx, offset.dy);
Paint paint = new Paint() final Paint paint = new Paint()
..blendMode = BlendMode.modulate ..blendMode = BlendMode.modulate
..shader = _overflowShader; ..shader = _overflowShader;
canvas.drawRect(Point.origin & size, paint); canvas.drawRect(Point.origin & size, paint);

View File

@ -821,7 +821,7 @@ class RenderShaderMask extends RenderProxyBox {
void paint(PaintingContext context, Offset offset) { void paint(PaintingContext context, Offset offset) {
if (child != null) { if (child != null) {
assert(needsCompositing); assert(needsCompositing);
Rect rect = Point.origin & size; final Rect rect = Point.origin & size;
context.pushShaderMask(offset, _shaderCallback(rect), rect, _blendMode, super.paint); context.pushShaderMask(offset, _shaderCallback(rect), rect, _blendMode, super.paint);
} }
} }
@ -940,7 +940,7 @@ abstract class _RenderCustomClip<T> extends RenderProxyBox {
set clipper (CustomClipper<T> newClipper) { set clipper (CustomClipper<T> newClipper) {
if (_clipper == newClipper) if (_clipper == newClipper)
return; return;
CustomClipper<T> oldClipper = _clipper; final CustomClipper<T> oldClipper = _clipper;
_clipper = newClipper; _clipper = newClipper;
assert(newClipper != null || oldClipper != null); assert(newClipper != null || oldClipper != null);
if (newClipper == null || oldClipper == null || if (newClipper == null || oldClipper == null ||
@ -1123,9 +1123,9 @@ class RenderClipOval extends _RenderCustomClip<Rect> {
bool hitTest(HitTestResult result, { Point position }) { bool hitTest(HitTestResult result, { Point position }) {
_updateClip(); _updateClip();
assert(_clip != null); assert(_clip != null);
Point center = _clip.center; final Point center = _clip.center;
// convert the position to an offset from the center of the unit circle // convert the position to an offset from the center of the unit circle
Offset offset = new Offset((position.x - center.x) / _clip.width, final Offset offset = new Offset((position.x - center.x) / _clip.width,
(position.y - center.y) / _clip.height); (position.y - center.y) / _clip.height);
// check if the point is outside the unit circle // check if the point is outside the unit circle
if (offset.distanceSquared > 0.25) // x^2 + y^2 > r^2 if (offset.distanceSquared > 0.25) // x^2 + y^2 > r^2
@ -1265,7 +1265,7 @@ class RenderPhysicalModel extends _RenderCustomClip<RRect> {
if (_shape == BoxShape.rectangle) { if (_shape == BoxShape.rectangle) {
return _borderRadius.toRRect(Point.origin & size); return _borderRadius.toRRect(Point.origin & size);
} else { } else {
Rect rect = Point.origin & size; final Rect rect = Point.origin & size;
return new RRect.fromRectXY(rect, rect.width / 2, rect.height / 2); return new RRect.fromRectXY(rect, rect.width / 2, rect.height / 2);
} }
} }
@ -1529,7 +1529,7 @@ class RenderTransform extends RenderProxyBox {
Matrix4 get _effectiveTransform { Matrix4 get _effectiveTransform {
if (_origin == null && _alignment == null) if (_origin == null && _alignment == null)
return _transform; return _transform;
Matrix4 result = new Matrix4.identity(); final Matrix4 result = new Matrix4.identity();
if (_origin != null) if (_origin != null)
result.translate(_origin.dx, _origin.dy); result.translate(_origin.dx, _origin.dy);
Offset translation; Offset translation;
@ -1564,8 +1564,8 @@ class RenderTransform extends RenderProxyBox {
@override @override
void paint(PaintingContext context, Offset offset) { void paint(PaintingContext context, Offset offset) {
if (child != null) { if (child != null) {
Matrix4 transform = _effectiveTransform; final Matrix4 transform = _effectiveTransform;
Offset childOffset = MatrixUtils.getAsTranslation(transform); final Offset childOffset = MatrixUtils.getAsTranslation(transform);
if (childOffset == null) if (childOffset == null)
context.pushTransform(needsCompositing, offset, transform, super.paint); context.pushTransform(needsCompositing, offset, transform, super.paint);
else else
@ -1673,7 +1673,7 @@ class RenderFittedBox extends RenderProxyBox {
} }
void _paintChildWithTransform(PaintingContext context, Offset offset) { void _paintChildWithTransform(PaintingContext context, Offset offset) {
Offset childOffset = MatrixUtils.getAsTranslation(_transform); final Offset childOffset = MatrixUtils.getAsTranslation(_transform);
if (childOffset == null) if (childOffset == null)
context.pushTransform(needsCompositing, offset, _transform, super.paint); context.pushTransform(needsCompositing, offset, _transform, super.paint);
else else
@ -1950,7 +1950,7 @@ class RenderCustomPaint extends RenderProxyBox {
set painter (CustomPainter newPainter) { set painter (CustomPainter newPainter) {
if (_painter == newPainter) if (_painter == newPainter)
return; return;
CustomPainter oldPainter = _painter; final CustomPainter oldPainter = _painter;
_painter = newPainter; _painter = newPainter;
_didUpdatePainter(_painter, oldPainter); _didUpdatePainter(_painter, oldPainter);
} }
@ -1975,7 +1975,7 @@ class RenderCustomPaint extends RenderProxyBox {
set foregroundPainter (CustomPainter newPainter) { set foregroundPainter (CustomPainter newPainter) {
if (_foregroundPainter == newPainter) if (_foregroundPainter == newPainter)
return; return;
CustomPainter oldPainter = _foregroundPainter; final CustomPainter oldPainter = _foregroundPainter;
_foregroundPainter = newPainter; _foregroundPainter = newPainter;
_didUpdatePainter(_foregroundPainter, oldPainter); _didUpdatePainter(_foregroundPainter, oldPainter);
} }
@ -2057,7 +2057,7 @@ class RenderCustomPaint extends RenderProxyBox {
// Canvas class to lock the canvas at a particular save count // Canvas class to lock the canvas at a particular save count
// such that restore() fails if it would take the lock count // such that restore() fails if it would take the lock count
// below that number. // below that number.
int debugNewCanvasSaveCount = canvas.getSaveCount(); final int debugNewCanvasSaveCount = canvas.getSaveCount();
if (debugNewCanvasSaveCount > debugPreviousCanvasSaveCount) { if (debugNewCanvasSaveCount > debugPreviousCanvasSaveCount) {
throw new FlutterError( throw new FlutterError(
'The $painter custom painter called canvas.save() or canvas.saveLayer() at least ' 'The $painter custom painter called canvas.save() or canvas.saveLayer() at least '
@ -2166,7 +2166,7 @@ class RenderPointerListener extends RenderProxyBoxWithHitTestBehavior {
@override @override
void debugFillDescription(List<String> description) { void debugFillDescription(List<String> description) {
super.debugFillDescription(description); super.debugFillDescription(description);
List<String> listeners = <String>[]; final List<String> listeners = <String>[];
if (onPointerDown != null) if (onPointerDown != null)
listeners.add('down'); listeners.add('down');
if (onPointerMove != null) if (onPointerMove != null)
@ -2275,7 +2275,7 @@ class RenderRepaintBoundary extends RenderProxyBox {
if (debugSymmetricPaintCount + debugAsymmetricPaintCount == 0) { if (debugSymmetricPaintCount + debugAsymmetricPaintCount == 0) {
description.add('usefulness ratio: no metrics collected yet (never painted)'); description.add('usefulness ratio: no metrics collected yet (never painted)');
} else { } else {
double percentage = 100.0 * debugAsymmetricPaintCount / (debugSymmetricPaintCount + debugAsymmetricPaintCount); final double percentage = 100.0 * debugAsymmetricPaintCount / (debugSymmetricPaintCount + debugAsymmetricPaintCount);
String diagnosis; String diagnosis;
if (debugSymmetricPaintCount + debugAsymmetricPaintCount < 5) { if (debugSymmetricPaintCount + debugAsymmetricPaintCount < 5) {
diagnosis = 'insufficient data to draw conclusion (less than five repaints)'; diagnosis = 'insufficient data to draw conclusion (less than five repaints)';
@ -2350,7 +2350,7 @@ class RenderIgnorePointer extends RenderProxyBox {
set ignoringSemantics(bool value) { set ignoringSemantics(bool value) {
if (value == _ignoringSemantics) if (value == _ignoringSemantics)
return; return;
bool oldEffectiveValue = _effectiveIgnoringSemantics; final bool oldEffectiveValue = _effectiveIgnoringSemantics;
_ignoringSemantics = value; _ignoringSemantics = value;
if (oldEffectiveValue != _effectiveIgnoringSemantics) if (oldEffectiveValue != _effectiveIgnoringSemantics)
markNeedsSemanticsUpdate(); markNeedsSemanticsUpdate();
@ -2576,8 +2576,8 @@ class RenderSemanticsGestureHandler extends RenderProxyBox implements SemanticsA
set onTap(GestureTapCallback value) { set onTap(GestureTapCallback value) {
if (_onTap == value) if (_onTap == value)
return; return;
bool wasSemanticBoundary = isSemanticBoundary; final bool wasSemanticBoundary = isSemanticBoundary;
bool hadHandler = _onTap != null; final bool hadHandler = _onTap != null;
_onTap = value; _onTap = value;
if ((value != null) != hadHandler) if ((value != null) != hadHandler)
markNeedsSemanticsUpdate(onlyChanges: isSemanticBoundary == wasSemanticBoundary); markNeedsSemanticsUpdate(onlyChanges: isSemanticBoundary == wasSemanticBoundary);
@ -2589,8 +2589,8 @@ class RenderSemanticsGestureHandler extends RenderProxyBox implements SemanticsA
set onLongPress(GestureLongPressCallback value) { set onLongPress(GestureLongPressCallback value) {
if (_onLongPress == value) if (_onLongPress == value)
return; return;
bool wasSemanticBoundary = isSemanticBoundary; final bool wasSemanticBoundary = isSemanticBoundary;
bool hadHandler = _onLongPress != null; final bool hadHandler = _onLongPress != null;
_onLongPress = value; _onLongPress = value;
if ((value != null) != hadHandler) if ((value != null) != hadHandler)
markNeedsSemanticsUpdate(onlyChanges: isSemanticBoundary == wasSemanticBoundary); markNeedsSemanticsUpdate(onlyChanges: isSemanticBoundary == wasSemanticBoundary);
@ -2602,8 +2602,8 @@ class RenderSemanticsGestureHandler extends RenderProxyBox implements SemanticsA
set onHorizontalDragUpdate(GestureDragUpdateCallback value) { set onHorizontalDragUpdate(GestureDragUpdateCallback value) {
if (_onHorizontalDragUpdate == value) if (_onHorizontalDragUpdate == value)
return; return;
bool wasSemanticBoundary = isSemanticBoundary; final bool wasSemanticBoundary = isSemanticBoundary;
bool hadHandler = _onHorizontalDragUpdate != null; final bool hadHandler = _onHorizontalDragUpdate != null;
_onHorizontalDragUpdate = value; _onHorizontalDragUpdate = value;
if ((value != null) != hadHandler) if ((value != null) != hadHandler)
markNeedsSemanticsUpdate(onlyChanges: isSemanticBoundary == wasSemanticBoundary); markNeedsSemanticsUpdate(onlyChanges: isSemanticBoundary == wasSemanticBoundary);
@ -2615,8 +2615,8 @@ class RenderSemanticsGestureHandler extends RenderProxyBox implements SemanticsA
set onVerticalDragUpdate(GestureDragUpdateCallback value) { set onVerticalDragUpdate(GestureDragUpdateCallback value) {
if (_onVerticalDragUpdate == value) if (_onVerticalDragUpdate == value)
return; return;
bool wasSemanticBoundary = isSemanticBoundary; final bool wasSemanticBoundary = isSemanticBoundary;
bool hadHandler = _onVerticalDragUpdate != null; final bool hadHandler = _onVerticalDragUpdate != null;
_onVerticalDragUpdate = value; _onVerticalDragUpdate = value;
if ((value != null) != hadHandler) if ((value != null) != hadHandler)
markNeedsSemanticsUpdate(onlyChanges: isSemanticBoundary == wasSemanticBoundary); markNeedsSemanticsUpdate(onlyChanges: isSemanticBoundary == wasSemanticBoundary);
@ -2750,7 +2750,7 @@ class RenderSemanticsAnnotations extends RenderProxyBox {
set checked(bool value) { set checked(bool value) {
if (checked == value) if (checked == value)
return; return;
bool hadValue = checked != null; final bool hadValue = checked != null;
_checked = value; _checked = value;
markNeedsSemanticsUpdate(onlyChanges: (value != null) == hadValue); markNeedsSemanticsUpdate(onlyChanges: (value != null) == hadValue);
} }
@ -2761,7 +2761,7 @@ class RenderSemanticsAnnotations extends RenderProxyBox {
set label(String value) { set label(String value) {
if (label == value) if (label == value)
return; return;
bool hadValue = label != null; final bool hadValue = label != null;
_label = value; _label = value;
markNeedsSemanticsUpdate(onlyChanges: (value != null) == hadValue); markNeedsSemanticsUpdate(onlyChanges: (value != null) == hadValue);
} }

View File

@ -93,7 +93,7 @@ class RenderRotatedBox extends RenderBox with RenderObjectWithChildMixin<RenderB
assert(_paintTransform != null || debugNeedsLayout || child == null); assert(_paintTransform != null || debugNeedsLayout || child == null);
if (child == null || _paintTransform == null) if (child == null || _paintTransform == null)
return false; return false;
Matrix4 inverse = new Matrix4.inverted(_paintTransform); final Matrix4 inverse = new Matrix4.inverted(_paintTransform);
return child.hitTest(result, position: MatrixUtils.transformPoint(inverse, position)); return child.hitTest(result, position: MatrixUtils.transformPoint(inverse, position));
} }

View File

@ -99,7 +99,7 @@ class SemanticsData {
@override @override
String toString() { String toString() {
StringBuffer buffer = new StringBuffer(); final StringBuffer buffer = new StringBuffer();
buffer.write('$runtimeType($rect'); buffer.write('$runtimeType($rect');
if (transform != null) if (transform != null)
buffer.write('; $transform'); buffer.write('; $transform');
@ -307,7 +307,7 @@ class SemanticsNode extends AbstractNode {
/// Restore this node to its default state. /// Restore this node to its default state.
void reset() { void reset() {
bool hadInheritedMergeAllDescendantsIntoThisNode = _inheritedMergeAllDescendantsIntoThisNode; final bool hadInheritedMergeAllDescendantsIntoThisNode = _inheritedMergeAllDescendantsIntoThisNode;
_actions = 0; _actions = 0;
_flags = 0; _flags = 0;
if (hadInheritedMergeAllDescendantsIntoThisNode) if (hadInheritedMergeAllDescendantsIntoThisNode)
@ -336,7 +336,7 @@ class SemanticsNode extends AbstractNode {
return true; return true;
}); });
assert(() { assert(() {
Set<SemanticsNode> seenChildren = new Set<SemanticsNode>(); final Set<SemanticsNode> seenChildren = new Set<SemanticsNode>();
for (SemanticsNode child in _newChildren) for (SemanticsNode child in _newChildren)
assert(seenChildren.add(child)); // check for duplicate adds assert(seenChildren.add(child)); // check for duplicate adds
return true; return true;
@ -411,7 +411,7 @@ class SemanticsNode extends AbstractNode {
} }
} }
} }
List<SemanticsNode> oldChildren = _children; final List<SemanticsNode> oldChildren = _children;
_children = _newChildren; _children = _newChildren;
oldChildren?.clear(); oldChildren?.clear();
_newChildren = oldChildren; _newChildren = oldChildren;
@ -565,7 +565,7 @@ class SemanticsNode extends AbstractNode {
@override @override
String toString() { String toString() {
StringBuffer buffer = new StringBuffer(); final StringBuffer buffer = new StringBuffer();
buffer.write('$runtimeType($id'); buffer.write('$runtimeType($id');
if (_dirty) if (_dirty)
buffer.write(' (${ owner != null && owner._dirtyNodes.contains(this) ? "dirty" : "STALE; owner=$owner" })'); buffer.write(' (${ owner != null && owner._dirtyNodes.contains(this) ? "dirty" : "STALE; owner=$owner" })');
@ -595,7 +595,7 @@ class SemanticsNode extends AbstractNode {
String result = '$prefixLineOne$this\n'; String result = '$prefixLineOne$this\n';
if (_children != null && _children.isNotEmpty) { if (_children != null && _children.isNotEmpty) {
for (int index = 0; index < _children.length - 1; index += 1) { for (int index = 0; index < _children.length - 1; index += 1) {
SemanticsNode child = _children[index]; final SemanticsNode child = _children[index];
result += '${child.toStringDeep("$prefixOtherLines \u251C", "$prefixOtherLines \u2502")}'; result += '${child.toStringDeep("$prefixOtherLines \u251C", "$prefixOtherLines \u2502")}';
} }
result += '${_children.last.toStringDeep("$prefixOtherLines \u2514", "$prefixOtherLines ")}'; result += '${_children.last.toStringDeep("$prefixOtherLines \u2514", "$prefixOtherLines ")}';
@ -631,9 +631,9 @@ class SemanticsOwner extends ChangeNotifier {
void sendSemanticsUpdate() { void sendSemanticsUpdate() {
if (_dirtyNodes.isEmpty) if (_dirtyNodes.isEmpty)
return; return;
List<SemanticsNode> visitedNodes = <SemanticsNode>[]; final List<SemanticsNode> visitedNodes = <SemanticsNode>[];
while (_dirtyNodes.isNotEmpty) { while (_dirtyNodes.isNotEmpty) {
List<SemanticsNode> localDirtyNodes = _dirtyNodes.where((SemanticsNode node) => !_detachedNodes.contains(node)).toList(); final List<SemanticsNode> localDirtyNodes = _dirtyNodes.where((SemanticsNode node) => !_detachedNodes.contains(node)).toList();
_dirtyNodes.clear(); _dirtyNodes.clear();
_detachedNodes.clear(); _detachedNodes.clear();
localDirtyNodes.sort((SemanticsNode a, SemanticsNode b) => a.depth - b.depth); localDirtyNodes.sort((SemanticsNode a, SemanticsNode b) => a.depth - b.depth);
@ -669,7 +669,7 @@ class SemanticsOwner extends ChangeNotifier {
} }
} }
visitedNodes.sort((SemanticsNode a, SemanticsNode b) => a.depth - b.depth); visitedNodes.sort((SemanticsNode a, SemanticsNode b) => a.depth - b.depth);
ui.SemanticsUpdateBuilder builder = new ui.SemanticsUpdateBuilder(); final ui.SemanticsUpdateBuilder builder = new ui.SemanticsUpdateBuilder();
for (SemanticsNode node in visitedNodes) { for (SemanticsNode node in visitedNodes) {
assert(node.parent?._dirty != true); // could be null (no parent) or false (not dirty) assert(node.parent?._dirty != true); // could be null (no parent) or false (not dirty)
// The _serialize() method marks the node as not dirty, and // The _serialize() method marks the node as not dirty, and
@ -712,13 +712,13 @@ class SemanticsOwner extends ChangeNotifier {
/// this function does nothing. /// this function does nothing.
void performAction(int id, SemanticsAction action) { void performAction(int id, SemanticsAction action) {
assert(action != null); assert(action != null);
SemanticsActionHandler handler = _getSemanticsActionHandlerForId(id, action); final SemanticsActionHandler handler = _getSemanticsActionHandlerForId(id, action);
handler?.performAction(action); handler?.performAction(action);
} }
SemanticsActionHandler _getSemanticsActionHandlerForPosition(SemanticsNode node, Point position, SemanticsAction action) { SemanticsActionHandler _getSemanticsActionHandlerForPosition(SemanticsNode node, Point position, SemanticsAction action) {
if (node.transform != null) { if (node.transform != null) {
Matrix4 inverse = new Matrix4.identity(); final Matrix4 inverse = new Matrix4.identity();
if (inverse.copyInverse(node.transform) == 0.0) if (inverse.copyInverse(node.transform) == 0.0)
return null; return null;
position = MatrixUtils.transformPoint(inverse, position); position = MatrixUtils.transformPoint(inverse, position);
@ -738,7 +738,7 @@ class SemanticsOwner extends ChangeNotifier {
} }
if (node.hasChildren) { if (node.hasChildren) {
for (SemanticsNode child in node._children.reversed) { for (SemanticsNode child in node._children.reversed) {
SemanticsActionHandler handler = _getSemanticsActionHandlerForPosition(child, position, action); final SemanticsActionHandler handler = _getSemanticsActionHandlerForPosition(child, position, action);
if (handler != null) if (handler != null)
return handler; return handler;
} }
@ -755,7 +755,7 @@ class SemanticsOwner extends ChangeNotifier {
final SemanticsNode node = rootSemanticsNode; final SemanticsNode node = rootSemanticsNode;
if (node == null) if (node == null)
return; return;
SemanticsActionHandler handler = _getSemanticsActionHandlerForPosition(node, position, action); final SemanticsActionHandler handler = _getSemanticsActionHandlerForPosition(node, position, action);
handler?.performAction(action); handler?.performAction(action);
} }

View File

@ -158,7 +158,7 @@ class RenderPadding extends RenderShiftedBox {
)); ));
return; return;
} }
BoxConstraints innerConstraints = constraints.deflate(padding); final BoxConstraints innerConstraints = constraints.deflate(padding);
child.layout(innerConstraints, parentUsesSize: true); child.layout(innerConstraints, parentUsesSize: true);
final BoxParentData childParentData = child.parentData; final BoxParentData childParentData = child.parentData;
childParentData.offset = new Offset(padding.left, padding.top); childParentData.offset = new Offset(padding.left, padding.top);
@ -325,7 +325,7 @@ class RenderPositionedBox extends RenderAligningShiftedBox {
final BoxParentData childParentData = child.parentData; final BoxParentData childParentData = child.parentData;
if (childParentData.offset.dy > 0.0) { if (childParentData.offset.dy > 0.0) {
// vertical alignment arrows // vertical alignment arrows
double headSize = math.min(childParentData.offset.dy * 0.2, 10.0); final double headSize = math.min(childParentData.offset.dy * 0.2, 10.0);
path path
..moveTo(offset.dx + size.width / 2.0, offset.dy) ..moveTo(offset.dx + size.width / 2.0, offset.dy)
..relativeLineTo(0.0, childParentData.offset.dy - headSize) ..relativeLineTo(0.0, childParentData.offset.dy - headSize)
@ -343,7 +343,7 @@ class RenderPositionedBox extends RenderAligningShiftedBox {
} }
if (childParentData.offset.dx > 0.0) { if (childParentData.offset.dx > 0.0) {
// horizontal alignment arrows // horizontal alignment arrows
double headSize = math.min(childParentData.offset.dx * 0.2, 10.0); final double headSize = math.min(childParentData.offset.dx * 0.2, 10.0);
path path
..moveTo(offset.dx, offset.dy + size.height / 2.0) ..moveTo(offset.dx, offset.dy + size.height / 2.0)
..relativeLineTo(childParentData.offset.dx - headSize, 0.0) ..relativeLineTo(childParentData.offset.dx - headSize, 0.0)
@ -614,14 +614,14 @@ class RenderFractionallySizedOverflowBox extends RenderAligningShiftedBox {
double minWidth = constraints.minWidth; double minWidth = constraints.minWidth;
double maxWidth = constraints.maxWidth; double maxWidth = constraints.maxWidth;
if (_widthFactor != null) { if (_widthFactor != null) {
double width = maxWidth * _widthFactor; final double width = maxWidth * _widthFactor;
minWidth = width; minWidth = width;
maxWidth = width; maxWidth = width;
} }
double minHeight = constraints.minHeight; double minHeight = constraints.minHeight;
double maxHeight = constraints.maxHeight; double maxHeight = constraints.maxHeight;
if (_heightFactor != null) { if (_heightFactor != null) {
double height = maxHeight * _heightFactor; final double height = maxHeight * _heightFactor;
minHeight = height; minHeight = height;
maxHeight = height; maxHeight = height;
} }
@ -870,7 +870,7 @@ class RenderCustomSingleChildLayoutBox extends RenderShiftedBox {
void performLayout() { void performLayout() {
size = _getSize(constraints); size = _getSize(constraints);
if (child != null) { if (child != null) {
BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints); final BoxConstraints childConstraints = delegate.getConstraintsForChild(constraints);
assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true)); assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true));
child.layout(childConstraints, parentUsesSize: !childConstraints.isTight); child.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
final BoxParentData childParentData = child.parentData; final BoxParentData childParentData = child.parentData;

View File

@ -60,7 +60,7 @@ abstract class RenderSliverFixedExtentBoxAdaptor extends RenderSliverMultiBoxAda
assert(remainingPaintExtent >= 0.0); assert(remainingPaintExtent >= 0.0);
final double targetEndScrollOffset = scrollOffset + remainingPaintExtent; final double targetEndScrollOffset = scrollOffset + remainingPaintExtent;
BoxConstraints childConstraints = constraints.asBoxConstraints( final BoxConstraints childConstraints = constraints.asBoxConstraints(
minExtent: itemExtent, minExtent: itemExtent,
maxExtent: itemExtent, maxExtent: itemExtent,
); );

View File

@ -468,7 +468,7 @@ class RenderSliverGrid extends RenderSliverMultiBoxAdaptor {
} }
final SliverGridGeometry firstChildGridGeometry = layout.getGeometryForChildIndex(firstIndex); final SliverGridGeometry firstChildGridGeometry = layout.getGeometryForChildIndex(firstIndex);
double leadingScrollOffset = firstChildGridGeometry.scrollOffset; final double leadingScrollOffset = firstChildGridGeometry.scrollOffset;
double trailingScrollOffset = firstChildGridGeometry.trailingScrollOffset; double trailingScrollOffset = firstChildGridGeometry.trailingScrollOffset;
if (firstChild == null) { if (firstChild == null) {

View File

@ -19,12 +19,12 @@ class RenderSliverList extends RenderSliverMultiBoxAdaptor {
assert(childManager.debugAssertChildListLocked()); assert(childManager.debugAssertChildListLocked());
childManager.setDidUnderflow(false); childManager.setDidUnderflow(false);
double scrollOffset = constraints.scrollOffset; final double scrollOffset = constraints.scrollOffset;
assert(scrollOffset >= 0.0); assert(scrollOffset >= 0.0);
double remainingPaintExtent = constraints.remainingPaintExtent; final double remainingPaintExtent = constraints.remainingPaintExtent;
assert(remainingPaintExtent >= 0.0); assert(remainingPaintExtent >= 0.0);
double targetEndScrollOffset = scrollOffset + remainingPaintExtent; final double targetEndScrollOffset = scrollOffset + remainingPaintExtent;
BoxConstraints childConstraints = constraints.asBoxConstraints(); final BoxConstraints childConstraints = constraints.asBoxConstraints();
int leadingGarbage = 0; int leadingGarbage = 0;
int trailingGarbage = 0; int trailingGarbage = 0;
bool reachedEnd = false; bool reachedEnd = false;

View File

@ -105,7 +105,7 @@ class RelativeRect {
if (a == null) if (a == null)
return new RelativeRect.fromLTRB(b.left * t, b.top * t, b.right * t, b.bottom * t); return new RelativeRect.fromLTRB(b.left * t, b.top * t, b.right * t, b.bottom * t);
if (b == null) { if (b == null) {
double k = 1.0 - t; final double k = 1.0 - t;
return new RelativeRect.fromLTRB(b.left * k, b.top * k, b.right * k, b.bottom * k); return new RelativeRect.fromLTRB(b.left * k, b.top * k, b.right * k, b.bottom * k);
} }
return new RelativeRect.fromLTRB( return new RelativeRect.fromLTRB(
@ -179,7 +179,7 @@ class StackParentData extends ContainerBoxParentDataMixin<RenderBox> {
@override @override
String toString() { String toString() {
List<String> values = <String>[]; final List<String> values = <String>[];
if (top != null) if (top != null)
values.add('top=$top'); values.add('top=$top');
if (right != null) if (right != null)
@ -493,9 +493,9 @@ class RenderIndexedStack extends RenderStack {
if (firstChild == null || index == null) if (firstChild == null || index == null)
return false; return false;
assert(position != null); assert(position != null);
RenderBox child = _childAtIndex(); final RenderBox child = _childAtIndex();
final StackParentData childParentData = child.parentData; final StackParentData childParentData = child.parentData;
Point transformed = new Point(position.x - childParentData.offset.dx, final Point transformed = new Point(position.x - childParentData.offset.dx,
position.y - childParentData.offset.dy); position.y - childParentData.offset.dy);
return child.hitTest(result, position: transformed); return child.hitTest(result, position: transformed);
} }
@ -504,7 +504,7 @@ class RenderIndexedStack extends RenderStack {
void paintStack(PaintingContext context, Offset offset) { void paintStack(PaintingContext context, Offset offset) {
if (firstChild == null || index == null) if (firstChild == null || index == null)
return; return;
RenderBox child = _childAtIndex(); final RenderBox child = _childAtIndex();
final StackParentData childParentData = child.parentData; final StackParentData childParentData = child.parentData;
context.paintChild(child, childParentData.offset + offset); context.paintChild(child, childParentData.offset + offset);
} }

View File

@ -295,10 +295,10 @@ class MinColumnWidth extends TableColumnWidth {
@override @override
double flex(Iterable<RenderBox> cells) { double flex(Iterable<RenderBox> cells) {
double aFlex = a.flex(cells); final double aFlex = a.flex(cells);
if (aFlex == null) if (aFlex == null)
return b.flex(cells); return b.flex(cells);
double bFlex = b.flex(cells); final double bFlex = b.flex(cells);
if (bFlex == null) if (bFlex == null)
return null; return null;
return math.min(aFlex, bFlex); return math.min(aFlex, bFlex);
@ -526,11 +526,11 @@ class RenderTable extends RenderBox {
assert(value >= 0); assert(value >= 0);
if (value == columns) if (value == columns)
return; return;
int oldColumns = columns; final int oldColumns = columns;
List<RenderBox> oldChildren = _children; final List<RenderBox> oldChildren = _children;
_columns = value; _columns = value;
_children = new List<RenderBox>()..length = columns * rows; _children = new List<RenderBox>()..length = columns * rows;
int columnsToCopy = math.min(columns, oldColumns); final int columnsToCopy = math.min(columns, oldColumns);
for (int y = 0; y < rows; y += 1) { for (int y = 0; y < rows; y += 1) {
for (int x = 0; x < columnsToCopy; x += 1) for (int x = 0; x < columnsToCopy; x += 1)
_children[x + y * columns] = oldChildren[x + y * oldColumns]; _children[x + y * columns] = oldChildren[x + y * oldColumns];
@ -538,7 +538,7 @@ class RenderTable extends RenderBox {
if (oldColumns > columns) { if (oldColumns > columns) {
for (int y = 0; y < rows; y += 1) { for (int y = 0; y < rows; y += 1) {
for (int x = columns; x < oldColumns; x += 1) { for (int x = columns; x < oldColumns; x += 1) {
int xy = x + y * oldColumns; final int xy = x + y * oldColumns;
if (oldChildren[xy] != null) if (oldChildren[xy] != null)
dropChild(oldChildren[xy]); dropChild(oldChildren[xy]);
} }
@ -715,8 +715,8 @@ class RenderTable extends RenderBox {
final Set<RenderBox> lostChildren = new HashSet<RenderBox>(); final Set<RenderBox> lostChildren = new HashSet<RenderBox>();
for (int y = 0; y < _rows; y += 1) { for (int y = 0; y < _rows; y += 1) {
for (int x = 0; x < _columns; x += 1) { for (int x = 0; x < _columns; x += 1) {
int xyOld = x + y * _columns; final int xyOld = x + y * _columns;
int xyNew = x + y * columns; final int xyNew = x + y * columns;
if (_children[xyOld] != null && (x >= columns || xyNew >= cells.length || _children[xyOld] != cells[xyNew])) if (_children[xyOld] != null && (x >= columns || xyNew >= cells.length || _children[xyOld] != cells[xyNew]))
lostChildren.add(_children[xyOld]); lostChildren.add(_children[xyOld]);
} }
@ -725,8 +725,8 @@ class RenderTable extends RenderBox {
int y = 0; int y = 0;
while (y * columns < cells.length) { while (y * columns < cells.length) {
for (int x = 0; x < columns; x += 1) { for (int x = 0; x < columns; x += 1) {
int xyNew = x + y * columns; final int xyNew = x + y * columns;
int xyOld = x + y * _columns; final int xyOld = x + y * _columns;
if (cells[xyNew] != null && (x >= _columns || y >= _rows || _children[xyOld] != cells[xyNew])) { if (cells[xyNew] != null && (x >= _columns || y >= _rows || _children[xyOld] != cells[xyNew])) {
if (!lostChildren.remove(cells[xyNew])) if (!lostChildren.remove(cells[xyNew]))
adoptChild(cells[xyNew]); adoptChild(cells[xyNew]);
@ -790,7 +790,7 @@ class RenderTable extends RenderBox {
assert(x >= 0 && x < columns && y >= 0 && y < rows); assert(x >= 0 && x < columns && y >= 0 && y < rows);
assert(_children.length == rows * columns); assert(_children.length == rows * columns);
final int xy = x + y * columns; final int xy = x + y * columns;
RenderBox oldChild = _children[xy]; final RenderBox oldChild = _children[xy];
if (oldChild == value) if (oldChild == value)
return; return;
if (oldChild != null) if (oldChild != null)
@ -833,8 +833,8 @@ class RenderTable extends RenderBox {
assert(_children.length == rows * columns); assert(_children.length == rows * columns);
double totalMinWidth = 0.0; double totalMinWidth = 0.0;
for (int x = 0; x < columns; x += 1) { for (int x = 0; x < columns; x += 1) {
TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth; final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth;
Iterable<RenderBox> columnCells = column(x); final Iterable<RenderBox> columnCells = column(x);
totalMinWidth += columnWidth.minIntrinsicWidth(columnCells, double.INFINITY); totalMinWidth += columnWidth.minIntrinsicWidth(columnCells, double.INFINITY);
} }
return totalMinWidth; return totalMinWidth;
@ -845,8 +845,8 @@ class RenderTable extends RenderBox {
assert(_children.length == rows * columns); assert(_children.length == rows * columns);
double totalMaxWidth = 0.0; double totalMaxWidth = 0.0;
for (int x = 0; x < columns; x += 1) { for (int x = 0; x < columns; x += 1) {
TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth; final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth;
Iterable<RenderBox> columnCells = column(x); final Iterable<RenderBox> columnCells = column(x);
totalMaxWidth += columnWidth.maxIntrinsicWidth(columnCells, double.INFINITY); totalMaxWidth += columnWidth.maxIntrinsicWidth(columnCells, double.INFINITY);
} }
return totalMaxWidth; return totalMaxWidth;
@ -863,7 +863,7 @@ class RenderTable extends RenderBox {
double rowHeight = 0.0; double rowHeight = 0.0;
for (int x = 0; x < columns; x += 1) { for (int x = 0; x < columns; x += 1) {
final int xy = x + y * columns; final int xy = x + y * columns;
RenderBox child = _children[xy]; final RenderBox child = _children[xy];
if (child != null) if (child != null)
rowHeight = math.max(rowHeight, child.getMaxIntrinsicHeight(widths[x])); rowHeight = math.max(rowHeight, child.getMaxIntrinsicHeight(widths[x]));
} }
@ -892,7 +892,7 @@ class RenderTable extends RenderBox {
Iterable<RenderBox> column(int x) sync* { Iterable<RenderBox> column(int x) sync* {
for (int y = 0; y < rows; y += 1) { for (int y = 0; y < rows; y += 1) {
final int xy = x + y * columns; final int xy = x + y * columns;
RenderBox child = _children[xy]; final RenderBox child = _children[xy];
if (child != null) if (child != null)
yield child; yield child;
} }
@ -906,7 +906,7 @@ class RenderTable extends RenderBox {
final int start = y * columns; final int start = y * columns;
final int end = (y + 1) * columns; final int end = (y + 1) * columns;
for (int xy = start; xy < end; xy += 1) { for (int xy = start; xy < end; xy += 1) {
RenderBox child = _children[xy]; final RenderBox child = _children[xy];
if (child != null) if (child != null)
yield child; yield child;
} }
@ -933,8 +933,8 @@ class RenderTable extends RenderBox {
double unflexedTableWidth = 0.0; // sum of the maxIntrinsicWidths of any column that has null flex double unflexedTableWidth = 0.0; // sum of the maxIntrinsicWidths of any column that has null flex
double totalFlex = 0.0; double totalFlex = 0.0;
for (int x = 0; x < columns; x += 1) { for (int x = 0; x < columns; x += 1) {
TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth; final TableColumnWidth columnWidth = _columnWidths[x] ?? defaultColumnWidth;
Iterable<RenderBox> columnCells = column(x); final Iterable<RenderBox> columnCells = column(x);
// apply ideal width (maxIntrinsicWidth) // apply ideal width (maxIntrinsicWidth)
final double maxIntrinsicWidth = columnWidth.maxIntrinsicWidth(columnCells, constraints.maxWidth); final double maxIntrinsicWidth = columnWidth.maxIntrinsicWidth(columnCells, constraints.maxWidth);
assert(maxIntrinsicWidth.isFinite); assert(maxIntrinsicWidth.isFinite);
@ -948,7 +948,7 @@ class RenderTable extends RenderBox {
minWidths[x] = minIntrinsicWidth; minWidths[x] = minIntrinsicWidth;
assert(maxIntrinsicWidth >= minIntrinsicWidth); assert(maxIntrinsicWidth >= minIntrinsicWidth);
// collect flex information while we're at it // collect flex information while we're at it
double flex = columnWidth.flex(columnCells); final double flex = columnWidth.flex(columnCells);
if (flex != null) { if (flex != null) {
assert(flex.isFinite); assert(flex.isFinite);
assert(flex > 0.0); assert(flex > 0.0);
@ -1058,7 +1058,7 @@ class RenderTable extends RenderBox {
final double delta = deficit / availableColumns; final double delta = deficit / availableColumns;
int newAvailableColumns = 0; int newAvailableColumns = 0;
for (int x = 0; x < columns; x += 1) { for (int x = 0; x < columns; x += 1) {
double availableDelta = widths[x] - minWidths[x]; final double availableDelta = widths[x] - minWidths[x];
if (availableDelta > 0.0) { if (availableDelta > 0.0) {
if (availableDelta <= delta) { if (availableDelta <= delta) {
// shrank to minimum // shrank to minimum
@ -1122,12 +1122,12 @@ class RenderTable extends RenderBox {
bool haveBaseline = false; bool haveBaseline = false;
double beforeBaselineDistance = 0.0; double beforeBaselineDistance = 0.0;
double afterBaselineDistance = 0.0; double afterBaselineDistance = 0.0;
List<double> baselines = new List<double>(columns); final List<double> baselines = new List<double>(columns);
for (int x = 0; x < columns; x += 1) { for (int x = 0; x < columns; x += 1) {
final int xy = x + y * columns; final int xy = x + y * columns;
RenderBox child = _children[xy]; final RenderBox child = _children[xy];
if (child != null) { if (child != null) {
TableCellParentData childParentData = child.parentData; final TableCellParentData childParentData = child.parentData;
assert(childParentData != null); assert(childParentData != null);
childParentData.x = x; childParentData.x = x;
childParentData.y = y; childParentData.y = y;
@ -1135,7 +1135,7 @@ class RenderTable extends RenderBox {
case TableCellVerticalAlignment.baseline: case TableCellVerticalAlignment.baseline:
assert(textBaseline != null); assert(textBaseline != null);
child.layout(new BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true); child.layout(new BoxConstraints.tightFor(width: widths[x]), parentUsesSize: true);
double childBaseline = child.getDistanceToBaseline(textBaseline, onlyReal: true); final double childBaseline = child.getDistanceToBaseline(textBaseline, onlyReal: true);
if (childBaseline != null) { if (childBaseline != null) {
beforeBaselineDistance = math.max(beforeBaselineDistance, childBaseline); beforeBaselineDistance = math.max(beforeBaselineDistance, childBaseline);
afterBaselineDistance = math.max(afterBaselineDistance, child.size.height - childBaseline); afterBaselineDistance = math.max(afterBaselineDistance, child.size.height - childBaseline);
@ -1164,7 +1164,7 @@ class RenderTable extends RenderBox {
} }
for (int x = 0; x < columns; x += 1) { for (int x = 0; x < columns; x += 1) {
final int xy = x + y * columns; final int xy = x + y * columns;
RenderBox child = _children[xy]; final RenderBox child = _children[xy];
if (child != null) { if (child != null) {
final TableCellParentData childParentData = child.parentData; final TableCellParentData childParentData = child.parentData;
switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) { switch (childParentData.verticalAlignment ?? defaultVerticalAlignment) {
@ -1199,10 +1199,10 @@ class RenderTable extends RenderBox {
bool hitTestChildren(HitTestResult result, { Point position }) { bool hitTestChildren(HitTestResult result, { Point position }) {
assert(_children.length == rows * columns); assert(_children.length == rows * columns);
for (int index = _children.length - 1; index >= 0; index -= 1) { for (int index = _children.length - 1; index >= 0; index -= 1) {
RenderBox child = _children[index]; final RenderBox child = _children[index];
if (child != null) { if (child != null) {
final BoxParentData childParentData = child.parentData; final BoxParentData childParentData = child.parentData;
Point transformed = new Point(position.x - childParentData.offset.dx, final Point transformed = new Point(position.x - childParentData.offset.dx,
position.y - childParentData.offset.dy); position.y - childParentData.offset.dy);
if (child.hitTest(result, position: transformed)) if (child.hitTest(result, position: transformed))
return true; return true;
@ -1234,22 +1234,22 @@ class RenderTable extends RenderBox {
} }
} }
for (int index = 0; index < _children.length; index += 1) { for (int index = 0; index < _children.length; index += 1) {
RenderBox child = _children[index]; final RenderBox child = _children[index];
if (child != null) { if (child != null) {
final BoxParentData childParentData = child.parentData; final BoxParentData childParentData = child.parentData;
context.paintChild(child, childParentData.offset + offset); context.paintChild(child, childParentData.offset + offset);
} }
} }
canvas = context.canvas; canvas = context.canvas;
Rect bounds = offset & size; final Rect bounds = offset & size;
if (border != null) { if (border != null) {
switch (border.verticalInside.style) { switch (border.verticalInside.style) {
case BorderStyle.solid: case BorderStyle.solid:
Paint paint = new Paint() final Paint paint = new Paint()
..color = border.verticalInside.color ..color = border.verticalInside.color
..strokeWidth = border.verticalInside.width ..strokeWidth = border.verticalInside.width
..style = PaintingStyle.stroke; ..style = PaintingStyle.stroke;
Path path = new Path(); final Path path = new Path();
for (int x = 1; x < columns; x += 1) { for (int x = 1; x < columns; x += 1) {
path.moveTo(bounds.left + _columnLefts[x], bounds.top); path.moveTo(bounds.left + _columnLefts[x], bounds.top);
path.lineTo(bounds.left + _columnLefts[x], bounds.bottom); path.lineTo(bounds.left + _columnLefts[x], bounds.bottom);
@ -1260,11 +1260,11 @@ class RenderTable extends RenderBox {
} }
switch (border.horizontalInside.style) { switch (border.horizontalInside.style) {
case BorderStyle.solid: case BorderStyle.solid:
Paint paint = new Paint() final Paint paint = new Paint()
..color = border.horizontalInside.color ..color = border.horizontalInside.color
..strokeWidth = border.horizontalInside.width ..strokeWidth = border.horizontalInside.width
..style = PaintingStyle.stroke; ..style = PaintingStyle.stroke;
Path path = new Path(); final Path path = new Path();
for (int y = 1; y < rows; y += 1) { for (int y = 1; y < rows; y += 1) {
path.moveTo(bounds.left, bounds.top + _rowTops[y]); path.moveTo(bounds.left, bounds.top + _rowTops[y]);
path.lineTo(bounds.right, bounds.top + _rowTops[y]); path.lineTo(bounds.right, bounds.top + _rowTops[y]);
@ -1292,16 +1292,16 @@ class RenderTable extends RenderBox {
@override @override
String debugDescribeChildren(String prefix) { String debugDescribeChildren(String prefix) {
StringBuffer result = new StringBuffer(); final StringBuffer result = new StringBuffer();
result.writeln('$prefix \u2502'); result.writeln('$prefix \u2502');
int lastIndex = _children.length - 1; final int lastIndex = _children.length - 1;
if (lastIndex < 0) { if (lastIndex < 0) {
result.writeln('$prefix \u2514\u2500table is empty'); result.writeln('$prefix \u2514\u2500table is empty');
} else { } else {
for (int y = 0; y < rows; y += 1) { for (int y = 0; y < rows; y += 1) {
for (int x = 0; x < columns; x += 1) { for (int x = 0; x < columns; x += 1) {
final int xy = x + y * columns; final int xy = x + y * columns;
RenderBox child = _children[xy]; final RenderBox child = _children[xy];
if (child != null) { if (child != null) {
if (xy < lastIndex) { if (xy < lastIndex) {
result.write('${child.toStringDeep("$prefix \u251C\u2500child ($x, $y): ", "$prefix \u2502")}'); result.write('${child.toStringDeep("$prefix \u251C\u2500child ($x, $y): ", "$prefix \u2502")}');

View File

@ -148,9 +148,9 @@ class RenderView extends RenderObject with RenderObjectWithChildMixin<RenderBox>
void compositeFrame() { void compositeFrame() {
Timeline.startSync('Compositing'); Timeline.startSync('Compositing');
try { try {
ui.SceneBuilder builder = new ui.SceneBuilder(); final ui.SceneBuilder builder = new ui.SceneBuilder();
layer.addToScene(builder, Offset.zero); layer.addToScene(builder, Offset.zero);
ui.Scene scene = builder.build(); final ui.Scene scene = builder.build();
ui.window.render(scene); ui.window.render(scene);
scene.dispose(); scene.dispose();
assert(() { assert(() {

View File

@ -675,7 +675,7 @@ class RenderViewport extends RenderViewportBase<SliverPhysicalContainerParentDat
if (leadingNegativeChild != null) { if (leadingNegativeChild != null) {
// negative scroll offsets // negative scroll offsets
double result = layoutOneSide( final double result = layoutOneSide(
leadingNegativeChild, leadingNegativeChild,
math.max(mainAxisExtent, centerOffset) - mainAxisExtent, math.max(mainAxisExtent, centerOffset) - mainAxisExtent,
0.0, 0.0,

View File

@ -182,7 +182,7 @@ abstract class SchedulerBinding extends BindingBase {
/// millisecond), so as to not cause the regular frame callbacks to /// millisecond), so as to not cause the regular frame callbacks to
/// get delayed. /// get delayed.
void scheduleTask(VoidCallback task, Priority priority) { void scheduleTask(VoidCallback task, Priority priority) {
bool isFirstTask = _taskQueue.isEmpty; final bool isFirstTask = _taskQueue.isEmpty;
_taskQueue.add(new _TaskEntry(task, priority.value)); _taskQueue.add(new _TaskEntry(task, priority.value));
if (isFirstTask) if (isFirstTask)
_ensureEventLoopCallback(); _ensureEventLoopCallback();
@ -209,7 +209,7 @@ abstract class SchedulerBinding extends BindingBase {
void _runTasks() { void _runTasks() {
if (_taskQueue.isEmpty) if (_taskQueue.isEmpty)
return; return;
_TaskEntry entry = _taskQueue.first; final _TaskEntry entry = _taskQueue.first;
// TODO(floitsch): for now we only expose the priority. It might // TODO(floitsch): for now we only expose the priority. It might
// be interesting to provide more info (like, how long the task // be interesting to provide more info (like, how long the task
// ran the last time, or how long is left in this frame). // ran the last time, or how long is left in this frame).
@ -354,7 +354,7 @@ abstract class SchedulerBinding extends BindingBase {
); );
} }
for (int id in callbacks.keys) { for (int id in callbacks.keys) {
_FrameCallbackEntry entry = callbacks[id]; final _FrameCallbackEntry entry = callbacks[id];
information.writeln('── callback $id ──'); information.writeln('── callback $id ──');
FlutterError.defaultStackFilter(entry.debugStack.toString().trimRight().split('\n')).forEach(information.writeln); FlutterError.defaultStackFilter(entry.debugStack.toString().trimRight().split('\n')).forEach(information.writeln);
} }
@ -533,7 +533,7 @@ abstract class SchedulerBinding extends BindingBase {
/// These mechanisms together combine to ensure that the durations we give /// These mechanisms together combine to ensure that the durations we give
/// during frame callbacks are monotonically increasing. /// during frame callbacks are monotonically increasing.
Duration _adjustForEpoch(Duration rawTimeStamp) { Duration _adjustForEpoch(Duration rawTimeStamp) {
Duration rawDurationSinceEpoch = _firstRawTimeStampInEpoch == null ? Duration.ZERO : rawTimeStamp - _firstRawTimeStampInEpoch; final Duration rawDurationSinceEpoch = _firstRawTimeStampInEpoch == null ? Duration.ZERO : rawTimeStamp - _firstRawTimeStampInEpoch;
return new Duration(microseconds: (rawDurationSinceEpoch.inMicroseconds / timeDilation).round() + _epochStart.inMicroseconds); return new Duration(microseconds: (rawDurationSinceEpoch.inMicroseconds / timeDilation).round() + _epochStart.inMicroseconds);
} }
@ -584,7 +584,7 @@ abstract class SchedulerBinding extends BindingBase {
assert(() { assert(() {
_debugFrameNumber += 1; _debugFrameNumber += 1;
if (debugPrintBeginFrameBanner || debugPrintEndFrameBanner) { if (debugPrintBeginFrameBanner || debugPrintEndFrameBanner) {
StringBuffer frameTimeStampDescription = new StringBuffer(); final StringBuffer frameTimeStampDescription = new StringBuffer();
if (rawTimeStamp != null) { if (rawTimeStamp != null) {
_debugDescribeTimeStamp(_currentFrameTimeStamp, frameTimeStampDescription); _debugDescribeTimeStamp(_currentFrameTimeStamp, frameTimeStampDescription);
} else { } else {
@ -612,7 +612,7 @@ abstract class SchedulerBinding extends BindingBase {
// POST-FRAME CALLBACKS // POST-FRAME CALLBACKS
_schedulerPhase = SchedulerPhase.postFrameCallbacks; _schedulerPhase = SchedulerPhase.postFrameCallbacks;
List<FrameCallback> localPostFrameCallbacks = final List<FrameCallback> localPostFrameCallbacks =
new List<FrameCallback>.from(_postFrameCallbacks); new List<FrameCallback>.from(_postFrameCallbacks);
_postFrameCallbacks.clear(); _postFrameCallbacks.clear();
for (FrameCallback callback in localPostFrameCallbacks) for (FrameCallback callback in localPostFrameCallbacks)
@ -636,7 +636,7 @@ abstract class SchedulerBinding extends BindingBase {
void _invokeTransientFrameCallbacks(Duration timeStamp) { void _invokeTransientFrameCallbacks(Duration timeStamp) {
Timeline.startSync('Animate'); Timeline.startSync('Animate');
assert(schedulerPhase == SchedulerPhase.transientCallbacks); assert(schedulerPhase == SchedulerPhase.transientCallbacks);
Map<int, _FrameCallbackEntry> callbacks = _transientCallbacks; final Map<int, _FrameCallbackEntry> callbacks = _transientCallbacks;
_transientCallbacks = new Map<int, _FrameCallbackEntry>(); _transientCallbacks = new Map<int, _FrameCallbackEntry>();
callbacks.forEach((int id, _FrameCallbackEntry callbackEntry) { callbacks.forEach((int id, _FrameCallbackEntry callbackEntry) {
if (!_removedIds.contains(id)) if (!_removedIds.contains(id))
@ -656,7 +656,7 @@ abstract class SchedulerBinding extends BindingBase {
if (timeStamp.inSeconds > 0) if (timeStamp.inSeconds > 0)
buffer.write('${timeStamp.inSeconds - timeStamp.inMinutes * Duration.SECONDS_PER_MINUTE}s '); buffer.write('${timeStamp.inSeconds - timeStamp.inMinutes * Duration.SECONDS_PER_MINUTE}s ');
buffer.write('${timeStamp.inMilliseconds - timeStamp.inSeconds * Duration.MILLISECONDS_PER_SECOND}'); buffer.write('${timeStamp.inMilliseconds - timeStamp.inSeconds * Duration.MILLISECONDS_PER_SECOND}');
int microseconds = timeStamp.inMicroseconds - timeStamp.inMilliseconds * Duration.MICROSECONDS_PER_MILLISECOND; final int microseconds = timeStamp.inMicroseconds - timeStamp.inMilliseconds * Duration.MICROSECONDS_PER_MILLISECOND;
if (microseconds > 0) if (microseconds > 0)
buffer.write('.${microseconds.toString().padLeft(3, "0")}'); buffer.write('.${microseconds.toString().padLeft(3, "0")}');
buffer.write('ms'); buffer.write('ms');

View File

@ -164,7 +164,7 @@ class Ticker {
// We take the _completer into a local variable so that isTicking is false // We take the _completer into a local variable so that isTicking is false
// when we actually complete the future (isTicking uses _completer to // when we actually complete the future (isTicking uses _completer to
// determine its state). // determine its state).
Completer<Null> localCompleter = _completer; final Completer<Null> localCompleter = _completer;
_completer = null; _completer = null;
_startTime = null; _startTime = null;
assert(!isActive); assert(!isActive);

View File

@ -92,7 +92,7 @@ class NetworkAssetBundle extends AssetBundle {
@override @override
Future<ByteData> load(String key) async { Future<ByteData> load(String key) async {
http.Response response = await http.get(_urlFromKey(key)); final http.Response response = await http.get(_urlFromKey(key));
if (response.statusCode == 200) if (response.statusCode == 200)
return null; return null;
return response.bodyBytes.buffer.asByteData(); return response.bodyBytes.buffer.asByteData();
@ -100,7 +100,7 @@ class NetworkAssetBundle extends AssetBundle {
@override @override
Future<String> loadString(String key, { bool cache: true }) async { Future<String> loadString(String key, { bool cache: true }) async {
http.Response response = await http.get(_urlFromKey(key)); final http.Response response = await http.get(_urlFromKey(key));
return response.statusCode == 200 ? response.body : null; return response.statusCode == 200 ? response.body : null;
} }
@ -199,7 +199,7 @@ abstract class CachingAssetBundle extends AssetBundle {
class PlatformAssetBundle extends CachingAssetBundle { class PlatformAssetBundle extends CachingAssetBundle {
@override @override
Future<ByteData> load(String key) { Future<ByteData> load(String key) {
Uint8List encoded = UTF8.encoder.convert(key); final Uint8List encoded = UTF8.encoder.convert(key);
return PlatformMessages.sendBinary('flutter/assets', encoded.buffer.asByteData()); return PlatformMessages.sendBinary('flutter/assets', encoded.buffer.asByteData());
} }
} }

View File

@ -50,7 +50,7 @@ class Clipboard {
/// Returns a future which completes to null if the data could not be /// Returns a future which completes to null if the data could not be
/// obtained, and to a [ClipboardData] object if it could. /// obtained, and to a [ClipboardData] object if it could.
static Future<ClipboardData> getData(String format) async { static Future<ClipboardData> getData(String format) async {
Map<String, dynamic> result = await PlatformMessages.invokeMethod( final Map<String, dynamic> result = await PlatformMessages.invokeMethod(
_kChannelName, _kChannelName,
'Clipboard.getData', 'Clipboard.getData',
<String>[format] <String>[format]

View File

@ -12,7 +12,7 @@ import 'dart:ui' as ui show Image, decodeImageFromList;
/// the returned [Future] resolves to the decoded image. Otherwise, the [Future] /// the returned [Future] resolves to the decoded image. Otherwise, the [Future]
/// resolves to [null]. /// resolves to [null].
Future<ui.Image> decodeImageFromList(Uint8List list) { Future<ui.Image> decodeImageFromList(Uint8List list) {
Completer<ui.Image> completer = new Completer<ui.Image>(); final Completer<ui.Image> completer = new Completer<ui.Image>();
ui.decodeImageFromList(list, (ui.Image image) { ui.decodeImageFromList(list, (ui.Image image) {
completer.complete(image); completer.complete(image);
}); });

View File

@ -92,7 +92,7 @@ class ImageConfiguration {
@override @override
String toString() { String toString() {
StringBuffer result = new StringBuffer(); final StringBuffer result = new StringBuffer();
result.write('ImageConfiguration('); result.write('ImageConfiguration(');
bool hasArguments = false; bool hasArguments = false;
if (bundle != null) { if (bundle != null) {
@ -340,7 +340,7 @@ class NetworkImage extends ImageProvider<NetworkImage> {
if (response == null || response.statusCode != 200) if (response == null || response.statusCode != 200)
return null; return null;
Uint8List bytes = response.bodyBytes; final Uint8List bytes = response.bodyBytes;
if (bytes.lengthInBytes == 0) if (bytes.lengthInBytes == 0)
return null; return null;
@ -402,7 +402,7 @@ class FileImage extends ImageProvider<FileImage> {
Future<ImageInfo> _loadAsync(FileImage key) async { Future<ImageInfo> _loadAsync(FileImage key) async {
assert(key == this); assert(key == this);
Uint8List bytes = await file.readAsBytes(); final Uint8List bytes = await file.readAsBytes();
if (bytes.lengthInBytes == 0) if (bytes.lengthInBytes == 0)
return null; return null;

View File

@ -163,8 +163,8 @@ class AssetImage extends AssetBundleImageProvider {
String _findNearest(SplayTreeMap<double, String> candidates, double value) { String _findNearest(SplayTreeMap<double, String> candidates, double value) {
if (candidates.containsKey(value)) if (candidates.containsKey(value))
return candidates[value]; return candidates[value];
double lower = candidates.lastKeyBefore(value); final double lower = candidates.lastKeyBefore(value);
double upper = candidates.firstKeyAfter(value); final double upper = candidates.firstKeyAfter(value);
if (lower == null) if (lower == null)
return candidates[upper]; return candidates[upper];
if (upper == null) if (upper == null)
@ -178,7 +178,7 @@ class AssetImage extends AssetBundleImageProvider {
static final RegExp _extractRatioRegExp = new RegExp(r"/?(\d+(\.\d*)?)x/"); static final RegExp _extractRatioRegExp = new RegExp(r"/?(\d+(\.\d*)?)x/");
double _parseScale(String key) { double _parseScale(String key) {
Match match = _extractRatioRegExp.firstMatch(key); final Match match = _extractRatioRegExp.firstMatch(key);
if (match != null && match.groupCount > 0) if (match != null && match.groupCount > 0)
return double.parse(match.group(1)); return double.parse(match.group(1));
return _naturalResolution; return _naturalResolution;

View File

@ -122,7 +122,7 @@ class ImageStream {
@override @override
String toString() { String toString() {
StringBuffer result = new StringBuffer(); final StringBuffer result = new StringBuffer();
result.write('$runtimeType('); result.write('$runtimeType(');
if (_completer == null) { if (_completer == null) {
result.write('unresolved; '); result.write('unresolved; ');
@ -181,7 +181,7 @@ class ImageStreamCompleter {
_current = image; _current = image;
if (_listeners.isEmpty) if (_listeners.isEmpty)
return; return;
List<ImageListener> localListeners = new List<ImageListener>.from(_listeners); final List<ImageListener> localListeners = new List<ImageListener>.from(_listeners);
for (ImageListener listener in localListeners) { for (ImageListener listener in localListeners) {
try { try {
listener(image, false); listener(image, false);

View File

@ -24,7 +24,7 @@ class PathProvider {
/// ///
/// On Android, this uses the `getCacheDir` API on the context. /// On Android, this uses the `getCacheDir` API on the context.
static Future<Directory> getTemporaryDirectory() async { static Future<Directory> getTemporaryDirectory() async {
Map<String, dynamic> result = await PlatformMessages.invokeMethod( final Map<String, dynamic> result = await PlatformMessages.invokeMethod(
_kChannelName, 'PathProvider.getTemporaryDirectory'); _kChannelName, 'PathProvider.getTemporaryDirectory');
if (result == null) if (result == null)
return null; return null;
@ -39,7 +39,7 @@ class PathProvider {
/// ///
/// On Android, this returns the AppData directory. /// On Android, this returns the AppData directory.
static Future<Directory> getApplicationDocumentsDirectory() async { static Future<Directory> getApplicationDocumentsDirectory() async {
Map<String, dynamic> result = await PlatformMessages.invokeMethod( final Map<String, dynamic> result = await PlatformMessages.invokeMethod(
_kChannelName, 'PathProvider.getApplicationDocumentsDirectory'); _kChannelName, 'PathProvider.getApplicationDocumentsDirectory');
if (result == null) if (result == null)
return null; return null;

Some files were not shown because too many files have changed in this diff Show More