Color conversion in Flutter
?? Excited to share a handy code snippet for color conversion in Flutter! ??
Have you ever needed to convert color codes between hexadecimal and Flutter Color objects? ?? Look no further! Here's a concise and efficient solution:
import 'package:flutter/material.dart';
void main() {
const Color mainColor = Color(0xffFF6801);
String mainHex = ColorConverter().colorToHex(mainColor);
print(mainHex);
const String hex = "#FF6801";
Color color = ColorConverter().hexToColor(hex);
print(color);
}
class ColorConverter {
Color hexToColor(String hexCode) {
try {
final int parsedColor = int.parse(hexCode.substring(1, 7), radix: 16);
return Color(parsedColor + 0xFF000000);
} catch (e) {
print("Invalid hex code: $hexCode");
return const Color(0xff000000);
}
}
String colorToHex(Color color) {
return '#${color.value.toRadixString(16)}';
}
}
? What does this code do?
?? Why is it useful?
?? How can you use it?
Simply copy and paste this code into your Flutter project! You can then utilize the hexToColor and colorToHex functions wherever you need color conversion.
Happy coding! Feel free to share your thoughts or questions below. Let's empower each other in the world of Flutter development! ?? #Flutter