Georgios
Georgios

Reputation: 1057

UI changes in a ListView.builder after Item Deletion

I have a list of StatefulWidgets (Containers). These Containers depict participants of a course.

The user is able to remove these participants by clicking on a FlatButton.

Since the list is retrieved directly from Firestore as a stream there is a small delay when clicking on the FlatButton and deleting.

In this case, I want to disable the button until this Container gets removed. I do this by wrapping the container with the AbsorbPointer and edit the value of the absorbing parameter with a boolean that changes within a setState.

The Problem occurs after the update of the list. The value of the absorbing for a certain Container remains true. Thus, the user can not delete another participant, that took the place in the list of the old deleted participant.

How can I reset the disabled value to be false after the length of the participants list gets reduced?

class _ParticipantList extends StatelessWidget {
  final CourseEventFormBloc courseEventFormBloc;

  const _ParticipantList({
    Key key,
    this.courseEventFormBloc,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CourseEventFormBloc, CourseEventFormState>(
      builder: (context, state) {
        return Expanded(
          child: ListView.builder(
            itemCount: state.participants.length,
            itemBuilder: (context, index) {
              return _ParticipantContainer(
                index: index,
                courseEventFormBloc: courseEventFormBloc,
              );
            },
          ),
        );
      },
    );
  }
}

class _ParticipantContainer extends StatefulWidget {
  final CourseEventFormBloc courseEventFormBloc;
  final int index;
  const _ParticipantContainer({
    Key key,
    @required this.index,
    @required this.courseEventFormBloc,
  }) : super(key: key);

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

class __ParticipantContainerState extends State<_ParticipantContainer> {
  bool disabled = false;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CourseEventFormBloc, CourseEventFormState>(
      builder: (context, state) {
        print('${widget.index} - disabled:$disabled');
        return AbsorbPointer(
          absorbing: disabled,
          child: Container(
            margin: const EdgeInsets.symmetric(vertical: 4.0),
            decoration: BoxDecoration(
              color: Colors.blueGrey.shade100,
              borderRadius: BorderRadius.all(Radius.circular(13)),
            ),
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height * 0.07,
            alignment: Alignment.center,
            child: Stack(
              // mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Align(
                  alignment: Alignment.center,
                  child: Text(state.participants[widget.index].name),
                ),
                SizedBox(width: 20.0),
                Align(
                  alignment: Alignment.centerLeft,
                  child: FlatButton(
                    onPressed: () {
                      // through this AlertDialog I can delete a participant
                      // showAlertDialog(context, index, state.participants[index]);
                      showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              //! I might get an error for the Bloc since the Dialog has another context
                              title: BlocBuilder<CourseEventFormBloc,
                                  CourseEventFormState>(
                                cubit: widget.courseEventFormBloc,
                                builder: (context, state) {
                                  return Text(state.participants.isNotEmpty
                                      ? state.participants[widget.index].name
                                      : '');
                                },
                              ),
                              content:
                                  Text('Möchtest du den Teilnehmer entfernen?'),
                              actions: <Widget>[
                                FlatButton(
                                  onPressed: () => Navigator.pop(context),
                                  child: Text(
                                    'nein',
                                    style: TextStyle(color: kDarkRosaColor),
                                  ),
                                ),
                                FlatButton(
                                  onPressed: () {
                                    widget.courseEventFormBloc.add(
                                      CourseEventAdminParticipantDeleted(
                                        widget.index,
                                        state.participants[widget.index],
                                        state.courseEventObject,
                                      ),
                                    );
                                    setState(() {
                                      disabled = true;
                                    });
                                    Navigator.pop(context);
                                  },
                                  child: Text(
                                    'ja',
                                    style: TextStyle(color: kDarkRosaColor),
                                  ),
                                ),
                              ],
                            );
                          });
                    },
                    child: Container(
                      // margin: const EdgeInsets.only(right: 27.0),
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(100),
                          border: Border.all(width: 2, color: kDarkRosaColor)),
                      child: Icon(
                        Icons.delete,
                        color: kDarkRosaColor,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

Does it make sense to use this before the build method of the stateful widget?

@override
  void didUpdateWidget(covariant _ParticipantContainer oldWidget) {
    super.didUpdateWidget(oldWidget);
    disabled = false;
  }

Upvotes: 0

Views: 253

Answers (2)

First_Strike
First_Strike

Reputation: 1089

Generate a key for every list item to prevent the framework from reusing the wrong state.

In fact this is the very purpose for non-global keys: to distinguish children which otherwise would become indistinguishable during a reconciliation process. https://api.flutter.dev/flutter/foundation/Key-class.html

The keys can be generate from any UUID-like property in your participant database, ( participant ID, or simply, name) by ValueKey().

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CourseEventFormBloc, CourseEventFormState>(
      builder: (context, state) {
        return Expanded(
          child: ListView.builder(
            itemCount: state.participants.length,
            itemBuilder: (context, index) {
              return _ParticipantContainer(
                key: ValueKey(state.participants[index].id), // Generate ValueKey based on UUID
                index: index, // Perhaps you should pass entire participant instead of an index
                courseEventFormBloc: courseEventFormBloc,
              );
            },
          ),
        );
      },
    );
  }

Override didUpdateWidget works for your special case. BUT keep in mind, if any ancestor has triggered a rebuild in midst of your network request, then didUpdateWidget will be called. As a result. the AbsorbPointer may be disabled earlier than you had expected, which is risky.

Upvotes: 3

Georgios
Georgios

Reputation: 1057

Since I am using Bloc, in the end, I added a String deletedId within the state class. When I am deleting a participant, I just pass his uid to the newly yielded state.

Furthermore, I got rid of the stateful widget and I am doing the following check to disallow clicks on a just deleted participant.

absorbing: state.deleteId == state.participants[index].uid,

The approach recommended by @First_Strike works similarly, only he would use another state management (Stateful Widget and not the Bloc).

Upvotes: 0

Related Questions