How can i remove a widget in a ListView in a specific index?

六月ゝ 毕业季﹏ 提交于 2020-12-12 11:57:47

问题


I have been searching for hours , to no vail. I have a ListView that is built with this constructor

ListView.builder( itemCount: 5, itemBuilder: (context, int index) { return ServiceCard(index: index,); }, ),

now in the ServiceCard widget I have a button to delete the current widget in the ListView tree for example the 3rd ServiceCard widget.

Tried many methods that didn't work. I am surprised that even the flutter documentation doesn't show how to implement such a common functionality.

I have tried giving the ListView a variable so that i can access it and remove the desired widget in it. unfortunately there is no such functionality.

I have tried giving the ListView a prepared List of ServiceCard widgets that i then used to use it's length for the itemCounter of the ListView. then removing an item form the List in the setState of the button on the specified ServiceCard widget.

I have tried using a method that takes an index as an argument and returns a ServiceCard only in the case where current index is equal to the index of the removed item. this unfortunately removes the last ServiceCard not the one designated.

here is the ServiceCard widget :

class ServiceCard extends StatefulWidget {
  ServiceCard({this.index});

  int index;


  @override
  _ServiceCardState createState() => _ServiceCardState();
}

class _ServiceCardState extends State<ServiceCard> {
  void onFormSubmitted() {
    var form = formKey.currentState;
    if (form.validate()) {
      form.save();
    }
  }

  @override
  Widget build(BuildContext context) {
    int index = widget.index;

    return Container(
      height: 440,
      child: Column(
        children: <Widget>[
          ExpandableRoundRectangleContainer(
            widgetList: <Widget>[
              Container(
                height: 370,
                child: Stack(
                  alignment: Alignment.bottomLeft,
                  children: <Widget>[
                    //column for tow TextField with headers
                    Column(
                      children: <Widget>[
                        HeaderTextWithFormTextFieldAndSizedBox(
                          headerText: 'Service Name',
                          hintText: 'Write your service name here...',
                          autoFocus: true,
                          iconData: Icons.info_outline,
                          validatorFunction: (String value) {
                            if (value.length > 0 && value.length < 6) {
                              return '*Service name should be more than 5 letters';
                            } else if (value.length == 0) {
                              return '* Service name is required';
                            }
                          },
                          onSaved: (String value) {},
                        ),
                        HeaderTextWithFormTextFieldAndSizedBox(
                          headerText: 'Service Description',
                          hintText: 'Write your service description here...',
                          autoFocus: false,
                          iconData: Icons.info_outline,
                          validatorFunction: (String value) {
                            if (value.length > 0 && value.length < 6) {
                              return '* Service description should be more than 5 letters';
                            } else if (value.length == 0) {
                              return '* Service description is required';
                            }
                          },
                          letterCount: 200,
                          maxLines: 3,
                          contentPadding: 13,
                          onSaved: (String value) {},
                        ),
                      ],
                    ),

                    //only add the add service button when it is the last card
                    Visibility(
//                        visible:   widget.index ==  serviceNamesList.length - 1 ,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: RoundButtonWithIconFix(
                          text: 'Add Another Service',
                          buttonWidth: 160,
                          buttonColor: kAppLightBlueColor,
                          onButtonPressed: () {},
                          icon: Icons.add_box,
                          color: Colors.white,
                          iconTextSpacing: 5,
                          iconSize: 25,
                        ),
                      ),
                    ),

                    Positioned(
                      bottom: 50,
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: RoundButtonWithIconFix(
                          text: 'Remove Service',
                          buttonWidth: 130,
                          buttonColor: kAppLightBlueColor,
                          onButtonPressed: () {
                            setState(() {
                            });
                          },
                          icon: Icons.delete,
                          color: Colors.white,
                          iconTextSpacing: 5,
                          iconSize: 25,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          Visibility(
//              visible: widget.index == serviceNamesList.length - 1  ,
            child: DoneButton(
              onPressed: onFormSubmitted,
            ),
          ),
        ],
      ),
    );
  }
}

回答1:


You could create a list and pass that to your ListView and use the remove function to remove the actual object and call setState((){}) to refresh your UI.

Here is a sample you can run:

class StreamBuilderIssue extends StatefulWidget {
  @override
  _StreamBuilderIssueState createState() => _StreamBuilderIssueState();
}

class _StreamBuilderIssueState extends State<StreamBuilderIssue> {
  List<ServiceCard> serviceCardList;

  void removeServiceCard(index) {
    setState(() {
      serviceCardList.remove(index);
    });
  }

  @override
  void initState() {
    super.initState();
    serviceCardList = List.generate(
        5, (index) => ServiceCard(removeServiceCard, index: index));
  }

  @override
  Widget build(BuildContext context) {
    print('build + ${serviceCardList.length}');
    return Scaffold(
      body: ListView(
        children: <Widget>[...serviceCardList],
      ),
    );
  }
}

class ServiceCard extends StatelessWidget {
  final int index;
  final Function(ServiceCard) removeServiceCard;

  const ServiceCard(this.removeServiceCard, {Key key, @required this.index})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Text(
            'Index: ${index.toString()} Hashcode: ${this.hashCode.toString()}'),
        RaisedButton(
          color: Colors.accents.elementAt(3 * index),
          onPressed: () {
            removeServiceCard(this);
          },
          child: Text('Delete me'),
        ),
      ],
    );
  }
}

And here is gif showing its behavior external link

I'm showing the index and the hashcode to show that it is indeed the desired object that gets removed



来源:https://stackoverflow.com/questions/56979595/how-can-i-remove-a-widget-in-a-listview-in-a-specific-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!