E/flutter ( 8110): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Converting object to an encodable object failed: Instance of ‘Color’
I keep getting this error
String colorToHex(Color color) {
return '#${color.value.toRadixString(16)}';
}
///
void setFontColor(Color newColor) async {
_fontColor = newColor;
// Convert the Color object to a hex color string
String hexColor = colorToHex(newColor);
await _prefs.setString('fontColor', hexColor);
notifyListeners();
}
Color _getFontColorFromString(SharedPreferences prefs) {
String fontColorString =
prefs.getString('fontColor') ?? AppConstants.fontColorHex;
// Remove any '#' symbol if present
fontColorString = fontColorString.replaceAll('#', '');
// Check if the string length is 6 (without alpha) or 8 (with alpha)
if (fontColorString.length == 6 || fontColorString.length == 8) {
// Add 'FF' as alpha if it's not present
if (fontColorString.length == 6) {
fontColorString = 'FF' + fontColorString;
}
// Parse the hex color string
Color fontColor = Color(int.parse(fontColorString, radix: 16));
return fontColor;
} //
else {
// Handle the case where the format is invalid
return Color(
int.parse(AppConstants.fontColorHex.replaceAll('0x', ''), radix: 16));
}
}
Some other method:
// Retrieve user preferences
Color fontColor = _getFontColorFromString(preferences);
2
Answers
Implementation of colorToHex Function will solve the problem
Try to store color as integer value representing its ARGB format and at time of retrieval again convert to Color object.