Flutter 添加项目到 ListView

Flutter add Items to ListView

我有一个 ListView,我想在每次按下按钮时添加一个新的文本小部件。当按下按钮时,用户应该能够在文本小部件中插入字符串。有什么办法吗?

ListView(children: [
         //New Widget here evertime the Button is pressed
        ]),
ElevatedButton(onPressed: ()
              {
                //Add New Item when this is pressed
              }
              , child: Text("Add Item"))

而不是 ListView 你应该使用 ListView.builder 和一个 List<Widget> 变量 _strings 来存储所有的新字符串。示例代码如下:

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'),
            )
          ],
        ),
      ),
    );
  }
}

使用 ListViewBuilder 而不是 StatefulWidget,我建议在脚手架小部件中使用 FloatingActionButton

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),
      ),
    );
}
}