[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));
  }
}
相关推荐
帅次9 小时前
Android 高级工程师面试:Flutter Widget 体系 近1年高频追问 20 题
android·flutter·面试·element·widget·setstate·renderobject
浮江雾13 小时前
Flutter第四节------核心概念学习笔记:从基础语法到异步编程
linux·服务器·开发语言·笔记·flutter·入门·基础
心中有国也有家13 小时前
AtomGit Flutter 鸿蒙客户端:Flutter 鸿蒙应用的错误处理与优雅降级策略
学习·flutter·华为·harmonyos
心中有国也有家1 天前
AtomGit Flutter 鸿蒙客户端: ChangeNotifier 模式
学习·flutter·华为·harmonyos
浮江雾1 天前
Flutter第三节----Dart中的数据类型
android·开发语言·学习·flutter·入门·函数
又菜又爱coding1 天前
Flutter Android 无线调试No supported devices connected
flutter
心中有国也有家2 天前
AtomGit Flutter 鸿蒙客户端:初始化流水线
学习·flutter·华为·harmonyos
ZZZMMM.zip2 天前
基于鸿蒙HarmonyOS NEXT开发AI英语口语应用:智能口语练习新体验与鸿蒙Flutter框架跨端实
人工智能·flutter·华为·harmonyos·鸿蒙·鸿蒙系统
心中有国也有家2 天前
AtomGit Flutter 鸿蒙客户端:白噪音场景的视觉设计
学习·flutter·华为·harmonyos
心中有国也有家2 天前
AtomGit Flutter 鸿蒙客户端:呼吸练习的完整生命周期
学习·flutter·华为·harmonyos