Add New Widget on button click with a finction that returns a widget

后端 未结 2 1806
感动是毒
感动是毒 2021-01-27 16:26

Hello i am new to Flutter and I want to know if there is a way to add new Widgets with a button click. I looked into many stack overflow similar Questions. but due to my poor kn

2条回答
  •  逝去的感伤
    2021-01-27 16:45

    Try this

    class AddWidget extends StatefulWidget {
      @override
      _AddWidgetState createState() => _AddWidgetState();
    }
    
    class _AddWidgetState extends State {
      List containerList = [];
    
      Widget returnWidget() {
        return Padding(
          padding: const EdgeInsets.all(8.0),
          child: Container(
            width: double.infinity,
            height: 40,
            color: Colors.red,
          ),
        );
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          child: Column(
            children: [
              Expanded(
                child: Container(
                  color: Colors.yellow,
                  height: 400,
                  width: double.infinity,
                  child: Column(children: containerList),
                ),
              ),
              RaisedButton(
                child: Text("Add"),
                onPressed: () {
                  setState(() {
                    containerList.add(returnWidget());
                  });
                },
              )
            ],
          ),
        );
      }
    }
    
    

提交回复
热议问题