How to take int from json and parse it as bool in dart?

2,881

Solution 1

Try this,

class Abc extends Model {
  bool playful;

  Abc({this.playful}) : super(id);

  Abc.fromJson(Map<String, dynamic> json) : this(playful: json['playful'] == 1);

  Map<String, dynamic> toJson() {
    final data = <String, dynamic>{};
    data['playful'] = this.playful ? 1 : 0;
    return data;
  }
}

Solution 2

As far as I know, Dart doesn't have any function or method for parsing booleans. So I would create a private function in this class which would return boolean for given integer.

bool parseBool(int integer) {
  return integer == 1;
}
Share:
2,881
Haroon Ashraf Awan
Author by

Haroon Ashraf Awan

I am Haroon Awan, a creative full-stack web &amp; mobile developer based in Multan, Pakistan with a computer science background. I have more than 5 years of experience in this field and have launched multiple projects from the empty repository to fully-functional production deployments. I am the go-to guy for any of your development needs and I strive to bring creativity, innovation with a strong analytical, problem-solving mindset. My vision is to quickly help startups and enterprises with prototypes and ideas by efficiently building those things into reality. My primary stack is Flutter, NodeJS, VueJS, and MongoDB. I have proficient experience in Dart, JavaScript programming language. My skills are: Frontend: HTML,CSS, SASS, Angular, JavaScript, Typescript, NuxtJS, VueJS. Backend: NodeJs, NestJS, GoLang, Django. API integrations, PHP, Laravel, API development. Databases: MySQL, MongoDB, PostgreSQL. Other: Git, Github, Bitbucket, AWS, Docker, Kubernetes, etc. The main plus point that differentiates me from other average developers is that I take a personal interest in projects that are under my responsibility. I thrive in a fun and challenging environment and can motivate teams to develop innovative solutions at the highest level of excellence. Let's build your product: [email protected] +923352000110

Updated on December 17, 2022

Comments

  • Haroon Ashraf Awan
    Haroon Ashraf Awan over 1 year

    I have my model as follows:

    class Abc extends Model {
      int playful;
    
      Abc({this.playful}) : super(id);
    
      Abc.fromJson(Map<String, dynamic> json) : this(playful: json['playful']);
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['playful'] = this.playful;
        return data;
      }
    }
    

    I am getting integer value playful (it is either 1 or 0) from json but I want to use it as a boolean in my app (receive as bool in app but send as int in database). How do I achieve it?

  • Haroon Ashraf Awan
    Haroon Ashraf Awan over 4 years
    Worked like a charm! Perfectly described. :) Thank you.