Home > Blockchain >  How to make api class where api response start with array?
How to make api class where api response start with array?

Time:11-29

How to make api class where api response start with array ? Api Response :-

             [
               {
                 "reqList": [
                              {
                                "_id": "123448478478",
                                "username": "12345",
                                "amount": 4100
                              },
                            ],
                  "_id": "636e2c5cf0142eed68343335",
                  "username": "umesh-rajput",
                  "amount": 95
                 }
              ]

CodePudding user response:

Future<List<MODEL NAME>> getAllBetNotification() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var token = prefs.getString('userToken');
url = 'API URL';
var response = await http.get(Uri.parse(url), headers: {
'Authorization': 'YOUR TOKEN',
  });
 if (response.statusCode == 200 || response.statusCode == 201) {
 // print(response.body);
 var list1 = (jsonDecode(response.body) as List)
    .map((dynamic i) =>
        UserNotificationModel.fromJson(i as Map<String, dynamic>))
    .toList();
 return list1;
  } else {
   print('do not send notification');
   return [];
       } 
  }

CodePudding user response:

Future<List<MODEL NAME>> getAllBetNotification() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var token = prefs.getString('userToken');
url = 'API URL';
var response = await http.get(Uri.parse(url), headers: {
'Authorization': 'YOUR TOKEN',
});
if (response.statusCode == 200 || response.statusCode == 201) {
// print(response.body);
var list1 = (jsonDecode(response.body) as List)
.map((dynamic i) =>
    UserNotificationModel.fromJson(i as Map<String, dynamic>))
.toList();
return list1;
} else {
print('do not send notification');
return [];
   } 
}

CodePudding user response:

We can handle this response as a list of individual JSON objects inside the response array.

This is general Pseudo code.

class DataProvider{
   List<YourModel> getDate(String URL) async {
   var response = await http.get(url);
   if(resonse.statuscode == 200)
   {
    var List<YourModel> modelList = 
          response.body.map((jsonObject)=>YourModel.toJson(jsonObject);
   );
    return modelList;
   }
    return [];
  }
}
  • Related