hexInputController property
Allows setting the color using text input, via TextEditingController.
Listens to String input and trying to convert it to the valid Color. Contains basic validator, that requires final input to be provided in one of those formats:
- RGB
- #RGB
- RRGGBB
- #RRGGBB
- AARRGGBB
- #AARRGGBB
Where: A stands for Alpha, R for Red, G for Green, and B for blue color.
It will only accept 3/6/8 long HEXs with an optional hash (#
) at the beginning.
Allowed characters are Latin A-F case insensitive and numbers 0-9.
It does respect the enableAlpha flag, so if alpha is disabled, all inputs
with transparency are also converted to non-transparent color values.
MaterialButton(
elevation: 3.0,
onPressed: () {
// The initial value can be provided directly to the controller.
final textController =
TextEditingController(text: '#2F19DB');
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
scrollable: true,
titlePadding: const EdgeInsets.all(0.0),
contentPadding: const EdgeInsets.all(0.0),
content: Column(
children: [
ColorPicker(
pickerColor: currentColor,
onColorChanged: changeColor,
colorPickerWidth: 300.0,
pickerAreaHeightPercent: 0.7,
enableAlpha:
true, // hexInputController will respect it too.
displayThumbColor: true,
showLabel: true,
paletteType: PaletteType.hsv,
pickerAreaBorderRadius: const BorderRadius.only(
topLeft: const Radius.circular(2.0),
topRight: const Radius.circular(2.0),
),
hexInputController: textController, // <- here
portraitOnly: true,
),
Padding(
padding: const EdgeInsets.all(16),
/* It can be any text field, for example:
* TextField
* TextFormField
* CupertinoTextField
* EditableText
* any text field from 3-rd party package
* your own text field
so basically anything that supports/uses
a TextEditingController for an editable text.
*/
child: CupertinoTextField(
controller: textController,
// Everything below is purely optional.
prefix: Padding(
padding: const EdgeInsets.only(left: 8),
child: const Icon(Icons.tag),
),
suffix: IconButton(
icon:
const Icon(Icons.content_paste_rounded),
onPressed: () async =>
copyToClipboard(textController.text),
),
autofocus: true,
maxLength: 9,
inputFormatters: [
// Any custom input formatter can be passed
// here or use any Form validator you want.
UpperCaseTextFormatter(),
FilteringTextInputFormatter.allow(
RegExp(kValidHexPattern)),
],
),
)
],
),
);
},
);
},
child: const Text('Change me via text input'),
color: currentColor,
textColor: useWhiteForeground(currentColor)
? const Color(0xffffffff)
: const Color(0xff000000),
),
Do not forget to dispose()
your TextEditingController if you creating
it inside any kind of StatefulWidget's State.
Reference: https://en.wikipedia.org/wiki/Web_colors#Hex_triplet
Implementation
final TextEditingController? hexInputController;