ronantakizawa/codereview-bench huggingface dataset:
Repository: flutter/flutter
File: packages/flutter/test/cupertino/sliding_segmented_control_test.dart (Dart)

Code before:
          return CupertinoSlidingSegmentedControl<int>(
            isMomentary: true,
            children: children,
            groupValue: groupValue,
            onValueChanged: defaultCallback,
          );
        },
      ),
    );

    final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('A')));
    final Finder scaleTransition = find.ancestor(
      of: find.text('A'),
      matching: find.byType(ScaleTransition),
    );

    await tester.pumpAndSettle(const Duration(milliseconds: 206));
    double scale = tester.widget<ScaleTransition>(scaleTransition).scale.value;
    expect(scale, greaterThan(1.0));

    await gesture.up();

    await tester.pumpAndSettle();
    scale = tester.widget<ScaleTransition>(scaleTransition).scale.value;
    // Spring animations approach but don't exactly reach normal scale.
    expect(scale, moreOrLessEquals(1.0, epsilon: 0.01));
  });
}


Review comment (suggestion):
I don't think this comment is relevant after our discussion [here](https://github.com/flutter/flutter/pull/164262#issuecomment-2964631402).
```suggestion
    expect(scale, moreOrLessEquals(1.0, epsilon: 0.01));
```
Or even
```suggestion
    expect(scale, moreOrLessEquals(1.0));
```

Code after:
          return CupertinoSlidingSegmentedControl<int>(
            isMomentary: true,
            children: children,
            onValueChanged: defaultCallback,
          );
        },
      ),
    );

    final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('A')));
    final Finder scaleTransition = find.ancestor(
      of: find.text('A'),
      matching: find.byType(ScaleTransition),
    );

    await tester.pumpAndSettle();
    double scale = tester.widget<ScaleTransition>(scaleTransition).scale.value;
    expect(scale, greaterThan(1.0));

    await gesture.up();

    await tester.pumpAndSettle();
    scale = tester.widget<ScaleTransition>(scaleTransition).scale.value;
    expect(scale, moreOrLessEquals(1.0));
  });
}
Repository: flutter/flutter
File: packages/flutter/test/cupertino/sliding_segmented_control_test.dart (Dart)

Code before:
  testWidgets('CupertinoSlidingSegmentedControl with momentary scales up selected segment', (
    WidgetTester tester,
  ) async {
    const Map<int, Widget> children = <int, Widget>{0: Text('A'), 1: Text('BB'), 2: Text('CCCC')};

    groupValue = 1;
    await tester.pumpWidget(
      boilerplate(
        builder: (BuildContext context) {
          return CupertinoSlidingSegmentedControl<int>(
            isMomentary: true,
            children: children,
            groupValue: groupValue,
            onValueChanged: defaultCallback,
          );
        },
      ),
    );

    final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('A')));
    final Finder scaleTransition = find.ancestor(
      of: find.text('A'),
      matching: find.byType(ScaleTransition),
    );

    await tester.pumpAndSettle();
    double scale = tester.widget<ScaleTransition>(scaleTransition).scale.value;
    expect(scale, greaterThan(1.0));

    await gesture.up();

    await tester.pumpAndSettle();
    scale = tester.widget<ScaleTransition>(scaleTransition).scale.value;
    expect(scale, moreOrLessEquals(1.0));
  });
}


Review comment (bug):
We might need to fix the failed test:
<img width="3408" height="814" alt="Screenshot 2025-07-16 at 2 46 46 PM" src="https://github.com/user-attachments/assets/15176092-95ef-4c34-b670-8417bcc91723" />


Code after:
  testWidgets('CupertinoSlidingSegmentedControl with momentary scales up selected segment', (
    WidgetTester tester,
  ) async {
    const Map<int, Widget> children = <int, Widget>{0: Text('A'), 1: Text('BB'), 2: Text('CCCC')};

    await tester.pumpWidget(
      boilerplate(
        builder: (BuildContext context) {
          return CupertinoSlidingSegmentedControl<int>(
            isMomentary: true,
            children: children,
            onValueChanged: defaultCallback,
          );
        },
      ),
    );

    final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('A')));
    final Finder scaleTransition = find.ancestor(
      of: find.text('A'),
      matching: find.byType(ScaleTransition),
    );

    await tester.pumpAndSettle();
    double scale = tester.widget<ScaleTransition>(scaleTransition).scale.value;
    expect(scale, greaterThan(1.0));

    await gesture.up();

    await tester.pumpAndSettle();
    scale = tester.widget<ScaleTransition>(scaleTransition).scale.value;
    expect(scale, moreOrLessEquals(1.0));
  });
}
Repository: flutter/flutter
File: packages/flutter/lib/src/cupertino/sheet.dart (Dart)

