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

470

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];
      },
    )
Share:
470
Arijeet
Author by

Arijeet

Updated on December 31, 2022

Comments

  • Arijeet
    Arijeet over 1 year

    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 ?

    • Dinesh Nagarajan
      Dinesh Nagarajan almost 3 years
      You need to check about ‘listsview’ state full widget and set state.
  • Arijeet
    Arijeet almost 3 years
    Thanks it worked. Any idea regarding how can we remove the cards that we want ?
  • Hemal Moradiya
    Hemal Moradiya almost 3 years
    just use remove method of array like this ` _cards.removeAt(index)`
  • Arijeet
    Arijeet almost 3 years
    I got your idea but here the problem is that the card widget is defined outside the class. So, setState() can't be used. I had given a cancel icon at the right of the card but i can't use the cardList because it is not defined here. Any suggestions ?
  • Hemal Moradiya
    Hemal Moradiya almost 3 years
    You have index of every item in list view, just store whatever index you want to remove in separate variable and use this index in removeAt parameter.