Function call using for-loop in flutter

166

Solution 1

Container(
    child: GridView.count(
      crossAxisCount: cardList.length,
      children: cardList.map((item) {
        return cards(item["img"],item["icon"], item["name"]);
      }).toList();,
),),

Solution 2

The vertical viewport was given unbounded height error because shrinkWrap and ScrollPhysics both are missing.

Container(
                child: GridView.count(
                  shrinkWrap: true,
                  physics: ScrollPhysics(),
                  crossAxisCount: cardList.length,
                  children: cardList.map((item) {
                    return cards(item["img"],item["icon"], item["name"]);
                  }).toList();,
                ),)
Share:
166
yamini r
Author by

yamini r

Updated on December 31, 2022

Comments

  • yamini r
    yamini r over 1 year

    I have a function written and want to call it using for-loop so that it is dynamic. The following code is for the function:

     var cardList = [
        {"img" : "assets/1.png", "icon" :"assets/icon1.png", "name" : "card1"},
        {"img" : "assets/2.png", "icon" :"assets/icon2.png", "name" : "card2"},
        {"img" : "assets/3.png", "icon" :"assets/icon3.png", "name" : "card3"},
        {"img" : "assets/4.png", "icon" :"assets/icon4.png", "name" : "card4"},
      ];
      Widget cards(img, icon, name){
        return Container(
          child: GestureDetector(
            onTap: () {},
            child: Card(
              elevation: 5.0,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
              child: Stack(
                children: [
                  Image(image: AssetImage(img)),
                  Row(
                    children: [
                    Padding(padding: EdgeInsets.only(top: 3.0)),
                    Image(image: AssetImage(icon),),
                    Container(
                      child: Text(
                        name,
                      ),
                    ),
                    ],
                  ),
                ],
              )
            )
          ),
        );
      }
    

    Now to call it in the main code, I have:

    Container(
                    child: GridView.count(
                      crossAxisCount: 2,
                      children: [
                        for(var i in cardList)
                        cards(...)//not sure how to call this
                      ],
                      ),
                  ),
    
  • yamini r
    yamini r over 2 years
    I tried it, but there was an error Vertical viewport was given unbounded height. I have given height and width to the very first container next to return, yet not working.
  • 宋永涛
    宋永涛 over 2 years
    @yaminir Container set height: double.infinity
  • yamini r
    yamini r over 2 years
    For which Container should I set this height?