EngineSense
EngineSense

Reputation: 3646

Convert to type class dart http response body

I just want to convert the response.body to class file named as Collection.

The response from http.post on flutter would result the below code from server

{"collection":{
   "data": "{\"id\": 1, 
           \"name\": \"Puspharaj\",
           \"picture\": \"https://lh3.googleusercontent.com/a-/AAuE7mC1vqaKk_Eylt- 
           fcKgJxuN96yQ72dBViK959TKsHQ=s96-c\"}",
   "statusCode": 202,
   "version": "1.0"}
}

The collection file in flutter has this code:

import 'dart:core';

class Collection {
var version = String;
/**
 * @return the data
 */
/**
 * @param data the data to set
 */
 var data = dynamic;
/**
 * @return the error
 */
/**
 * @param error the error to set
 */
var error = String;
var statusCode = int;
var isBooleanStatus = bool;
}

When i tried to convert it says

A value of type 'String' can't be assigned to a variable of type 'Type'. Try changing the type of the variable, or casting the right-hand type to 'Type'

So the end result should be like this:

Collection{
version : 1.0
data : "{\"id\": 1, 
           \"name\": \"Puspharaj\",
           \"picture\": \"https://lh3.googleusercontent.com/a-/AAuE7mC1vqaKk_Eylt- 
           fcKgJxuN96yQ72dBViK959TKsHQ=s96-c\"}"
statusCode : 202
}

So i can extract the only data i wanted. Like data only or the statuscode . So how do convert the response body code to the flutter code?. Please any help appreciated.

Upvotes: 0

Views: 663

Answers (2)

xion
xion

Reputation: 1369

if your data is with known columns, you should create another class for itself like below; else Darish's answer is more appropriate

class Collection {
  Data data;
  String statusCode;
  String version;

  Collection(this.data, this.statusCode, this.version);
}

class Data {
  String id;
  String name;
  String picture;

  Data(this.id, this.name, this.picture);
}

Upvotes: 0

Darish
Darish

Reputation: 11501

Try this

class Collection {
String version;
/**
 * @return the data
 */
/**
 * @param data the data to set
 */
 Map<String, dynamic> data;
/**
 * @return the error
 */
/**
 * @param error the error to set
 */
String error;
int statusCode;
bool isBooleanStatus;
}

Upvotes: 0

Related Questions