SliverList setState to Affect Only Selected Item Flutter

Viewed 102

I have a button on every item on my SliverList. When I click a specific list item button, I wish it change to a different widget by using setState. Only that specific item button should change to a different widget while the rest on the list retains its own item button.

Example below. The problem of course is that when I click any button on the list, all buttons on every item on the list changes. What is needed so that it affects only the specific item on the list whose button was pressed?

SliverList(
   delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
     final item = gd[index];
     return Container(
       child: Column(
         children: [
           item.mypicwidget(context,item.pid),
           _shownewwidget
              ? item.newwidget(context)
              : RaisedButton(
                   onPressed: () {
                      setState(() {
                        _shownewwidget=true;
                      });
                   },
                  child: const Text('Press Me'),
                ),
]
),
);
1 Answers

Figured this out.

I believe the approach is to add to the existing list an object key to represent whether widget1 or widget2 to render, eg. tag: 'normal' or tag: 'clicked'. Depending on index.tag, either widget1 or widget2 will be displayed. So for a widget with a button wherein the tag is normal, the button will have a function when clicked changes the index.tag of the item from normal to clicked. When the Sliverlist sees this new value, it automatically renders the corresponding widget.

Related