[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));
  }
}
相关推荐
FungLeo2 小时前
Flutter fl_chart 0.70 破坏性 API 迁移实录:duration/getTooltipColor/withValues 全解
flutter·fl_chart
FungLeo8 小时前
Flutter 吸顶分组列表实战:语义桶分组 + 点击头平滑滚动
android·flutter
FungLeo9 小时前
Flutter 超长 StatefulWidget 拆分术:part of + extension on State 实战
android·flutter·dart
GitLqr10 小时前
Impeller 时代:Shader Jank 消失了,但渲染性能的战场也变了
flutter·面试·性能优化
恋猫de小郭13 小时前
Flutter 的另外一种形态?社区 DartNative 要来了。
android·前端·flutter
阿里云云原生1 天前
还原一次用户等待:深度解析 Flutter RUM SDK 如何打通 Dart 到 Native 的观测链路
flutter
_阿南_1 天前
flutter 展示的字体突然奔放了
android·flutter·ios
GitLqr1 天前
玩转 Dart typedef:不仅是函数别名那么简单
flutter·面试·dart
FungLeo1 天前
Flutter 两个反直觉布局坑:ListTile 水波纹 / VerticalDivider 踩坑实录
android·flutter
年小个大2 天前
受 go-zero 启发,我给 Flutter 写了一套 CLI 脚手架
android·flutter·架构