Search code examples
fluttermaterialbutton

Create a button which creates a widget in flutter


I wanna define a function or something like that to make a new widget on my button press, Also, I wanna create that widget in a specific column. Anybody can help?


Solution

  • you can define bool variable to control show or hide that widget and in button onPressed method change that variable in setState.

    something like this code:

    var _showWidget = false;
    
      void changeShow(){
        setState(() {
          _showWidget = !_showWidget;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              RaisedButton(
                child: _showWidget? Text('Show'): Text('Hide'),
                onPressed: changeShow
              ),
              if (_showWidget)
                Container(
                  width: 150,
                  height: 50,
                  color: Colors.green,
                  child: Center(child: Text('Hello Word')),
                ),
            ],
          ),
        );
      }