I have a ListView and i would like to add a new Text Widget every Time i pressed a Button. The User should be able to insert the String inside the Text Widget when the Button is pressed. Is there any way to do this?
ListView(children: [
//New Widget here evertime the Button is pressed
]),
ElevatedButton(onPressed: ()
{
//Add New Item when this is pressed
}
, child: Text("Add Item"))
CodePudding user response:
Instead of ListView
you should use a ListView.builder
, and a List<Widget>
variable _strings
where all the new strings stored. An example code below:
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<Widget> _strings = [];
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
body: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: _strings.length,
itemBuilder: (context, index) => _strings[index],
),
),
ElevatedButton(
onPressed: () {
setState(
() {
_strings.add(
Text('new text added'),
);
},
);
},
child: Text('Add String'),
)
],
),
),
);
}
}
CodePudding user response:
Use a ListViewBuilder
instead with a StatefulWidget
and I'd suggest using a FloatingActionButton
in the Scaffold Widget.
class MyApp extends StatefulWidget {
const MyApp();
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List<String> list = [];
_onPressed(String val) {
setState((){
list.add(val);
});
_listViewBuilder() {
return ListView.builder(
itemCount: list.length,
itemBuilder: (context, index) {
return Text(list[index]);
});
}
@override
Widget build(BuildContext context){
Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _listViewBuilder(),
floatingActionButton: FloatingActionButton(
onPressed: (){
_onPressed("Text To Add");
},
tooltip: 'add',
child: const Icon(Icons.add),
),
);
}
}