Skip to content
This repository was archived by the owner on Nov 20, 2024. It is now read-only.

fix super.key false positive for use_key_in_widget_constructors #3295

Merged
merged 2 commits into from
Mar 17, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions lib/src/rules/use_key_in_widget_constructors.dart
Original file line number Diff line number Diff line change
@@ -79,6 +79,7 @@ class _Visitor extends SimpleAstVisitor<void> {
classElement.isPublic &&
hasWidgetAsAscendant(classElement) &&
!isExactWidget(classElement) &&
!_hasKeySuperParameterInitializerArg(node) &&
!node.initializers.any((initializer) {
if (initializer is SuperConstructorInvocation) {
var staticElement = initializer.staticElement;
@@ -98,12 +99,23 @@ class _Visitor extends SimpleAstVisitor<void> {
super.visitConstructorDeclaration(node);
}

bool _defineKeyParameter(ConstructorElement element) =>
element.parameters.any((e) => e.name == 'key' && _isKeyType(e.type));

bool _defineKeyArgument(ArgumentList argumentList) => argumentList.arguments
.any((a) => a.staticParameterElement?.name == 'key');

bool _defineKeyParameter(ConstructorElement element) =>
element.parameters.any((e) => e.name == 'key' && _isKeyType(e.type));

bool _isKeyType(DartType type) =>
DartTypeUtilities.implementsInterface(type, 'Key', '');

bool _hasKeySuperParameterInitializerArg(ConstructorDeclaration node) {
for (var parameter in node.parameters.parameters) {
var element = parameter.declaredElement;
if (element is SuperFormalParameterElement && element.name == 'key') {
return true;
}
}

return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
analyzer:
enable-experiment:
- super-parameters
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
flutter:../../../../mock_packages/flutter/lib/
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// test w/ `dart test -N use_key_in_widget_constructors`

import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';

/// https://github.com/flutter/flutter/issues/100297
class OtherWidget extends StatelessWidget {
const OtherWidget({required super.key}); //OK

@override
Widget build(BuildContext context) {
return Container();
}
}