如何根据需求动态地插入和删除窗口小部件?

问题描述 投票:0回答:1

这个问题很普遍。但是,我尝试通过在单击按钮时将容器添加到列中来模拟事件。但是,该容器未添加到列或未呈现在屏幕上。除此之外,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"),
        )
      ]),
    ));
  }
}

这里是输出:

enter image description here

flutter flutter-layout flutter-animation flutter-test
1个回答
0
投票

问题是,您正在使用箭头功能,这意味着您在右侧编写的任何内容都将返回某些内容,并且您未将其分配给也不是实际要求的任何变量,这就是为什么它显示错误。 >

在解决您的问题时,用以下一个替换setState。

setState(() {
              containersList.add(Container(
                color: Colors.lightBlue,
                height: 100,
                width: 200,
              ));
            });
© www.soinside.com 2019 - 2024. All rights reserved.