Search code examples
jsonflutterdartflutter-web

How to get Color value from a json string and use it in Flutter Dart


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.


Solution

  • 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']);