In this flutter example we will learn how to add widget dynamically on button click. Here we are using the statefull widget to maintain the adding widget state. We are adding the widgets to List and updating to listview.
Let's get started
Step 1: Create Flutter application
Step 2: Create a statefull widget
Step 3: Take a List of type widget to maintain the dynamic widgets
List<Widget> _cardList = [];
void _addCardWidget() {
setState(() {
_cardList.add(_card());
});
}
|
The _card() method will return the widget with below widget items
Widget _card() {
return Container(
height: 80,
margin: EdgeInsets.only(top: 5,left: 8,right: 8),
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(16),
color:Colors.orangeAccent[100],
),
child: Center(
child: ListTile(
leading: CircleAvatar(
radius : 28 ,
backgroundColor: Colors.white ,
child: CircleAvatar(
radius: 26,
backgroundImage: NetworkImage(
"https://i.pinimg.com/originals/71/83/70/7183704aac01413c86805c19c1586e2b.jpg"),
),
),
title: Text(
"Freedom Fighter",
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700,color: Colors.deepPurple),
),
subtitle: Text(
'Freedom Fighter',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 16,
color: Colors.white),
),
trailing: Card(
elevation: 1,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
width: 50,
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('5',
style: TextStyle(
fontSize: 20, color: Colors.grey)),
SizedBox(
width: 1,
),
Icon(
Icons.access_alarms_outlined,
textDirection: TextDirection.rtl,
size: 20,
color: Colors.grey,
)
],
),
),
|
Step 4: Call this method on button event. Here we are using the FloatingActionButton to add widgets dynamically
FloatingActionButton(
onPressed: _addCardWidget,
tooltip: 'Add',
child: Icon(Icons.add),
),
|
Step 5: Pass the List widgets to listview by Listview.Builder widget
ListView.builder(
itemCount: _cardList.length,
itemBuilder: (context,index){
return _cardList[index];
})
|
Step 6: Let's run the application on physical device or emulator/simulator
Article Contributed By :
|
|
|
|
14254 Views |