【问题标题】:Flutter Dart - 'Map<dynamic, dynamic>' can't be assigned to the parameter type 'Map<int, Color>'Flutter Dart - 'Map<dynamic, dynamic>' 不能分配给参数类型'Map<int, Color>'
【发布时间】:2021-10-27 09:57:59
【问题描述】:

这是我的代码。

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

我该如何解决这个问题?

【问题讨论】:

  • 尝试使用Map&lt;int, Color&gt; swatch = {};
  • @Sahdeep Singh 太棒了!有效。您是否认为您也可以将此信息作为答案,以便我可以接受它作为官方答案?
  • 您可以添加它并接受或下面的答案也很好,您也可以接受。干杯。

标签: flutter dart dart-null-safety


【解决方案1】:

在上面代码的第 8 行,变量 swatch 被定义为 Map,默认为 dynamic,因此 swatch 的完整类型被创建为 Map&lt;dynamic, dynamic&gt;,但是这个变量被赋值为Map&lt;int,Color&gt; 这就是你得到错误的原因。

要修复此更改

Map swatch = &lt;int, Color&gt;{};

final swatch = &lt;int, Color&gt;{};

dart 中的一个建议是省略局部变量的类型,因为

通常情况下,局部变量的类型很容易推断出来,所以它 没有必要对它们进行注释。

访问dart docs 了解有关此建议的更多信息

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 2021-10-02
    • 2021-03-23
    • 2023-04-05
    • 2020-12-27
    • 2020-12-15
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多