Search code examples
flutterdartforeachtyping

Flutter forEach typing: Unable to type a forach callback (The argument type N can't be assigned to the parameter type 'void Function(dynamic)')


total noob question here:

dart forEach typing problem

If I don't specify a type, it says Try adding an explicit type, or remove implicit-dynamic from your analysis options file.dart(implicit_dynamic_parameter)

When I add the type double in front of the function param, it says The argument type 'void Function(double)' can't be assigned to the parameter type 'void Function(dynamic)'

Also I really don't understand why the type is not inferred from the array declaration above ?

final List strengths = <double>[.05]; // type of array items in a forEach loop seems obvious

I have tried a lot of different things and syntax that I saw everywhere on the internet but the only way to fix my problem was to delete analysis_options.yaml

I am sure I really miss the obvious...Could you point me the right direction ?


Other related questions I have saw and couldn't adapt to my case:

The real function code:

MaterialColor createMaterialColor(Color color) {
  final List strengths = <double>[.05];
  final swatch = <int, Color>{};
  final int r = color.red, g = color.green, b = color.blue;

  for (int i = 1; i < 10; i++) {
    strengths.add(0.1 * i);
  }
  strengths.forEach((double strength) {
    final double ds = 0.5 - strength;
    swatch[(strength * 1000).round()] = Color.fromRGBO(
      r + ((ds < 0 ? r : (255 - r)) * ds).round(),
      g + ((ds < 0 ? g : (255 - g)) * ds).round(),
      b + ((ds < 0 ? b : (255 - b)) * ds).round(),
      1,
    );
  });
  return MaterialColor(color.value, swatch);
}

Solution

  • Declare Your List like this:

    final List<double> strengths = <double>[.05];