enable prefer_function_declarations_over_variables lint (#77398)

This commit is contained in:
Michael Goderbauer 2021-03-05 18:29:04 -08:00 committed by GitHub
parent 3571882e43
commit 807bb29888
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
70 changed files with 274 additions and 276 deletions

View file

@ -159,7 +159,7 @@ linter:
- prefer_final_locals
- prefer_for_elements_to_map_fromIterable
- prefer_foreach
# - prefer_function_declarations_over_variables # not yet tested
- prefer_function_declarations_over_variables
- prefer_generic_function_type_aliases
- prefer_if_elements_to_conditional_expressions
- prefer_if_null_operators

View file

@ -5,7 +5,6 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
@ -21,9 +20,9 @@ void main() {
await tester.pumpAndSettle();
final Offset location = tester.getCenter(find.byType(ListView));
int frameCount = 0;
final FrameCallback frameCounter = (Duration elapsed) {
void frameCounter(Duration elapsed) {
frameCount += 1;
};
}
tester.binding.addPersistentFrameCallback(frameCounter);
const int timeInSecond = 1;

View file

@ -77,7 +77,7 @@ Future<void> main() async {
Directory(path.join(hostAppDir.path, 'gradle', 'wrapper')),
);
final Function clean = () async {
Future<void> clean() async {
section('Clean');
await inDirectory(hostAppDir, () async {
await exec(gradlewExecutable,
@ -87,7 +87,7 @@ Future<void> main() async {
},
);
});
};
}
if (!Platform.isWindows) {
section('Make $gradlewExecutable executable');

View file

@ -179,7 +179,6 @@ class FakeDevice extends AndroidDevice {
FakeDevice({String deviceId}) : super(deviceId: deviceId);
static String output = '';
static ExitErrorFactory exitErrorFactory = () => null;
static List<CommandArgs> commandLog = <CommandArgs>[];
@ -222,8 +221,5 @@ class FakeDevice extends AndroidDevice {
arguments: arguments,
environment: environment,
));
final dynamic exitError = exitErrorFactory();
if (exitError != null)
throw exitError;
}
}

View file

@ -4,7 +4,7 @@
import 'localizations_utils.dart';
HeaderGenerator generateCupertinoHeader = (String regenerateInstructions) {
String generateCupertinoHeader(String regenerateInstructions) {
return '''
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@ -27,11 +27,11 @@ import '../cupertino_localizations.dart';
// These classes are constructed by the [getCupertinoTranslation] method at the
// bottom of this file, and used by the [_GlobalCupertinoLocalizationsDelegate.load]
// method defined in `flutter_localizations/lib/src/cupertino_localizations.dart`.''';
};
}
/// Returns the source of the constructor for a GlobalCupertinoLocalizations
/// subclass.
ConstructorGenerator generateCupertinoConstructor = (LocaleInfo locale) {
String generateCupertinoConstructor(LocaleInfo locale) {
final String localeName = locale.originalString;
return '''
/// Create an instance of the translation bundle for ${describeLocale(localeName)}.
@ -58,7 +58,7 @@ ConstructorGenerator generateCupertinoConstructor = (LocaleInfo locale) {
singleDigitSecondFormat: singleDigitSecondFormat,
decimalFormat: decimalFormat,
);''';
};
}
const String cupertinoFactoryName = 'getCupertinoTranslation';

View file

@ -4,7 +4,7 @@
import 'localizations_utils.dart';
HeaderGenerator generateMaterialHeader = (String regenerateInstructions) {
String generateMaterialHeader(String regenerateInstructions) {
return '''
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
@ -27,11 +27,11 @@ import '../material_localizations.dart';
// These classes are constructed by the [getMaterialTranslation] method at the
// bottom of this file, and used by the [_MaterialLocalizationsDelegate.load]
// method defined in `flutter_localizations/lib/src/material_localizations.dart`.''';
};
}
/// Returns the source of the constructor for a GlobalMaterialLocalizations
/// subclass.
ConstructorGenerator generateMaterialConstructor = (LocaleInfo locale) {
String generateMaterialConstructor(LocaleInfo locale) {
final String localeName = locale.originalString;
return '''
/// Create an instance of the translation bundle for ${describeLocale(localeName)}.
@ -60,7 +60,7 @@ ConstructorGenerator generateMaterialConstructor = (LocaleInfo locale) {
decimalFormat: decimalFormat,
twoDigitZeroPaddedFormat: twoDigitZeroPaddedFormat,
);''';
};
}
const String materialFactoryName = 'getMaterialTranslation';

View file

@ -2223,7 +2223,7 @@ class _NavigationBarComponentsTransition {
/// Navigation bars' hero rect tween that will move between the static bars
/// but keep a constant size that's the bigger of both navigation bars.
CreateRectTween _linearTranslateWithLargestRectSizeTween = (Rect? begin, Rect? end) {
RectTween _linearTranslateWithLargestRectSizeTween(Rect? begin, Rect? end) {
final Size largestSize = Size(
math.max(begin!.size.width, end!.size.width),
math.max(begin.size.height, end.size.height),
@ -2232,9 +2232,9 @@ CreateRectTween _linearTranslateWithLargestRectSizeTween = (Rect? begin, Rect? e
begin: begin.topLeft & largestSize,
end: end.topLeft & largestSize,
);
};
}
final HeroPlaceholderBuilder _navBarHeroLaunchPadBuilder = (
Widget _navBarHeroLaunchPadBuilder(
BuildContext context,
Size heroSize,
Widget child,
@ -2258,10 +2258,10 @@ final HeroPlaceholderBuilder _navBarHeroLaunchPadBuilder = (
visible: false,
child: child,
);
};
}
/// Navigation bars' hero flight shuttle builder.
final HeroFlightShuttleBuilder _navBarHeroFlightShuttleBuilder = (
Widget _navBarHeroFlightShuttleBuilder(
BuildContext flightContext,
Animation<double> animation,
HeroFlightDirection flightDirection,
@ -2310,4 +2310,4 @@ final HeroFlightShuttleBuilder _navBarHeroFlightShuttleBuilder = (
topNavBar: fromNavBar,
);
}
};
}

View file

@ -876,7 +876,9 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti
///
/// Do not call [onError] directly, instead, call [reportError], which
/// forwards to [onError] if it is not null.
static FlutterExceptionHandler? onError = (FlutterErrorDetails details) => presentError(details);
static FlutterExceptionHandler? onError = _defaultErrorHandler;
static void _defaultErrorHandler(FlutterErrorDetails details) => presentError(details);
/// Called by the Flutter framework before attempting to parse a [StackTrace].
///
@ -901,7 +903,9 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti
/// return stack;
/// };
/// ```
static StackTraceDemangler demangleStackTrace = (StackTrace stackTrace) => stackTrace;
static StackTraceDemangler demangleStackTrace = _defaultStackTraceDemangler;
static StackTrace _defaultStackTraceDemangler(StackTrace stackTrace) => stackTrace;
/// Called whenever the Flutter framework wants to present an error to the
/// users.

View file

@ -99,7 +99,7 @@ class AnimatedIcon extends StatelessWidget {
/// horizontally (e.g back arrow will point right).
final TextDirection? textDirection;
static final _UiPathFactory _pathFactory = () => ui.Path();
static ui.Path _pathFactory() => ui.Path();
@override
Widget build(BuildContext context) {

View file

@ -524,7 +524,7 @@ class _RangeSliderState extends State<RangeSlider> with TickerProviderStateMixin
// immediately selected while the drag displacement is zero. If the first
// non-zero displacement is negative, then the left thumb is selected, and if its
// positive, then the right thumb is selected.
static final RangeThumbSelector _defaultRangeThumbSelector = (
Thumb? _defaultRangeThumbSelector(
TextDirection textDirection,
RangeValues values,
double tapValue,
@ -566,9 +566,7 @@ class _RangeSliderState extends State<RangeSlider> with TickerProviderStateMixin
return Thumb.end;
}
return null;
};
}
@override
Widget build(BuildContext context) {

View file

@ -758,14 +758,14 @@ class ResizeImage extends ImageProvider<_SizeAwareCacheKey> {
@override
ImageStreamCompleter load(_SizeAwareCacheKey key, DecoderCallback decode) {
final DecoderCallback decodeResize = (Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
Future<ui.Codec> decodeResize(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
assert(
cacheWidth == null && cacheHeight == null && allowUpscaling == null,
'ResizeImage cannot be composed with another ImageProvider that applies '
'cacheWidth, cacheHeight, or allowUpscaling.'
);
return decode(bytes, cacheWidth: width, cacheHeight: height, allowUpscaling: this.allowUpscaling);
};
}
final ImageStreamCompleter completer = imageProvider.load(key.providerCacheKey, decodeResize);
if (!kReleaseMode) {
completer.debugLabel = '${completer.debugLabel} - Resized(${key.width}×${key.height})';

View file

@ -945,18 +945,18 @@ class RenderListWheelViewport
Offset offsetToCenter,
) {
// Paint child cylindrically, without [overAndUnderCenterOpacity].
final PaintingContextCallback painter = (PaintingContext context, Offset offset) {
void painter(PaintingContext context, Offset offset) {
context.paintChild(
child,
// Paint everything in the center (e.g. angle = 0), then transform.
offset + offsetToCenter,
);
};
}
// Paint child cylindrically, with [overAndUnderCenterOpacity].
final PaintingContextCallback opacityPainter = (PaintingContext context, Offset offset) {
void opacityPainter(PaintingContext context, Offset offset) {
context.pushOpacity(offset, (overAndUnderCenterOpacity * 255).round(), painter);
};
}
context.pushTransform(
needsCompositing,

View file

@ -1031,7 +1031,7 @@ class HeroController extends NavigatorObserver {
_flights.remove(flight.manifest.tag);
}
static final HeroFlightShuttleBuilder _defaultHeroFlightShuttleBuilder = (
Widget _defaultHeroFlightShuttleBuilder(
BuildContext flightContext,
Animation<double> animation,
HeroFlightDirection flightDirection,
@ -1040,7 +1040,7 @@ class HeroController extends NavigatorObserver {
) {
final Hero toHero = toHeroContext.widget as Hero;
return toHero.child;
};
}
}
/// Enables or disables [Hero]es in the widget subtree.

View file

@ -3171,9 +3171,9 @@ class _RouteEntry extends RouteTransitionRecord {
);
}
static final _RouteEntryPredicate isPresentPredicate = (_RouteEntry entry) => entry.isPresent;
static final _RouteEntryPredicate suitableForTransitionAnimationPredicate = (_RouteEntry entry) => entry.suitableForTransitionAnimation;
static final _RouteEntryPredicate willBePresentPredicate = (_RouteEntry entry) => entry.willBePresent;
static bool isPresentPredicate(_RouteEntry entry) => entry.isPresent;
static bool suitableForTransitionAnimationPredicate(_RouteEntry entry) => entry.suitableForTransitionAnimation;
static bool willBePresentPredicate(_RouteEntry entry) => entry.willBePresent;
static _RouteEntryPredicate isRoutePredicate(Route<dynamic> route) {
return (_RouteEntry entry) => entry.route == route;

View file

@ -849,11 +849,11 @@ mixin RestorationMixin<S extends StatefulWidget> on State<S> {
if (!property.isRegistered) {
property._register(restorationId, this);
final VoidCallback listener = () {
void listener() {
if (bucket == null)
return;
_updateProperty(property);
};
}
property.addListener(listener);
_properties[property] = listener;
}

View file

@ -18,15 +18,15 @@ void main() {
);
final List<String> log = <String>[];
final VoidCallback listener1 = () { log.add('listener1'); };
final VoidCallback listener3 = () { log.add('listener3'); };
final VoidCallback listener4 = () { log.add('listener4'); };
final VoidCallback listener2 = () {
void listener1() { log.add('listener1'); }
void listener3() { log.add('listener3'); }
void listener4() { log.add('listener4'); }
void listener2() {
log.add('listener2');
controller.removeListener(listener1);
controller.removeListener(listener3);
controller.addListener(listener4);
};
}
controller.addListener(listener1);
controller.addListener(listener2);
@ -51,15 +51,15 @@ void main() {
);
final List<String> log = <String>[];
final AnimationStatusListener listener1 = (AnimationStatus status) { log.add('listener1'); };
final AnimationStatusListener listener3 = (AnimationStatus status) { log.add('listener3'); };
final AnimationStatusListener listener4 = (AnimationStatus status) { log.add('listener4'); };
final AnimationStatusListener listener2 = (AnimationStatus status) {
void listener1(AnimationStatus status) { log.add('listener1'); }
void listener3(AnimationStatus status) { log.add('listener3'); }
void listener4(AnimationStatus status) { log.add('listener4'); }
void listener2(AnimationStatus status) {
log.add('listener2');
controller.removeStatusListener(listener1);
controller.removeStatusListener(listener3);
controller.addStatusListener(listener4);
};
}
controller.addStatusListener(listener1);
controller.addStatusListener(listener2);
@ -86,12 +86,12 @@ void main() {
);
final List<String> log = <String>[];
final VoidCallback listener1 = () { log.add('listener1'); };
final VoidCallback badListener = () {
void listener1() { log.add('listener1'); }
void badListener() {
log.add('badListener');
throw ArgumentError();
};
final VoidCallback listener2 = () { log.add('listener2'); };
}
void listener2() { log.add('listener2'); }
controller.addListener(listener1);
controller.addListener(badListener);
@ -109,12 +109,12 @@ void main() {
);
final List<String> log = <String>[];
final AnimationStatusListener listener1 = (AnimationStatus status) { log.add('listener1'); };
final AnimationStatusListener badListener = (AnimationStatus status) {
void listener1(AnimationStatus status) { log.add('listener1'); }
void badListener(AnimationStatus status) {
log.add('badListener');
throw ArgumentError();
};
final AnimationStatusListener listener2 = (AnimationStatus status) { log.add('listener2'); };
}
void listener2(AnimationStatus status) { log.add('listener2'); }
controller.addStatusListener(listener1);
controller.addStatusListener(badListener);

View file

@ -8,7 +8,7 @@ import 'package:flutter/widgets.dart';
void main() {
test('AnimationLocalStatusListenersMixin with AnimationLazyListenerMixin - removing unregistered listener is no-op', () {
final _TestAnimationLocalStatusListeners uut = _TestAnimationLocalStatusListeners();
final AnimationStatusListener fakeListener = (AnimationStatus status) { };
void fakeListener(AnimationStatus status) { }
uut.removeStatusListener(fakeListener);
expect(uut.callsToStart, 0);
expect(uut.callsToStop, 0);
@ -16,7 +16,7 @@ void main() {
test('AnimationLocalListenersMixin with AnimationLazyListenerMixin - removing unregistered listener is no-op', () {
final _TestAnimationLocalListeners uut = _TestAnimationLocalListeners();
final VoidCallback fakeListener = () { };
void fakeListener() { }
uut.removeListener(fakeListener);
expect(uut.callsToStart, 0);
expect(uut.callsToStop, 0);

View file

@ -496,7 +496,7 @@ void main() {
setUp(() { color = null; });
testWidgets('dynamic color works in cupertino override theme', (WidgetTester tester) async {
final CupertinoDynamicColor Function() typedColor = () => color! as CupertinoDynamicColor;
CupertinoDynamicColor typedColor() => color! as CupertinoDynamicColor;
await tester.pumpWidget(
MaterialApp(

View file

@ -31,7 +31,7 @@ void main() {
);
}
final VoidCallback uiTestGroup = () {
void uiTestGroup() {
testWidgets("doesn't invoke anything without user interaction", (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
@ -956,9 +956,9 @@ void main() {
initialFirstCellY + 50
);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
};
}
final VoidCallback stateMachineTestGroup = () {
void stateMachineTestGroup() {
testWidgets('starts in inactive state', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
@ -1345,7 +1345,7 @@ void main() {
);
expect(tester.widget<CupertinoActivityIndicator>(find.byType(CupertinoActivityIndicator)).progress, 100.0 / 100.0);
});
};
}
group('UI tests long list', uiTestGroup);

View file

@ -93,7 +93,7 @@ void main() {
testWidgets('Passes onEditingComplete to underlying CupertinoTextField',
(WidgetTester tester) async {
final VoidCallback onEditingComplete = () {};
void onEditingComplete() {}
await tester.pumpWidget(
CupertinoApp(

View file

@ -217,7 +217,7 @@ void main() {
}
}
final VoidCallback dynamicColorsTestGroup = () {
void dynamicColorsTestGroup() {
testWidgets('CupertinoTheme.of resolves colors', (WidgetTester tester) async {
final CupertinoThemeData data = CupertinoThemeData(brightness: currentBrightness, primaryColor: CupertinoColors.systemRed);
final CupertinoThemeData theme = await testTheme(tester, data);
@ -249,7 +249,7 @@ void main() {
colorMatches(theme.textTheme.pickerTextStyle.color, CupertinoColors.label);
colorMatches(theme.textTheme.dateTimePickerTextStyle.color, CupertinoColors.label);
});
};
}
currentBrightness = Brightness.light;
group('light colors', dynamicColorsTestGroup);

View file

@ -34,13 +34,13 @@ class B extends A with ChangeNotifier {
void main() {
testWidgets('ChangeNotifier', (WidgetTester tester) async {
final List<String> log = <String>[];
final VoidCallback listener = () { log.add('listener'); };
final VoidCallback listener1 = () { log.add('listener1'); };
final VoidCallback listener2 = () { log.add('listener2'); };
final VoidCallback badListener = () {
void listener() { log.add('listener'); }
void listener1() { log.add('listener1'); }
void listener2() { log.add('listener2'); }
void badListener() {
log.add('badListener');
throw ArgumentError();
};
}
final TestNotifier test = TestNotifier();
@ -111,15 +111,15 @@ void main() {
final TestNotifier test = TestNotifier();
final List<String> log = <String>[];
final VoidCallback listener1 = () { log.add('listener1'); };
final VoidCallback listener3 = () { log.add('listener3'); };
final VoidCallback listener4 = () { log.add('listener4'); };
final VoidCallback listener2 = () {
void listener1() { log.add('listener1'); }
void listener3() { log.add('listener3'); }
void listener4() { log.add('listener4'); }
void listener2() {
log.add('listener2');
test.removeListener(listener1);
test.removeListener(listener3);
test.addListener(listener4);
};
}
test.addListener(listener1);
test.addListener(listener2);
@ -141,8 +141,8 @@ void main() {
final TestNotifier source = TestNotifier();
final List<String> log = <String>[];
final VoidCallback listener3 = () { log.add('listener3'); };
final VoidCallback listener2 = () { log.add('listener2'); };
void listener3() { log.add('listener3'); }
void listener2() { log.add('listener2'); }
void listener1() {
log.add('listener1');
source.addListener(listener2);
@ -167,7 +167,7 @@ void main() {
log.add('selfRemovingListener');
source.removeListener(selfRemovingListener);
}
final VoidCallback listener1 = () { log.add('listener1'); };
void listener1() { log.add('listener1'); }
source.addListener(listener1);
source.addListener(selfRemovingListener);
@ -205,8 +205,8 @@ void main() {
final List<String> log = <String>[];
final Listenable merged = Listenable.merge(<Listenable>[source1, source2]);
final VoidCallback listener1 = () { log.add('listener1'); };
final VoidCallback listener2 = () { log.add('listener2'); };
void listener1() { log.add('listener1'); }
void listener2() { log.add('listener2'); }
merged.addListener(listener1);
source1.notify();
@ -237,7 +237,7 @@ void main() {
final List<String> log = <String>[];
final Listenable merged = Listenable.merge(<Listenable?>[null, source1, null, source2, null]);
final VoidCallback listener = () { log.add('listener'); };
void listener() { log.add('listener'); }
merged.addListener(listener);
source1.notify();
@ -252,7 +252,7 @@ void main() {
final List<String> log = <String>[];
final Listenable merged = Listenable.merge(<Listenable>[source1, source2]);
final VoidCallback listener = () { log.add('listener'); };
void listener() { log.add('listener'); }
merged.addListener(listener);
source1.notify();
@ -279,7 +279,7 @@ void main() {
final ValueNotifier<double> notifier = ValueNotifier<double>(2.0);
final List<double> log = <double>[];
final VoidCallback listener = () { log.add(notifier.value); };
void listener() { log.add(notifier.value); }
notifier.addListener(listener);
notifier.value = 3.0;
@ -325,7 +325,7 @@ void main() {
final TestNotifier source1 = TestNotifier();
final TestNotifier source2 = TestNotifier();
final VoidCallback fakeListener = () { };
void fakeListener() { }
final Listenable listenableUnderTest = Listenable.merge(<Listenable>[source1, source2]);
expect(source1.isListenedTo, isFalse);

View file

@ -1197,7 +1197,7 @@ void main() {
});
test('callback property test', () {
final Function onClick = () { };
void onClick() { }
final ObjectFlagProperty<Function> present = ObjectFlagProperty<Function>(
'onClick',
onClick,
@ -1631,7 +1631,7 @@ void main() {
});
test('has property test', () {
final Function onClick = () { };
void onClick() { }
final ObjectFlagProperty<Function> has = ObjectFlagProperty<Function>.has(
'onClick',
onClick,
@ -1656,8 +1656,8 @@ void main() {
test('iterable flags property test', () {
// Normal property
{
final Function onClick = () { };
final Function onMove = () { };
void onClick() { }
void onMove() { }
final Map<String, Function> value = <String, Function>{
'click': onClick,
'move': onMove,
@ -1675,8 +1675,8 @@ void main() {
// Reversed-order property
{
final Function onClick = () { };
final Function onMove = () { };
void onClick() { }
void onMove() { }
final Map<String, Function> value = <String, Function>{
'move': onMove,
'click': onClick,
@ -1692,7 +1692,7 @@ void main() {
// Partially empty property
{
final Function onClick = () { };
void onClick() { }
final Map<String, Function?> value = <String, Function?>{
'move': null,
'click': onClick,

View file

@ -11,7 +11,7 @@ import 'package:flutter/material.dart';
import '../rendering/mock_canvas.dart';
const List<String> menuItems = <String>['one', 'two', 'three', 'four'];
final ValueChanged<String?> onChanged = (_) { };
void onChanged<T>(T _) { }
final Type dropdownButtonType = DropdownButton<String>(
onChanged: (_) { },
items: const <DropdownMenuItem<String>>[],

View file

@ -14,7 +14,7 @@ import '../rendering/mock_canvas.dart';
import '../widgets/semantics_tester.dart';
const List<String> menuItems = <String>['one', 'two', 'three', 'four'];
final ValueChanged<String?> onChanged = (_) { };
void onChanged<T>(T _) { }
final Type dropdownButtonType = DropdownButton<String>(
onChanged: (_) { },

View file

@ -70,9 +70,9 @@ void main () {
final SemanticsTester semanticsTester = SemanticsTester(tester);
int callbackCount = 0;
final VoidCallback callback = () {
void callback() {
callbackCount++;
};
}
await tester.pumpWidget(TestWidget(
tapHandler: (BuildContext context) {
@ -132,9 +132,9 @@ void main () {
testWidgets('forLongPress Wrapper', (WidgetTester tester) async {
final SemanticsTester semanticsTester = SemanticsTester(tester);
int callbackCount = 0;
final VoidCallback callback = () {
void callback() {
callbackCount++;
};
}
await tester.pumpWidget(TestWidget(
longPressHandler: (BuildContext context) {

View file

@ -965,7 +965,7 @@ void main() {
final Key buildCounterKey = UniqueKey();
const String counterText = 'I show instead of count';
final Widget counter = Text('hello', key: counterKey);
final InputCounterWidgetBuilder buildCounter = (
Widget buildCounter(
BuildContext context, {
required int currentLength,
required int? maxLength,
@ -975,7 +975,7 @@ void main() {
'${currentLength.toString()} of ${maxLength.toString()}',
key: buildCounterKey,
);
};
}
await tester.pumpWidget(buildFrame(
counterText: counterText,

View file

@ -466,12 +466,12 @@ void main() {
child: Text('XXX'),
),
);
final WidgetPredicate popupMenu = (Widget widget) {
bool popupMenu(Widget widget) {
final String widgetType = widget.runtimeType.toString();
// TODO(mraleph): Remove the old case below.
return widgetType == '_PopupMenu<int?>' // normal case
|| widgetType == '_PopupMenu'; // for old versions of Dart that don't reify method type arguments
};
}
Future<void> openMenu(TextDirection textDirection, Alignment alignment) async {
return TestAsyncUtils.guard<void>(() async {

View file

@ -1347,9 +1347,9 @@ void main() {
int? divisions,
bool enabled = true,
}) {
final ValueChanged<RangeValues> onChanged = (RangeValues newValues) {
void onChanged(RangeValues newValues) {
values = newValues;
};
}
return MaterialApp(
home: Scaffold(
// The builder is used to pass the context from the MaterialApp widget

View file

@ -380,30 +380,29 @@ void main() {
canceledPressed = true;
}
final ControlsWidgetBuilder builder =
(BuildContext context, { VoidCallback? onStepContinue, VoidCallback? onStepCancel }) {
return Container(
margin: const EdgeInsets.only(top: 16.0),
child: ConstrainedBox(
constraints: const BoxConstraints.tightFor(height: 48.0),
child: Row(
children: <Widget>[
TextButton(
onPressed: onStepContinue,
child: const Text('Let us continue!'),
Widget builder(BuildContext context, { VoidCallback? onStepContinue, VoidCallback? onStepCancel }) {
return Container(
margin: const EdgeInsets.only(top: 16.0),
child: ConstrainedBox(
constraints: const BoxConstraints.tightFor(height: 48.0),
child: Row(
children: <Widget>[
TextButton(
onPressed: onStepContinue,
child: const Text('Let us continue!'),
),
Container(
margin: const EdgeInsetsDirectional.only(start: 8.0),
child: TextButton(
onPressed: onStepCancel,
child: const Text('Cancel This!'),
),
Container(
margin: const EdgeInsetsDirectional.only(start: 8.0),
child: TextButton(
onPressed: onStepCancel,
child: const Text('Cancel This!'),
),
),
],
),
),
],
),
);
};
),
);
}
await tester.pumpWidget(
MaterialApp(

View file

@ -252,7 +252,7 @@ void main() {
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.macOS, TargetPlatform.windows, TargetPlatform.linux }), skip: kIsWeb);
testWidgets('TextField passes onEditingComplete to EditableText', (WidgetTester tester) async {
final VoidCallback onEditingComplete = () { };
void onEditingComplete() { }
await tester.pumpWidget(
MaterialApp(
@ -489,10 +489,10 @@ void main() {
testWidgets('TextInputFormatter gets correct selection value', (WidgetTester tester) async {
late TextEditingValue actualOldValue;
late TextEditingValue actualNewValue;
final FormatEditUpdateCallback callBack = (TextEditingValue oldValue, TextEditingValue newValue) {
void callBack(TextEditingValue oldValue, TextEditingValue newValue) {
actualOldValue = oldValue;
actualNewValue = newValue;
};
}
final FocusNode focusNode = FocusNode();
final TextEditingController controller = TextEditingController(text: '123');
await tester.pumpWidget(

View file

@ -201,7 +201,7 @@ void main() {
});
testWidgets('Passes onEditingComplete to underlying TextField', (WidgetTester tester) async {
final VoidCallback onEditingComplete = () { };
void onEditingComplete() { }
await tester.pumpWidget(
MaterialApp(

View file

@ -136,9 +136,9 @@ void main() {
});
test('Returns null if an error is caught resolving an image', () {
final DecoderCallback _basicDecoder = (Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
Future<ui.Codec> _basicDecoder(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
return PaintingBinding.instance!.instantiateImageCodec(bytes, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling ?? false);
};
}
final ErrorImageProvider errorImage = ErrorImageProvider();
expect(() => imageCache!.putIfAbsent(errorImage, () => errorImage.load(errorImage, _basicDecoder)), throwsA(isA<Error>()));
bool caughtError = false;

View file

@ -4,6 +4,7 @@
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
@ -16,9 +17,9 @@ import 'mocks_for_image_cache.dart';
void main() {
TestRenderingFlutterBinding();
final DecoderCallback _basicDecoder = (Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
Future<ui.Codec> _basicDecoder(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
return PaintingBinding.instance!.instantiateImageCodec(bytes, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling ?? false);
};
}
FlutterExceptionHandler? oldError;
setUp(() {

View file

@ -18,9 +18,9 @@ import '../rendering/rendering_tester.dart';
void main() {
TestRenderingFlutterBinding();
final DecoderCallback _basicDecoder = (Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
Future<Codec> _basicDecoder(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool? allowUpscaling}) {
return PaintingBinding.instance!.instantiateImageCodec(bytes, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling ?? false);
};
}
late _FakeHttpClient httpClient;

View file

@ -4,6 +4,7 @@
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
@ -98,12 +99,12 @@ void main() {
final MemoryImage memoryImage = MemoryImage(bytes);
final ResizeImage resizeImage = ResizeImage(memoryImage, width: 123, height: 321);
final DecoderCallback decode = (Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) {
Future<ui.Codec> decode(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) {
expect(cacheWidth, 123);
expect(cacheHeight, 321);
expect(allowUpscaling, false);
return PaintingBinding.instance!.instantiateImageCodec(bytes, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling);
};
}
resizeImage.load(await resizeImage.obtainKey(ImageConfiguration.empty), decode);
});

View file

@ -105,7 +105,7 @@ void main() {
await tester.idle();
expect(mockCodec.numFramesAsked, 0);
final ImageListener listener = (ImageInfo image, bool synchronousCall) { };
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
await tester.idle();
expect(mockCodec.numFramesAsked, 1);
@ -120,7 +120,7 @@ void main() {
scale: 1.0,
);
final ImageListener listener = (ImageInfo image, bool synchronousCall) { };
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
await tester.idle();
expect(mockCodec.numFramesAsked, 0);
@ -143,7 +143,7 @@ void main() {
await tester.idle();
expect(mockCodec.numFramesAsked, 0);
final ImageListener listener = (ImageInfo image, bool synchronousCall) { };
void listener(ImageInfo image, bool synchronousCall) { }
final ImageStreamListener streamListener = ImageStreamListener(listener);
imageStream.addListener(streamListener);
await tester.idle();
@ -291,7 +291,7 @@ void main() {
scale: 1.0,
);
final ImageListener listener = (ImageInfo image, bool synchronousCall) { };
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
codecCompleter.complete(mockCodec);
// MultiFrameImageStreamCompleter only sets an error handler for the next
@ -467,7 +467,7 @@ void main() {
scale: 1.0,
);
final ImageListener listener = (ImageInfo image, bool synchronousCall) { };
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
final ImageStreamCompleterHandle handle = imageStream.keepAlive();
@ -508,13 +508,13 @@ void main() {
);
final List<ImageInfo> emittedImages1 = <ImageInfo>[];
final ImageListener listener1 = (ImageInfo image, bool synchronousCall) {
void listener1(ImageInfo image, bool synchronousCall) {
emittedImages1.add(image);
};
}
final List<ImageInfo> emittedImages2 = <ImageInfo>[];
final ImageListener listener2 = (ImageInfo image, bool synchronousCall) {
void listener2(ImageInfo image, bool synchronousCall) {
emittedImages2.add(image);
};
}
imageStream.addListener(ImageStreamListener(listener1));
imageStream.addListener(ImageStreamListener(listener2));
@ -554,7 +554,7 @@ void main() {
scale: 1.0,
);
final ImageListener listener = (ImageInfo image, bool synchronousCall) { };
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
codecCompleter.complete(mockCodec);
@ -587,7 +587,7 @@ void main() {
scale: 1.0,
);
final ImageListener listener = (ImageInfo image, bool synchronousCall) { };
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
codecCompleter.complete(mockCodec);
@ -623,9 +623,9 @@ void main() {
);
dynamic capturedException;
final ImageErrorListener errorListener = (dynamic exception, StackTrace? stackTrace) {
void errorListener(dynamic exception, StackTrace? stackTrace) {
capturedException = exception;
};
}
streamUnderTest.addListener(ImageStreamListener(
(ImageInfo image, bool synchronousCall) { },
@ -658,7 +658,7 @@ void main() {
scale: 1.0,
);
final ImageListener listener = (ImageInfo image, bool synchronousCall) { };
void listener(ImageInfo image, bool synchronousCall) { }
imageStream.addListener(ImageStreamListener(listener));
codecCompleter.complete(mockCodec);
@ -723,9 +723,9 @@ void main() {
);
int onImageCount = 0;
final ImageListener activeListener = (ImageInfo image, bool synchronousCall) {
void activeListener(ImageInfo image, bool synchronousCall) {
onImageCount += 1;
};
}
bool lastListenerDropped = false;
imageStream.addOnLastListenerRemovedCallback(() {
lastListenerDropped = true;

View file

@ -51,16 +51,16 @@ void main() {
});
test('RenderShaderMask getters and setters', () {
final ShaderCallback callback1 = (Rect bounds) {
Shader callback1(Rect bounds) {
assert(false); // The test should not call this.
const LinearGradient gradient = LinearGradient(colors: <Color>[Colors.red]);
return gradient.createShader(Rect.zero);
};
final ShaderCallback callback2 = (Rect bounds) {
}
Shader callback2(Rect bounds) {
assert(false); // The test should not call this.
const LinearGradient gradient = LinearGradient(colors: <Color>[Colors.blue]);
return gradient.createShader(Rect.zero);
};
}
final RenderShaderMask box = RenderShaderMask(shaderCallback: callback1);
expect(box.shaderCallback, equals(callback1));
box.shaderCallback = callback2;

View file

@ -106,9 +106,9 @@ void main() {
);
final List<RenderObject> visitedChildren = <RenderObject>[];
final RenderObjectVisitor visitor = (RenderObject child) {
void visitor(RenderObject child) {
visitedChildren.add(child);
};
}
stack.visitChildrenForSemantics(visitor);

View file

@ -616,18 +616,18 @@ void main() {
config.isFocused = true;
config.isTextField = true;
final VoidCallback onShowOnScreen = () { };
final VoidCallback onScrollDown = () { };
final VoidCallback onScrollUp = () { };
final VoidCallback onScrollLeft = () { };
final VoidCallback onScrollRight = () { };
final VoidCallback onLongPress = () { };
final VoidCallback onDecrease = () { };
final VoidCallback onIncrease = () { };
final MoveCursorHandler onMoveCursorForwardByCharacter = (bool _) { };
final MoveCursorHandler onMoveCursorBackwardByCharacter = (bool _) { };
final VoidCallback onTap = () { };
final VoidCallback onCustomAction = () { };
void onShowOnScreen() { }
void onScrollDown() { }
void onScrollUp() { }
void onScrollLeft() { }
void onScrollRight() { }
void onLongPress() { }
void onDecrease() { }
void onIncrease() { }
void onMoveCursorForwardByCharacter(bool _) { }
void onMoveCursorBackwardByCharacter(bool _) { }
void onTap() { }
void onCustomAction() { }
config.onShowOnScreen = onShowOnScreen;
config.onScrollDown = onScrollDown;

View file

@ -30,9 +30,9 @@ void main() {
final TestChannelBuffersFlutterBinding binding = TestChannelBuffersFlutterBinding();
expect(binding.defaultBinaryMessenger, isNotNull);
bool didCallCallback = false;
final ui.PlatformMessageResponseCallback callback = (ByteData? responseData) {
void callback(ByteData? responseData) {
didCallCallback = true;
};
}
const String payload = 'bar';
final ByteData data = _makeByteData(payload);
ui.channelBuffers.push(channel, data, callback);

View file

@ -148,7 +148,7 @@ void main() {
test('OnPlatformViewCreated callback', () async {
viewsController.registerViewType('webview');
final List<int> createdViews = <int>[];
final PlatformViewCreatedCallback callback = (int id) { createdViews.add(id); };
void callback(int id) { createdViews.add(id); }
final AndroidViewController controller1 = PlatformViewsService.initAndroidView(
id: 0,

View file

@ -8,14 +8,14 @@ import 'package:flutter/widgets.dart';
void main() {
testWidgets('AnimatedList', (WidgetTester tester) async {
final AnimatedListItemBuilder builder = (BuildContext context, int index, Animation<double> animation) {
Widget builder(BuildContext context, int index, Animation<double> animation) {
return SizedBox(
height: 100.0,
child: Center(
child: Text('item $index'),
),
);
};
}
final GlobalKey<AnimatedListState> listKey = GlobalKey<AnimatedListState>();
await tester.pumpWidget(

View file

@ -5,7 +5,7 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/widgets.dart';
final RouteFactory generateRoute = (RouteSettings settings) => PageRouteBuilder<void>(
Route<void> generateRoute(RouteSettings settings) => PageRouteBuilder<void>(
settings: settings,
pageBuilder: (BuildContext context, Animation<double> animation1, Animation<double> animation2) {
return const Placeholder();

View file

@ -212,7 +212,7 @@ void main() {
late Iterable<User> lastOptions;
late AutocompleteOnSelected<User> lastOnSelected;
late User lastUserSelected;
late final AutocompleteOptionToString<User> displayStringForOption = (User option) => option.name;
String displayStringForOption(User option) => option.name;
late FocusNode focusNode;
late TextEditingController textEditingController;

View file

@ -320,13 +320,13 @@ Future<void> main() async {
);
bool called = false;
final DecoderCallback decode = (Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) {
Future<ui.Codec> decode(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) {
expect(cacheWidth, 20);
expect(cacheHeight, 30);
expect(allowUpscaling, false);
called = true;
return PaintingBinding.instance!.instantiateImageCodec(bytes, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling);
};
}
final ImageProvider resizeImage = image.placeholder;
expect(image.placeholder, isA<ResizeImage>());
expect(called, false);
@ -343,13 +343,13 @@ Future<void> main() async {
);
bool called = false;
final DecoderCallback decode = (Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) {
Future<ui.Codec> decode(Uint8List bytes, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) {
expect(cacheWidth, null);
expect(cacheHeight, null);
expect(allowUpscaling, false);
called = true;
return PaintingBinding.instance!.instantiateImageCodec(bytes, cacheWidth: cacheWidth, cacheHeight: cacheHeight);
};
}
// image.placeholder should be an instance of MemoryImage instead of ResizeImage
final ImageProvider memoryImage = image.placeholder;
expect(image.placeholder, isA<MemoryImage>());

View file

@ -117,7 +117,7 @@ void main() {
final Set<String> logs = <String>{};
final GlobalKey<RawGestureDetectorState> detectorKey = GlobalKey();
final VoidCallback performLayout = () {
void performLayout() {
detectorKey.currentState!.replaceGestureRecognizers(<Type, GestureRecognizerFactory>{
TapGestureRecognizer: GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
() => TapGestureRecognizer(),
@ -126,7 +126,7 @@ void main() {
},
),
});
};
}
bool hasLayoutPerformer = false;
late VoidCallback introduceLayoutPerformer;

View file

@ -252,7 +252,7 @@ void main() {
}, variant: buttonVariant);
testWidgets('cache render object', (WidgetTester tester) async {
final GestureTapCallback inputCallback = () { };
void inputCallback() { }
await tester.pumpWidget(
Center(

View file

@ -2244,7 +2244,7 @@ Future<void> main() async {
testWidgets('On an iOS back swipe and snap, only a single flight should take place', (WidgetTester tester) async {
int shuttlesBuilt = 0;
final HeroFlightShuttleBuilder shuttleBuilder = (
Widget shuttleBuilder(
BuildContext flightContext,
Animation<double> animation,
HeroFlightDirection flightDirection,
@ -2253,7 +2253,7 @@ Future<void> main() async {
) {
shuttlesBuilt += 1;
return const Text("I'm flying in a jetplane");
};
}
final GlobalKey<NavigatorState> navigatorKey = GlobalKey();
await tester.pumpWidget(

View file

@ -477,13 +477,13 @@ void main() {
dynamic capturedException;
StackTrace? capturedStackTrace;
ImageInfo? capturedImage;
final ImageErrorListener errorListener = (dynamic exception, StackTrace? stackTrace) {
void errorListener(dynamic exception, StackTrace? stackTrace) {
capturedException = exception;
capturedStackTrace = stackTrace;
};
final ImageListener listener = (ImageInfo info, bool synchronous) {
}
void listener(ImageInfo info, bool synchronous) {
capturedImage = info;
};
}
final Exception testException = Exception('cannot resolve host');
final StackTrace testStack = StackTrace.current;
@ -519,13 +519,13 @@ void main() {
dynamic reportedException;
StackTrace? reportedStackTrace;
ImageInfo? capturedImage;
final ImageErrorListener errorListener = (dynamic exception, StackTrace? stackTrace) {
void errorListener(dynamic exception, StackTrace? stackTrace) {
capturedException = exception;
capturedStackTrace = stackTrace;
};
final ImageListener listener = (ImageInfo info, bool synchronous) {
}
void listener(ImageInfo info, bool synchronous) {
capturedImage = info;
};
}
FlutterError.onError = (FlutterErrorDetails flutterError) {
reportedException = flutterError.exception;
reportedStackTrace = flutterError.stack;
@ -568,13 +568,13 @@ void main() {
dynamic capturedException;
StackTrace? capturedStackTrace;
ImageInfo? capturedImage;
final ImageErrorListener errorListener = (dynamic exception, StackTrace? stackTrace) {
void errorListener(dynamic exception, StackTrace? stackTrace) {
capturedException = exception;
capturedStackTrace = stackTrace;
};
final ImageListener listener = (ImageInfo info, bool synchronous) {
}
void listener(ImageInfo info, bool synchronous) {
capturedImage = info;
};
}
final Exception testException = Exception('cannot resolve host');
final StackTrace testStack = StackTrace.current;
@ -611,14 +611,14 @@ void main() {
StackTrace? capturedStackTrace;
ImageInfo? capturedImage;
int errorListenerCalled = 0;
final ImageErrorListener errorListener = (dynamic exception, StackTrace? stackTrace) {
void errorListener(dynamic exception, StackTrace? stackTrace) {
capturedException = exception;
capturedStackTrace = stackTrace;
errorListenerCalled++;
};
final ImageListener listener = (ImageInfo info, bool synchronous) {
}
void listener(ImageInfo info, bool synchronous) {
capturedImage = info;
};
}
final Exception testException = Exception('cannot resolve host');
final StackTrace testStack = StackTrace.current;
@ -656,14 +656,14 @@ void main() {
dynamic reportedException;
StackTrace? reportedStackTrace;
ImageInfo? capturedImage;
final ImageErrorListener errorListener = (dynamic exception, StackTrace? stackTrace) {
void errorListener(dynamic exception, StackTrace? stackTrace) {
errorListenerCalled = true;
reportedException = exception;
reportedStackTrace = stackTrace;
};
final ImageListener listener = (ImageInfo info, bool synchronous) {
}
void listener(ImageInfo info, bool synchronous) {
capturedImage = info;
};
}
final Exception testException = Exception('cannot resolve host');
final StackTrace testStack = StackTrace.current;
@ -698,12 +698,12 @@ void main() {
testWidgets('Removing listener removes one listener and error listener', (WidgetTester tester) async {
int errorListenerCalled = 0;
ImageInfo? capturedImage;
final ImageErrorListener errorListener = (dynamic exception, StackTrace? stackTrace) {
void errorListener(dynamic exception, StackTrace? stackTrace) {
errorListenerCalled++;
};
final ImageListener listener = (ImageInfo info, bool synchronous) {
}
void listener(ImageInfo info, bool synchronous) {
capturedImage = info;
};
}
final Exception testException = Exception('cannot resolve host');
final StackTrace testStack = StackTrace.current;
@ -805,10 +805,10 @@ void main() {
testWidgets('Precache completes with onError on error', (WidgetTester tester) async {
dynamic capturedException;
StackTrace? capturedStackTrace;
final ImageErrorListener errorListener = (dynamic exception, StackTrace? stackTrace) {
void errorListener(dynamic exception, StackTrace? stackTrace) {
capturedException = exception;
capturedStackTrace = stackTrace;
};
}
final Exception testException = Exception('cannot resolve host');
final StackTrace testStack = StackTrace.current;
@ -1419,8 +1419,8 @@ void main() {
),
));
final bool Function(_TestImageProvider) loadCalled = (_TestImageProvider provider) => provider.loadCalled;
final bool Function(_TestImageProvider) loadNotCalled = (_TestImageProvider provider) => !provider.loadCalled;
bool loadCalled(_TestImageProvider provider) => provider.loadCalled;
bool loadNotCalled(_TestImageProvider provider) => !provider.loadCalled;
expect(find.bySemanticsLabel('5'), findsOneWidget);
expect(imageProviders.length, 12);

View file

@ -68,7 +68,7 @@ void main() {
// so if our widget is 200 pixels tall, it should fit exactly 3 times.
// but if we are offset by 300 pixels, there will be 4, numbered 1-4.
final IndexedWidgetBuilder itemBuilder = (BuildContext context, int index) {
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return SizedBox(
key: ValueKey<int>(index),
@ -76,7 +76,7 @@ void main() {
height: 400.0, // should be overridden by itemExtent
child: Text('$index', textDirection: TextDirection.ltr),
);
};
}
Widget buildWidget() {
return Directionality(
@ -141,7 +141,7 @@ void main() {
// so if our widget is 200 pixels wide, it should fit exactly 4 times.
// but if we are offset by 300 pixels, there will be 5, numbered 1-5.
final IndexedWidgetBuilder itemBuilder = (BuildContext context, int index) {
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return SizedBox(
key: ValueKey<int>(index),
@ -149,7 +149,7 @@ void main() {
height: 500.0, // this should be ignored
child: Text('$index'),
);
};
}
Widget buildWidget() {
return Directionality(
@ -215,10 +215,10 @@ void main() {
// items are 300 tall. Scrolling should cause two or three items
// to be built.
final IndexedWidgetBuilder itemBuilder = (BuildContext context, int index) {
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return Text('$index', key: ValueKey<int>(index), textDirection: TextDirection.ltr);
};
}
final Widget testWidget = Directionality(
textDirection: TextDirection.ltr,

View file

@ -68,7 +68,7 @@ void main() {
// so if our widget is 200 pixels tall, it should fit exactly 3 times.
// but if we are offset by 300 pixels, there will be 4, numbered 1-4.
final IndexedWidgetBuilder itemBuilder = (BuildContext context, int index) {
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return SizedBox(
key: ValueKey<int>(index),
@ -76,7 +76,7 @@ void main() {
height: 200.0,
child: Text('$index', textDirection: TextDirection.ltr),
);
};
}
Widget builder() {
return Directionality(
@ -131,7 +131,7 @@ void main() {
// so if our widget is 200 pixels wide, it should fit exactly 4 times.
// but if we are offset by 300 pixels, there will be 5, numbered 1-5.
final IndexedWidgetBuilder itemBuilder = (BuildContext context, int index) {
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return SizedBox(
key: ValueKey<int>(index),
@ -139,7 +139,7 @@ void main() {
width: 200.0,
child: Text('$index', textDirection: TextDirection.ltr),
);
};
}
Widget builder() {
return Directionality(
@ -182,7 +182,7 @@ void main() {
final List<int> callbackTracker = <int>[];
final List<String?> text = <String?>[];
final IndexedWidgetBuilder itemBuilder = (BuildContext context, int index) {
Widget itemBuilder(BuildContext context, int index) {
callbackTracker.add(index);
return SizedBox(
key: ValueKey<int>(index),
@ -190,7 +190,7 @@ void main() {
height: 220.0,
child: Text('$index', textDirection: TextDirection.ltr),
);
};
}
void collectText(Widget widget) {
if (widget is Text)
@ -233,7 +233,7 @@ void main() {
late StateSetter setState;
ThemeData themeData = ThemeData.light();
final IndexedWidgetBuilder itemBuilder = (BuildContext context, int index) {
Widget itemBuilder(BuildContext context, int index) {
return Container(
key: ValueKey<int>(index),
width: 500.0, // this should be ignored
@ -241,7 +241,7 @@ void main() {
color: Theme.of(context).primaryColor,
child: Text('$index', textDirection: TextDirection.ltr),
);
};
}
final Widget viewport = ListView.builder(
itemBuilder: itemBuilder,
@ -273,7 +273,7 @@ void main() {
});
testWidgets('ListView padding', (WidgetTester tester) async {
final IndexedWidgetBuilder itemBuilder = (BuildContext context, int index) {
Widget itemBuilder(BuildContext context, int index) {
return Container(
key: ValueKey<int>(index),
width: 500.0, // this should be ignored
@ -281,7 +281,7 @@ void main() {
color: Colors.green[500],
child: Text('$index', textDirection: TextDirection.ltr),
);
};
}
await tester.pumpWidget(
Directionality(

View file

@ -880,7 +880,7 @@ void main() {
group('scroll notifications', () {
testWidgets('no onSelectedItemChanged callback on first build', (WidgetTester tester) async {
bool itemChangeCalled = false;
final ValueChanged<int> onItemChange = (_) { itemChangeCalled = true; };
void onItemChange(int _) { itemChangeCalled = true; }
await tester.pumpWidget(
Directionality(

View file

@ -1424,8 +1424,8 @@ void main() {
await gesture.addPointer(location: const Offset(5, 5));
addTearDown(gesture.removePointer);
final PointerHoverEventListener onHover = (_) {};
final VoidCallback onPaintChild = () { logs.add('paint'); };
void onHover(PointerHoverEvent _) {}
void onPaintChild() { logs.add('paint'); }
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
@ -1471,7 +1471,7 @@ void main() {
await gesture.addPointer(location: const Offset(100, 100));
addTearDown(gesture.removePointer);
final VoidCallback onPaintChild = () { logPaints.add('paint'); };
void onPaintChild() { logPaints.add('paint'); }
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(
@ -1521,7 +1521,7 @@ void main() {
await gesture.addPointer(location: const Offset(100, 100));
addTearDown(gesture.removePointer);
final VoidCallback onPaintChild = () { logPaints.add('paint'); };
void onPaintChild() { logPaints.add('paint'); }
await tester.pumpWidget(_Scaffold(
topLeft: SizedBox(

View file

@ -870,10 +870,10 @@ void main() {
viewsController.registerViewType('webview');
int factoryInvocationCount = 0;
final ValueGetter<EagerGestureRecognizer> constructRecognizer = () {
EagerGestureRecognizer constructRecognizer() {
factoryInvocationCount += 1;
return EagerGestureRecognizer();
};
}
await tester.pumpWidget(
AndroidView(
@ -1919,10 +1919,10 @@ void main() {
viewsController.registerViewType('webview');
int factoryInvocationCount = 0;
final ValueGetter<EagerGestureRecognizer> constructRecognizer = () {
EagerGestureRecognizer constructRecognizer() {
factoryInvocationCount += 1;
return EagerGestureRecognizer();
};
}
await tester.pumpWidget(
UiKitView(
@ -2194,10 +2194,10 @@ void main() {
testWidgets('PlatformViewRenderBox reconstructed with same gestureRecognizers', (WidgetTester tester) async {
int factoryInvocationCount = 0;
final ValueGetter<EagerGestureRecognizer> constructRecognizer = () {
EagerGestureRecognizer constructRecognizer() {
++ factoryInvocationCount;
return EagerGestureRecognizer();
};
}
final PlatformViewSurface platformViewSurface = PlatformViewSurface(
controller: controller,
@ -2218,10 +2218,10 @@ void main() {
testWidgets('PlatformViewSurface rebuilt with same gestureRecognizers', (WidgetTester tester) async {
int factoryInvocationCount = 0;
final ValueGetter<EagerGestureRecognizer> constructRecognizer = () {
EagerGestureRecognizer constructRecognizer() {
++ factoryInvocationCount;
return EagerGestureRecognizer();
};
}
await tester.pumpWidget(
PlatformViewSurface(

View file

@ -50,10 +50,12 @@ typedef DriverLogCallback = void Function(String source, String message);
/// messages from the driver subsystem.
///
/// The default implementation prints `"$source: $message"` to stderr.
DriverLogCallback driverLog = (String source, String message) {
DriverLogCallback driverLog = _defaultDriverLogger;
void _defaultDriverLogger(String source, String message) {
try {
stderr.writeln('$source: $message');
} on FileSystemException {
// May encounter IO error: https://github.com/flutter/flutter/issues/69314
}
};
}

View file

@ -1035,7 +1035,7 @@ void main() {
group('extension commands', () {
int invokes = 0;
final VoidCallback stubCallback = () => invokes++;
void stubCallback() => invokes++;
final Widget debugTree = Directionality(
textDirection: TextDirection.ltr,

View file

@ -35,8 +35,7 @@ class FrameTimingSummarizer {
);
final List<Duration> vsyncOverheadSorted =
List<Duration>.from(vsyncOverhead)..sort();
final Duration Function(Duration, Duration) add =
(Duration a, Duration b) => a + b;
Duration add(Duration a, Duration b) => a + b;
return FrameTimingSummarizer._(
frameBuildTime: frameBuildTime,
frameRasterizerTime: frameRasterizerTime,

View file

@ -241,8 +241,7 @@ class WebAssetServer implements AssetReader {
// load the through the isolate APIs.
final Directory directory =
await _loadDwdsDirectory(globals.fs, globals.logger);
final shelf.Middleware middleware =
(FutureOr<shelf.Response> Function(shelf.Request) innerHandler) {
shelf.Handler middleware(FutureOr<shelf.Response> Function(shelf.Request) innerHandler) {
return (shelf.Request request) async {
if (request.url.path.endsWith('dwds/src/injected/client.js')) {
final Uri uri = directory.uri.resolve('src/injected/client.js');
@ -254,7 +253,7 @@ class WebAssetServer implements AssetReader {
}
return innerHandler(request);
};
};
}
logging.Logger.root.onRecord.listen((logging.LogRecord event) {
globals.printTrace('${event.loggerName}: ${event.message}');

View file

@ -420,13 +420,13 @@ String _generateLookupBody(
bool useDeferredLoading,
String fileName,
) {
final String Function(LocaleInfo) generateSwitchClauseTemplate = (LocaleInfo locale) {
String generateSwitchClauseTemplate(LocaleInfo locale) {
return (useDeferredLoading ?
switchClauseDeferredLoadingTemplate : switchClauseTemplate)
.replaceAll('@(localeClass)', '$className${locale.camelCase()}')
.replaceAll('@(appClass)', className)
.replaceAll('@(library)', '${fileName}_${locale.languageCode}');
};
}
return lookupBodyTemplate
.replaceAll('@(lookupAllCodesSpecified)', _generateLookupByAllCodes(
allBundles,

View file

@ -14,7 +14,6 @@ import '../application_package.dart';
import '../base/common.dart';
import '../base/context.dart';
import '../base/io.dart' as io;
import '../base/signals.dart';
import '../base/terminal.dart';
import '../base/user_messages.dart';
import '../base/utils.dart';
@ -1068,7 +1067,7 @@ abstract class FlutterCommand extends Command<void> {
}
void _registerSignalHandlers(String commandPath, DateTime startTime) {
final SignalHandler handler = (io.ProcessSignal s) {
void handler(io.ProcessSignal s) {
globals.cache.releaseLock();
_sendPostUsage(
commandPath,
@ -1076,7 +1075,7 @@ abstract class FlutterCommand extends Command<void> {
startTime,
globals.systemClock.now(),
);
};
}
globals.signals.addHandler(io.ProcessSignal.SIGTERM, handler);
globals.signals.addHandler(io.ProcessSignal.SIGINT, handler);
}

View file

@ -37,7 +37,7 @@ import '../../src/context.dart';
import '../../src/fakes.dart';
import '../../src/testbed.dart';
final Generator _kNoColorOutputPlatform = () => FakePlatform(
FakePlatform _kNoColorOutputPlatform() => FakePlatform(
localeName: 'en_US.UTF-8',
environment: <String, String>{},
stdoutSupportsAnsi: false,

View file

@ -40,7 +40,7 @@ const String frameworkRevision = '12345678';
const String frameworkChannel = 'omega';
const String _kDisabledPlatformRequestedMessage = 'currently not supported on your local environment.';
// TODO(fujino): replace FakePlatform.fromPlatform() with FakePlatform()
final Generator _kNoColorTerminalPlatform = () => FakePlatform.fromPlatform(const LocalPlatform())..stdoutSupportsAnsi = false;
FakePlatform _kNoColorTerminalPlatform() => FakePlatform.fromPlatform(const LocalPlatform())..stdoutSupportsAnsi = false;
final Map<Type, Generator> noColorTerminalOverride = <Type, Generator>{
Platform: _kNoColorTerminalPlatform,
};

View file

@ -25,7 +25,7 @@ import '../src/common.dart';
import '../src/context.dart';
import '../src/fakes.dart';
final Generator _kNoColorTerminalPlatform = () => FakePlatform(stdoutSupportsAnsi: false);
FakePlatform _kNoColorTerminalPlatform() => FakePlatform(stdoutSupportsAnsi: false);
final Map<Type, Generator> noColorTerminalOverride = <Type, Generator>{
Platform: _kNoColorTerminalPlatform,
};

View file

@ -22,7 +22,7 @@ import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/fakes.dart';
final Generator _kNoColorTerminalPlatform = () => FakePlatform(stdoutSupportsAnsi: false);
FakePlatform _kNoColorTerminalPlatform() => FakePlatform(stdoutSupportsAnsi: false);
final Map<Type, Generator> noColorTerminalOverride = <Type, Generator>{
Platform: _kNoColorTerminalPlatform,
};

View file

@ -198,8 +198,7 @@ void main() {
class MockOperatingSystemUtils extends Mock implements OperatingSystemUtils {}
final Generator _kNoColorTerminalPlatform =
() => FakePlatform(stdoutSupportsAnsi: false);
FakePlatform _kNoColorTerminalPlatform() => FakePlatform(stdoutSupportsAnsi: false);
final Map<Type, Generator> noColorTerminalOverride = <Type, Generator>{
Platform: _kNoColorTerminalPlatform,
};

View file

@ -797,7 +797,7 @@ void fakeData(
throw StateError('Unexpected call to Cache.setStampFor(${invocation.positionalArguments}, ${invocation.namedArguments})');
});
final Answering<ProcessResult> syncAnswer = (Invocation invocation) {
ProcessResult syncAnswer(Invocation invocation) {
bool argsAre(String a1, [ String a2, String a3, String a4, String a5, String a6, String a7, String a8, String a9 ]) {
const ListEquality<String> equality = ListEquality<String>();
final List<String> args = invocation.positionalArguments.single as List<String>;
@ -828,7 +828,7 @@ void fakeData(
}
throw StateError('Unexpected call to ProcessManager.run(${invocation.positionalArguments}, ${invocation.namedArguments})');
};
}
when(pm.runSync(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer(syncAnswer);
when(pm.run(any, workingDirectory: anyNamed('workingDirectory'))).thenAnswer((Invocation invocation) async {

View file

@ -87,11 +87,13 @@ typedef _ProcessFactory = Process Function(List<String> command);
/// A ProcessManager that starts Processes by delegating to a ProcessFactory.
class MockProcessManager extends Mock implements ProcessManager {
_ProcessFactory processFactory = (List<String> commands) => FakeProcess();
_ProcessFactory processFactory = _defaulProcessFactory;
bool canRunSucceeds = true;
bool runSucceeds = true;
List<String> commands;
static Process _defaulProcessFactory(List<String> commands) => FakeProcess();
@override
bool canRun(dynamic command, { String workingDirectory }) => canRunSucceeds;

View file

@ -143,7 +143,7 @@ class TestPlatformLocation extends PlatformLocation {
String hash = '';
@override
Object? Function() state = () => null;
Object? get state => null;
/// Mocks the base href of the document.
String baseHref = '';

View file

@ -50,12 +50,12 @@ typedef LoggingFunction = void Function(LogMessage log);
/// '[${log.levelName}]::${log.tag}--${log.time}: ${log.message}'
///
/// Exits with status code 1 if the `log` is [LoggingLevel.severe].
LoggingFunction defaultLoggingFunction = (LogMessage log) {
void defaultLoggingFunction(LogMessage log) {
print('[${log.levelName}]::${log.tag}--${log.time}: ${log.message}');
if (log.level == LoggingLevel.severe) {
exit(1);
}
};
}
/// Represents a logging message created by the logger.
///