-1

App screenshot 查看屏幕截图上的删除图标按钮。我想获取单击按钮的索引以删除列表视图的选定项目。我应该怎么办?谢谢您的帮助!

4

1 回答 1

1

在这个例子中,我展示了如何轻松地做到这一点,创建一个包含项目名称的列表和一个返回小部件的函数:

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final List<String> items = ['item1', 'item2', 'item3'];  //creating a list of the title of the items

  Widget itemWidget({String text, VoidCallback onPressed}) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(                            //widget that will be called on the ListView
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          Icon(Icons.account_circle, size: 50,),
          Text(text, style: TextStyle(fontSize: 20),),   //receiving the text
          IconButton(
            icon: Icon(Icons.delete),
            onPressed: onPressed,    //receiving the function
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return itemWidget(
            text: items[index],
            onPressed: () {
              setState(() {
                items.removeAt(index);          //remove the item at the current index
              });
            },
          );
        },
      ),
    );
  }
} 

用户界面:

在此处输入图像描述

于 2020-04-05T19:29:49.193 回答