Flutter自定义Color常量提示无效,无法正常使用问题求助
解决Flutter自定义颜色常量无效的问题
问题根源在于你定义的颜色变量不是编译时常量,但在const Text组件的TextStyle中指定了该变量,而const组件要求所有参数必须是编译时常量。
1. 修改自定义颜色文件
把颜色变量声明为static const,确保它是编译时常量:
import 'package:flutter/material.dart'; class ColorSkh { static const Color innovation = const Color.fromARGB(255, 59, 18, 45); static const Color fresh = const Color.fromARGB(255, 172, 155, 163); static const Color hightech = const Color.fromARGB(255, 0, 128, 157); static const Color sophisticated = const Color.fromARGB(255, 230, 231, 232); static const Color sk = const Color.fromARGB(255, 191, 205, 217); static const Color white = const Color.fromARGB(255, 255, 255, 255); }
2. 调整使用代码(可选)
如果不想修改颜色文件,也可以去掉Text组件的const关键字,这样就允许使用非常量的颜色变量:
SizedBox( height: height * 0.10, child: Align( alignment: Alignment.centerLeft, child: ElevatedButton.icon( onPressed: onPressed, icon: const Icon(Icons.settings), // 去掉Text的const修饰符 label: Text('Settings', style: TextStyle(backgroundColor: ColorSkh.innovation)), style: ElevatedButton.styleFrom( backgroundColor: Colors.white, ), ), ), )
两种方案任选其一即可解决“无效常量”的错误。
内容的提问来源于stack exchange,提问作者idperez
相关产品推荐
相关产品推荐

