Flutter Dart - 'Map<dynamic, dynamic>' 无法分配给参数类型 'Map<int, Color>'
Flutter Dart - 'Map<dynamic, dynamic>' can't be assigned to the parameter type 'Map<int, Color>'
这是我的代码。
import 'package:flutter/material.dart';
class WpCreateColor {
final Color wpColor = Color.fromARGB(255, 77, 203, 79);
MaterialColor createMaterialColor() {
List strengths = <double>[.05];
Map swatch = <int, Color>{};
final int r = wpColor.red, g = wpColor.green, b = wpColor.blue;
for (int i = 1; i < 10; i++) {
strengths.add(0.1 * i);
}
strengths.forEach((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(wpColor.value, swatch);
}
}
并且出现以下错误:
Map<dynamic, dynamic> swatch
The argument type 'Map<dynamic, dynamic>' can't be assigned to the parameter type 'Map<int, Color>'.dartargument_type_not_assignable
我该如何解决这个问题?
在上述代码的第 8 行,变量 swatch
被定义为 Map
,默认情况下类型为 dynamic
,因此 swatch
的完整类型为创建为 Map<dynamic, dynamic>
,但是此变量的值被分配给 Map<int,Color>
的值,这就是您收到错误的原因。
要解决此问题,更改:
Map swatch = <int, Color>{};
至
final swatch = <int, Color>{};
dart 中的一个建议是省略局部变量的类型,因为
Usually, the types of local variables can be easily inferred, so it
isn’t necessary to annotate them.
访问 dart docs 了解有关此建议的更多信息
这是我的代码。
import 'package:flutter/material.dart';
class WpCreateColor {
final Color wpColor = Color.fromARGB(255, 77, 203, 79);
MaterialColor createMaterialColor() {
List strengths = <double>[.05];
Map swatch = <int, Color>{};
final int r = wpColor.red, g = wpColor.green, b = wpColor.blue;
for (int i = 1; i < 10; i++) {
strengths.add(0.1 * i);
}
strengths.forEach((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(wpColor.value, swatch);
}
}
并且出现以下错误:
Map<dynamic, dynamic> swatch
The argument type 'Map<dynamic, dynamic>' can't be assigned to the parameter type 'Map<int, Color>'.dartargument_type_not_assignable
我该如何解决这个问题?
在上述代码的第 8 行,变量 swatch
被定义为 Map
,默认情况下类型为 dynamic
,因此 swatch
的完整类型为创建为 Map<dynamic, dynamic>
,但是此变量的值被分配给 Map<int,Color>
的值,这就是您收到错误的原因。
要解决此问题,更改:
Map swatch = <int, Color>{};
至
final swatch = <int, Color>{};
dart 中的一个建议是省略局部变量的类型,因为
Usually, the types of local variables can be easily inferred, so it isn’t necessary to annotate them.
访问 dart docs 了解有关此建议的更多信息