Code before:
  bool updateShouldNotify(_CupertinoSheetScope oldWidget) => false;
}

/// A mixin that replaces the entire screen with an iOS sheet transition for a
/// [PageRoute].
///
/// See also:
///
///  * [CupertinoSheetRoute], which is a [PageRoute] that leverages this mixin.
mixin _CupertinoSheetRouteTransitionMixin<T> on PageRoute<T> {
  /// Builds the primary contents of the route.
  @protected
  Widget buildContent(BuildContext context);

  @override
  Duration get transitionDuration => const Duration(milliseconds: 500);

  @override
  DelegatedTransitionBuilder? get delegatedTransition =>
      (
        BuildContext context,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
        bool allowSnapshotting,
        Widget? child,
      ) => CupertinoSheetTransition.delegateTransition(
        context,
        animation,
        secondaryAnimation,
        allowSnapshotting,
        child,
        topGap: topGap,
      );

  /// Determines whether the content can be dragged.
  ///
  /// If `true`, dragging is enabled; otherwise, it remains fixed.
  bool get enableDrag;

  /// The gap between the top of the screen and the top of the sheet as a ratio
  /// of the screen height (0.0 to 1.0). Defaults to [_kTopGapRatio].
  double get topGap;

  @override
  Widget buildPage(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
  ) {
    return buildContent(context);
  }

Review comment (suggestion):
I think this can be simplified to
```dart
_topGap != null ? null : CupertinoSheetTransition.delegateTransition;
```

Code after:
  @override
  double get topGap => _topGap ?? _kTopGapRatio;

  @override
  bool get _hasCustomTopGap => _topGap != null;

  @override
  Widget buildContent(BuildContext context) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: ClipRSuperellipse(
        borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
        child: CupertinoUserInterfaceLevel(
          data: CupertinoUserInterfaceLevelData.elevated,
          child: _CupertinoSheetScope(child: builder(context)),
        ),
      ),
    );
  }

  /// Checks if a Cupertino sheet view exists in the widget tree above the current
  /// context.
  static bool hasParentSheet(BuildContext context) {
    return _CupertinoSheetScope.maybeOf(context) != null;
  }

  /// Pops the entire [CupertinoSheetRoute], if a sheet route exists in the stack.
  ///
  /// Used if to pop an entire sheet at once, if there is nested navigation within
  /// that sheet.
  static void popSheet(BuildContext context) {
    if (hasParentSheet(context)) {
      Navigator.of(context, rootNavigator: true).pop();
    }
  }

  @override
  Color? get barrierColor => CupertinoColors.transparent;

  @override
  bool get barrierDismissible => false;

  @override
  String? get barrierLabel => null;

  @override
  bool get maintainState => true;

  @override
  bool get opaque => false;
Repository: flutter/flutter
File: packages/flutter/lib/src/cupertino/sheet.dart (Dart)

Code before:
  }

  @override
  bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) {
    if (this is CupertinoSheetRoute<dynamic>) {
      return !hasCustomTopGap;
    }
    return true;
  }

  @override
  bool canTransitionTo(TransitionRoute<dynamic> nextRoute) {
    if (this is CupertinoSheetRoute<dynamic>) {
      return !hasCustomTopGap && nextRoute is _CupertinoSheetRouteTransitionMixin;
    }
    return nextRoute is _CupertinoSheetRouteTransitionMixin;
  }

  @override
  Widget buildTransitions(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child,
  ) {
    return buildPageTransitions<T>(
      this,
      context,
      animation,
      secondaryAnimation,
      child,
      enableDrag,
      topGap,
    );
  }
}

class _CupertinoDragGestureDetector<T> extends StatefulWidget {
  const _CupertinoDragGestureDetector({
    super.key,
    required this.enabledCallback,
    required this.onStartPopGesture,
    required this.child,
  });

  final Widget child;

  final ValueGetter<bool> enabledCallback;

