3

I have a JSON assigned to a variable called user

 var user= {
'Name':'khan',
'Country':'Pakistan',
'color':'Color(0xffffff)',
};

Suppose I want to get data from it and use it somewhere.

 String encodedjson=jsonEncode(user);
    Map <String,dynamic> decodedJson=jsonDecode(encodedjson);
var colordata=decodedJson['color'];

Now I want to use colordata Let say I want to put the color in a container background

i.e

 Container(width: 200,height:200,color:colordata,)

This will give me an error because colordata is not the type Color.. So what should I do use JSON color like this.

2
  • Are you able to change what's stored in the JSON? Commented Apr 30, 2021 at 23:08
  • Yes, I can dot it in my actual code. Commented Apr 30, 2021 at 23:14

3 Answers 3

5

You can store the color as a hex literal/int, which is JSON encodable, then pass it to the Color constructor:

var user= {
'Name':'khan',
'Country':'Pakistan',
'color': 0xffffff,
};
String encodedjson=jsonEncode(user);
Map<String,dynamic> decodedJson=jsonDecode(encodedjson);
var colordata = Color(decodedJson['color']);
Sign up to request clarification or add additional context in comments.

4 Comments

Actually, the change in a JSON is occuerd using ColorPicker. void changeColor(Color color) {user['color']=color;}
@MehranUllah Could you rephrase what you said. It was not clear.
Actually, the change in a JSON is occuerd using ColorPicker. void changeColor(Color color) {user['color']=color;}
@MehranUllah Then do user['color']=color.value;
0

Just to add more clarity if you have a a color like this:

    final whiteValue = jsonDecode(jsonEncode(Color(0xFFFFFFFF).value));
    print("COLOR VAL $whiteValue"); // prints 4294967295
    final newWhite = Color(whiteValue);
    print(newWhite); // prints Color(0xffffffff)

you want to encode the value property and then interpolate that in, hopefully this adds some clarity to what the above answer was getting at.

Comments

0

A solution would be to use the individual rgb values.

var user= {
'Name':'khan',
'Country':'Pakistan',
'color':jsonifyColor(Colors.red),
};

Map<String, int> jsonifyColor(Color color) {
    return {
      'red': color.red,
      'blue': color.blue,
      'green': color.green,
      'alpha': color.alpha,
    };
  }

Color deJsonifyColor(Map<String, int> colorMap) {
    return Color.fromARGB(
      colorMap['alpha']!,
      colorMap['red']!,
      colorMap['green']!,
      colorMap['blue']!,
    );
  }

var colordata = deJsonifyColor(user['color']);

Container(width: 200,height:200,color:colordata,)

Comments

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.