Home > Software design >  Flutter onPressed trigger State of another widget
Flutter onPressed trigger State of another widget

Time:08-01

I need help with flutter build management. My Goal is to rebuild my side navigation bar with the SmallSideMenu() or the opposite SideMenu().

Do you have an idea how I can trigger the Build process of my LargeView widget, so that it's rebuilt with the correspondent SideMenu?

The button is defined like this:

IconButton(
            onPressed: () {
              checkState();
            },
            icon: HeroIcon(
              HeroIcons.arrowNarrowRight,
              size: 16.0,
            ),
          ),

The value of the sideMenuOpen variable and function is set globally;

checkState() {
  if (sideMenuOpen == true) {
   sideMenuOpen = false;
   } else {
     sideMenuOpen = true;
   }
 }

the SideMenu is defined here.

class LargeView extends StatefulWidget {
  const LargeView({
    Key? key,
  }) : super(key: key);

  @override
  State<LargeView> createState() => _LargeViewState();
}

class _LargeViewState extends State<LargeView> {
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: SizedBox(
            width: 100,
            child: sideMenuOpen ? SideMenu() : SmallSideMenu(),
          ),
        ),
        Expanded(
          flex: 10,
          child: Container(
            width: double.infinity,
            padding: const EdgeInsets.all(20.0),
            color: greyColor,
            child: Expanded(
                child: Container(
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(15.0)),
                    child: localNavigator())),
          ),
        )
      ],
    );
  }
}

first widget should displayed widget

CodePudding user response:

You can use ValueNotifier instead of single bool. And to update UI it can be used on ValueListenableBuilder.

final ValueNotifier<bool> sideMenuOpen = ValueNotifier(false);

And

child: SizedBox(
  width: 100,
  child: ValueListenableBuilder<bool>(
    valueListenable: sideMenuOpen,
    builder: (context, value, child) => value
        ? SideMenu(),
        : SmallSideMenu(),
  ),
),

And change value like

sideMenuOpen.value = true;

CodePudding user response:

make sideMenuOpen a state in stateful widget and use setState as

checkState() {
  if (sideMenuOpen == true) {
setState((){
sideMenuOpen = false;
});

   } else {
     setState((){
sideMenuOpen = true;
});
   }
 }

if you want to keep state (open/close) of navigation bar globally for that use some state management like provider instead of using global function.

  • Related