Home > Software design >  How can a ListView child remove itself from the list if it has it's own class?
How can a ListView child remove itself from the list if it has it's own class?

Time:09-04

Newbie flutter design question.

I have a ListView and I'd like to create a class for the child widgets since they are fairly complex. But each child widget includes a 'delete' control, and so I need a way for a child to tell the parent ListView the child wants to delete itself. Having the child call setState on the parent via a callback feels wrong... Not sure how to do this nicely. Thanks!

CodePudding user response:

Try this:

class ListWidget extends StatefulWidget {
  const ListWidget({Key? key}) : super(key: key);

  @override
  State<ListWidget> createState() => _ListWidgetState();
}

class _ListWidgetState extends State<ListWidget> {
  List _list = [1, 2, 3, 4, 5, 6];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemBuilder: (context, index) {
          return _buildItem(
              onClick: () {
                setState(() {
                  _list.removeAt(index);
                });
              },
              title: _list[index].toString());
        },
        itemCount: _list.length,
      ),
    );
  }

  _buildItem({required Function() onClick, required String title}) {
    return Container(
      child: Row(
        children: [
          InkWell(onTap: onClick, child: Icon(Icons.delete)),
          Text('delete $title'),
        ],
      ),
    );
  }
}
  • Related