How to get value and list from Future with custom model in flutter

386

firstly use https://javiercbk.github.io/json_to_dart/ to create your data model from your json data


Here is UserData class:

class UserData {
    String? userName;
    String? userFName;
    String? compType;
    String? compDepr;
    String? compCode;
    String? deprJob;
    String? compCodeSub;
    String? private1;
    String? private2;
    String? createUser;
    String? updateUser;
    String? createdAt;
    String? updatedAt;
    int? id;

    UserData(
        {this.userName,
        this.userFName,
        this.compType,
        this.compDepr,
        this.compCode,
        this.deprJob,
        this.compCodeSub,
        this.private1,
        this.private2,
        this.createUser,
        this.updateUser,
        this.createdAt,
        this.updatedAt,
        this.id});

    UserData.fromJson(Map<String, dynamic> json) {
      userName = json['user_name'];
      userFName = json['user_f_name'];
      compType = json['comp_type'];
      compDepr = json['comp_depr'];
      compCode = json['comp_code'];
      deprJob = json['depr_job'];
      compCodeSub = json['comp_code_sub'];
      private1 = json['private_1'];
      private2 = json['private_2'];
      createUser = json['create_user'];
      updateUser = json['update_user'];
      createdAt = json['created_at'];
      updatedAt = json['updated_at'];
      id = json['id'];
    }

    Map<String, dynamic> toJson() {
      final Map<String, dynamic> data = new Map<String, dynamic>();
      data['user_name'] = userName;
      data['user_f_name'] = userFName;
      data['comp_type'] = compType;
      data['comp_depr'] = compDepr;
      data['comp_code'] = compCode;
      data['depr_job'] = deprJob;
      data['comp_code_sub'] = compCodeSub;
      data['private_1'] = private1;
      data['private_2'] = private2;
      data['create_user'] = createUser;
      data['update_user'] = updateUser;
      data['created_at'] = createdAt;
      data['updated_at'] = updatedAt;
      data['id'] = id;
      return data;
    }
}


Then you can get your data from your server and transform it to your data model:

Future<List<UserData>> getUserData() async {
  const token = 'your_token';

  const myUrl = "your_url";

  http.Response response = await http.get(Uri.parse(myUrl), headers: {
    'Accept': 'application/json',
    'Authorization': 'Bearer $token'
  });

  // here you get your response data as Map
  final Map<String, dynamic> responseData = json.decode(response.body);
  // here you convert your data list to UserData list
  final userDataList = (responseData['data'] as List)
      .map((e) => UserData.fromJson(e))
      .toList();

  for (final element in userDataList) {
    // if you need comp_type you can get it from your model
    print(element.compType);
  }

  return userDataList;
}
Share:
386
murat murat
Author by

murat murat

Updated on January 01, 2023

Comments

  • murat murat
    murat murat about 1 year

    I am calling an API to get data from server and i try make a dart file (model). after get in a field value and all data show list. but i cannot found how to make. i was try many options but always take a syntax error or diffrent errors. my getdata work i can print console but can't take in value. have a easy way?

    my json;

    {
        "success": true,
        "message": "User List",
        "data": [
            {
                "user_name": "user1",
                "user_f_name": "User",
                "comp_type": "AGN",
                "comp_depr": "SALES",
                "comp_code": "AHN0001",
                "depr_job": "",
                "comp_code_sub": "",
                "private_1": "",
                "private_2": "",
                "create_user": "",
                "update_user": "",
                "created_at": 2021-09-06T21:01:01.000000Z,
                "updated_at": "2021-09-06T21:01:01.000000Z",
                "id": 0
            },
            {
                "user_name": "user2",
                "user_f_name": "",
                "comp_type": "",
                "comp_depr": "",
                "comp_code": "",
                "depr_job": "",
                "comp_code_sub": "",
                "private_1": "",
                "private_2": "",
                "create_user": "",
                "update_user": "",
                "created_at": "2021-09-06T20:49:45.000000Z",
                "updated_at": "2021-09-06T20:49:45.000000Z",
                "id": 0
            }
        ]
    }
    

    my code try one data;

     Future<Map<String, dynamic>> getData3() async {
        final prefs = await SharedPreferences.getInstance();
        final key = 'token';
        final value = prefs.get(key) ?? 0;
        final prefsu = await SharedPreferences.getInstance();
        final keyu = 'user';
        final valueu = prefsu.get(keyu) ?? 0;
        var username = "$valueu";
       
    
        String myUrl =
            String myUrl = "$serverUrl/userchecks/$username";
        http.Response response = await http.get(Uri.parse(myUrl), headers: {
          'Accept': 'application/json',
          'Authorization': 'Bearer $value'
        });
       
        var data1 = json.decode(response.body);    
        print('Response status : ${response.statusCode}');
        print(json.decode(response.body));
        print(data1['user_f_name']);
          
        return (json.decode(response.body));
      }
    

    my code try list data

    Future<Map<String, dynamic>> getData() async {
        final prefs = await SharedPreferences.getInstance();
        final key = 'token';
        final value = prefs.get(key) ?? 0;
    
        String myUrl = "$serverUrl/userchecks";
        http.Response response = await http.get(Uri.parse(myUrl), headers: {
          'Accept': 'application/json',
          'Authorization': 'Bearer $value'
        });
    
        print('Response status : ${response.statusCode}');
        print(json.decode(response.body));
        final data1 = json.decode(response.body);
        print(data1['user_f_name']);
    
        return json.decode(response.body);
      }
    
    • Spike L
      Spike L over 2 years
      Please append your error message if possible.
    • murat murat
      murat murat over 2 years
      for example last error message if try call a model and call give message return Userdprcheck.fromJson(response.data); "The getter 'data' isn't defined for the type 'Response'. Try importing the library that defines 'data', correcting the name to the name of an existing getter, or defining a getter or field named 'data'." if change code return Userdprcheck.fromJson(response.body); give error " The argument type 'String' can't be assigned to the parameter type 'Map<String, dynamic>'."
    • Yeasin Sheikh
      Yeasin Sheikh over 2 years
      on json.decode(response.body) use json.decode(response.body)['data']. Can you include your data mode. Then it would be easy to test
    • murat murat
      murat murat over 2 years
      i take same error again. Future<Userdprcheck> getData3() async { final prefs = await SharedPreferences.getInstance(); final key = 'token'; final value = prefs.get(key) ?? 0; return Userdprcheck.fromJson(response.body)['data']; } The argument type 'String' can't be assigned to the parameter type 'Map<String, dynamic>'.
    • murat murat
      murat murat over 2 years
      my example model : class Userdprcheck { String compType = 'cc'; Userdprcheck({required this.compType}); Userdprcheck.fromJson(Map<String, dynamic> json) { compType = json['comp_type']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['comp_type'] = this.compType; return data; }}