Flutter Dart报错Map<dynamic, dynamic>无法赋值给Map<int, Color>如何解决
报错原因及解决方案
原因
MaterialColor构造函数要求传入的色板参数类型为Map<int, Color>,但你声明swatch变量时仅写了Map swatch,未指定泛型,Dart会将该变量推断为Map<dynamic, dynamic>,类型不匹配触发报错。
解决方法
仅需修改swatch变量的声明,显式指定泛型即可,两种写法均可生效:
- 显式标注变量泛型类型
Map<int, Color> swatch = <int, Color>{};
- 用
final关键字让Dart自动推断右侧初始化值的泛型类型,写法更简洁
final swatch = <int, Color>{};
优化后的完整代码
import 'package:flutter/material.dart'; class WpCreateColor { final Color wpColor = const Color.fromARGB(255, 77, 203, 79); MaterialColor createMaterialColor() { final strengths = <double>[.05]; // 修正swatch的类型声明 final 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); } // 此处改用官方更推荐的for-in循环替代forEach,非必须修改 for (final strength in strengths) { 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); } }
内容的提问来源于stack exchange,提问作者edn
相关产品推荐
相关产品推荐