  final ValueGetter<_CupertinoDragGestureController<T>> onStartPopGesture;


Review comment (suggestion):
Ideally, I think it would be better if it could be simplified down to
```dart
bool canTransitionTo(TransitionRoute<dynamic> nextRoute) {
   return nextRoute is _CupertinoSheetRouteTransitionMixin && !hasCustomTopGap;
}
```

But at worst it could be 
```dart
bool canTransitionTo(TransitionRoute<dynamic> nextRoute) {
   if (this is CupertinoSheetRoute<dynamic> && hasCustomTopGap) {
      return false;
    }
   return nextRoute is _CupertinoSheetRouteTransitionMixin && !hasCustomTopGap;
}

Code after:
  ) {
    final bool linearTransition = route.popGestureInProgress;
    return CupertinoSheetTransition(
      primaryRouteAnimation: animation,
      secondaryRouteAnimation: secondaryAnimation,
      linearTransition: linearTransition,
      topGap: topGap,
      child: _CupertinoDragGestureDetector<T>(
        enabledCallback: () => enableDrag,
        onStartPopGesture: () => _startPopGesture<T>(route, topGap),
        child: child,
      ),
    );
  }

  @override
  bool canTransitionFrom(TransitionRoute<dynamic> previousRoute) {
    return !_hasCustomTopGap;
  }

  @override
  bool canTransitionTo(TransitionRoute<dynamic> nextRoute) {
    if (this is CupertinoSheetRoute<dynamic> && _hasCustomTopGap) {
      return false;
    }
    return nextRoute is _CupertinoSheetRouteTransitionMixin;
  }

  @override
  Widget buildTransitions(
    BuildContext context,
    Animation<double> animation,
    Animation<double> secondaryAnimation,
    Widget child,
  ) {
    return buildPageTransitions<T>(
      this,
      context,
      animation,
      secondaryAnimation,
      child,
      enableDrag,
      topGap,
    );
  }
}

class _CupertinoDragGestureDetector<T> extends StatefulWidget {
  const _CupertinoDragGestureDetector({
    super.key,
    required this.enabledCallback,
Repository: flutter/flutter
File: packages/flutter_tools/test/commands.shard/hermetic/build_ios_test.dart (Dart)

Code before:
  );

  FakeCommand setUpRsyncCommand({void Function(List<String> command)? onRun}) {
    return FakeCommand(
      command: const <String>[
        'rsync',
        '-8',
        '-av',
        '--delete',
        'build/ios/Release-iphoneos/Runner.app',
        'build/ios/iphoneos',
      ],
      onRun: onRun,
    );
  }

  FakeCommand setUpXCResultCommand({
    String stdout = '',
    void Function(List<String> command)? onRun,
  }) {
    return FakeCommand(
      command: const <String>[
        'xcrun',
        'xcresulttool',
        'get',
        'build-results',
        '--path',
        _xcBundleDirectoryPath,
        '--format',
        'json',
      ],
      stdout: stdout,
      onRun: onRun,
    );
  }

  // Creates a FakeCommand for the xcodebuild call to build the app
  // in the given configuration.
  FakeCommand setUpFakeXcodeBuildHandler({
    bool verbose = false,
    bool simulator = false,
    bool customNaming = false,
    bool disablePortPublication = false,
    String? deviceId,
    int exitCode = 0,
    String? stdout,
    void Function(List<String> command)? onRun,
  }) {
    return FakeCommand(
      command: <String>[
        'xcrun',

Review comment (suggestion):
Can the checks around the version be removed now that the minimum required is 16?

https://github.com/flutter/flutter/blob/a0a27839c6a391b8f81160fba6c3b46b1eb3000a/packages/flutter_tools/lib/src/ios/xcresult.dart#L43

Code after:
  );

  FakeCommand setUpRsyncCommand({void Function(List<String> command)? onRun}) {
    return FakeCommand(
      command: const <String>[
        'rsync',
        '-8',
        '-av',
        '--delete',
        'build/ios/Release-iphoneos/Runner.app',
        'build/ios/iphoneos',
      ],
      onRun: onRun,
    );
  }

  // Sets up xcresulttool command for Xcode versions below 16.
  FakeCommand setUpLegacyXCResultCommand({
    String stdout = '',
    void Function(List<String> command)? onRun,
  }) {
    return FakeCommand(
      command: const <String>[
        'xcrun',
        'xcresulttool',
        'get',
        '--path',
        _xcBundleDirectoryPath,
        '--format',
        'json',
      ],
      stdout: stdout,
      onRun: onRun,
    );
  }

  // Creates a FakeCommand for the xcodebuild call to build the app
  // in the given configuration.
  FakeCommand setUpFakeXcodeBuildHandler({
    bool verbose = false,
    bool simulator = false,
    bool customNaming = false,
    bool disablePortPublication = false,
    String? deviceId,
    int exitCode = 0,
    String? stdout,
    void Function(List<String> command)? onRun,
  }) {
    return FakeCommand(
      command: <String>[
        'xcrun',
Repository: flutter/flutter
File: packages/flutter_tools/test/src/context.dart (Dart)

Code before:
    final List<DoctorValidator> superValidators = super.validators;
    return superValidators.map<DoctorValidator>((DoctorValidator v) {
      if (v is AndroidLicenseValidator) {
        return FakeAndroidLicenseValidator();
      }
      return v;
    }).toList();
  }
}

class NoopIOSSimulatorUtils implements IOSSimulatorUtils {
  const NoopIOSSimulatorUtils();

  @override
  Future<List<IOSSimulator>> getAttachedDevices() async => <IOSSimulator>[];

  @override
  Future<List<IOSSimulatorRuntime>> getAvailableIOSRuntimes() async => <IOSSimulatorRuntime>[];
}

class FakeXcodeProjectInterpreter implements XcodeProjectInterpreter {
  @override
  bool get isInstalled => true;

  @override
  String get versionText => 'Xcode 16';

  @override
  Version get version => Version(16, null, null);

  @override
  String get build => '16A242D';

  @override
  Future<Map<String, String>> getBuildSettings(
    String projectPath, {
    XcodeProjectBuildContext? buildContext,
    Duration timeout = const Duration(minutes: 1),
  }) async {
    return <String, String>{};
  }

  @override
  Future<String> pluginsBuildSettingsOutput(
    Directory podXcodeProject, {
    Duration timeout = const Duration(minutes: 1),
  }) async {
    return '';
  }

  @override

Review comment (suggestion):
```suggestion
  String get versionText => 'Xcode 15';
```

Code after:
    final List<DoctorValidator> superValidators = super.validators;
    return superValidators.map<DoctorValidator>((DoctorValidator v) {
      if (v is AndroidLicenseValidator) {
        return FakeAndroidLicenseValidator();
      }
      return v;
    }).toList();
  }
}

class NoopIOSSimulatorUtils implements IOSSimulatorUtils {
  const NoopIOSSimulatorUtils();

  @override
  Future<List<IOSSimulator>> getAttachedDevices() async => <IOSSimulator>[];

  @override
  Future<List<IOSSimulatorRuntime>> getAvailableIOSRuntimes() async => <IOSSimulatorRuntime>[];
}

class FakeXcodeProjectInterpreter implements XcodeProjectInterpreter {
  @override
  bool get isInstalled => true;

  @override
  String get versionText => 'Xcode 15';

  @override
  Version get version => Version(15, 0, 0);

  @override
  String get build => '15A240D';

  @override
  Future<Map<String, String>> getBuildSettings(
    String projectPath, {
    XcodeProjectBuildContext? buildContext,
    Duration timeout = const Duration(minutes: 1),
  }) async {
    return <String, String>{};
  }

  @override
  Future<String> pluginsBuildSettingsOutput(
    Directory podXcodeProject, {
    Duration timeout = const Duration(minutes: 1),
  }) async {
    return '';
  }

  @override
Repository: flutter/flutter
File: packages/flutter/test/widgets/form_test.dart (Dart)

Code before:

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Form(
            key: formKey,
            child: Column(
              children: <Widget>[
                TextFormField(initialValue: 'foo', validator: errorText),
                TextFormField(initialValue: 'bar', validator: errorText),
              ],
            ),
          ),
        ),
      ),
    );

    formKey.currentState?.validate();
    await tester.pump();

    expect(find.text(errorText('foo')), findsOneWidget);
    expect(find.text(errorText('bar')), findsOneWidget);

    final List<FormFieldState<dynamic>> fields = formKey.currentState!.fields.toList();

    expect(fields.every((field) => field.isValid), isFalse);
  });

  testWidgets('isValid evaluates validity without updating error UI', (WidgetTester tester) async {
    final formKey = GlobalKey<FormState>();
    String errorText(String? value) => '$value/error';

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Form(
            key: formKey,
            child: TextFormField(initialValue: 'foo', validator: errorText),
          ),
        ),
      ),
    );

    final FormFieldState<dynamic> field = formKey.currentState!.fields.single;

    expect(field.isValid, isFalse);

    // No error UI should be shown.
    expect(find.text(errorText('foo')), findsNothing);
    expect(field.hasError, isFalse);
  });

Review comment (suggestion):
Should this be `fields.any(...)` instead of `fields.every(...)`? With `.every`, this will pass if at least one it not valid. With `.any`, this would pass only if all are not valid.



Code after:
    expect(find.text(errorText('foo')), findsOneWidget);

    fieldKey.currentState?.clearError();
    await tester.pump();

    expect(find.text(errorText('foo')), findsNothing);

    // Value is preserved.
    expect(find.text('foo'), findsOneWidget);
  });

  testWidgets('clearError() clears all field errors', (WidgetTester tester) async {
    final formKey = GlobalKey<FormState>();
    String errorText(String? value) => '$value/error';

    await tester.pumpWidget(
      MaterialApp(
        home: Scaffold(
          body: Form(
            key: formKey,
            child: Column(
              children: <Widget>[
                TextFormField(initialValue: 'foo', validator: errorText),
                TextFormField(initialValue: 'bar', validator: errorText),
              ],
            ),
          ),
        ),
      ),
    );

    formKey.currentState?.validate();
    await tester.pump();

    expect(find.text(errorText('foo')), findsOneWidget);
    expect(find.text(errorText('bar')), findsOneWidget);

    formKey.currentState?.clearError();
    await tester.pump();

    expect(find.text(errorText('foo')), findsNothing);
    expect(find.text(errorText('bar')), findsNothing);

    // Values are preserved.
    expect(find.text('foo'), findsOneWidget);
    expect(find.text('bar'), findsOneWidget);
  });

  testWidgets('exposes all registered FormFieldStates with their values', (
    WidgetTester tester,
  ) async {
Repository: flutter/flutter
File: packages/flutter/test/widgets/utils.dart (Dart)

Code before:
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file defines basic widgets for use in tests for Widgets in `flutter/widgets`.

import 'package:flutter/widgets.dart';

/// Get a color for use in a widget test.
///
/// The returned color will be fully opaque,
/// but the [Color.r], [Color.g], and [Color.b] channels
/// will each be randomized between `00` and `FF`.
Color getTestColor(int index) {
  const colors = [
    Color(0xFFFF0000),
    Color(0xFF00FF00),
    Color(0xFF0000FF),
    Color(0xFFFFFF00),
    Color(0xFFFF00FF),
    Color(0xFF00FFFF),
  ];

  return colors[index % colors.length];
}

// TODO(justinmc): replace with `RawButton` or equivalent when available.
/// A very basic button for use in widget tests.
class TestButton extends StatelessWidget {
  const TestButton({
    required this.child,
    this.focusNode,
    this.autofocus = false,
    this.onPressed,
    super.key,
  });

  final bool autofocus;

Review comment (suggestion):
I still have an irrational fear of the word "random" when applied to tests. Maybe something like this:

"
The returned color will be fully opaque, but the [Color.r], [Color.g], and [Color.b] channels will vary sequentially based on `index`, cycling every sixth integer.
"

Code after:
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// This file defines basic widgets for use in tests for Widgets in `flutter/widgets`.

import 'package:flutter/widgets.dart';

/// Get a color for use in a widget test.
///
/// The returned color will be fully opaque,
/// but the [Color.r], [Color.g], and [Color.b] channels
/// will vary sequentially based on index, cycling every sixth integer.
Color getTestColor(int index) {
  const colors = [
    Color(0xFFFF0000),
    Color(0xFF00FF00),
    Color(0xFF0000FF),
    Color(0xFFFFFF00),
    Color(0xFFFF00FF),
    Color(0xFF00FFFF),
  ];

  return colors[index % colors.length];
}

// TODO(justinmc): replace with `RawButton` or equivalent when available.
/// A very basic button for use in widget tests.
class TestButton extends StatelessWidget {
  const TestButton({
    required this.child,
    this.focusNode,
    this.autofocus = false,
    this.onPressed,
    super.key,
  });

  final bool autofocus;