Can you parse an int from a sqlite database that was originally a bool, back into a bool after querying the database?

150

You can put a ternary operator on your User.fromJson function. Take a look:

factory User.fromJson(Map<String, dynamic> json) {
    return User(
      success = json['success'] == 1 ? true : false,
      userID = json['UserID'],
      firstName = json['FirstName'],
      lastName = json['LastName'],
      email = json['Email'],
    );
  }

This way if the value is 1 it will set the value to true and if is 0 (or any other value) will set the value to false.

Share:
150
Carter
Author by

Carter

Updated on December 25, 2022

Comments

  • Carter
    Carter over 1 year

    I am currently getting a User from a sqlite database I created where I am going to use the data in a FutueBuilder. Now when I store the User data there is a Bool that gets stored in the sqlite database, since sqlite doesn't support boolean types, this gets turned into an int. When I query the user data table, and then run the data through a function that uses the User object to turn the queried data into a user object, it errors out, since the function expects a Boolean, and not an int. What can I do to get around this?

    This is where I query the user data table, then send the result to the function to get added to my user list

      Future<dynamic> getUser() async {
        List _user =[];
        final db = await database;
        var res = await db.query("user");
        if (res.length == 0) {
          return null;
        }
        else {
          var resMap = res[0];
          return _user.add(User.fromJson(resMap));
        }
      }
    

    This is the user model and the function that will convert the data into a User object for me. This is where it has an issue due to the model expecting a boolean, but the database now passes it an int since it converted the original boolean to an int.

    User userFromJson(String str) => User.fromJson(json.decode(str));
    
    
    class User {
    
      bool success;
    
      String userID;
    
      String firstName;
    
      String lastName;
    
      String email;
    
    
      User({this.success, this.userID, this.firstName, this.lastName, this.email});
    
      factory User.fromJson(Map<String, dynamic> json) {
        return User(
          success: json['success'],
          userID: json['UserID'],
          firstName: json['FirstName'],
          lastName: json['LastName'],
          email: json['Email'],
        );
      }