compute method

  1. @override
Future<void> compute(
  1. ChangeBuilder builder
)
override

Computes the changes for this producer using builder.

This method should not modify fixKind.

Implementation

@override
Future<void> compute(ChangeBuilder builder) async {
  final node = this.node;
  if (node is! InstanceCreationExpression) return;

  final childArgument = node.argumentList.argumentByName('child');
  final otherArguments = node.argumentList.arguments.where(
    (argument) => argument != childArgument,
  );

  Future<void> build(String replacement) {
    return builder.addDartFileEdit(file, (builder) {
      builder.addSimpleReplacement(range.entity(node), replacement);
    });
  }

  if (otherArguments.isEmpty) {
    if (childArgument == null) {
      await build('const SizedBox.shrink()');
    } else {
      await build(childArgument.expression.toSource());
    }
  } else if (otherArguments.length == 1) {
    final otherArgument = otherArguments.single as NamedExpression;

    final widget = switch (otherArgument.name.label.name) {
      'alignment' => 'Align',
      'padding' || 'margin' => 'Padding',
      'color' => 'ColoredBox',
      'decoration' || 'foregroundDecoration' => 'DecoratedBox',
      'width' || 'height' => 'SizedBox',
      'constraints' => 'ConstrainedBox',
      'transform' => 'Transform',
      'clipBehavior' => 'ClipRRect',
      _ => null,
    };

    if (widget == null) return;

    final arguments = node.argumentList
        .toSource()
        .replaceFirst('foregroundDecoration:', 'decoration:')
        .replaceFirst('margin:', 'padding:');

    await build('$widget$arguments');
  } else if (_canBeSizedBox(node)) {
    await build('SizedBox${node.argumentList.toSource()}');
  } else if (_canBeTransform(node)) {
    final arguments = node.argumentList.arguments
        .whereType<NamedExpression>()
        .map((argument) {
          if (argument.name.label.name == 'transformAlignment') {
            return 'alignment: ${argument.expression.toSource()}';
          }
          return argument.toSource();
        })
        .join(', ');
    await build('Transform($arguments)');
  }
}