Home > Enterprise >  access array of object data in flutter
access array of object data in flutter

Time:08-25

I am getting an array of object from my rest API and try to access in flutter but I can not access.I want to access posts,comments,like and status.

The error code is The getter 'data' isn't defined for the type 'List'. 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 and error is given by line snapshot.data!.data[index].posts[postPosition].url and snapshot.data!.data[index].status The data from API:

[
    {
        "_id": "6304e73ecdc5d350cc33e902",
        "userId": "6304e42231ef2e7a4dec924d",
        "posts": [
            {
                "postType": "image",
                "post": "https://www.theskinnybeep.com/wp-content/uploads/2019/01/Versace-Man-2019.jpg",
                "_id": "6304e73ecdc5d350cc33e903"
            },
            {
                "postType": "image",
                "post": "https://www.theskinnybeep.com/wp-content/uploads/2019/01/Versace-Man-2019.jpg",
                "_id": "6304e73ecdc5d350cc33e904"
            }
        ],
        "status": "testing status",
        "comments": [
            {
                "commentText": "Testing comment",
                "commentAt": "2022-08-23T14:41:55.646Z",
                "commentReplys": [
                    {
                        "userId": "6304e02d481e08d44e618d41",
                        "replyText": "Testing comment",
                        "replyAt": "2022-08-23T14:41:55.646Z",
                        "replyLikes": [
                            {
                                "userId": "6304e02d481e08d44e618d41",
                                "_id": "6304e73ecdc5d350cc33e907",
                                "isNotified": true
                            },
                            {
                                "userId": "6304e42231ef2e7a4dec924d",
                                "isNotified": true,
                                "_id": "6305f8d07d513ce62b9c099f"
                            }
                        ],
                        "_id": "6304e73ecdc5d350cc33e906"
                    },
                    {
                        "userId": "6304e02d481e08d44e618d41",
                        "replyText": "reply text testing",
                        "replyAt": "2022-08-23T15:57:51.259Z",
                        "_id": "6304f90191c32e0deac663b8",
                        "replyLikes": [
                            {
                                "userId": "6304e42231ef2e7a4dec924d",
                                "isNotified": true,
                                "_id": "6305f8d07d513ce62b9c099f"
                            }
                        ]
                    }
                ],
                "commentLikes": [
                    {
                        "userId": "6304e42231ef2e7a4dec924d",
                        "isNotified": true,
                        "_id": "6305f8f67d513ce62b9c09a2"
                    }
                ],
                "commentId": "bc174de0-22f1-11ed-9c5d-23d89a83ff32",
                "_id": "6304e73ecdc5d350cc33e905"
            },
            {
                "commentText": "Testing comment",
                "commentAt": "2022-08-23T15:02:11.123Z",
                "commentId": "90928740-22f4-11ed-b912-e99836187b6d",
                "_id": "6304ec67825b5926f0f074cf",
                "commentReplys": [
                    {
                        "userId": "6304e02d481e08d44e618d41",
                        "replyText": "reply text testing",
                        "replyAt": "2022-08-23T15:57:51.259Z",
                        "_id": "6304f90191c32e0deac663b8",
                        "replyLikes": [
                            {
                                "userId": "6304e42231ef2e7a4dec924d",
                                "isNotified": true,
                                "_id": "6305f8d07d513ce62b9c099f"
                            }
                        ]
                    }
                ],
                "commentLikes": [
                    {
                        "userId": "6304e42231ef2e7a4dec924d",
                        "isNotified": true,
                        "_id": "6305f8f67d513ce62b9c09a2"
                    }
                ]
            },
            {
                "commentText": "Testing comment",
                "commentAt": "2022-08-23T15:02:11.123Z",
                "commentId": "90928740-22f4-11ed-b912-e99836187b6d",
                "_id": "6304ec81825b5926f0f074d1",
                "commentReplys": [
                    {
                        "userId": "6304e02d481e08d44e618d41",
                        "replyText": "reply text testing",
                        "replyAt": "2022-08-23T15:57:51.259Z",
                        "_id": "6304f90191c32e0deac663b8",
                        "replyLikes": [
                            {
                                "userId": "6304e42231ef2e7a4dec924d",
                                "isNotified": true,
                                "_id": "6305f8d07d513ce62b9c099f"
                            }
                        ]
                    }
                ],
                "commentLikes": [
                    {
                        "userId": "6304e42231ef2e7a4dec924d",
                        "isNotified": true,
                        "_id": "6305f8f67d513ce62b9c09a2"
                    }
                ]
            }
        ],
        "likes": [
            {
                "userId": "6304e42231ef2e7a4dec924d",
                "_id": "63052dc7a1728d463769681b"
            }
        ],
        "__v": 0
    },
    {
        "_id": "63070a03584ed0febe5b5a5f",
        "status": "testing",
        "posts": [],
        "comments": [],
        "likes": []
    }
]

