Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter for loop not being called

Tags:

flutter

dart

I am trying to make a rough clone of Reddit using flutter to help me learn but I'm getting stuck where my for loop isn't being called, in initialisation. The part of my code where it fails is here:

class RedditTable extends StatelessWidget {
  List posts;
  List containers;
  RedditTable(List posts) {
    this.posts = posts;
    this.containers = new List<Container>();

    for (var i = 0; i == posts.length; i++) {
      var post = posts[i]["data"];
      var title = post["title"];
      var container = new Container(
          margin: new EdgeInsets.symmetric(horizontal: 4.0),
          child: new Text(title)
      );
      containers.add(container);
    }
  }

The for loop isn't being called and hence the containers list is not being populated. When I print posts.length just before the loop I get an output of 25 but doing the same thing in the loop returns nothing.

like image 962
Wrumble Avatar asked Dec 22 '25 14:12

Wrumble


1 Answers

Use for (var i = 0; i < posts.length; i++) instead of for (var i = 0; i == posts.length; i++).

As you don't really use i you can use for-in or list transformation:

    for (var post in posts) {
      var title = post["data"]["title"];
      var container = new Container(
        margin: new EdgeInsets.symmetric(horizontal: 4.0),
        child: new Text(title),
      );
      containers.add(container);
    }

    // or 

    containers = posts.map((post) => new Container(
      margin: new EdgeInsets.symmetric(horizontal: 4.0),
      child: new Text(post["data"]["title"]),
    )).toList();
like image 119
Alexandre Ardhuin Avatar answered Dec 24 '25 06:12

Alexandre Ardhuin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!