Home > front end >  How to return an array when an object comes from the server?
How to return an array when an object comes from the server?

Time:09-11

I am using this structure - return (details['home_store'] as List).map((e) => DetailsModel.fromJson(e)).toList(); When I receive data from the server in this format -

{
   "homestore": [
     {
       "id": 1,
     },
   ]
}

And what should I do when the data comes in this format?

{
       "id": 1,
     },

CodePudding user response:

Try this

DetailsModel.fromJson(details)

Or if you have several elements

class DetailsModel {
  final String id;
  final String name;
  final String age;

  DetailsModel({
    required this.id,
    required this.name,
    required this.age,
  });

  factory DetailsModel.fromJson(Map<String, dynamic> details) {
    return DetailsModel(
      id: details['id'],
      name: details['name'],
      age: details['age'],
    );
  }
}

Just edit your Model class. You can add more fields to it.

  • Related