hex_to_color
A Flutter package for converting hex color strings to Flutter Color objects and vice versa.
Features
- Convert hex color strings to Flutter Color objects
- Convert Flutter Color objects to hex color strings
- Support for 6-digit (RRGGBB) and 8-digit (AARRGGBB) hex color codes
- Support for hex strings with or without the '#' prefix
- Convenient String extension method for easy conversion
Installation
Add this to your package's pubspec.yaml
file:
dependencies:
hex_to_color: ^0.1.0
Then run:
flutter pub get
Usage
Import the package
import 'package:hex_to_color/hex_to_color.dart';
Convert hex string to Color
There are three ways to convert a hex color string to a Flutter Color:
1. Using HexColor constructor
// With '#' prefix
final color1 = HexColor('#FF5733');
// Without '#' prefix
final color2 = HexColor('33FF57');
2. Using static fromHex method
final color = HexColor.fromHex('#FF5733');
3. Using String extension
final color = '#FF5733'.toColor();
With alpha channel
You can specify an alpha value using 8-digit hex codes:
// 80 = 50% opacity
final colorWithAlpha = HexColor('80FF5733');
Convert Color to hex string
You can convert a Color object back to a hex string:
final color = HexColor('#FF5733');
// With alpha and # prefix (default)
String hexWithAlpha = color.toHex(); // #FFFF5733
// Without alpha
String hexWithoutAlpha = color.toHex(withAlpha: false); // #FF5733
// Without # prefix
String hexWithoutHashSign = color.toHex(includeHashSign: false); // FFFF5733
Example
import 'package:flutter/material.dart';
import 'package:hex_to_color/hex_to_color.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Hex To Color Example'),
backgroundColor: '#FF5733'.toColor(),
),
body: Center(
child: Container(
width: 200,
height: 200,
color: HexColor('#33FF57'),
child: Center(
child: Text(
'Hex Color',
style: TextStyle(
color: HexColor('#3357FF'),
fontSize: 24,
),
),
),
),
),
),
),
);
}
License
This project is licensed under the MIT License - see the LICENSE file for details.