Home > Software design >  How to get data from api in flutter where response is inside of list?
How to get data from api in flutter where response is inside of list?

Time:11-02

The below given code in my response which I need to display in Listview builder, now I need the data of name which in inside result, how do i fetch it and display it in text?

{
        "message": "sucess",
        "error": false,
        "code": 200,
        "result": [
            {
                "id": 1,
                "name": "Lab Report"
            },
            {
                "id": 2,
                "name": "News"
            },
            {
                "id": 3,
                "name": "X-ray"
            },
            {
                "id": 8,
                "name": "Blood Test"
            }
        ],
        "status": 200
    }

And below is my model class of the response now I want the data which is inside of result and need to display in Listview builder

import 'dart:convert';

PostFromJson postFromJsonFromJson(String str) => PostFromJson.fromJson(json.decode(str));

String postFromJsonToJson(PostFromJson data) => json.encode(data.toJson());

class PostFromJson {
  PostFromJson({
    this.message,
    this.error,
    this.code,
    required this.result,
    this.status,
  });

  String? message;
  bool? error;
  int? code;
  List<Result> result;
  int? status;

  factory PostFromJson.fromJson(Map<String, dynamic> json) => PostFromJson(
    message: json["message"],
    error: json["error"],
    code: json["code"],
    result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
    status: json["status"],
  );

  Map<String, dynamic> toJson() => {
    "message": message,
    "error": error,
    "code": code,
    "result": List<dynamic>.from(result.map((x) => x.toJson())),
    "status": status,
  };
}

class Result {
  Result({
     this.id,
    this.name,
  });

  int? id;
  String? name;

  factory Result.fromJson(Map<String, dynamic> json) => Result(
    id: json["id"],
    name: json["name"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
  };
}

CodePudding user response:

final name = data['result'][0].name;

final id = data['result'][0].id;

CodePudding user response:

There are a lot of resources available online on how to fetching data, parsing, modeling, and showing in the UI (from API).

Here's one official doc from Flutter: https://docs.flutter.dev/cookbook/networking/fetch-data

EDIT (after adding the model):

final response = await http.get("url");
final post = postFromJsonFromJson(response);

//Use list with ListView.builder(...)
final results = post.result; //List<Result>

CodePudding user response:

Use this model

class Response{
  final String message;
  final bool error;
  final int code;
  final List<Result> result;
  final int status;
  const Response({required this.message,required this.error, required this.code,required this.result,required this.status});

  factory Response.fromJson(Map<String, dynamic> json) {
    List<Result> data = [];
    data = json["result"]
        .map<Result>((json) => Result.fromJson(json))
        .toList();

    return Response(
        message:json['message'],
        error: json['error'],
        code: json['code'],
      result: data,
      status: json['status']
    );
  }
}

class Result{
  final int id;
  final String name;

  const Result({ required this.id,required this.name});

  factory Result.fromJson(Map<String, dynamic> json) {
    return Result(
        id: json['code'],
      name:json['name'],
    );
  }
}

and declare a variable

 Response? responseData;

set the api response in the responseData as Response

 responseData = Response.fromJson(jsonDecode(response.body));

You can access the name inside the result like this,

  responseData.result[index].name

Listview builder will be

return Container(
  child: Column(
    children: [
      ListView.builder(
        shrinkWrap: true,
        itemCount: responseData?.result.length,
          itemBuilder: (context,index) =>options(context,index)
      )
    ],
  ),
);


 Widget options(BuildContext context, int index){
  return Text(responseData.result[index].name);
 }

CodePudding user response:

You must be getting the data from model you created, you can use your model like this

class MyWidget extends StatelessWidget {
  

  PostFromJson data;
  
  MyWidget(this.data);
  
  
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
          itemCount: data.result.length,
          itemBuilder: (BuildContext context, int index) {
            return ListTile(
                leading: const Icon(Icons.list),
               
                title: Text(data.result[index].id.toString()));
          });
    
  }
}
  • Related