Search code examples
flutterandroid-widgetflutter-layoutflutter-sliver

Flutter how to do for inside for loop with list widget?


i need to do for inside for loop inside widgets. i create two widgets and i called it form another widget. it says "Not in range 0..6, inclusive:7"

Code :

List<Widget> ListMyClips(i) {
    List<Widget> list = new List();
    var lengthItems = widget.data["recommended"][7]["blocks"][i]["items"].length;
    for (var c = 0; c <= lengthItems; i++) {
        list.add(
            ClipRRect(
                borderRadius: new BorderRadius.circular(100.0),
                child: Image.network(
                    first[widget.data["recommended"][7]["blocks"][i]["items"][c]
                        ["id"]]["image"]["full"],
                    width: 56,
                ),
            ),
        );
    }

    return list;
}

List <Widget> ListMyWidgets() {
    var lengthBlocks = widget.data["recommended"][7]["blocks"].length;
    List <Widget> list = new List();
    for (var i = 0; i <= lengthBlocks; i++) {
        list.add(ListTile(
            trailing: Icon(FontAwesomeIcons.chevronRight),
            title: Row(
                children: ListMyClips(i),
            ),
        ));
    }
    return list;
}

what i need is, dynamically for inside for loop which it will create list of list tiles.


Solution

  • With Dart 2.3 new features, you can use a for inside a collections, to minimize the boilerplate code and make it more legible.

    Before Dart 2.3

    Row(
     children: <Widget>[
       europeanCountries
       .map((country) => Text("New $country"))
       .toList();
      ],
    )
    

    With Dart 2.3

    Row(
     children: <Widget>[
      for (var country in europeanCountries) Text("New ${country.data}")
      ],
    )
    

    Check more features that could help you in here: What's new in Dart 2.3

    PS: Change your functions name to a camelCase form. This way, you should be creating a class instead of a method