Home > Software design >  how to change between multi widgets in flutter?
how to change between multi widgets in flutter?

Time:12-14

I have a line contains 4 outlinedbuttons and i have 4 widgets ( listview , ListWheelScrollView ,image png and svg image ) i want to display one widget only when i pressed at one outlinedbutton . what should i use for do this in flutter? provide some code will be helpfull

Container(
             padding: EdgeInsets.all(8.0),
             height: 100,
             child: Row(
               children: [
                 Expanded(
                   child: OutlinedButton(
           onPressed: () =>
              //show widget1
       
                 )),
            Expanded(
                   child: OutlinedButton(
           onPressed: () =>
              //show widget2
       
                 )),
 Expanded(
                   child: OutlinedButton(
           onPressed: () =>
              //show widget3
       
                 )),
 Expanded(
                   child: OutlinedButton(
           onPressed: () =>
              //show widget4
       
                 )),
               ],
             ),
           )

CodePudding user response:

You can do it in different ways.. A simple one would be creating 4 boolean variables for each widget. On pressing button true value for particular widget and false other 3 values. On the otherside, use if(isthiswidget) to display widget if value is true. some demo of code

bool widget1, widget2, widget3, widget4 = false;

onpressing widget1

onPressed: (){
widget1 = true;
widget2, widget3, widget4 = false;}

onpressing widget2

onPressed: (){
   setState(() {
     widget2 = true;
     widget1, widget3, widget4 = false;
   });
   }

do same for other functions

in UI set condition before every widget

if(widget1)
Container(), //display widget1
if(widget2)
Container() //display widget2
if(widget3)
Container(), //display widget3
if(widget4)
Container() //display widget4

note: use setstate, provider or any other statemanagement method to update realtime values and UI

CodePudding user response:

create this var to identify which widget to show, it will get value from 0 to 3

int widgetNum = 0;

and in onPressed of each button add this, don't forget to add correct num

onPressed: () =>setState(() {
      //for example 
      widgetNum = 2; //for first btn will be = 0 etc..
    });

and use visibility to show widget

Column(
   children:[
     Visibility(
       visible: widgetNum==2, // for first widget will be ==0 etc..
       child: Container(
      // your widget 
     ))]
)
  • Related