[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));
  }
}
相关推荐
阅文作家助手开发团队_山神7 小时前
第五章:Flutter Quill渲染原理深度剖析:Delta到RichText的华丽转身
flutter
未来猫咪花7 小时前
# Flutter状态管理对比:view_model vs Riverpod
flutter·ios·android studio
阅文作家助手开发团队_山神1 天前
第四章(下) Delta 到 HTML 转换:块级与行内样式渲染深度解析
flutter
MaoJiu1 天前
Flutter造轮子系列:flutter_permission_kit
flutter·swiftui
阅文作家助手开发团队_山神1 天前
第四章(下):Delta 到 HTML 转换的核心方法解析
flutter
xiaoyan20151 天前
flutter3.32+deepseek+dio+markdown搭建windows版流式输出AI模板
flutter·openai·deepseek
阅文作家助手开发团队_山神1 天前
第四章(上):HTML 到 Delta 转换的核心方法解析
flutter
stringwu1 天前
Flutter高效开发利器:Riverpod框架简介及实践指南
flutter
耳東陈1 天前
Flutter开箱即用一站式解决方案2.0-全局无需Context的Toast
flutter
阅文作家助手开发团队_山神2 天前
第三章: Flutter-quill 数据格式Delta
flutter