Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter add Items to ListView

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"))
like image 488
blurryface Avatar asked Jul 06 '26 11:07

blurryface


1 Answers

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'),
            )
          ],
        ),
      ),
    );
  }
}
like image 83
esentis Avatar answered Jul 08 '26 02:07

esentis