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];
},
)
Author by
Arijeet
Updated on December 31, 2022Comments
-
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 almost 3 yearsYou need to check about ‘listsview’ state full widget and set state.
-
-
Arijeet almost 3 yearsThanks it worked. Any idea regarding how can we remove the cards that we want ?
-
Hemal Moradiya almost 3 yearsjust use remove method of array like this ` _cards.removeAt(index)`
-
Arijeet almost 3 yearsI 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 almost 3 yearsYou 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.