如何动态地将小部件添加到行中?

时间:2019-11-28 06:03:25

标签: flutter

我在Row小部件中有一个DropdownButton(类型为String的条目)和一个IconButton。每次从DropdownButton中选择一个条目并点击IconButton时,都应在初始Row下面的Row小部件中创建一个以选定条目作为其子级的InputChip。该怎么办?

1 个答案:

答案 0 :(得分:1)

class _MyHomePageState extends State<MyHomePage> {
  List<String> templist = new List();

  @override
  Widget build(BuildContext context) {
    SizeConfig().init(context);
    return Scaffold(
        body: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Wrap(
          children: templist
              .map(
                (f) => Chip(
                  label: Text(f),
                  deleteIcon: CircleAvatar(
                    minRadius: 10.0,
                    child: Icon(
                      Icons.clear,
                      color: Colors.white,
                      size: 20,
                    ),
                  ),
                  deleteIconColor: Colors.red,
                  onDeleted: () {
                    setState(() {
                      templist.remove(f);
                    });
                  },
                ),
              )
              .toList(),
        ),
        new DropdownButton<String>(
          isExpanded: true,
          hint: Text("Click here"),
          items: <String>['A', 'B', 'C', 'D'].map((String value) {
            return new DropdownMenuItem<String>(
              value: value,
              child: new Text(value),
            );
          }).toList(),
          onChanged: (value) {
            setState(() {
              templist.add(value);
            });
          },
        )
      ],
    ));
  }
}