[go: nahoru, domu]

Skip to content

Commit

Permalink
Enable use_if_null_to_convert_nulls_to_bools lint (flutter#98753)
Browse files Browse the repository at this point in the history
  • Loading branch information
tgucio committed Feb 22, 2022
1 parent a7790d8 commit e4351ff
Show file tree
Hide file tree
Showing 71 changed files with 179 additions and 166 deletions.
2 changes: 1 addition & 1 deletion analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion dev/devicelab/lib/framework/browser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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}',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 4 additions & 4 deletions dev/manual_tests/lib/density.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
),
Expand Down Expand Up @@ -566,7 +566,7 @@ class _MyHomePageState extends State<MyHomePage> {
onChanged: _model.enable
? (bool? value) {
setState(() {
checkboxValues[index] = value == true;
checkboxValues[index] = value ?? false;
});
}
: null,
Expand Down
2 changes: 1 addition & 1 deletion dev/manual_tests/lib/text.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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>())
Expand Down
4 changes: 2 additions & 2 deletions packages/flutter/lib/src/cupertino/date_picker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/cupertino/nav_bar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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',
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/cupertino/text_field.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 4 additions & 4 deletions packages/flutter/lib/src/foundation/diagnostics.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand All @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/gestures/recognizer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}());
Expand Down
6 changes: 3 additions & 3 deletions packages/flutter/lib/src/material/checkbox.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down
8 changes: 4 additions & 4 deletions packages/flutter/lib/src/material/input_decorator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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 :
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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',
Expand Down
6 changes: 3 additions & 3 deletions packages/flutter/lib/src/material/scaffold.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 '
Expand Down Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/material/slider_theme.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions packages/flutter/lib/src/material/toggleable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/flutter/lib/src/rendering/editable.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions packages/flutter/lib/src/rendering/object.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter/lib/src/rendering/paragraph.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions packages/flutter/lib/src/rendering/proxy_box.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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',
);

Expand Down
6 changes: 3 additions & 3 deletions packages/flutter/lib/src/semantics/semantics.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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));
Expand Down
Loading

0 comments on commit e4351ff

Please sign in to comment.