Home > Mobile >  For loop is looping only once for object in flutter
For loop is looping only once for object in flutter

Time:08-27

I have two object of a class and I use for loop to display the data of object.The loop is looping only once though I have two object.

The code:

 Widget build(BuildContext context) {
    return FutureBuilder<List<Posts>>(
        future: fetchPost(),
        builder: ((context, snapshot) {
          if (snapshot.hasData) {
            // return ListView.builder(itemCount: snapshot.data!.length,itemBuilder: (context,index){
            for (int i = 0; i < snapshot.data!.length; i  ) {
              print(i);
              DateTime date=snapshot.data![i].postAt;
              final difference = DateTime.now().subtract(Duration(hours:snapshot.data![i].postAt.hour));
              return Container(
                  child: Column(
                children: [
                  Row(
                    children: [
                      IconButton(
                          iconSize: 50,
                          onPressed: () {},
                          icon: CircleAvatar(
                            radius: 80,
                            backgroundImage: NetworkImage(snapshot.data![i].user[0].profile),
                          )
                      )
                    ]
                  )
                ]
                  )
              );}
          }

How to fix this.Thanks in advance.

CodePudding user response:

If you are using for loop to return if is not a correct way.

When your runs then it returns the container, return means return from loop ,retrun from function so return without for loop with ListView.builder

CodePudding user response:

Use map instead of for loop.

snapshot.data!.map((e) {
    DateTime date = e.postAt;
    final difference = DateTime.now().subtract(Duration(hours: e.postAt.hour));
    return Container(
        child: Column(
            children: [
              Row(
                children: [
                  IconButton(
                      iconSize: 50,
                      onPressed: () {},
                      icon: CircleAvatar(
                        radius: 80,
                        backgroundImage: NetworkImage(snapshot.data![i].user[0].profile),
                      )
                  )
                ]
              )
            ]
        )
   );
});
  • Related