📜  Flutter:删除项目不会反映在 UI 上 - 无论代码示例

📅  最后修改于: 2022-03-11 14:58:52.782000             🧑  作者: Mango

代码示例1
class MyList extends StatefulWidget {
  @override
  _MyListState createState() => _MyListState();
}

class _MyListState extends State {
  List list = List.generate(100, (i) => i.toString());

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: list.length,
      itemBuilder: (context, index) {
        return MyItem(list[index], onDelete: () => removeItem(index));
      },
    );
  }

  void removeItem(int index) {
    setState(() {
      list = List.from(list)
        ..removeAt(index);
    });
  }
}

class MyItem extends StatelessWidget {
  final String title;
  final VoidCallback onDelete;

  MyItem(this.title, {this.onDelete});

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text(this.title),
      onTap: this.onDelete,
    );
  }
}