How to convert string to color in Flutter - flutter

I want to convert the string to color but I can't,
My Code
String color = "0xffff5252";
Color result= Color(int.parse(color, radix: 16));
print("$result");
** I get the following problem**
Invalid radix-16 number (at character 1) 0xffff5252

You can try something like below
String color = "0xffff5252";
Color result= Color(int.parse(color));
print(result);

if youe motive is to define a color by first defining into string and then by parsing it, then there's a much simpler way to define color,
const Color primary = Color(0xFF92A3FD);
const Color secondary = Color(0xFF9DCEFF);
const Color thirdColor = Color(0xFFC58BF2);
const Color fourthColor = Color(0xFFEEA4CE);
const Color bgTextField = Color(0xFFF7F8F8);
const Color facebookColor = Color(0xFF3b5998);
const Color googleColor = Color(0xFFDB4437);

Try this hexToColor function:
// Construct a color from a hex code string, of the format RRGGBB.
Color hexToColor(String code) {
return Color(int.parse(code.substring(1, 6), radix: 16) + 0xFF000000);
}
This worked for me to store a color & use it as a profile avatar color.

Related

Randomize swatch for a color passed to a function in Flutter

I have a function that gets Color as an argument. I want to generate a list of random swatches for that color within that function. For example, if the color passed is Colors.amber I want a list like:
[ Colors.amber[100], Colors.amber[800], Colors.amber[500], Colors.amber[900], Colors.amber[300]... ]
Is it possible? Any advice or help would be appreciated. Thank you in advance.
You can randomize only the list of "plus colors":
Flutter Colors
List<int> types = [50, 100, 200, 300, 400, 600, 700, 800, 900]
And randomize a number between 0..8
int get getRandomNumber => 0 + Random().nextInt(8 - 0);
Use to get the random color
Color? selectedColor = Colors.amber[types[getRandomNumber]];
Update:
Using this method extension, we can create a "workaround"
extension HexColor on Color {
/// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
Color fromHex(String hexString) {
final buffer = StringBuffer();
if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
buffer.write(hexString.replaceFirst('#', ''));
return Color(int.parse(buffer.toString(), radix: 16));
}
/// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
String toHex({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')}';
}
And using this function
Color getRandomColor(String selectedColor) {
final List<int> types = [50, 100, 200, 300, 400, 600, 700, 800, 900];
int getRandomNumber = 0 + Random().nextInt(8 - 0);
return Color.fromHex(selectedColor)[types[getRandomNumber]];
}
//true will return "#ffffff", false will return "ffffff"
Color _color = getRandomColor(Color.red.toHex(true));
Found a simple solution
Let color be the passed parameter. Now find the index of that color in the Colors.primaries list.
for(int i=0;i<Colors.primaries.length;i++){
if(color==Colors.primaries[i]){
colorIndex=i;
}
}
Use this index to generate the random swatch of the preferred color.
Colors.primaries[colorIndex][Random.nextInt(9) * 100]

Material-UI Theme const concatenation

I am using const in my material-UI theme in order to define colors
for example
const tableHeader=grey[400]
in order to use semantic constant names I want to create several constants and give them the same color
for example somthing like
const tableHeader, borderDefault = grey[400]
is there any such way
(the eaxmple above don't work)
apart from Maryja Piaredryj answer, there's another way. Store these colors in the material-UI theme, and then use this using makeStyles or useTheme.
const theme = createMuiTheme({
custom: {
palette: {
borders: grey[400]
}
}
});
Now use this in makeStyles as a regular theme property
const useStyles = makeStyles((theme) => ({
borderStyle:{
borderColor:theme.custom.palette.borders;
}
}));
Unfortunately, you should assign value to every variable separately.
But you can think of choosing another data structure to store color variables, smth like
const THEME = {
borders: grey[400]
}
const tableHeader = THEME.borders;
const borderDefault = THEME.borders;

How to properly save and use my template [e.g. for colors]?

The way I currently save my design template (colors, constraints, sizes...) in flutter projects is by creating a file called: style_constants.dart in lib/theme/ This is for instance how the file could look like:
import 'package:flutter/material.dart';
const Color colorShade1 = Color(0xFFEFF0F2);
const Color colorShade2 = Color(0xFF777777);
const Color colorShade3 = Color(0xFF424242);
const Color colorShade4 = Color(0xFF4B4935);
const Color colorShade5 = Color(0xFF3D2916);
const Color colorShade6 = Color(0xFF1D1C0A);
const Color colorBackground = Color(0xFF101A24);
const Color colorPrimary1 = Color(0xFFCC9757);
const Color colorRed = Color(0xFFEB5757);
// TabBar
const double kTabIconHeight = 28;
// CTA
const double kCtaHeight = 52;
const double kCtaWidth = 358;
const Color colorCtaBackground = Colors.white;
const TextStyle ktsCta = TextStyle(color: colorRed, fontSize: 19, fontWeight: FontWeight.w700);
The way I'm doing it works, HOWEVER it is most probably NOT the best way to do it. I found on the official dart page that it would be better to do it this way:
class Color {
static const red = '#f00';
static const green = '#0f0';
static const blue = '#00f';
static const black = '#000';
static const white = '#fff';
}
I tried to incorporate it but somehow did NOT work. Can you please show me the best-practice in terms of saving your own design a.k.a. CSS template?
I see 2 issues with your way of implementing your Color class. First is that your class has the same typo as the material Color from flutter which might cause conflicts when adding it into a file where the package material.dart is also imported. The second one is more of a personal taste, I am not a big fan of using HEX color format as flutter Color constructor takes an int as its parameter. On my projects I am saving my colors like this:
class MyColors {
static const someRed = Color(0xFFFF6666);
static const someGreen = Color(0xFF24B356);
// etc...
}
The conversion from HEX to int is quite easy, you only need to replace the # by 0xFF. For example a color static const hexSomeBlue = "#8d91b8"; will became static const someBlue = Color(0xFF8d91b8);

How to convert Color to a list of RGB values in Dart & Flutter?

I would like to be able to take a Color and convert it into a List<int> so like [0,255,255].
How do I do that?
List<int> getRGB(Color c) {
return [c.red, c.blue, c.green];
}
To use
Color c = Colors.red;
print(getRGB(c));

Converting short colorVal = CellStyle.getBottomBorderColor () to RGB value while using Apache POI Java library

I am reading Excel sheet using Apache POI and writing it to a PDF using iText library.This has been achieved successfully but I am getting default black border for every cell that I write to PDF. So I need to get the cell border color using Apache POI which can be achieved using CellStyle class method getBottomBorderColor() which returns a short value.However I need a way to convert this value to RGB value so that while writing cell to PDF I can apply that RGB color value to the cell border.
The short value from CellStyle.getBottomBorderColor is an index of the color in the color palette of the workbook. This is an olld approach for storing colors from the old binary *.xls Excel format. So in apache poi there is only HSSFPalette which only should be used in HSSF and not more be used in XSSF.
In newer *.xlsx Excel formats, the color will either be stored directly as hex value or as reference to a theme color. So for XSSF there is XSSFCellStyle.getBottomBorderXSSFColor to get that color directly and not via index.
So unfortunately we have to differ both aproaches dependent on the kind of Excel workbook.
Example:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import java.io.FileInputStream;
class ExcelCellBorderColor{
public static void main(String[] args) throws Exception {
Workbook wb = WorkbookFactory.create(new FileInputStream("ExcelCellBorderColor.xlsx"));
//Workbook wb = WorkbookFactory.create(new FileInputStream("ExcelCellBorderColor.xls"));
String strrgb;
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
CellStyle style = cell.getCellStyle();
if (style instanceof XSSFCellStyle) {
XSSFColor xssfcolor = ((XSSFCellStyle)style).getBottomBorderXSSFColor();
if (xssfcolor != null) {
byte[] brgb = xssfcolor .getRGB();
strrgb = "R:"+String.format("%02X", brgb[0])+",G:"+String.format("%02X", brgb[1])+",B:"+String.format("%02X", brgb[2]);
System.out.println("Cell " + cell.getAddress() + " has border bottom color: " + strrgb);
}
} else if (style instanceof HSSFCellStyle) {
short colorindex = ((HSSFCellStyle)style).getBottomBorderColor();
HSSFPalette palette = ((HSSFWorkbook)wb).getCustomPalette();
HSSFColor hssfcolor = palette.getColor(colorindex);
if (hssfcolor != null) {
short[] srgb = hssfcolor.getTriplet();
strrgb = "R:"+String.format("%02X", srgb[0])+",G:"+String.format("%02X", srgb[1])+",B:"+String.format("%02X", srgb[2]);
System.out.println("Cell " + cell.getAddress() + " has border bottom color index: " + colorindex + ". This is " + strrgb);
}
}
}
}
wb.close();
}
}
you can archive this by using this color class
CTScRgbColor scrgb = (CTScRgbColor)ch;
int r = scrgb.getR();
int g = scrgb.getG();
int b = scrgb.getB();
color = new Color(255 * r / 100000, 255 * g / 100000, 255 * b / 100000);