Search code examples
flutterdartwidgetstateprovider

How can I display or hide widget according to change in value using provider / State management( In flutter)?


This is how I want to display and remove a widget from different values.

image here


Solution

  • I note that the question title asks for using provider / State management, however I believe the base state management that Flutter uses is sufficient for this problem and using it would only overly complicate it.

    You can use inline if statements to show widgets conditionally. They require an else statement, so showing a SizedBox with a height of 0 can be used to show "nothing".

    bool showWidget = false;
    
    showWidget ? WidgetC() : SizedBox(height: 0)
    

    Here is a working example. This one uses a bool value, but it could be anything, for example you could use

     _value > 3 ? WidgetC() : SizedBox(height: 0)
    

    or

    _value != "Test" ? WidgetC() : SizedBox(height: 0)
    

    Here is example:

    class HideWidgetTest extends StatefulWidget {
      const HideWidgetTest({Key? key}) : super(key: key);
    
      @override
      State<HideWidgetTest> createState() => _HideWidgetTestState();
    }
    
    class _HideWidgetTestState extends State<HideWidgetTest> {
      bool _showWidget = true;
    
      void _toggleShowWidget() {
        setState(() {
          _showWidget = !_showWidget;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                WidgetA(),
                WidgetB(),
                _showWidget ? WidgetC() : SizedBox(height: 0),
                TextButton(
                    onPressed: () => _toggleShowWidget(),
                    child: Text('Hide Widget C')),
              ],
            ),
          ),
        );
      }
    }
    
    class WidgetA extends StatelessWidget {
      const WidgetA({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Text('Widget A');
      }
    }
    
    class WidgetB extends StatelessWidget {
      const WidgetB({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Text('Widget B');
      }
    }
    
    class WidgetC extends StatelessWidget {
      const WidgetC({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Text('Widget C');
      }
    }
    

    Gif Showing example