如何在flutter中按需动态插入和移除widgets?

How to dynamically insert and remove widgets based on demand in flutter?

这个问题很常见。但是,我尝试通过在点击按钮时向列添加容器来模拟事件。但是,容器不会添加到 Column 中或不会呈现在屏幕上。 除此之外,setState 方法会显示未被引用的警告。

这是代码

import 'package:flutter/material.dart';
import 'package:focus7/Configurations/size_config.dart';

class Demo2 extends StatefulWidget {
  @override
  _Demo2State createState() => _Demo2State();
}

class _Demo2State extends State<Demo2> {
  List<Widget> containersList = [
    Container(
      color: Colors.amberAccent,
      height: 100,
      width: 200,
    ),
    Container(
      color: Colors.red,
      height: 100,
      width: 200,
    ),
    Container(
      color: Colors.brown,
      height: 100,
      width: 200,
    ),
    Container(
      color: Colors.green,
      height: 100,
      width: 200,
    ),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SafeArea(
      child: Column(children: <Widget>[
        ...containersList,
        RaisedButton(
          onPressed: () {
            setState() => containersList.add(Container(
                  color: Colors.lightBlue,
                  height: 100,
                  width: 200,
                ));
          },
          child: Text("click"),
        )
      ]),
    ));
  }
}

这是输出:

问题是你正在使用箭头函数,这意味着无论你在右侧写什么都会 return 一些东西,你没有将它分配给任何不是实际需要的变量,那就是为什么显示错误。

在解决您的问题时将您的 setState 替换为以下设置。

setState(() {
              containersList.add(Container(
                color: Colors.lightBlue,
                height: 100,
                width: 200,
              ));
            });