getBestConstructorForCopyWith function
ConstructorDeclaration?
getBestConstructorForCopyWith(
- ClassDeclaration node
Gets the best constructor for copyWith generation Returns null if no suitable constructor is found
Implementation
ConstructorDeclaration? getBestConstructorForCopyWith(ClassDeclaration node) {
final constructors = node.members
.whereType<ConstructorDeclaration>()
.toList();
if (constructors.isEmpty) {
return null; // Cannot generate copyWith!
}
// Priority 1: Unnamed constructor with named parameters
final unnamedWithNamedParams = constructors.firstWhereOrNull((c) {
final name = c.name?.lexeme;
final hasNamedParams = c.parameters.parameters.any((p) => p.isNamed);
return name == null && hasNamedParams;
});
if (unnamedWithNamedParams != null) {
return unnamedWithNamedParams;
}
// Priority 2: Any unnamed constructor
final unnamed = constructors.firstWhereOrNull((c) => c.name?.lexeme == null);
if (unnamed != null) {
return unnamed;
}
// Priority 3: Named constructor with most named parameters
final bestNamed = constructors.reduce((a, b) {
final aNamedCount = a.parameters.parameters.where((p) => p.isNamed).length;
final bNamedCount = b.parameters.parameters.where((p) => p.isNamed).length;
return aNamedCount >= bNamedCount ? a : b;
});
return bestNamed;
}