Enable use_if_null_to_convert_nulls_to_bools lint (#98753)

This commit is contained in:
Tomasz Gucio 2022-02-22 23:39:20 +01:00 committed by GitHub
parent a7790d8e3a
commit e4351ff053
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
71 changed files with 179 additions and 166 deletions

View File

@ -235,7 +235,7 @@ linter:
# - use_decorated_box # not yet tested
- use_full_hex_values_for_flutter_colors
- use_function_type_syntax_for_parameters
# - use_if_null_to_convert_nulls_to_bools # blocked on https://github.com/dart-lang/sdk/issues/47436
- use_if_null_to_convert_nulls_to_bools
- use_is_even_rather_than_modulo
- use_key_in_widget_constructors
- use_late_for_private_fields_and_variables

View File

@ -136,7 +136,7 @@ Future<void> main() async {
final List<double> scrollOffset = <double>[];
final List<Duration> delays = <Duration>[];
binding.addPersistentFrameCallback((Duration timeStamp) {
if (controller?.hasClients == true) {
if (controller?.hasClients ?? false) {
// This if is necessary because by the end of the test the widget tree
// is destroyed.
frameTimestamp.add(timeStamp.inMicroseconds);

View File

@ -93,7 +93,7 @@ class Chrome {
options.url!,
if (io.Platform.environment['CHROME_NO_SANDBOX'] == 'true')
'--no-sandbox',
if (options.headless == true)
if (options.headless ?? false)
'--headless',
if (withDebugging)
'--remote-debugging-port=${options.debugPort}',

View File

@ -171,7 +171,7 @@ class MotionEventsBodyState extends State<MotionEventsBody> {
}
Future<void> saveRecordedEvents(ByteData data, BuildContext context) async {
if (await channel.invokeMethod<bool>('getStoragePermission') == true) {
if (await channel.invokeMethod<bool>('getStoragePermission') ?? false) {
showMessage(
context, 'External storage permissions are required to save events');
return;

View File

@ -230,9 +230,9 @@ class _LeaveBehindListItem extends StatelessWidget {
confirmDismiss: !confirmDismiss ? null : (DismissDirection dismissDirection) async {
switch(dismissDirection) {
case DismissDirection.endToStart:
return await _showConfirmationDialog(context, 'archive') == true;
return await _showConfirmationDialog(context, 'archive') ?? false;
case DismissDirection.startToEnd:
return await _showConfirmationDialog(context, 'delete') == true;
return await _showConfirmationDialog(context, 'delete') ?? false;
case DismissDirection.horizontal:
case DismissDirection.vertical:
case DismissDirection.up:

View File

@ -322,14 +322,14 @@ class _OptionsState extends State<Options> {
LabeledCheckbox(
label: 'Enabled',
onChanged: (bool? checked) {
widget.model.enable = checked == true;
widget.model.enable = checked ?? false;
},
value: widget.model.enable,
),
LabeledCheckbox(
label: 'Slow',
onChanged: (bool? checked) {
widget.model.slowAnimations = checked == true;
widget.model.slowAnimations = checked ?? false;
Future<void>.delayed(const Duration(milliseconds: 150)).then((_) {
if (widget.model.slowAnimations) {
timeDilation = 20.0;
@ -343,7 +343,7 @@ class _OptionsState extends State<Options> {
LabeledCheckbox(
label: 'RTL',
onChanged: (bool? checked) {
widget.model.rtl = checked == true;
widget.model.rtl = checked ?? false;
},
value: widget.model.rtl,
),
@ -566,7 +566,7 @@ class _MyHomePageState extends State<MyHomePage> {
onChanged: _model.enable
? (bool? value) {
setState(() {
checkboxValues[index] = value == true;
checkboxValues[index] = value ?? false;
});
}
: null,

View File

@ -337,7 +337,7 @@ class _FuzzerState extends State<Fuzzer> with SingleTickerProviderStateMixin {
}
int depthOf(TextSpan node) {
if (node.children == null || node.children?.isEmpty == true)
if (node.children == null || (node.children?.isEmpty ?? false))
return 0;
int result = 0;
for (final TextSpan child in node.children!.cast<TextSpan>())

View File

@ -673,8 +673,8 @@ class _CupertinoDatePickerDateTimeState extends State<CupertinoDatePicker> {
void _onSelectedItemChange(int index) {
final DateTime selected = selectedDateTime;
final bool isDateInvalid = widget.minimumDate?.isAfter(selected) == true
|| widget.maximumDate?.isBefore(selected) == true;
final bool isDateInvalid = (widget.minimumDate?.isAfter(selected) ?? false)
|| (widget.maximumDate?.isBefore(selected) ?? false);
if (isDateInvalid)
return;

View File

@ -1330,7 +1330,7 @@ class CupertinoNavigationBarBackButton extends StatelessWidget {
final ModalRoute<dynamic>? currentRoute = ModalRoute.of(context);
if (onPressed == null) {
assert(
currentRoute?.canPop == true,
currentRoute?.canPop ?? false,
'CupertinoNavigationBarBackButton should only be used in routes that can be popped',
);
}

View File

@ -1010,7 +1010,7 @@ class _CupertinoTextFieldState extends State<CupertinoTextField> with Restoratio
}
@override
bool get wantKeepAlive => _controller?.value.text.isNotEmpty == true;
bool get wantKeepAlive => _controller?.value.text.isNotEmpty ?? false;
bool _shouldShowAttachment({
required OverlayVisibilityMode attachment,

View File

@ -1617,7 +1617,7 @@ abstract class DiagnosticsNode {
'allowTruncate': allowTruncate,
if (hasChildren)
'hasChildren': hasChildren,
if (linePrefix?.isNotEmpty == true)
if (linePrefix?.isNotEmpty ?? false)
'linePrefix': linePrefix,
if (!allowWrap)
'allowWrap': allowWrap,
@ -2209,7 +2209,7 @@ class FlagProperty extends DiagnosticsProperty<bool> {
@override
String valueToString({ TextTreeConfiguration? parentConfiguration }) {
if (value == true) {
if (value ?? false) {
if (ifTrue != null)
return ifTrue!;
} else if (value == false) {
@ -2221,7 +2221,7 @@ class FlagProperty extends DiagnosticsProperty<bool> {
@override
bool get showName {
if (value == null || (value == true && ifTrue == null) || (value == false && ifFalse == null)) {
if (value == null || ((value ?? false) && ifTrue == null) || (!(value ?? true) && ifFalse == null)) {
// We are missing a description for the flag value so we need to show the
// flag name. The property will have DiagnosticLevel.hidden for this case
// so users will not see this the property in this case unless they are
@ -2233,7 +2233,7 @@ class FlagProperty extends DiagnosticsProperty<bool> {
@override
DiagnosticLevel get level {
if (value == true) {
if (value ?? false) {
if (ifTrue == null)
return DiagnosticLevel.hidden;
}

View File

@ -191,7 +191,7 @@ abstract class GestureRecognizer extends GestureArenaMember with DiagnosticableT
// The 19 in the line below is the width of the prefix used by
// _debugLogDiagnostic in arena.dart.
final String prefix = debugPrintGestureArenaDiagnostics ? '${' ' * 19}' : '';
debugPrint('$prefix$this calling $name callback.${ report?.isNotEmpty == true ? " $report" : "" }');
debugPrint('$prefix$this calling $name callback.${ (report?.isNotEmpty ?? false) ? " $report" : "" }');
}
return true;
}());

View File

@ -468,7 +468,7 @@ class _CheckboxState extends State<Checkbox> with TickerProviderStateMixin, Togg
?? const Color(0xFFFFFFFF);
return Semantics(
checked: widget.value == true,
checked: widget.value ?? false,
child: buildToggleable(
mouseCursor: effectiveMouseCursor,
focusNode: widget.focusNode,
@ -660,13 +660,13 @@ class _CheckboxPainter extends ToggleablePainter {
_drawBox(canvas, outer, paint, side, true);
if (tNormalized <= 0.5) {
final double tShrink = 1.0 - tNormalized * 2.0;
if (previousValue == true)
if (previousValue ?? false)
_drawCheck(canvas, origin, tShrink, strokePaint);
else
_drawDash(canvas, origin, tShrink, strokePaint);
} else {
final double tExpand = (tNormalized - 0.5) * 2.0;
if (value == true)
if (value ?? false)
_drawCheck(canvas, origin, tExpand, strokePaint);
else
_drawDash(canvas, origin, tExpand, strokePaint);

View File

@ -2095,7 +2095,7 @@ class _InputDecoratorState extends State<InputDecorator> with TickerProviderStat
? _getDefaultBorderColor(themeData)
: themeData.errorColor;
} else {
borderColor = (decoration!.filled == true && decoration!.border?.isOutline != true)
borderColor = ((decoration!.filled ?? false) && !(decoration!.border?.isOutline ?? false))
? Colors.transparent
: themeData.disabledColor;
}
@ -2188,7 +2188,7 @@ class _InputDecoratorState extends State<InputDecorator> with TickerProviderStat
);
final bool decorationIsDense = decoration!.isDense == true; // isDense == null, same as false
final bool decorationIsDense = decoration!.isDense ?? false;
final double iconSize = decorationIsDense ? 18.0 : 24.0;
final Widget? icon = decoration!.icon == null ? null :
@ -2284,7 +2284,7 @@ class _InputDecoratorState extends State<InputDecorator> with TickerProviderStat
} else if (!border.isOutline) {
// 4.0: the vertical gap between the inline elements and the floating label.
floatingLabelHeight = (4.0 + 0.75 * labelStyle.fontSize!) * MediaQuery.textScaleFactorOf(context);
if (decoration!.filled == true) { // filled == null same as filled == false
if (decoration!.filled ?? false) {
contentPadding = decorationContentPadding ?? (decorationIsDense
? const EdgeInsets.fromLTRB(12.0, 8.0, 12.0, 8.0)
: const EdgeInsets.fromLTRB(12.0, 12.0, 12.0, 12.0));
@ -3656,7 +3656,7 @@ class InputDecoration {
if (counter != null) 'counter: $counter',
if (counterText != null) 'counterText: $counterText',
if (counterStyle != null) 'counterStyle: $counterStyle',
if (filled == true) 'filled: true', // filled == null same as filled == false
if (filled ?? false) 'filled: true',
if (fillColor != null) 'fillColor: $fillColor',
if (focusColor != null) 'focusColor: $focusColor',
if (hoverColor != null) 'hoverColor: $hoverColor',

View File

@ -193,7 +193,7 @@ class ScaffoldMessengerState extends State<ScaffoldMessenger> with TickerProvide
// and there is a SnackBar that would have timed out that has already
// completed its timer, dismiss that SnackBar. If the timer hasn't finished
// yet, let it timeout as normal.
if (_accessibleNavigation == true
if ((_accessibleNavigation ?? false)
&& !mediaQuery.accessibleNavigation
&& _snackBarTimer != null
&& !_snackBarTimer!.isActive) {
@ -2628,7 +2628,7 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
}
if (widget.bottomSheet != oldWidget.bottomSheet) {
assert(() {
if (widget.bottomSheet != null && _currentBottomSheet?._isLocalHistoryEntry == true) {
if (widget.bottomSheet != null && (_currentBottomSheet?._isLocalHistoryEntry ?? false)) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'Scaffold.bottomSheet cannot be specified while a bottom sheet displayed '
@ -2673,7 +2673,7 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin, Resto
// and there is a SnackBar that would have timed out that has already
// completed its timer, dismiss that SnackBar. If the timer hasn't finished
// yet, let it timeout as normal.
if (_accessibleNavigation == true
if ((_accessibleNavigation ?? false)
&& !mediaQuery.accessibleNavigation
&& _snackBarTimer != null
&& !_snackBarTimer!.isActive) {

View File

@ -2458,7 +2458,7 @@ class RoundRangeSliderThumbShape extends RangeSliderThumbShape {
// Add a stroke of 1dp around the circle if this thumb would overlap
// the other thumb.
if (isOnTop == true) {
if (isOnTop ?? false) {
final Paint strokePaint = Paint()
..color = sliderTheme.overlappingShapeStrokeColor!
..strokeWidth = 1.0

View File

@ -185,12 +185,12 @@ mixin ToggleableStateMixin<S extends StatefulWidget> on TickerProviderStateMixin
if (tristate) {
if (value == null)
_positionController.value = 0.0;
if (value != false)
if (value ?? true)
_positionController.forward();
else
_positionController.reverse();
} else {
if (value == true)
if (value ?? false)
_positionController.forward();
else
_positionController.reverse();
@ -282,7 +282,7 @@ mixin ToggleableStateMixin<S extends StatefulWidget> on TickerProviderStateMixin
if (!isInteractive) MaterialState.disabled,
if (_hovering) MaterialState.hovered,
if (_focused) MaterialState.focused,
if (value != false) MaterialState.selected,
if (value ?? true) MaterialState.selected,
};
/// Typically wraps a `painter` that draws the actual visuals of the

View File

@ -1331,7 +1331,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin,
if (hasFocus && !readOnly)
config.onSetText = _handleSetText;
if (selectionEnabled && selection?.isValid == true) {
if (selectionEnabled && (selection?.isValid ?? false)) {
config.textSelection = selection;
if (_textPainter.getOffsetBefore(selection!.extentOffset) != null) {
config
@ -1447,7 +1447,7 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin,
assert(false, '${recognizer.runtimeType} is not supported.');
}
}
final SemanticsNode newChild = (_cachedChildNodes?.isNotEmpty == true)
final SemanticsNode newChild = (_cachedChildNodes?.isNotEmpty ?? false)
? _cachedChildNodes!.removeFirst()
: SemanticsNode();
newChild

View File

@ -2719,7 +2719,7 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im
// RenderObject are still up-to date. Therefore, we will later only rebuild
// the semantics subtree starting at the identified semantics boundary.
final bool wasSemanticsBoundary = _semantics != null && _cachedSemanticsConfiguration?.isSemanticBoundary == true;
final bool wasSemanticsBoundary = _semantics != null && (_cachedSemanticsConfiguration?.isSemanticBoundary ?? false);
_cachedSemanticsConfiguration = null;
bool isEffectiveSemanticsBoundary = _semanticsConfiguration.isSemanticBoundary && wasSemanticsBoundary;
RenderObject node = this;
@ -3021,7 +3021,7 @@ abstract class RenderObject extends AbstractNode with DiagnosticableTreeMixin im
super.debugFillProperties(properties);
properties.add(FlagProperty('needsCompositing', value: _needsCompositing, ifTrue: 'needs compositing'));
properties.add(DiagnosticsProperty<Object?>('creator', debugCreator, defaultValue: null, level: DiagnosticLevel.debug));
properties.add(DiagnosticsProperty<ParentData>('parentData', parentData, tooltip: _debugCanParentUseSize == true ? 'can use size' : null, missingIfNull: true));
properties.add(DiagnosticsProperty<ParentData>('parentData', parentData, tooltip: (_debugCanParentUseSize ?? false) ? 'can use size' : null, missingIfNull: true));
properties.add(DiagnosticsProperty<Constraints>('constraints', _constraints, missingIfNull: true));
// don't access it via the "layer" getter since that's only valid when we don't need paint
properties.add(DiagnosticsProperty<ContainerLayer>('layer', _layerHandle.layer, defaultValue: null));
@ -3804,7 +3804,7 @@ class _SwitchableSemanticsFragment extends _InterestingSemanticsFragment {
? _SemanticsGeometry(parentSemanticsClipRect: parentSemanticsClipRect, parentPaintClipRect: parentPaintClipRect, ancestors: _ancestorChain)
: null;
if (!_mergeIntoParent && (geometry?.dropFromTree == true))
if (!_mergeIntoParent && (geometry?.dropFromTree ?? false))
return; // Drop the node, it's not going to be visible.
owner._semantics ??= SemanticsNode(showOnScreen: owner.showOnScreen);

View File

@ -1004,7 +1004,7 @@ class RenderParagraph extends RenderBox
assert(false, '${recognizer.runtimeType} is not supported.');
}
}
final SemanticsNode newChild = (_cachedChildNodes?.isNotEmpty == true)
final SemanticsNode newChild = (_cachedChildNodes?.isNotEmpty ?? false)
? _cachedChildNodes!.removeFirst()
: SemanticsNode();
newChild

View File

@ -2701,7 +2701,7 @@ class RenderFittedBox extends RenderProxyBox {
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
if (size.isEmpty || child?.size.isEmpty == true)
if (size.isEmpty || (child?.size.isEmpty ?? false))
return false;
_updatePaintData();
return result.addWithPaintTransform(
@ -4751,11 +4751,11 @@ class RenderSemanticsAnnotations extends RenderProxyBox {
config.isSemanticBoundary = container;
config.explicitChildNodes = explicitChildNodes;
assert(
(scopesRoute == true && explicitChildNodes == true) || scopesRoute != true,
((scopesRoute ?? false) && explicitChildNodes) || !(scopesRoute ?? false),
'explicitChildNodes must be set to true if scopes route is true',
);
assert(
!(toggled == true && checked == true),
!((toggled ?? false) && (checked ?? false)),
'A semantics node cannot be toggled and checked at the same time',
);

View File

@ -601,7 +601,7 @@ class SemanticsData with Diagnosticable {
properties.add(AttributedStringProperty('decreasedValue', attributedDecreasedValue));
properties.add(AttributedStringProperty('hint', attributedHint));
properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
if (textSelection?.isValid == true)
if (textSelection?.isValid ?? false)
properties.add(MessageProperty('textSelection', '[${textSelection!.start}, ${textSelection!.end}]'));
properties.add(IntProperty('platformViewId', platformViewId, defaultValue: null));
properties.add(IntProperty('maxValueLength', maxValueLength, defaultValue: null));
@ -2456,7 +2456,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin {
}
}
Int32List? customSemanticsActionIds;
if (data.customSemanticsActionIds?.isNotEmpty == true) {
if (data.customSemanticsActionIds?.isNotEmpty ?? false) {
customSemanticsActionIds = Int32List(data.customSemanticsActionIds!.length);
for (int i = 0; i < data.customSemanticsActionIds!.length; i++) {
customSemanticsActionIds[i] = data.customSemanticsActionIds![i];
@ -2618,7 +2618,7 @@ class SemanticsNode extends AbstractNode with DiagnosticableTreeMixin {
properties.add(AttributedStringProperty('hint', _attributedHint));
properties.add(EnumProperty<TextDirection>('textDirection', _textDirection, defaultValue: null));
properties.add(DiagnosticsProperty<SemanticsSortKey>('sortKey', sortKey, defaultValue: null));
if (_textSelection?.isValid == true)
if (_textSelection?.isValid ?? false)
properties.add(MessageProperty('text selection', '[${_textSelection!.start}, ${_textSelection!.end}]'));
properties.add(IntProperty('platformViewId', platformViewId, defaultValue: null));
properties.add(IntProperty('maxValueLength', maxValueLength, defaultValue: null));

View File

@ -895,7 +895,7 @@ class RestorationBucket {
return;
}
_childrenToAdd[child.restorationId]?.remove(child);
if (_childrenToAdd[child.restorationId]?.isEmpty == true) {
if (_childrenToAdd[child.restorationId]?.isEmpty ?? false) {
_childrenToAdd.remove(child.restorationId);
}
}

View File

@ -1333,7 +1333,10 @@ class _WidgetsAppState extends State<WidgetsApp> with WidgetsBindingObserver {
}
bool get _usesRouter => widget.routerDelegate != null;
bool get _usesNavigator => widget.home != null || widget.routes?.isNotEmpty == true || widget.onGenerateRoute != null || widget.onUnknownRoute != null;
bool get _usesNavigator => widget.home != null
|| (widget.routes?.isNotEmpty ?? false)
|| widget.onGenerateRoute != null
|| widget.onUnknownRoute != null;
// ROUTER

View File

@ -322,7 +322,7 @@ class _DismissibleState extends State<Dismissible> with TickerProviderStateMixin
bool _dismissThresholdReached = false;
@override
bool get wantKeepAlive => _moveController?.isAnimating == true || _resizeController?.isAnimating == true;
bool get wantKeepAlive => (_moveController?.isAnimating ?? false) || (_resizeController?.isAnimating ?? false);
@override
void dispose() {

View File

@ -1846,7 +1846,7 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
);
}
}
if (widget.selectionEnabled && pasteEnabled && widget.selectionControls?.canPaste(this) == true) {
if (widget.selectionEnabled && pasteEnabled && (widget.selectionControls?.canPaste(this) ?? false)) {
_clipboardStatus?.update();
}
}
@ -3006,19 +3006,29 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
}
VoidCallback? _semanticsOnCopy(TextSelectionControls? controls) {
return widget.selectionEnabled && copyEnabled && _hasFocus && controls?.canCopy(this) == true
return widget.selectionEnabled
&& copyEnabled
&& _hasFocus
&& (controls?.canCopy(this) ?? false)
? () => controls!.handleCopy(this, _clipboardStatus)
: null;
}
VoidCallback? _semanticsOnCut(TextSelectionControls? controls) {
return widget.selectionEnabled && cutEnabled && _hasFocus && controls?.canCut(this) == true
return widget.selectionEnabled
&& cutEnabled
&& _hasFocus
&& (controls?.canCut(this) ?? false)
? () => controls!.handleCut(this, _clipboardStatus)
: null;
}
VoidCallback? _semanticsOnPaste(TextSelectionControls? controls) {
return widget.selectionEnabled && pasteEnabled && _hasFocus && controls?.canPaste(this) == true && (_clipboardStatus == null || _clipboardStatus!.value == ClipboardStatus.pasteable)
return widget.selectionEnabled
&& pasteEnabled
&& _hasFocus
&& (controls?.canPaste(this) ?? false)
&& (_clipboardStatus == null || _clipboardStatus!.value == ClipboardStatus.pasteable)
? () => controls!.handlePaste(this)
: null;
}

View File

@ -800,7 +800,7 @@ class HeroController extends NavigatorObserver {
@override
void didReplace({ Route<dynamic>? newRoute, Route<dynamic>? oldRoute }) {
assert(navigator != null);
if (newRoute?.isCurrent == true) {
if (newRoute?.isCurrent ?? false) {
// Only run hero animations if the top-most route got replaced.
_maybeStartHeroTransition(oldRoute, newRoute, HeroFlightDirection.push, false);
}

View File

@ -215,7 +215,7 @@ abstract class Route<T> {
@mustCallSuper
TickerFuture didPush() {
return TickerFuture.complete()..then<void>((void _) {
if (navigator?.widget.requestFocus == true) {
if (navigator?.widget.requestFocus ?? false) {
navigator!.focusScopeNode.requestFocus();
}
});
@ -231,7 +231,7 @@ abstract class Route<T> {
@protected
@mustCallSuper
void didAdd() {
if (navigator?.widget.requestFocus == true) {
if (navigator?.widget.requestFocus ?? false) {
// This TickerFuture serves two purposes. First, we want to make sure
// that animations triggered by other operations will finish before focusing the
// navigator. Second, navigator.focusScopeNode might acquire more focused
@ -514,7 +514,7 @@ abstract class Route<T> {
return _navigator!._history.cast<_RouteEntry?>().firstWhere(
(_RouteEntry? e) => e != null && _RouteEntry.isRoutePredicate(this)(e),
orElse: () => null,
)?.isPresent == true;
)?.isPresent ?? false;
}
}
@ -5359,7 +5359,7 @@ class _HistoryProperty extends RestorableProperty<Map<String?, List<Object>>?> {
}
assert(!entry.hasPage);
restorationEnabled = restorationEnabled && entry.restorationInformation?.isRestorable == true;
restorationEnabled = restorationEnabled && (entry.restorationInformation?.isRestorable ?? false);
entry.restorationEnabled = restorationEnabled;
if (restorationEnabled) {
assert(entry.restorationId != null);

View File

@ -747,7 +747,7 @@ mixin RestorationMixin<S extends StatefulWidget> on State<S> {
assert(_debugDoingRestore || !_properties.keys.map((RestorableProperty<Object?> r) => r._restorationId).contains(restorationId),
'"$restorationId" is already registered to another property.',
);
final bool hasSerializedValue = bucket?.contains(restorationId) == true;
final bool hasSerializedValue = bucket?.contains(restorationId) ?? false;
final Object? initialValue = hasSerializedValue
? property.fromPrimitives(bucket!.read<Object>(restorationId))
: property.createDefaultValue();
@ -850,7 +850,7 @@ mixin RestorationMixin<S extends StatefulWidget> on State<S> {
return false;
}
final RestorationBucket? potentialNewParent = RestorationScope.of(context);
return potentialNewParent != _currentParent && potentialNewParent?.isReplacing == true;
return potentialNewParent != _currentParent && (potentialNewParent?.isReplacing ?? false);
}
List<RestorableProperty<Object?>>? _debugPropertiesWaitingForReregistration;

View File

@ -100,7 +100,7 @@ abstract class ScrollView extends StatelessWidget {
assert(shrinkWrap != null),
assert(dragStartBehavior != null),
assert(clipBehavior != null),
assert(!(controller != null && primary == true),
assert(!(controller != null && (primary ?? false)),
'Primary ScrollViews obtain their ScrollController via inheritance from a PrimaryScrollController widget. '
'You cannot both set primary to true and pass an explicit controller.',
),
@ -109,7 +109,7 @@ abstract class ScrollView extends StatelessWidget {
assert(anchor >= 0.0 && anchor <= 1.0),
assert(semanticChildCount == null || semanticChildCount >= 0),
primary = primary ?? controller == null && identical(scrollDirection, Axis.vertical),
physics = physics ?? (primary == true || (primary == null && controller == null && identical(scrollDirection, Axis.vertical)) ? const AlwaysScrollableScrollPhysics() : null),
physics = physics ?? ((primary ?? false) || (primary == null && controller == null && identical(scrollDirection, Axis.vertical)) ? const AlwaysScrollableScrollPhysics() : null),
super(key: key);
/// {@template flutter.widgets.scroll_view.scrollDirection}

View File

@ -902,7 +902,7 @@ class RawScrollbar extends StatefulWidget {
'isAlwaysShown is deprecated.'
),
assert(
!((thumbVisibility == false || isAlwaysShown == false) && trackVisibility == true),
!((thumbVisibility == false || isAlwaysShown == false) && (trackVisibility ?? false)),
'A scrollbar track cannot be drawn without a scrollbar thumb.'
),
assert(minThumbLength != null),
@ -1533,7 +1533,7 @@ class RawScrollbarState<T extends RawScrollbar> extends State<T> with TickerProv
super.didUpdateWidget(oldWidget);
if (widget.isAlwaysShown != oldWidget.isAlwaysShown
|| widget.thumbVisibility != oldWidget.thumbVisibility) {
if (widget.isAlwaysShown == true || widget.thumbVisibility == true) {
if ((widget.isAlwaysShown ?? false) || (widget.thumbVisibility ?? false)) {
assert(_debugScheduleCheckHasValidScrollPosition());
_fadeoutTimer?.cancel();
_fadeoutAnimationController.animateTo(1.0);

View File

@ -153,7 +153,7 @@ class SingleChildScrollView extends StatelessWidget {
}) : assert(scrollDirection != null),
assert(dragStartBehavior != null),
assert(clipBehavior != null),
assert(!(controller != null && primary == true),
assert(!(controller != null && (primary ?? false)),
'Primary ScrollViews obtain their ScrollController via inheritance from a PrimaryScrollController widget. '
'You cannot both set primary to true and pass an explicit controller.',
),

View File

@ -67,7 +67,7 @@ class _RenderSliverLayoutBuilder extends RenderSliver with RenderObjectWithChild
@override
void paint(PaintingContext context, Offset offset) {
// This renderObject does not introduce additional offset to child's position.
if (child?.geometry?.visible == true)
if (child?.geometry?.visible ?? false)
context.paintChild(child!, offset);
}

View File

@ -1056,7 +1056,7 @@ class _SelectionToolbarOverlayState extends State<_SelectionToolbarOverlay> with
}
void _toolbarVisibilityChanged() {
if (widget.visibility?.value != false) {
if (widget.visibility?.value ?? true) {
_controller.forward();
} else {
_controller.reverse();
@ -1139,7 +1139,7 @@ class _SelectionHandleOverlayState extends State<_SelectionHandleOverlay> with S
}
void _handleVisibilityChanged() {
if (widget.visibility?.value != false) {
if (widget.visibility?.value ?? true) {
_controller.forward();
} else {
_controller.reverse();

View File

@ -2473,7 +2473,7 @@ class InspectorSelection {
Element? _currentElement;
set currentElement(Element? element) {
if (element?.debugIsDefunct == true) {
if (element?.debugIsDefunct ?? false) {
_currentElement = null;
_current = null;
return;

View File

@ -84,7 +84,7 @@ class PathBoundsMatcher extends Matcher {
final Map<Matcher, dynamic> failedMatcher = <Matcher, dynamic> {};
for(int idx = 0; idx < matchers.length; idx++) {
if (!(matchers[idx]?.matches(values[idx], matchState) != false)) {
if (!(matchers[idx]?.matches(values[idx], matchState) ?? true)) {
failedMatcher[matchers[idx]!] = values[idx];
}
}

View File

@ -34,7 +34,7 @@ class TestDataSource extends DataTableSource {
final Set<int> _selectedRows = <int>{};
void _handleSelected(int index, bool? selected) {
if (selected == true) {
if (selected ?? false) {
_selectedRows.add(index);
} else {
_selectedRows.remove(index);

View File

@ -367,7 +367,7 @@ class TestSemantics {
buf.writeln("$indent hint: '$hint',");
if (textDirection != null)
buf.writeln('$indent textDirection: $textDirection,');
if (textSelection?.isValid == true)
if (textSelection?.isValid ?? false)
buf.writeln('$indent textSelection:\n[${textSelection!.start}, ${textSelection!.end}],');
if (scrollIndex != null)
buf.writeln('$indent scrollIndex: $scrollIndex,');

View File

@ -321,7 +321,7 @@ class VMServiceFlutterDriver extends FlutterDriver {
stackTrace,
);
}
if ((response['isError'] as bool?) == true)
if ((response['isError'] as bool?) ?? false)
throw DriverError('Error in Flutter application: ${response['response']}');
return response['response'] as Map<String, dynamic>;
}

View File

@ -151,7 +151,7 @@ class WebFlutterDriver extends FlutterDriver {
final Object? responseData = response['response'];
if (isError is! bool?) {
throw _createMalformedExtensionResponseError(data);
} else if (isError == true) {
} else if (isError ?? false) {
throw DriverError('Error in Flutter application: $responseData');
}

View File

@ -63,7 +63,7 @@ class AndroidWorkflow implements Workflow {
@override
bool get canLaunchDevices => appliesToHostPlatform && _androidSdk != null
&& _androidSdk?.adbPath != null
&& _androidSdk?.validateSdkWellFormed().isEmpty == true;
&& (_androidSdk?.validateSdkWellFormed().isEmpty ?? false);
@override
bool get canListEmulators => canListDevices && _androidSdk?.emulatorPath != null;

View File

@ -232,7 +232,7 @@ class _Element extends _Entry {
_Attribute? firstAttribute(String name) {
for (final _Attribute child in children.whereType<_Attribute>()) {
if (child.key?.startsWith(name) == true) {
if (child.key?.startsWith(name) ?? false) {
return child;
}
}
@ -241,7 +241,7 @@ class _Element extends _Entry {
_Element? firstElement(String name) {
for (final _Element child in children.whereType<_Element>()) {
if (child.name?.startsWith(name) == true) {
if (child.name?.startsWith(name) ?? false) {
return child;
}
}
@ -249,7 +249,7 @@ class _Element extends _Entry {
}
Iterable<_Element> allElements(String name) {
return children.whereType<_Element>().where((_Element e) => e.name?.startsWith(name) == true);
return children.whereType<_Element>().where((_Element e) => e.name?.startsWith(name) ?? false);
}
}
@ -332,7 +332,7 @@ class ApkManifestData {
final _Attribute? enabled = activity.firstAttribute('android:enabled');
final Iterable<_Element> intentFilters = activity.allElements('intent-filter');
final bool isEnabledByDefault = enabled == null;
final bool isExplicitlyEnabled = enabled != null && enabled.value?.contains('0xffffffff') == true;
final bool isExplicitlyEnabled = enabled != null && (enabled.value?.contains('0xffffffff') ?? false);
if (!(isEnabledByDefault || isExplicitlyEnabled)) {
continue;
}

View File

@ -39,7 +39,7 @@ class DartDevelopmentService {
}) async {
final Uri ddsUri = Uri(
scheme: 'http',
host: (ipv6 == true ? io.InternetAddress.loopbackIPv6 : io.InternetAddress.loopbackIPv4).host,
host: ((ipv6 ?? false) ? io.InternetAddress.loopbackIPv6 : io.InternetAddress.loopbackIPv4).host,
port: hostPort ?? 0,
);
logger.printTrace(
@ -51,7 +51,7 @@ class DartDevelopmentService {
observatoryUri,
serviceUri: ddsUri,
enableAuthCodes: disableServiceAuthCodes != true,
ipv6: ipv6 == true,
ipv6: ipv6 ?? false,
);
unawaited(_ddsInstance?.done.whenComplete(() {
if (!_completer.isCompleted) {

View File

@ -447,7 +447,7 @@ class StdoutLogger extends Logger {
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
);
if (emphasis == true) {
if (emphasis ?? false) {
message = terminal.bolden(message);
}
message = terminal.color(message, color ?? TerminalColor.red);
@ -475,7 +475,7 @@ class StdoutLogger extends Logger {
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
);
if (emphasis == true) {
if (emphasis ?? false) {
message = terminal.bolden(message);
}
message = terminal.color(message, color ?? TerminalColor.cyan);
@ -500,13 +500,13 @@ class StdoutLogger extends Logger {
shouldWrap: wrap ?? _outputPreferences.wrapText,
columnWidth: _outputPreferences.wrapColumn,
);
if (emphasis == true) {
if (emphasis ?? false) {
message = terminal.bolden(message);
}
if (color != null) {
message = terminal.color(message, color);
}
if (newline != false) {
if (newline ?? true) {
message = '$message\n';
}
writeToStdOut(message);
@ -812,7 +812,7 @@ class BufferLogger extends Logger {
int? hangingIndent,
bool? wrap,
}) {
if (newline != false) {
if (newline ?? true) {
_status.writeln(wrapText(message,
indent: indent,
hangingIndent: hangingIndent,

View File

@ -458,7 +458,7 @@ class _DefaultProcessUtils implements ProcessUtils {
}
if (mappedLine != null) {
final String message = '$prefix$mappedLine';
if (stdoutErrorMatcher?.hasMatch(mappedLine) == true) {
if (stdoutErrorMatcher?.hasMatch(mappedLine) ?? false) {
_logger.printError(message, wrap: false);
} else if (trace) {
_logger.printTrace(message);

View File

@ -121,7 +121,7 @@ class BuildIOSArchiveCommand extends _BuildIOSSubCommand {
Future<void> validateCommand() async {
final String? exportOptions = exportOptionsPlist;
if (exportOptions != null) {
if (argResults?.wasParsed('export-method') == true) {
if (argResults?.wasParsed('export-method') ?? false) {
throwToolExit(
'"--export-options-plist" is not compatible with "--export-method". Either use "--export-options-plist" and '
'a plist describing how the IPA should be exported by Xcode, or use "--export-method" to create a new plist.\n'

View File

@ -116,7 +116,7 @@ class ConfigCommand extends FlutterCommand {
return FlutterCommandResult.success();
}
if (argResults?.wasParsed('analytics') == true) {
if (argResults?.wasParsed('analytics') ?? false) {
final bool value = boolArg('analytics');
// The tool sends the analytics event *before* toggling the flag
// intentionally to be sure that opt-out events are sent correctly.
@ -131,19 +131,19 @@ class ConfigCommand extends FlutterCommand {
globals.printStatus('Analytics reporting ${value ? 'enabled' : 'disabled'}.');
}
if (argResults?.wasParsed('android-sdk') == true) {
if (argResults?.wasParsed('android-sdk') ?? false) {
_updateConfig('android-sdk', stringArg('android-sdk')!);
}
if (argResults?.wasParsed('android-studio-dir') == true) {
if (argResults?.wasParsed('android-studio-dir') ?? false) {
_updateConfig('android-studio-dir', stringArg('android-studio-dir')!);
}
if (argResults?.wasParsed('clear-ios-signing-cert') == true) {
if (argResults?.wasParsed('clear-ios-signing-cert') ?? false) {
_updateConfig('ios-signing-cert', '');
}
if (argResults?.wasParsed('build-dir') == true) {
if (argResults?.wasParsed('build-dir') ?? false) {
final String buildDir = stringArg('build-dir')!;
if (globals.fs.path.isAbsolute(buildDir)) {
throwToolExit('build-dir should be a relative path');
@ -156,7 +156,7 @@ class ConfigCommand extends FlutterCommand {
if (configSetting == null) {
continue;
}
if (argResults?.wasParsed(configSetting) == true) {
if (argResults?.wasParsed(configSetting) ?? false) {
final bool keyValue = boolArg(configSetting);
globals.config.setValue(configSetting, keyValue);
globals.printStatus('Setting "$configSetting" value to "$keyValue".');

View File

@ -56,7 +56,7 @@ class DebugAdapterCommand extends FlutterCommand {
globals.stdio.stdout.nonBlocking,
fileSystem: globals.fs,
platform: globals.platform,
ipv6: ipv6 == true,
ipv6: ipv6 ?? false,
enableDds: enableDds,
test: boolArg('test'),
);

View File

@ -34,7 +34,7 @@ class DoctorCommand extends FlutterCommand {
@override
Future<FlutterCommandResult> runCommand() async {
globals.flutterVersion.fetchTagsAndUpdate();
if (argResults?.wasParsed('check-for-remote-artifacts') == true) {
if (argResults?.wasParsed('check-for-remote-artifacts') ?? false) {
final String engineRevision = stringArg('check-for-remote-artifacts')!;
if (engineRevision.startsWith(RegExp(r'[a-f0-9]{1,40}'))) {
final bool success = await globals.doctor?.checkRemoteArtifacts(engineRevision) ?? false;

View File

@ -100,7 +100,7 @@ class ScreenshotCommand extends FlutterCommand {
@override
Future<FlutterCommandResult> runCommand() async {
File? outputFile;
if (argResults?.wasParsed(_kOut) == true) {
if (argResults?.wasParsed(_kOut) ?? false) {
outputFile = globals.fs.file(stringArg(_kOut));
}

View File

@ -71,7 +71,7 @@ class SymbolizeCommand extends FlutterCommand {
if (!_fileSystem.isFileSync(stringArg('debug-info')!)) {
throwToolExit('${stringArg('debug-info')} does not exist.');
}
if (argResults?.wasParsed('input') == true && !_fileSystem.isFileSync(stringArg('input')!)) {
if ((argResults?.wasParsed('input') ?? false) && !_fileSystem.isFileSync(stringArg('input')!)) {
throwToolExit('${stringArg('input')} does not exist.');
}
return super.validateCommand();
@ -83,7 +83,7 @@ class SymbolizeCommand extends FlutterCommand {
IOSink output;
// Configure output to either specified file or stdout.
if (argResults?.wasParsed('output') == true) {
if (argResults?.wasParsed('output') ?? false) {
final File outputFile = _fileSystem.file(stringArg('output'));
if (!outputFile.parent.existsSync()) {
outputFile.parent.createSync(recursive: true);
@ -99,7 +99,7 @@ class SymbolizeCommand extends FlutterCommand {
}
// Configure input from either specified file or stdin.
if (argResults?.wasParsed('input') == true) {
if (argResults?.wasParsed('input') ?? false) {
input = _fileSystem.file(stringArg('input')).openRead();
} else {
input = _stdio.stdin;

View File

@ -95,7 +95,7 @@ class DevFSFileContent extends DevFSContent {
if (fileStat.type == FileSystemEntityType.notFound) {
_fileStat = null;
_linkTarget = null;
} else if (devFSConfig?.cacheSymlinks == true) {
} else if (devFSConfig?.cacheSymlinks ?? false) {
_linkTarget = linkTarget;
}
}

View File

@ -130,7 +130,7 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider {
NoIdeValidator(),
if (proxyValidator.shouldShow)
proxyValidator,
if (globals.deviceManager?.canListAnything == true)
if (globals.deviceManager?.canListAnything ?? false)
DeviceValidator(
deviceManager: globals.deviceManager,
userMessages: globals.userMessages,
@ -153,11 +153,11 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider {
_workflows!.add(globals.iosWorkflow!);
}
if (androidWorkflow?.appliesToHostPlatform == true) {
if (androidWorkflow?.appliesToHostPlatform ?? false) {
_workflows!.add(androidWorkflow!);
}
if (fuchsiaWorkflow?.appliesToHostPlatform == true) {
if (fuchsiaWorkflow?.appliesToHostPlatform ?? false) {
_workflows!.add(fuchsiaWorkflow!);
}
@ -169,7 +169,7 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider {
_workflows!.add(macOSWorkflow);
}
if (windowsWorkflow?.appliesToHostPlatform == true) {
if (windowsWorkflow?.appliesToHostPlatform ?? false) {
_workflows!.add(windowsWorkflow!);
}

View File

@ -273,7 +273,7 @@ class FlutterManifest {
Map<String, Object?>? get supportedPlatforms {
if (isPlugin) {
final YamlMap? plugin = _flutterDescriptor['plugin'] as YamlMap?;
if (plugin?.containsKey('platforms') == true) {
if (plugin?.containsKey('platforms') ?? false) {
final YamlMap? platformsMap = plugin!['platforms'] as YamlMap?;
return platformsMap?.value.cast<String, Object?>();
}

View File

@ -393,8 +393,8 @@ Future<void> _writeAndroidPluginRegistrant(FlutterProject project, List<Plugin>
final List<String> pluginsUsingV1 = <String>[];
for (final Map<String, Object?> plugin in androidPlugins) {
final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) == true;
final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) == true;
final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) ?? false;
final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) ?? false;
if (supportsEmbeddingV1 && !supportsEmbeddingV2) {
templateContext['needsShim'] = true;
if (plugin['name'] != null) {
@ -431,8 +431,8 @@ Future<void> _writeAndroidPluginRegistrant(FlutterProject project, List<Plugin>
'Take a look at the docs for migrating an app: https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects'
);
for (final Map<String, Object?> plugin in androidPlugins) {
final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) == true;
final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) == true;
final bool supportsEmbeddingV1 = (plugin['supportsEmbeddingV1'] as bool?) ?? false;
final bool supportsEmbeddingV2 = (plugin['supportsEmbeddingV2'] as bool?) ?? false;
if (!supportsEmbeddingV1 && supportsEmbeddingV2) {
throwToolExit(
'The plugin `${plugin['name']}` requires your app to be migrated to '

View File

@ -723,7 +723,7 @@ class FuchsiaDevice extends Device {
continue;
}
final int? port = vmService.httpAddress?.port;
if (port != null && uiIsolate.name?.contains(isolateName) == true) {
if (port != null && (uiIsolate.name?.contains(isolateName) ?? false)) {
return port;
}
}
@ -821,7 +821,7 @@ class FuchsiaIsolateDiscoveryProtocol {
continue;
}
final int? port = service?.httpAddress?.port;
if (port != null && uiIsolate.name?.contains(_isolateName) == true) {
if (port != null && (uiIsolate.name?.contains(_isolateName) ?? false)) {
_foundUri.complete(_device.ipv6
? Uri.parse('http://[$_ipv6Loopback]:$port/')
: Uri.parse('http://$_ipv4Loopback:$port/'));

View File

@ -230,7 +230,7 @@ class FuchsiaPackageServer {
if (_process == null) {
return false;
}
return (await globals.fuchsiaSdk?.fuchsiaPM.publish(_repo, package.path)) == true;
return (await globals.fuchsiaSdk?.fuchsiaPM.publish(_repo, package.path)) ?? false;
}
@override

View File

@ -14,7 +14,7 @@ class IOSEmulators extends EmulatorDiscovery {
bool get supportsPlatform => globals.platform.isMacOS;
@override
bool get canListAnything => globals.iosWorkflow?.canListEmulators == true;
bool get canListAnything => globals.iosWorkflow?.canListEmulators ?? false;
@override
Future<List<Emulator>> get emulators async => getEmulators();

View File

@ -561,9 +561,9 @@ return result.exitCode != 0 &&
Future<void> diagnoseXcodeBuildFailure(XcodeBuildResult result, Usage flutterUsage, Logger logger) async {
final XcodeBuildExecution? xcodeBuildExecution = result.xcodeBuildExecution;
if (xcodeBuildExecution != null &&
xcodeBuildExecution.environmentType == EnvironmentType.physical &&
result.stdout?.toUpperCase().contains('BITCODE') == true) {
if (xcodeBuildExecution != null
&& xcodeBuildExecution.environmentType == EnvironmentType.physical
&& (result.stdout?.toUpperCase().contains('BITCODE') ?? false)) {
BuildEvent('xcode-bitcode-failure',
type: 'ios',
command: xcodeBuildExecution.buildCommands.toString(),
@ -575,9 +575,9 @@ Future<void> diagnoseXcodeBuildFailure(XcodeBuildResult result, Usage flutterUsa
// Building for iOS Simulator, but the linked and embedded framework 'App.framework' was built for iOS.
// or
// Building for iOS, but the linked and embedded framework 'App.framework' was built for iOS Simulator.
if (result.stdout?.contains('Building for iOS') == true
&& result.stdout?.contains('but the linked and embedded framework') == true
&& result.stdout?.contains('was built for iOS') == true) {
if ((result.stdout?.contains('Building for iOS') ?? false)
&& (result.stdout?.contains('but the linked and embedded framework') ?? false)
&& (result.stdout?.contains('was built for iOS') ?? false)) {
logger.printError('');
logger.printError('Your Xcode project requires migration. See https://flutter.dev/docs/development/ios-project-migration for details.');
logger.printError('');
@ -585,11 +585,11 @@ Future<void> diagnoseXcodeBuildFailure(XcodeBuildResult result, Usage flutterUsa
logger.printError(' flutter clean');
return;
}
if (xcodeBuildExecution != null &&
xcodeBuildExecution.environmentType == EnvironmentType.physical &&
result.stdout?.contains('BCEROR') == true &&
if (xcodeBuildExecution != null
&& xcodeBuildExecution.environmentType == EnvironmentType.physical
&& (result.stdout?.contains('BCEROR') ?? false)
// May need updating if Xcode changes its outputs.
result.stdout?.contains("Xcode couldn't find a provisioning profile matching") == true) {
&& (result.stdout?.contains("Xcode couldn't find a provisioning profile matching") ?? false)) {
logger.printError(noProvisioningProfileInstruction, emphasis: true);
return;
}
@ -603,9 +603,9 @@ Future<void> diagnoseXcodeBuildFailure(XcodeBuildResult result, Usage flutterUsa
logger.printError(noDevelopmentTeamInstruction, emphasis: true);
return;
}
if (xcodeBuildExecution != null &&
xcodeBuildExecution.environmentType == EnvironmentType.physical &&
xcodeBuildExecution.buildSettings['PRODUCT_BUNDLE_IDENTIFIER']?.contains('com.example') == true) {
if (xcodeBuildExecution != null
&& xcodeBuildExecution.environmentType == EnvironmentType.physical
&& (xcodeBuildExecution.buildSettings['PRODUCT_BUNDLE_IDENTIFIER']?.contains('com.example') ?? false)) {
logger.printError('');
logger.printError('It appears that your application still contains the default signing identifier.');
logger.printError("Try replacing 'com.example' with your signing id in Xcode:");

View File

@ -45,7 +45,7 @@ Future<void> processPodsIfNeeded(
xcodeProject: xcodeProject,
buildMode: buildMode,
dependenciesChanged: !fingerprinter.doesFingerprintMatch(),
) == true;
) ?? false;
if (didPodInstall) {
fingerprinter.writeFingerprint();
}

View File

@ -206,7 +206,7 @@ class XCDevice {
unawaited(stdoutSubscription.cancel());
unawaited(stderrSubscription.cancel());
}).whenComplete(() async {
if (_deviceIdentifierByEvent?.hasListener == true) {
if (_deviceIdentifierByEvent?.hasListener ?? false) {
// Tell listeners the process died.
await _deviceIdentifierByEvent?.close();
}

View File

@ -62,7 +62,7 @@ class CmakeCustomCommandMigration extends ProjectMigrator {
// Manually-specified variables were not used by the project:
// FLUTTER_TARGET_PLATFORM
// ------------------------------
if (addCustomCommandOriginal?.contains('linux-x64') == true) {
if (addCustomCommandOriginal?.contains('linux-x64') ?? false) {
newProjectContents = newProjectContents.replaceAll('linux-x64', r'${FLUTTER_TARGET_PLATFORM}');
}
}

View File

@ -474,7 +474,7 @@ class LinuxPlugin extends PluginPlatform implements NativeOrDartPlugin {
bool? ffiPlugin,
this.defaultPackage,
}) : ffiPlugin = ffiPlugin ?? false,
assert(pluginClass != null || dartPluginClass != null || ffiPlugin == true || defaultPackage != null);
assert(pluginClass != null || dartPluginClass != null || (ffiPlugin ?? false) || defaultPackage != null);
factory LinuxPlugin.fromYaml(String name, YamlMap yaml) {
assert(validate(yaml));

View File

@ -164,7 +164,7 @@ class PreviewDevice extends Device {
@override
Future<bool> stopApp(covariant ApplicationPackage app, {String? userIdentifier}) async {
return _process?.kill() == true;
return _process?.kill() ?? false;
}
@override

View File

@ -290,7 +290,7 @@ abstract class FlutterCommand extends Command<void> {
}
String get targetFile {
if (argResults?.wasParsed('target') == true) {
if (argResults?.wasParsed('target') ?? false) {
return stringArg('target')!;
}
final List<String>? rest = argResults?.rest;
@ -422,8 +422,8 @@ abstract class FlutterCommand extends Command<void> {
late final bool enableDds = () {
bool ddsEnabled = false;
if (argResults?.wasParsed('disable-dds') == true) {
if (argResults?.wasParsed('dds') == true) {
if (argResults?.wasParsed('disable-dds') ?? false) {
if (argResults?.wasParsed('dds') ?? false) {
throwToolExit(
'The "--[no-]dds" and "--[no-]disable-dds" arguments are mutually exclusive. Only specify "--[no-]dds".');
}
@ -444,8 +444,8 @@ abstract class FlutterCommand extends Command<void> {
return ddsEnabled;
}();
bool get _hostVmServicePortProvided => argResults?.wasParsed('observatory-port') == true ||
argResults?.wasParsed('host-vmservice-port') == true;
bool get _hostVmServicePortProvided => (argResults?.wasParsed('observatory-port') ?? false)
|| (argResults?.wasParsed('host-vmservice-port') ?? false);
int _tryParseHostVmservicePort() {
final String? observatoryPort = stringArg('observatory-port');
@ -464,7 +464,7 @@ abstract class FlutterCommand extends Command<void> {
if (argResults?.wasParsed('dds-port') != true && _hostVmServicePortProvided) {
// If an explicit DDS port is _not_ provided, use the host-vmservice-port for DDS.
return _tryParseHostVmservicePort();
} else if (argResults?.wasParsed('dds-port') == true) {
} else if (argResults?.wasParsed('dds-port') ?? false) {
// If an explicit DDS port is provided, use dds-port for DDS.
return int.tryParse(stringArg('dds-port')!) ?? 0;
}
@ -473,7 +473,7 @@ abstract class FlutterCommand extends Command<void> {
}
Uri? get devToolsServerAddress {
if (argResults?.wasParsed(kDevToolsServerAddress) == true) {
if (argResults?.wasParsed(kDevToolsServerAddress) ?? false) {
final Uri? uri = Uri.tryParse(stringArg(kDevToolsServerAddress)!);
if (uri != null && uri.host.isNotEmpty && uri.port != 0) {
return uri;
@ -493,8 +493,8 @@ abstract class FlutterCommand extends Command<void> {
if (!_usesPortOption || !_hostVmServicePortProvided) {
return null;
}
if (argResults?.wasParsed('observatory-port') == true &&
argResults?.wasParsed('host-vmservice-port') == true) {
if ((argResults?.wasParsed('observatory-port') ?? false)
&& (argResults?.wasParsed('host-vmservice-port') ?? false)) {
throwToolExit('Only one of "--observatory-port" and '
'"--host-vmservice-port" may be specified.');
}
@ -612,8 +612,8 @@ abstract class FlutterCommand extends Command<void> {
bool get reportNullSafety => false;
late final Duration? deviceDiscoveryTimeout = () {
if (argResults?.options.contains(FlutterOptions.kDeviceTimeout) == true
&& argResults?.wasParsed(FlutterOptions.kDeviceTimeout) == true) {
if ((argResults?.options.contains(FlutterOptions.kDeviceTimeout) ?? false)
&& (argResults?.wasParsed(FlutterOptions.kDeviceTimeout) ?? false)) {
final int? timeoutSeconds = int.tryParse(stringArg(FlutterOptions.kDeviceTimeout)!);
if (timeoutSeconds == null) {
throwToolExit( 'Could not parse "--${FlutterOptions.kDeviceTimeout}" argument. It must be an integer.');
@ -1000,7 +1000,7 @@ abstract class FlutterCommand extends Command<void> {
// Explicitly check for `true` and `false` so that `null` results in not
// passing a flag. Examine the entrypoint file to determine if it
// is opted in or out.
final bool wasNullSafetyFlagParsed = argResults?.wasParsed(FlutterOptions.kNullSafety) == true;
final bool wasNullSafetyFlagParsed = argResults?.wasParsed(FlutterOptions.kNullSafety) ?? false;
if (!wasNullSafetyFlagParsed && (argParser.options.containsKey('target') || forcedTargetFile != null)) {
final File entrypointFile = forcedTargetFile ?? globals.fs.file(targetFile);
final LanguageVersion languageVersion = determineLanguageVersion(

View File

@ -205,12 +205,12 @@ class FlutterCommandRunner extends CommandRunner<void> {
wrapColumn: wrapColumn,
);
if ((topLevelResults['show-test-device'] as bool?) == true ||
topLevelResults['device-id'] == FlutterTesterDevices.kTesterDeviceId) {
if (((topLevelResults['show-test-device'] as bool?) ?? false)
|| topLevelResults['device-id'] == FlutterTesterDevices.kTesterDeviceId) {
FlutterTesterDevices.showFlutterTesterDevice = true;
}
if ((topLevelResults['show-web-server-device'] as bool?) == true ||
topLevelResults['device-id'] == WebServerDevice.kWebServerDeviceId) {
if (((topLevelResults['show-web-server-device'] as bool?) ?? false)
|| topLevelResults['device-id'] == WebServerDevice.kWebServerDeviceId) {
WebServerDevice.showWebServerDevice = true;
}
@ -231,13 +231,13 @@ class FlutterCommandRunner extends CommandRunner<void> {
return MapEntry<Type, Generator>(type, () => value);
}),
body: () async {
globals.logger.quiet = (topLevelResults['quiet'] as bool?) == true;
globals.logger.quiet = (topLevelResults['quiet'] as bool?) ?? false;
if (globals.platform.environment['FLUTTER_ALREADY_LOCKED'] != 'true') {
await globals.cache.lock();
}
if ((topLevelResults['suppress-analytics'] as bool?) == true) {
if ((topLevelResults['suppress-analytics'] as bool?) ?? false) {
globals.flutterUsage.suppressAnalytics = true;
}
@ -258,7 +258,7 @@ class FlutterCommandRunner extends CommandRunner<void> {
// See if the user specified a specific device.
globals.deviceManager?.specifiedDeviceId = topLevelResults['device-id'] as String?;
if ((topLevelResults['version'] as bool?) == true) {
if ((topLevelResults['version'] as bool?) ?? false) {
globals.flutterUsage.sendCommand('version');
globals.flutterVersion.fetchTagsAndUpdate();
String status;

View File

@ -166,7 +166,7 @@ class Template {
throwToolExit('Failed to flutter create at ${destination.path}.');
}
int fileCount = 0;
final bool implementationTests = (context['implementationTests'] as bool?) == true;
final bool implementationTests = (context['implementationTests'] as bool?) ?? false;
/// Returns the resolved destination path corresponding to the specified
/// raw destination path, after performing language filtering and template
@ -184,38 +184,38 @@ class Template {
relativeDestinationPath = relativeDestinationPath.replaceAll('$platform-$language.tmpl', platform);
}
final bool android = (context['android'] as bool?) == true;
final bool android = (context['android'] as bool?) ?? false;
if (relativeDestinationPath.contains('android') && !android) {
return null;
}
final bool ios = (context['ios'] as bool?) == true;
final bool ios = (context['ios'] as bool?) ?? false;
if (relativeDestinationPath.contains('ios') && !ios) {
return null;
}
// Only build a web project if explicitly asked.
final bool web = (context['web'] as bool?) == true;
final bool web = (context['web'] as bool?) ?? false;
if (relativeDestinationPath.contains('web') && !web) {
return null;
}
// Only build a Linux project if explicitly asked.
final bool linux = (context['linux'] as bool?) == true;
final bool linux = (context['linux'] as bool?) ?? false;
if (relativeDestinationPath.startsWith('linux.tmpl') && !linux) {
return null;
}
// Only build a macOS project if explicitly asked.
final bool macOS = (context['macos'] as bool?) == true;
final bool macOS = (context['macos'] as bool?) ?? false;
if (relativeDestinationPath.startsWith('macos.tmpl') && !macOS) {
return null;
}
// Only build a Windows project if explicitly asked.
final bool windows = (context['windows'] as bool?) == true;
final bool windows = (context['windows'] as bool?) ?? false;
if (relativeDestinationPath.startsWith('windows.tmpl') && !windows) {
return null;
}
// Only build a Windows UWP project if explicitly asked.
final bool windowsUwp = (context['winuwp'] as bool?) == true;
final bool windowsUwp = (context['winuwp'] as bool?) ?? false;
if (relativeDestinationPath.startsWith('winuwp.tmpl') && !windowsUwp) {
return null;
}

View File

@ -866,7 +866,7 @@ class FlutterVmService {
final List<vm_service.IsolateRef> refs = await _getIsolateRefs();
for (final vm_service.IsolateRef ref in refs) {
final vm_service.Isolate? isolate = await getIsolateOrNull(ref.id!);
if (isolate != null && isolate.extensionRPCs?.contains(extensionName) == true) {
if (isolate != null && (isolate.extensionRPCs?.contains(extensionName) ?? false)) {
return ref;
}
}

View File

@ -293,7 +293,7 @@ class VsCode {
final String jsonString = fileSystem.file(packageJsonPath).readAsStringSync();
try {
final Map<String, dynamic>? jsonObject = castStringKeyedMap(json.decode(jsonString));
if (jsonObject?.containsKey('version') == true) {
if (jsonObject?.containsKey('version') ?? false) {
return jsonObject!['version'] as String;
}
} on FormatException {

View File

@ -230,7 +230,7 @@ class IosProject extends XcodeBasedProject {
// https://flutter.dev/docs/deployment/ios#review-xcode-project-settings
// The only source of truth for the name is Xcode's interpretation of the build settings.
String? productName;
if (globals.xcodeProjectInterpreter?.isInstalled == true) {
if (globals.xcodeProjectInterpreter?.isInstalled ?? false) {
final Map<String, String>? xcodeBuildSettings = await buildSettingsForBuildInfo(buildInfo);
if (xcodeBuildSettings != null) {
productName = xcodeBuildSettings['FULL_PRODUCT_NAME'];

View File

@ -158,7 +158,7 @@ abstract class FlutterTestDriver {
_vmService!.streamListen('Debug'),
]);
if ((await _vmService!.getVM()).isolates?.isEmpty != false) {
if ((await _vmService!.getVM()).isolates?.isEmpty ?? true) {
await isolateStarted.future;
}
@ -287,7 +287,7 @@ abstract class FlutterTestDriver {
return _vmService!.onDebugEvent
.where((Event event) {
return event.isolate?.id == isolateId
&& event.kind?.startsWith(kind) == true;
&& (event.kind?.startsWith(kind) ?? false);
}).first;
}
@ -302,7 +302,7 @@ abstract class FlutterTestDriver {
// don't need to wait for the event.
final VmService vmService = _vmService!;
final Isolate isolate = await vmService.getIsolate(isolateId);
if (isolate.pauseEvent?.kind?.startsWith(kind) == true) {
if (isolate.pauseEvent?.kind?.startsWith(kind) ?? false) {
_debugPrint('Isolate was already at "$kind" (${isolate.pauseEvent!.kind}).');
event.ignore();
} else {
@ -324,7 +324,7 @@ abstract class FlutterTestDriver {
Future<bool> isAtAsyncSuspension() async {
final Isolate isolate = await getFlutterIsolate();
return isolate.pauseEvent?.atAsyncSuspension == true;
return isolate.pauseEvent?.atAsyncSuspension ?? false;
}
Future<Isolate?> stepOverOrOverAsyncSuspension({ bool waitForNextPause = true }) async {