Arijeet
Arijeet

Reputation: 1223

How to add a card widget dynamically whenever floating action button is clicked in flutter?

I am very new to flutter and was just curious to know how can we create a new card widget everytime a button (lets say FAB) is clicked.

Suppose this is the card widget :

return Card(
 child: Column(
  children: [
  Text('name'),
  Text('standard'),
  Text('Roll No'),
    ],
   ),
 );

I want the cards to build with the same content everytime the FAB is clicked. Can someone help me with this ?

Upvotes: 2

Views: 1697

Answers (1)

Hemal Moradiya
Hemal Moradiya

Reputation: 2097

First declare a List of widget type

List<Widget> _cardList = [];

Then create your widget which you want to add on button click, e.g.

  Widget _card() {
    return Card(
      child: Column(
        children: [
          Text('name'),
          Text('standard'),
          Text('Roll No'),
        ],
      ),
    );
  }

add your widget in List on button click

FloatingActionButton(
            child: Icon(Icons.add),
            onPressed: () {
              setState(() {
                _cardList.add(_card());
              });
            },
          ),

Now use a ListView.builder for create a list of widget

 ListView.builder(
      shrinkWrap: true,
      itemCount: _cardList.length,
      itemBuilder: (context, index) {
        return _cardList[index];
      },
    )

Upvotes: 3

Related Questions