Issue
I have a listview in a flutter application I am working on, and I want to be able to add extra items to the listview based on when a button is pressed. The button should be below all of the items. I want to add an extra container every time a button is pressed. Ideally, it would be a widget. I am not sure how to do this. Here is my code:
body: ListView(
children: <Widget>[
Container( //this is the container I would like to add another of when a button is pressed
height: 200,
child: optionsChoices(),
), //end container
Container(
height: 200,
child: optionsChoices(),
),
Container(
height: 200,
child: optionsChoices(),
),
Container(
height: 200,
child: optionsChoices(),
),
]
)
Thanks!
Solution
You can use ListView.builder()
to generate the items fro your listview. Store an object or values to a List
type variable and pass it to the listview.
Here’s a complete example source:
import 'package:flutter/material.dart';
class Demo extends StatefulWidget {
@override
_DemoState createState() => _DemoState();
}
class _DemoState extends State<Demo> {
List<int> items = [];
@override
void initState() {
items = List.generate(3, (i) {
// add some dummy items on activity start
return i;
});
super.initState();
}
Widget listViewItem({int index}) {
// widget layout for listview items
return Container(
height: 200,
child:
Text("$index") // just for the demo, you can pass optionsChoices()
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("DEMO"),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, i) {
return listViewItem(index: i); // item layout
},
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
setState(() {
// add another item to the list
items.add(items.length);
});
}));
}
}
Answered By – OMi Shah
Answer Checked By – David Marino (FlutterFixes Volunteer)