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"))
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'),
)
],
),
),
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With