Flutter code:

Widget build(BuildContext context) {
    return SizedBox(
      height: 600,
      child: FutureBuilder<List<Posts>>(
        future: fetchPost(),
        builder: ((context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
                scrollDirection: Axis.vertical,
                shrinkWrap: true,
                itemCount: snapshot.data!.length,
                itemBuilder: (context, index) {
                  return ListView.builder(
                     scrollDirection: Axis.vertical,
                      shrinkWrap: true, 
                      itemCount: snapshot.data!.data[index].posts!.length,
                      itemBuilder: (context, postPosition) {
                       return Column(
                      children: [
                        Text(snapshot.data!.data[index].status),
                        ListView.builder(itemCount:snapshot.data!.data[index].posts.length,itemBuilder: (context, postPosition) {
                          return Column(children: [
                            Image.network(snapshot.data!.data[index].posts[postPosition].url)
                          ],);
                      })
                      ],

                       );
                      }
                }
                );
          } else
            return CircularProgressIndicator();
        }),
      ),
    );
}

The Posts class:

List<Posts> postsFromJson(String str) => List<Posts>.from(json.decode(str).map((x) => Posts.fromJson(x)));

String postsToJson(List<Posts> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Posts {
    Posts({
         this.id,
         this.userId,
        required this.posts,
         this.status,
        this.comments,
         this.likes,
    });

    String? id;
    String? userId;
    List<Post> posts;
    String? status;
    List<Comment>? comments;
    List<Like>? likes;
    factory Posts.fromJson(Map<String, dynamic> json) => Posts(
        id: json["_id"],
        userId: json["userId"],
        posts:  List<Post>.from(json["posts"].map((x) => Post.fromJson(x))),
        status: json["status"],
        comments: List<Comment>.from(json["comments"].map((x) => Comment.fromJson(x))),
        likes: List<Like>.from(json["likes"].map((x) => Like.fromJson(x))),
    );

  get length => null;

  get data => null;

    Map<String, dynamic> toJson() => {
        "_id": id,
        "userId": userId,
        "posts": List<dynamic>.from(posts.map((x) => x.toJson())),
        "status": status,
        "comments": List<dynamic>.from(comments!.map((x) => x.toJson())),
        "likes": List<dynamic>.from(likes!.map((x) => x.toJson())),
    };
}

CodePudding user response:

I am not sure how your IDE lets you compile the code while you added type in FutureBuilder. The problem seems here. After snapshot.data you should not add another data variable. snapshot.data!.data should not be added.

                      itemCount: snapshot.data![index].posts!.length,
                      itemBuilder: (context, postPosition) {
                       return Column(
                      children: [
                        Text(snapshot.data![index].status),
                        ListView.builder(itemCount:snapshot.data![index].posts.length,itemBuilder: (context, postPosition) {
                          return Column(children: [
                            Image.network(snapshot.data![index].posts[postPosition].url)
                          ],);

CodePudding user response:

from your api response and you named it as "class:Post" it not a list. but Post.post is a list. Try to delete the list just like this, and print the result. you may have other error when casting it to your widget because the code will be a bit different. you can ask more if you face other difficulties

example:

PostModel postModelFromJson(String str) =>
    postModel.fromJson(json.decode(str));

String postModelToJson(PostModel data) =>
    json.encode(data.toJson());
  • Related