[Flutter]用16进制颜色字符串初始化Color

使用:

Dart 复制代码
// 使用Color的静态方法 fromARGB() 来创建颜色对象。透明度为 255(完全不透明)
Color a = Color.fromARGB(255, 42, 35, 72);
// 使用八位的十六进制数来表示颜色,其中前两位表示透明度,后六位表示红色、绿色和蓝色通道的值。0xFF 表示完全不透明
Color b = Color(0xFF282344);

// 使用自定义的HexColor类,它可以从十六进制字符串中创建颜色对象。为6位时默认不透明,为8位时FF表示不透明。
Color c = HexColor.fromHex("#282344");
Color d = HexColor.fromHex('#FF282344');

// 颜色转为十六进制字符串
String aHex6 = a.toHex6();  
String aHex8 = a.toHex8();  

String cHex61 = c.toHex6();  
String cHex81 = c.toHex8();  

拓展:

Dart 复制代码
import 'package:flutter/material.dart';

extension ColorUtils on Color {
  // 转换Color对象为8位16进制字符串
  String toHex8({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${alpha.toRadixString(16).padLeft(2, '0')}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}';

  // 转换Color对象为6位16进制字符串
  String toHex6({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}';
}

class HexColor {
  // 解析16进制字符串为Color对象
  static Color fromHex(String hexString) {
    String hex = hexString.replaceAll('#', '');
    if (hex.length == 6) {
      hex = 'FF' + hex; // 默认透明度为1(FF)
    } else if (hex.length == 3) {
      hex = 'FF' + hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; // 简写形式
    }
    return Color(int.parse(hex, radix: 16));
  }
}
相关推荐
Forever不止如此1 小时前
【CustomPainter】绘制圆环
flutter·custompainter·圆环
wills7772 小时前
Flutter Error: Type ‘UnmodifiableUint8ListView‘ not found
flutter
AiFlutter1 天前
Flutter之Package教程
flutter
Mingyueyixi1 天前
Flutter Spacer引发的The ParentDataWidget Expanded(flex: 1) 惨案
前端·flutter
crasowas1 天前
Flutter问题记录 - 适配Xcode 16和iOS 18
flutter·ios·xcode
老田低代码2 天前
Dart自从引入null check后写Flutter App总有一种难受的感觉
前端·flutter
AiFlutter3 天前
Flutter Web首次加载时添加动画
前端·flutter
ZemanZhang4 天前
Flutter启动无法运行热重载
flutter
AiFlutter5 天前
Flutter-底部选择弹窗(showModalBottomSheet)
flutter