Implementing null-aware operators throughout the repository (#143804)

This pull request fixes #143803 by taking advantage of Dart's null-aware operators.

And unlike `switch` expressions ([9 PRs](https://github.com/flutter/flutter/pull/143634) and counting), the Flutter codebase is already fantastic when it comes to null-aware coding. After refactoring the entire repo, all the changes involving `?.` and `??` can fit into a single pull request.
This commit is contained in:
Nate 2024-02-23 12:02:22 -07:00 committed by GitHub
parent 39585e66c1
commit c53a18f4e4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
55 changed files with 93 additions and 365 deletions

View file

@ -91,11 +91,7 @@ Iterable<InlineSpanSemanticsInformation> combineSemanticsInfoSyncStar(List<Inlin
workingText += info.text; workingText += info.text;
workingLabel ??= ''; workingLabel ??= '';
final String? infoSemanticsLabel = info.semanticsLabel; final String? infoSemanticsLabel = info.semanticsLabel;
if (infoSemanticsLabel != null) { workingLabel += infoSemanticsLabel ?? info.text;
workingLabel += infoSemanticsLabel;
} else {
workingLabel += info.text;
}
} }
} }
assert(workingLabel != null); assert(workingLabel != null);
@ -115,11 +111,7 @@ Iterable<InlineSpanSemanticsInformation> combineSemanticsInfoList(List<InlineSpa
workingText += info.text; workingText += info.text;
workingLabel ??= ''; workingLabel ??= '';
final String? infoSemanticsLabel = info.semanticsLabel; final String? infoSemanticsLabel = info.semanticsLabel;
if (infoSemanticsLabel != null) { workingLabel += infoSemanticsLabel ?? info.text;
workingLabel += infoSemanticsLabel;
} else {
workingLabel += info.text;
}
} }
} }
assert(workingLabel != null); assert(workingLabel != null);

View file

