如何在构建器外部调用列表视图的索引?

问题描述 投票:0回答:1

我正在为listview.builder之外的.removeAt分配一个图标,我认为问题在于调用索引,如何在listview构建器之外调用索引?请帮助,这是我的代码示例:

    newList(){
    return new ListView.builder(
              physics: ClampingScrollPhysics(),
              shrinkWrap: true,
              scrollDirection: Axis.horizontal,
              itemCount: newRoutineList.length,
              itemBuilder: (context, index) {
                return newRoutineList[index];
              });
  }

enter image description here

这是listview.builder之外的函数,我在其中为.removeAt创建一个图标

new Container(
                              width: 70,
                              alignment: Alignment(0.5, 1),
                              child: IconButton(
                                icon: Icon(Icons.clear),
                                color: Colors.redAccent,
                                onPressed: () {
                                  newRoutineList.removeAt(index);
                                },
                              ),
                            )

enter image description here

listview flutter indexing builder
1个回答
0
投票

您可以执行此操作。如果还可以使用Map代替List

List newRoutineList = new List();
@override
void initState() {
 super.initState();
 newRoutineList.add("A");
 newRoutineList.add("B");
 newRoutineList.add("C");
 newRoutineList.add("D");
 newRoutineList.add("E");
}

Widget newList() {
 return new ListView.builder(
    physics: ClampingScrollPhysics(),
    shrinkWrap: true,
    scrollDirection: Axis.horizontal,
    itemCount: newRoutineList.length,
    itemBuilder: (context, index) {
      return Container(
        width: 70,
        alignment: Alignment(0.5, 1),
        child: IconButton(
          icon: Icon(Icons.clear),
          color: Colors.redAccent,
          onPressed: () {
            setState(() {
              newRoutineList.removeAt(index);
            });
          },
        ),
      );
    });
}

@override
Widget build(BuildContext context) {
  return Scaffold(
      appBar: AppBar(
        title: Text("Test"),
      ),
      body: newList());
}
© www.soinside.com 2019 - 2024. All rights reserved.