Home > Net >  Change state after onClick to show items
Change state after onClick to show items

Time:10-12

I would want to expand/show this column when I click on an IconButton which I set isExpanded = true. But nothing happens when I tap on the IconButton. Here's my code:

IconButton(
      onPressed: () {
          if (isExpanded) isExpanded = false;
          isExpanded = true;                     // i tried wrapping in setState and wont work too
      },
      icon: const Icon(Icons.more_horiz)
)
...["general-chat", "gm", "gn", "self-introduction"].map((channel) => isExpanded ? ListTile(
        leading: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                     const Icon(Icons.chat_bubble_rounded, size: 21),
                ],
               ),
               horizontalTitleGap: 0,
               title: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                             Text(channel),
                              ],
                        ),
                        onTap: () {},
                            ): Row(
                            children: [
                              SizedBox(width: 1),
                             ],
))

CodePudding user response:

try this: use operator not ! to your value

IconButton(
   onPressed: () {
      setState(() { 
          isExpanded = !isExpanded;    // notice there "!" before isexpadned
      });                 
   },

CodePudding user response:

you just have to inverse the value of the variable and call setstate to update the UI.

onPressed: () {
      setState(() { 
          isExpanded = !isExpanded;
      });                 
   },

CodePudding user response:

If you used a stateful widget, you may try to set state in IconButton on pressed

onPressed: () {
          if (isExpanded) {
              isExpanded = false;            
           } else{
              isExpanded = true; 
           } 
          setState(() {  });    
      },

  • Related