@ -16,20 +16,13 @@ class TestSpecs {
int startTime; int startTime;
int? _endTime; int? _endTime;
int get milliseconds { int get milliseconds => endTime - startTime;
return endTime - startTime;
}
set endTime(int value) { set endTime(int value) {
_endTime = value; _endTime = value;
} }
int get endTime { int get endTime => _endTime ?? 0;
if (_endTime == null) {
return 0;
}
return _endTime!;
}
String toJson() { String toJson() {
return json.encode( return json.encode(

View file

@ -158,13 +158,10 @@ class Version {
int nextZ = previousVersion.z; int nextZ = previousVersion.z;
int? nextM = previousVersion.m; int? nextM = previousVersion.m;
int? nextN = previousVersion.n; int? nextN = previousVersion.n;
if (nextVersionType == null) { nextVersionType ??= switch (previousVersion.type) {
if (previousVersion.type == VersionType.latest || previousVersion.type == VersionType.gitDescribe) { VersionType.stable => VersionType.stable,
nextVersionType = VersionType.development; VersionType.latest || VersionType.gitDescribe || VersionType.development => VersionType.development,
} else { };
nextVersionType = previousVersion.type;
}
}
switch (increment) { switch (increment) {
case 'x': case 'x':

View file

@ -32,11 +32,7 @@ Future<void> main() async {
final TaskResult? firstInstallFailure = testResults final TaskResult? firstInstallFailure = testResults
.firstWhereOrNull((TaskResult element) => element.failed); .firstWhereOrNull((TaskResult element) => element.failed);
if (firstInstallFailure != null) { return firstInstallFailure ?? TaskResult.success(null);
return firstInstallFailure;
}
return TaskResult.success(null);
}, },
); );

View file

@ -32,11 +32,7 @@ Future<void> main() async {
final TaskResult? firstInstallFailure = testResults final TaskResult? firstInstallFailure = testResults
.firstWhereOrNull((TaskResult element) => element.failed); .firstWhereOrNull((TaskResult element) => element.failed);
if (firstInstallFailure != null) { return firstInstallFailure ?? TaskResult.success(null);
return firstInstallFailure;
}
return TaskResult.success(null);
}, },
); );

View file

@ -572,12 +572,7 @@ class BlinkTraceEvent {
/// Returns null if the value is null. /// Returns null if the value is null.
int? _readInt(Map<String, dynamic> json, String key) { int? _readInt(Map<String, dynamic> json, String key) {
final num? jsonValue = json[key] as num?; final num? jsonValue = json[key] as num?;
return jsonValue?.toInt();
if (jsonValue == null) {
return null;
}
return jsonValue.toInt();
} }
/// Used by [Chrome.launch] to detect a glibc bug and retry launching the /// Used by [Chrome.launch] to detect a glibc bug and retry launching the

View file

@ -1290,11 +1290,7 @@ class PerfTest {
}) { }) {
return inDirectory<TaskResult>(testDirectory, () async { return inDirectory<TaskResult>(testDirectory, () async {
late Device selectedDevice; late Device selectedDevice;
if (device != null) { selectedDevice = device ?? await devices.workingDevice;
selectedDevice = device!;
} else {
selectedDevice = await devices.workingDevice;
}
await selectedDevice.unlock(); await selectedDevice.unlock();
final String deviceId = selectedDevice.deviceId; final String deviceId = selectedDevice.deviceId;
final String? localEngine = localEngineFromEnv; final String? localEngine = localEngineFromEnv;

View file

@ -223,10 +223,7 @@ class _AndroidSemanticsMatcher extends Matcher {
Description describeMismatch(dynamic item, Description mismatchDescription, Description describeMismatch(dynamic item, Description mismatchDescription,
Map<dynamic, dynamic> matchState, bool verbose) { Map<dynamic, dynamic> matchState, bool verbose) {
final String? failure = matchState['failure'] as String?; final String? failure = matchState['failure'] as String?;
if (failure == null) { return mismatchDescription.add(failure ?? 'hasAndroidSemantics matcher does not complete successfully');
return mismatchDescription.add('hasAndroidSemantics matcher does not complete successfully');
}
return mismatchDescription.add(failure);
} }
bool _failWithMessage(String value, Map<dynamic, dynamic> matchState) { bool _failWithMessage(String value, Map<dynamic, dynamic> matchState) {

View file

@ -62,12 +62,8 @@ class AppStateModel extends Model {
// Adds a product to the cart. // Adds a product to the cart.
void addProductToCart(int productId) { void addProductToCart(int productId) {
final int? value = _productsInCart[productId]; final int value = _productsInCart[productId] ?? 0;
if (value == null) { _productsInCart[productId] = value + 1;
_productsInCart[productId] = 1;
} else {
_productsInCart[productId] = value+1;
}
notifyListeners(); notifyListeners();
} }

View file

@ -86,9 +86,7 @@ Future<void> main(List<String> args) async {
final Map<String, dynamic> tokenFileTokens = _readTokenFile(tokenFile as File); final Map<String, dynamic> tokenFileTokens = _readTokenFile(tokenFile as File);
final String version = tokenFileTokens['version'] as String; final String version = tokenFileTokens['version'] as String;
tokenFileTokens.remove('version'); tokenFileTokens.remove('version');
if (versionMap[version] == null) { versionMap[version] ??= <String>[];
versionMap[version] = List<String>.empty(growable: true);
}
versionMap[version]!.add(tokenFile.uri.pathSegments.last); versionMap[version]!.add(tokenFile.uri.pathSegments.last);
tokens.addAll(tokenFileTokens); tokens.addAll(tokenFileTokens);

View file

@ -953,9 +953,6 @@ class CupertinoDynamicColor extends Color with Diagnosticable {
/// * [resolve], which is similar to this function, but returns a /// * [resolve], which is similar to this function, but returns a
/// non-nullable value, and does not allow a null `resolvable` color. /// non-nullable value, and does not allow a null `resolvable` color.
static Color? maybeResolve(Color? resolvable, BuildContext context) { static Color? maybeResolve(Color? resolvable, BuildContext context) {
if (resolvable == null) {
return null;
}
return (resolvable is CupertinoDynamicColor) return (resolvable is CupertinoDynamicColor)
? resolvable.resolveFrom(context) ? resolvable.resolveFrom(context)
: resolvable; : resolvable;

View file

@ -684,10 +684,8 @@ class _CupertinoDatePickerDateTimeState extends State<CupertinoDatePicker> {
// Lazily calculate the column width of the column being displayed only. // Lazily calculate the column width of the column being displayed only.
double _getEstimatedColumnWidth(_PickerColumnType columnType) { double _getEstimatedColumnWidth(_PickerColumnType columnType) {
if (estimatedColumnWidths[columnType.index] == null) { estimatedColumnWidths[columnType.index] ??=
estimatedColumnWidths[columnType.index] = CupertinoDatePicker._getColumnWidth(columnType, localizations, context, widget.showDayOfWeek);
CupertinoDatePicker._getColumnWidth(columnType, localizations, context, widget.showDayOfWeek);
}
return estimatedColumnWidths[columnType.index]!; return estimatedColumnWidths[columnType.index]!;
} }

View file

@ -94,10 +94,7 @@ class CupertinoUserInterfaceLevel extends InheritedWidget {
/// [CupertinoUserInterfaceLevel] encloses the given context. /// [CupertinoUserInterfaceLevel] encloses the given context.
static CupertinoUserInterfaceLevelData? maybeOf(BuildContext context) { static CupertinoUserInterfaceLevelData? maybeOf(BuildContext context) {
final CupertinoUserInterfaceLevel? query = context.dependOnInheritedWidgetOfExactType<CupertinoUserInterfaceLevel>(); final CupertinoUserInterfaceLevel? query = context.dependOnInheritedWidgetOfExactType<CupertinoUserInterfaceLevel>();
if (query != null) { return query?._data;
return query._data;
}
return null;
} }
@override @override

View file

@ -2257,10 +2257,7 @@ class EnumProperty<T extends Enum?> extends DiagnosticsProperty<T> {
@override @override
String valueToString({ TextTreeConfiguration? parentConfiguration }) { String valueToString({ TextTreeConfiguration? parentConfiguration }) {
if (value == null) { return value?.name ?? 'null';
return value.toString();
}
return value!.name;
} }
} }

View file

@ -47,13 +47,9 @@ class PersistentHashMap<K extends Object, V> {
/// is not in the map. /// is not in the map.
@pragma('dart2js:as:trust') @pragma('dart2js:as:trust')
V? operator[](K key) { V? operator[](K key) {
if (_root == null) {
return null;
}
// Unfortunately can not use unsafeCast<V?>(...) here because it leads // Unfortunately can not use unsafeCast<V?>(...) here because it leads
// to worse code generation on VM. // to worse code generation on VM.
return _root.get(0, key, key.hashCode) as V?; return _root?.get(0, key, key.hashCode) as V?;
} }
} }

View file

@ -461,10 +461,7 @@ abstract class OneSequenceGestureRecognizer extends GestureRecognizer {
} }
GestureArenaEntry _addPointerToArena(int pointer) { GestureArenaEntry _addPointerToArena(int pointer) {
if (_team != null) { return _team?.add(pointer, this) ?? GestureBinding.instance.gestureArena.add(pointer, this);
return _team!.add(pointer, this);
}
return GestureBinding.instance.gestureArena.add(pointer, this);
} }
/// Causes events related to the given pointer ID to be routed to this recognizer. /// Causes events related to the given pointer ID to be routed to this recognizer.

View file

@ -560,10 +560,8 @@ class DrawerControllerState extends State<DrawerController> with SingleTickerPro
double get _width { double get _width {
final RenderBox? box = _drawerKey.currentContext?.findRenderObject() as RenderBox?; final RenderBox? box = _drawerKey.currentContext?.findRenderObject() as RenderBox?;
if (box != null) { // return _kWidth if drawer not being shown currently
return box.size.width; return box?.size.width ?? _kWidth;
}
return _kWidth; // drawer not being shown currently
} }
bool _previouslyOpened = false; bool _previouslyOpened = false;

View file

@ -154,10 +154,7 @@ class _RenderMenuItem extends RenderShiftedBox {
@override @override
Size computeDryLayout(BoxConstraints constraints) { Size computeDryLayout(BoxConstraints constraints) {
if (child == null) { return child?.getDryLayout(constraints) ?? Size.zero;
return Size.zero;
}
return child!.getDryLayout(constraints);
} }
@override @override

View file

@ -442,10 +442,8 @@ class _StepperState extends State<Stepper> with TickerProviderStateMixin {
if (isActive) MaterialState.selected else MaterialState.disabled, if (isActive) MaterialState.selected else MaterialState.disabled,
}; };
final Color? resolvedConnectorColor = widget.connectorColor?.resolve(states); final Color? resolvedConnectorColor = widget.connectorColor?.resolve(states);
if (resolvedConnectorColor != null) {
return resolvedConnectorColor; return resolvedConnectorColor ?? (isActive ? colorScheme.primary : Colors.grey.shade400);
}
return isActive ? colorScheme.primary : Colors.grey.shade400;
} }
Widget _buildLine(bool visible, bool isActive) { Widget _buildLine(bool visible, bool isActive) {

View file

@ -238,13 +238,7 @@ abstract class BorderRadiusGeometry {
if (visual != null && logical != null) { if (visual != null && logical != null) {
return '$visual + $logical'; return '$visual + $logical';
} }
if (visual != null) { return visual ?? logical ?? 'BorderRadius.zero';
return visual;
}
if (logical != null) {
return logical;
}
return 'BorderRadius.zero';
} }
@override @override

View file

@ -510,13 +510,7 @@ abstract class ShapeBorder {
if (identical(a, b)) { if (identical(a, b)) {
return a; return a;
} }
ShapeBorder? result; final ShapeBorder? result = b?.lerpFrom(a, t) ?? a?.lerpTo(b, t);
if (b != null) {
result = b.lerpFrom(a, t);
}
if (result == null && a != null) {
result = a.lerpTo(b, t);
}
return result ?? (t < 0.5 ? a : b); return result ?? (t < 0.5 ? a : b);
} }
@ -700,13 +694,7 @@ abstract class OutlinedBorder extends ShapeBorder {
if (identical(a, b)) { if (identical(a, b)) {
return a; return a;
} }
ShapeBorder? result; final ShapeBorder? result = b?.lerpFrom(a, t) ?? a?.lerpTo(b, t);
if (b != null) {
result = b.lerpFrom(a, t);
}
if (result == null && a != null) {
result = a.lerpTo(b, t);
}
return result as OutlinedBorder? ?? (t < 0.5 ? a : b); return result as OutlinedBorder? ?? (t < 0.5 ? a : b);
} }
} }

View file

@ -468,10 +468,7 @@ class RenderAspectRatio extends RenderProxyBox {
if (height.isFinite) { if (height.isFinite) {
return height * _aspectRatio; return height * _aspectRatio;
} }
if (child != null) { return child?.getMinIntrinsicWidth(height) ?? 0.0;
return child!.getMinIntrinsicWidth(height);
}
return 0.0;
} }
@override @override
@ -479,10 +476,7 @@ class RenderAspectRatio extends RenderProxyBox {
if (height.isFinite) { if (height.isFinite) {
return height * _aspectRatio; return height * _aspectRatio;
} }
if (child != null) { return child?.getMaxIntrinsicWidth(height) ?? 0.0;
return child!.getMaxIntrinsicWidth(height);
}
return 0.0;
} }
@override @override
@ -490,10 +484,7 @@ class RenderAspectRatio extends RenderProxyBox {
if (width.isFinite) { if (width.isFinite) {
return width / _aspectRatio; return width / _aspectRatio;
} }
if (child != null) { return child?.getMinIntrinsicHeight(width) ?? 0.0;
return child!.getMinIntrinsicHeight(width);
}
return 0.0;
} }
@override @override
@ -501,10 +492,7 @@ class RenderAspectRatio extends RenderProxyBox {
if (width.isFinite) { if (width.isFinite) {
return width / _aspectRatio; return width / _aspectRatio;
} }
if (child != null) { return child?.getMaxIntrinsicHeight(width) ?? 0.0;
return child!.getMaxIntrinsicHeight(width);
}
return 0.0;
} }
Size _applyAspectRatio(BoxConstraints constraints) { Size _applyAspectRatio(BoxConstraints constraints) {

View file

@ -51,10 +51,7 @@ class DisposableBuildContext<T extends State> {
/// Otherwise, asserts the [_state] is still mounted and returns its context. /// Otherwise, asserts the [_state] is still mounted and returns its context.
BuildContext? get context { BuildContext? get context {
assert(_debugValidate()); assert(_debugValidate());
if (_state == null) { return _state?.context;
return null;
}
return _state!.context;
} }
/// Called from asserts or tests to determine whether this object is in a /// Called from asserts or tests to determine whether this object is in a

View file

@ -1039,10 +1039,7 @@ class DraggableScrollableActuator extends StatefulWidget {
/// otherwise. /// otherwise.
static bool reset(BuildContext context) { static bool reset(BuildContext context) {
final _InheritedResetNotifier? notifier = context.dependOnInheritedWidgetOfExactType<_InheritedResetNotifier>(); final _InheritedResetNotifier? notifier = context.dependOnInheritedWidgetOfExactType<_InheritedResetNotifier>();
if (notifier == null) { return notifier?._sendReset() ?? false;
return false;
}
return notifier._sendReset();
} }
@override @override

View file

@ -578,10 +578,7 @@ abstract class Route<T> {
/// rendered. It is even possible for the route to be active but for the stateful /// rendered. It is even possible for the route to be active but for the stateful
/// widgets within the route to not be instantiated. See [ModalRoute.maintainState]. /// widgets within the route to not be instantiated. See [ModalRoute.maintainState].
bool get isActive { bool get isActive {
if (_navigator == null) { return _navigator?._firstRouteEntryWhereOrNull(_RouteEntry.isRoutePredicate(this))?.isPresent ?? false;
return false;
}
return _navigator!._firstRouteEntryWhereOrNull(_RouteEntry.isRoutePredicate(this))?.isPresent ?? false;
} }
} }

View file

@ -64,10 +64,7 @@ class RouteInformation {
'This feature was deprecated after v3.8.0-3.0.pre.' 'This feature was deprecated after v3.8.0-3.0.pre.'
) )
String get location { String get location {
if (_location != null) { return _location ?? Uri.decodeComponent(
return _location;
}
return Uri.decodeComponent(
Uri( Uri(
path: uri.path.isEmpty ? '/' : uri.path, path: uri.path.isEmpty ? '/' : uri.path,
queryParameters: uri.queryParametersAll.isEmpty ? null : uri.queryParametersAll, queryParameters: uri.queryParametersAll.isEmpty ? null : uri.queryParametersAll,
@ -1562,10 +1559,7 @@ mixin PopNavigatorRouterDelegateMixin<T> on RouterDelegate<T> {
@override @override
Future<bool> popRoute() { Future<bool> popRoute() {
final NavigatorState? navigator = navigatorKey?.currentState; final NavigatorState? navigator = navigatorKey?.currentState;
if (navigator == null) { return navigator?.maybePop() ?? SynchronousFuture<bool>(false);
return SynchronousFuture<bool>(false);
}
return navigator.maybePop();
} }
} }

View file

@ -190,10 +190,7 @@ class ScrollPhysics {
/// reference to it to use later, as the values may update, may not update, or /// reference to it to use later, as the values may update, may not update, or
/// may update to reflect an entirely unrelated scrollable. /// may update to reflect an entirely unrelated scrollable.
double applyPhysicsToUserOffset(ScrollMetrics position, double offset) { double applyPhysicsToUserOffset(ScrollMetrics position, double offset) {
if (parent == null) { return parent?.applyPhysicsToUserOffset(position, offset) ?? offset;
return offset;
}
return parent!.applyPhysicsToUserOffset(position, offset);
} }
/// Whether the scrollable should let the user adjust the scroll offset, for /// Whether the scrollable should let the user adjust the scroll offset, for
@ -297,10 +294,7 @@ class ScrollPhysics {
/// scrolling back from being overscrolled, if for some reason the position /// scrolling back from being overscrolled, if for some reason the position
/// ends up overscrolled. /// ends up overscrolled.
double applyBoundaryConditions(ScrollMetrics position, double value) { double applyBoundaryConditions(ScrollMetrics position, double value) {
if (parent == null) { return parent?.applyBoundaryConditions(position, value) ?? 0.0;
return 0.0;
}
return parent!.applyBoundaryConditions(position, value);
} }
/// Describes what the scroll position should be given new viewport dimensions. /// Describes what the scroll position should be given new viewport dimensions.
@ -394,10 +388,7 @@ class ScrollPhysics {
// https://github.com/flutter/flutter/issues/120340 // https://github.com/flutter/flutter/issues/120340
// https://github.com/flutter/flutter/issues/109675 // https://github.com/flutter/flutter/issues/109675
Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) { Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) {
if (parent == null) { return parent?.createBallisticSimulation(position, velocity);
return null;
}
return parent!.createBallisticSimulation(position, velocity);
} }
static final SpringDescription _kDefaultSpring = SpringDescription.withDampingRatio( static final SpringDescription _kDefaultSpring = SpringDescription.withDampingRatio(
@ -467,10 +458,7 @@ class ScrollPhysics {
/// ///
/// By default, physics for platforms other than iOS doesn't carry momentum. /// By default, physics for platforms other than iOS doesn't carry momentum.
double carriedMomentum(double existingVelocity) { double carriedMomentum(double existingVelocity) {
if (parent == null) { return parent?.carriedMomentum(existingVelocity) ?? 0.0;
return 0.0;
}
return parent!.carriedMomentum(existingVelocity);
} }
/// The minimum amount of pixel distance drags must move by to start motion /// The minimum amount of pixel distance drags must move by to start motion

View file

@ -2059,10 +2059,7 @@ abstract class MultiSelectableSelectionContainerDelegate extends SelectionContai
final List<Rect> selectionRectsWithinDrawableArea = currSelectableSelectionRects.map((Rect selectionRect) { final List<Rect> selectionRectsWithinDrawableArea = currSelectableSelectionRects.map((Rect selectionRect) {
final Matrix4 transform = getTransformFrom(selectables[index]); final Matrix4 transform = getTransformFrom(selectables[index]);
final Rect localRect = MatrixUtils.transformRect(transform, selectionRect); final Rect localRect = MatrixUtils.transformRect(transform, selectionRect);
if (drawableArea != null) { return drawableArea?.intersect(localRect) ?? localRect;
return drawableArea.intersect(localRect);
}
return localRect;
}).where((Rect selectionRect) { }).where((Rect selectionRect) {
return selectionRect.isFinite && !selectionRect.isEmpty; return selectionRect.isFinite && !selectionRect.isEmpty;
}).toList(); }).toList();

View file

@ -435,34 +435,22 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix
@override @override
double computeMinIntrinsicWidth(double height) { double computeMinIntrinsicWidth(double height) {
if (child != null) { return child?.getMinIntrinsicWidth(height) ?? 0.0;
return child!.getMinIntrinsicWidth(height);
}
return 0.0;
} }
@override @override
double computeMaxIntrinsicWidth(double height) { double computeMaxIntrinsicWidth(double height) {
if (child != null) { return child?.getMaxIntrinsicWidth(height) ?? 0.0;
return child!.getMaxIntrinsicWidth(height);
}
return 0.0;
} }
@override @override
double computeMinIntrinsicHeight(double width) { double computeMinIntrinsicHeight(double width) {
if (child != null) { return child?.getMinIntrinsicHeight(width) ?? 0.0;
return child!.getMinIntrinsicHeight(width);
}
return 0.0;
} }
@override @override
double computeMaxIntrinsicHeight(double width) { double computeMaxIntrinsicHeight(double width) {
if (child != null) { return child?.getMaxIntrinsicHeight(width) ?? 0.0;
return child!.getMaxIntrinsicHeight(width);
}
return 0.0;
} }
// We don't override computeDistanceToActualBaseline(), because we // We don't override computeDistanceToActualBaseline(), because we

View file

@ -732,12 +732,7 @@ class InspectorReferenceData {
int count = 1; int count = 1;
/// The value. /// The value.
Object? get value { Object? get value => _ref?.target ?? _value;
if (_ref != null) {
return _ref!.target;
}
return _value;
}
} }
// Production implementation of [WidgetInspectorService]. // Production implementation of [WidgetInspectorService].

View file

@ -471,12 +471,7 @@ void main() {
// Theme brightness is preferred, otherwise MediaQuery brightness is // Theme brightness is preferred, otherwise MediaQuery brightness is
// used. If both are null, defaults to light. // used. If both are null, defaults to light.
late final Brightness effectiveBrightness; final Brightness effectiveBrightness = themeBrightness ?? mediaBrightness ?? Brightness.light;
if (themeBrightness != null) {
effectiveBrightness = themeBrightness;
} else {
effectiveBrightness = mediaBrightness ?? Brightness.light;
}
expect( expect(
text.style!.color!.value, text.style!.color!.value,

View file

@ -23,10 +23,7 @@ class StateMarkerState extends State<StateMarker> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (widget.child != null) { return widget.child ?? Container();
return widget.child!;
}
return Container();
} }
} }

View file

@ -44,10 +44,7 @@ class StateMarkerState extends State<StateMarker> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (widget.child != null) { return widget.child ?? Container();
return widget.child!;
}
return Container();
} }
} }

View file

@ -3128,8 +3128,5 @@ Future<void> _testGestureTap(WidgetTester tester, Finder tooltip) async {
} }
SemanticsNode _findDebugSemantics(RenderObject object) { SemanticsNode _findDebugSemantics(RenderObject object) {
if (object.debugSemantics != null) { return object.debugSemantics ?? _findDebugSemantics(object.parent!);
return object.debugSemantics!;
}
return _findDebugSemantics(object.parent!);
} }

View file

@ -1495,8 +1495,5 @@ void main() {
} }
SemanticsNode findDebugSemantics(RenderObject object) { SemanticsNode findDebugSemantics(RenderObject object) {
if (object.debugSemantics != null) { return object.debugSemantics ?? findDebugSemantics(object.parent!);
return object.debugSemantics!;
}
return findDebugSemantics(object.parent!);
} }

View file

@ -59,10 +59,7 @@ class MyTestRenderingFlutterBinding extends TestRenderingFlutterBinding {
static MyTestRenderingFlutterBinding? _instance; static MyTestRenderingFlutterBinding? _instance;
static MyTestRenderingFlutterBinding ensureInitialized() { static MyTestRenderingFlutterBinding ensureInitialized() {
if (_instance != null) { return _instance ?? MyTestRenderingFlutterBinding();
return _instance!;
}
return MyTestRenderingFlutterBinding();
} }
@override @override

View file

@ -1055,10 +1055,7 @@ class ConditionalRepaintBoundary extends RenderProxyBox {
@override @override
OffsetLayer updateCompositedLayer({required covariant OffsetLayer? oldLayer}) { OffsetLayer updateCompositedLayer({required covariant OffsetLayer? oldLayer}) {
if (offsetLayerFactory != null) { return offsetLayerFactory?.call(oldLayer) ?? super.updateCompositedLayer(oldLayer: oldLayer);
return offsetLayerFactory!.call(oldLayer);
}
return super.updateCompositedLayer(oldLayer: oldLayer);
} }
@override @override

View file

@ -88,10 +88,7 @@ class TestRenderingFlutterBinding extends BindingBase with SchedulerBinding, Ser
/// idempotent; calling it a second time will just return the /// idempotent; calling it a second time will just return the
/// previously-created instance. /// previously-created instance.
static TestRenderingFlutterBinding ensureInitialized({ VoidCallback? onErrors }) { static TestRenderingFlutterBinding ensureInitialized({ VoidCallback? onErrors }) {
if (_instance != null) { return _instance ?? TestRenderingFlutterBinding(onErrors: onErrors);
return _instance!;
}
return TestRenderingFlutterBinding(onErrors: onErrors);
} }
final List<FlutterErrorDetails> _errors = <FlutterErrorDetails>[]; final List<FlutterErrorDetails> _errors = <FlutterErrorDetails>[];

View file

@ -19,10 +19,7 @@ class StateMarkerState extends State<StateMarker> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (widget.child != null) { return widget.child ?? Container();
return widget.child!;
}
return Container();
} }
} }

View file

@ -50,10 +50,7 @@ void main() {
final SimpleAsyncRouteInformationParser parser = SimpleAsyncRouteInformationParser(); final SimpleAsyncRouteInformationParser parser = SimpleAsyncRouteInformationParser();
final SimpleAsyncRouterDelegate delegate = SimpleAsyncRouterDelegate( final SimpleAsyncRouterDelegate delegate = SimpleAsyncRouterDelegate(
builder: (BuildContext context, RouteInformation? information) { builder: (BuildContext context, RouteInformation? information) {
if (information == null) { return Text(information?.uri.toString() ?? 'waiting');
return const Text('waiting');
}
return Text(information.uri.toString());
}, },
); );
addTearDown(delegate.dispose); addTearDown(delegate.dispose);
@ -97,10 +94,7 @@ void main() {
final CompleterRouteInformationParser parser = CompleterRouteInformationParser(); final CompleterRouteInformationParser parser = CompleterRouteInformationParser();
final SimpleAsyncRouterDelegate delegate = SimpleAsyncRouterDelegate( final SimpleAsyncRouterDelegate delegate = SimpleAsyncRouterDelegate(
builder: (BuildContext context, RouteInformation? information) { builder: (BuildContext context, RouteInformation? information) {
if (information == null) { return Text(information?.uri.toString() ?? 'waiting');
return const Text('waiting');
}
return Text(information.uri.toString());
}, },
); );
addTearDown(delegate.dispose); addTearDown(delegate.dispose);

View file

@ -2080,12 +2080,8 @@ class _TestDialogRouteWithCustomBarrierCurve<T> extends PopupRoute<T> {
final Color? barrierColor; final Color? barrierColor;
@override @override
Curve get barrierCurve { Curve get barrierCurve => _barrierCurve ?? super.barrierCurve;
if (_barrierCurve == null) {
return super.barrierCurve;
}
return _barrierCurve;
}
final Curve? _barrierCurve; final Curve? _barrierCurve;
@override @override

View file

@ -366,10 +366,7 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
/// ///
/// This is called automatically by [testWidgets]. /// This is called automatically by [testWidgets].
static TestWidgetsFlutterBinding ensureInitialized([@visibleForTesting Map<String, String>? environment]) { static TestWidgetsFlutterBinding ensureInitialized([@visibleForTesting Map<String, String>? environment]) {
if (_instance != null) { return _instance ?? binding.ensureInitialized(environment);
return _instance!;
}
return binding.ensureInitialized(environment);
} }
@override @override

View file

@ -521,11 +521,7 @@ class AndroidSdk {
final String executable = globals.platform.isWindows final String executable = globals.platform.isWindows
? 'sdkmanager.bat' ? 'sdkmanager.bat'
: 'sdkmanager'; : 'sdkmanager';
final String? path = getCmdlineToolsPath(executable, skipOldTools: true); return getCmdlineToolsPath(executable, skipOldTools: true);
if (path != null) {
return path;
}
return null;
} }
/// Returns the version of the Android SDK manager tool or null if not found. /// Returns the version of the Android SDK manager tool or null if not found.

View file

@ -163,11 +163,7 @@ class Java {
RegExp(r'java\s+(?<version>\d+(\.\d+)?(\.\d+)?)\s+\d\d\d\d-\d\d-\d\d'); RegExp(r'java\s+(?<version>\d+(\.\d+)?(\.\d+)?)\s+\d\d\d\d-\d\d-\d\d');
final RegExpMatch? match = secondJdkVersionRegex.firstMatch(versionLines[0]); final RegExpMatch? match = secondJdkVersionRegex.firstMatch(versionLines[0]);
if (match != null) { if (match != null) {
final Version? parsedVersion = Version.parse(match.namedGroup('version')); return Version.parse(match.namedGroup('version'));
if (parsedVersion == null) {
return null;
}
return parsedVersion;
} }
_logger.printWarning(_formatJavaVersionWarning(rawVersionOutput)); _logger.printWarning(_formatJavaVersionWarning(rawVersionOutput));
return null; return null;

View file

@ -557,11 +557,9 @@ class Cache {
/// Return the top-level directory in the cache; this is `bin/cache`. /// Return the top-level directory in the cache; this is `bin/cache`.
Directory getRoot() { Directory getRoot() {
if (_rootOverride != null) { return _fileSystem.directory(
return _fileSystem.directory(_fileSystem.path.join(_rootOverride.path, 'bin', 'cache')); _fileSystem.path.join(_rootOverride?.path ?? flutterRoot!, 'bin', 'cache'),
} else { );
return _fileSystem.directory(_fileSystem.path.join(flutterRoot!, 'bin', 'cache'));
}
} }
String getHostPlatformArchName() { String getHostPlatformArchName() {

View file

@ -84,10 +84,7 @@ abstract class AnalyzeBase {
bool get isFlutterRepo => argResults['flutter-repo'] as bool; bool get isFlutterRepo => argResults['flutter-repo'] as bool;
String get sdkPath { String get sdkPath {
final String? dartSdk = argResults['dart-sdk'] as String?; final String? dartSdk = argResults['dart-sdk'] as String?;
if (dartSdk != null) { return dartSdk ?? artifacts.getArtifactPath(Artifact.engineDartSdkPath);
return dartSdk;
}
return artifacts.getArtifactPath(Artifact.engineDartSdkPath);
} }
bool get isBenchmarking => argResults['benchmark'] as bool; bool get isBenchmarking => argResults['benchmark'] as bool;
String? get protocolTrafficLog => argResults['protocol-traffic-log'] as String?; String? get protocolTrafficLog => argResults['protocol-traffic-log'] as String?;

View file

@ -399,14 +399,7 @@ class PackagesGetCommand extends FlutterCommand {
return findPlugins(rootProject, throwOnError: false); return findPlugins(rootProject, throwOnError: false);
})(); })();
late final String? _androidEmbeddingVersion = (() { late final String? _androidEmbeddingVersion = _rootProject?.android.getEmbeddingVersion().toString().split('.').last;
final FlutterProject? rootProject = _rootProject;
if (rootProject == null) {
return null;
}
return rootProject.android.getEmbeddingVersion().toString().split('.').last;
})();
/// The pub packages usage values are incorrect since these are calculated/sent /// The pub packages usage values are incorrect since these are calculated/sent
/// before pub get completes. This needs to be performed after dependency resolution. /// before pub get completes. This needs to be performed after dependency resolution.

View file

@ -224,10 +224,7 @@ ${migrateConfig.getOutputFileString()}''';
/// Finds the fallback revision to use when no base revision is found in the migrate config. /// Finds the fallback revision to use when no base revision is found in the migrate config.
String getFallbackBaseRevision(Logger logger, FlutterVersion flutterVersion) { String getFallbackBaseRevision(Logger logger, FlutterVersion flutterVersion) {
// Use the .metadata file if it exists. // Use the .metadata file if it exists.
if (versionRevision != null) { return versionRevision ?? flutterVersion.frameworkRevision;
return versionRevision!;
}
return flutterVersion.frameworkRevision;
} }
} }

View file

@ -1178,12 +1178,7 @@ class IOSDeviceLogReader extends DeviceLogReader {
bool isWirelesslyConnected = false, bool isWirelesslyConnected = false,
bool isCoreDevice = false, bool isCoreDevice = false,
}) { }) {
final int sdkVersion; final int sdkVersion = majorSdkVersion ?? (useSyslog ? 12 : 13);
if (majorSdkVersion != null) {
sdkVersion = majorSdkVersion;
} else {
sdkVersion = useSyslog ? 12 : 13;
}
return IOSDeviceLogReader._( return IOSDeviceLogReader._(
iMobileDevice, sdkVersion, '1234', 'test', isWirelesslyConnected, isCoreDevice, 'Runner', usingCISystem); iMobileDevice, sdkVersion, '1234', 'test', isWirelesslyConnected, isCoreDevice, 'Runner', usingCISystem);
} }

View file

@ -637,12 +637,7 @@ class IOSDeployDebugger {
); );
} }
if (_stdinWriteFuture != null) { _stdinWriteFuture = _stdinWriteFuture?.then<void>((_) => writeln()) ?? writeln();
_stdinWriteFuture = _stdinWriteFuture!.then<void>((_) => writeln());
} else {
_stdinWriteFuture = writeln();
}
return _stdinWriteFuture; return _stdinWriteFuture;
} }

View file

@ -847,12 +847,7 @@ void _parseIssueInStdout(XcodeBuildExecution xcodeBuildExecution, Logger logger,
String? _parseMissingPlatform(String message) { String? _parseMissingPlatform(String message) {
final RegExp pattern = RegExp(r'error:(.*?) is not installed\. To use with Xcode, first download and install the platform'); final RegExp pattern = RegExp(r'error:(.*?) is not installed\. To use with Xcode, first download and install the platform');
final RegExpMatch? match = pattern.firstMatch(message); return pattern.firstMatch(message)?.group(1);
if (match != null) {
final String? version = match.group(1);
return version;
}
return null;
} }
// The result of [_handleXCResultIssue]. // The result of [_handleXCResultIssue].

View file

@ -717,11 +717,7 @@ class VersionUpstreamValidator {
// URLs without ".git" suffix will remain unaffected. // URLs without ".git" suffix will remain unaffected.
static final RegExp _patternUrlDotGit = RegExp(r'(.*)(\.git)$'); static final RegExp _patternUrlDotGit = RegExp(r'(.*)(\.git)$');
static String stripDotGit(String url) { static String stripDotGit(String url) {
final RegExpMatch? match = _patternUrlDotGit.firstMatch(url); return _patternUrlDotGit.firstMatch(url)?.group(1)! ?? url;
if (match == null) {
return url;
}
return match.group(1)!;
} }
} }

View file

@ -329,10 +329,7 @@ class IosProject extends XcodeBasedProject {
Future<String?> _getTeamIdentifier(XcodeProjectBuildContext buildContext) async { Future<String?> _getTeamIdentifier(XcodeProjectBuildContext buildContext) async {
final Map<String, String>? buildSettings = await _buildSettingsForXcodeProjectBuildContext(buildContext); final Map<String, String>? buildSettings = await _buildSettingsForXcodeProjectBuildContext(buildContext);
if (buildSettings != null) { return buildSettings?[kTeamIdKey];
return buildSettings[kTeamIdKey];
}
return null;
} }
Future<List<String>> _getAssociatedDomains(XcodeProjectBuildContext buildContext) async { Future<List<String>> _getAssociatedDomains(XcodeProjectBuildContext buildContext) async {

View file

@ -1130,10 +1130,7 @@ class TestDeviceDiscoverySupportFilter extends DeviceDiscoverySupportFilter {
@override @override
bool isDeviceSupportedForProject(Device device) { bool isDeviceSupportedForProject(Device device) {
if (isAlwaysSupportedForProjectOverride != null) { return isAlwaysSupportedForProjectOverride ?? super.isDeviceSupportedForProject(device);
return isAlwaysSupportedForProjectOverride!;
}
return super.isDeviceSupportedForProject(device);
} }
} }

View file

@ -24,90 +24,60 @@ class FlutterIOOverrides extends io.IOOverrides {
@override @override
io.Directory createDirectory(String path) { io.Directory createDirectory(String path) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.directory(path) ?? super.createDirectory(path);
return super.createDirectory(path);
}
return _fileSystemDelegate.directory(path);
} }
@override @override
io.File createFile(String path) { io.File createFile(String path) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.file(path) ?? super.createFile(path);
return super.createFile(path);
}
return _fileSystemDelegate.file(path);
} }
@override @override
io.Link createLink(String path) { io.Link createLink(String path) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.link(path) ?? super.createLink(path);
return super.createLink(path);
}
return _fileSystemDelegate.link(path);
} }
@override @override
Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive) { Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.file(path).watch(events: events, recursive: recursive)
return super.fsWatch(path, events, recursive); ?? super.fsWatch(path, events, recursive);
}
return _fileSystemDelegate.file(path).watch(events: events, recursive: recursive);
} }
@override @override
bool fsWatchIsSupported() { bool fsWatchIsSupported() {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.isWatchSupported ?? super.fsWatchIsSupported();
return super.fsWatchIsSupported();
}
return _fileSystemDelegate.isWatchSupported;
} }
@override @override
Future<FileSystemEntityType> fseGetType(String path, bool followLinks) { Future<FileSystemEntityType> fseGetType(String path, bool followLinks) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.type(path, followLinks: followLinks)
return super.fseGetType(path, followLinks); ?? super.fseGetType(path, followLinks);
}
return _fileSystemDelegate.type(path, followLinks: followLinks);
} }
@override @override
FileSystemEntityType fseGetTypeSync(String path, bool followLinks) { FileSystemEntityType fseGetTypeSync(String path, bool followLinks) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.typeSync(path, followLinks: followLinks)
return super.fseGetTypeSync(path, followLinks); ?? super.fseGetTypeSync(path, followLinks);
}
return _fileSystemDelegate.typeSync(path, followLinks: followLinks);
} }
@override @override
Future<bool> fseIdentical(String path1, String path2) { Future<bool> fseIdentical(String path1, String path2) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.identical(path1, path2) ?? super.fseIdentical(path1, path2);
return super.fseIdentical(path1, path2);
}
return _fileSystemDelegate.identical(path1, path2);
} }
@override @override
bool fseIdenticalSync(String path1, String path2) { bool fseIdenticalSync(String path1, String path2) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.identicalSync(path1, path2) ?? super.fseIdenticalSync(path1, path2);
return super.fseIdenticalSync(path1, path2);
}
return _fileSystemDelegate.identicalSync(path1, path2);
} }
@override @override
io.Directory getCurrentDirectory() { io.Directory getCurrentDirectory() {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.currentDirectory ?? super.getCurrentDirectory();
return super.getCurrentDirectory();
}
return _fileSystemDelegate.currentDirectory;
} }
@override @override
io.Directory getSystemTempDirectory() { io.Directory getSystemTempDirectory() {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.systemTempDirectory ?? super.getSystemTempDirectory();
return super.getSystemTempDirectory();
}
return _fileSystemDelegate.systemTempDirectory;
} }
@override @override
@ -120,17 +90,11 @@ class FlutterIOOverrides extends io.IOOverrides {
@override @override
Future<FileStat> stat(String path) { Future<FileStat> stat(String path) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.stat(path) ?? super.stat(path);
return super.stat(path);
}
return _fileSystemDelegate.stat(path);
} }
@override @override
FileStat statSync(String path) { FileStat statSync(String path) {
if (_fileSystemDelegate == null) { return _fileSystemDelegate?.statSync(path) ?? super.statSync(path);
return super.statSync(path);
}
return _fileSystemDelegate.statSync(path);
} }
} }