0

I want to store a ColorSwatch in json, and extract it in an object's .fromJson method.

I've tried storing it in JSON as:

"colorSwatch": "ColorSwatch(0xFFFFB7DE, { 'highlight': Color(0xFFFFB7DE), 'splash': Color(0xFFF94CBF) })"

Then extracting it with:

colorSwatch = jsonMap['colorSwatch'],

It didn't work. I tried changing the JSON to:

"colorSwatch": "0xFFFFB7DE, { 'highlight': Color(0xFFFFB7DE), 'splash': Color(0xFFF94CBF) }"

Then modifying the object's .fromJson method to:

colorSwatch = ColorSwatch(jsonMap['colorSwatch']),

It didn't work. I then tried:

colorSwatch = jsonMap['colorSwatch'] as ColorSwatch,

Didn't work.

I then tried saving the highlight and splash colours in json separately and extracting with

highlight = jsonMap['highlight'] as int,
splash = jsonMap['splash'] as int,
colorSwatch = new ColorSwatch(0xFFFFD28E, {'highlight': Color(highlight), 'splash': Color(splash)}),

But aparently I'm only allowed to do operations on static variables in an object's fromJson method.

So I'm stuck.

I want the ColorSwatch object attached to the Riddle object, so all the properties associated with a Riddle are in one place and don't need to be assembled elsewhere when needed.

  • It doesn't seem possible to build an Object, here ColorSwatch, inside another objects .fromJson method, is this correct?
  • So that means I have to extract the entire object in a single line of code, how do I do this?

1 Answer 1

1

Json doesn't support hexadecimals so you need to write them as a string and convert them using int.tryparse:

  var hexadecimalString = 'ff542144';
  var decimalInteger = int.tryParse(hexadecimalString, radix: 16);

for your ColorSwatch you need a helper class like this:

class ColorSwatch {
  final Color swatch;
  final Color splash;
  final Color highlight;

  ColorSwatch(this.swatch, this.splash, this.highlight);

  factory ColorSwatch.fromJson(Map<String, dynamic> json) {
    return ColorSwatch(
      Color(int.tryParse(json['colorSwatch'], radix: 16)),
      Color(int.tryParse(json['highlight'], radix: 16)),
      Color(int.tryParse(json['splash'], radix: 16)),
    );
  }

  String toJson() {
    return jsonEncode({
      'colorSwatch': swatch.value.toRadixString(16),
      'highlight': highlight.value.toRadixString(16),
      'splash': splash.value.toRadixString(16),
    });
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Aligator, that's was a helpful answer. In the end I: 1. saved the hexadecimal color values individually to JSON, 2. extracted them using Color(int.parse(json['highlight'], radix 16)); The hexadecimal conversion solved it for me, I owe you for that. Cheers Sam.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.