【问题标题】:How to add a card widget dynamically whenever floating action button is clicked in flutter?每当在颤动中单击浮动操作按钮时,如何动态添加卡片小部件?
【发布时间】:2021-10-02 22:22:03
【问题描述】:

我对 Flutter 很陌生,只是想知道如何在每次单击按钮(比如说 FAB)时创建一个新的卡片小部件。

假设这是卡片小部件:

return Card(
 child: Column(
  children: [
  Text('name'),
  Text('standard'),
  Text('Roll No'),
    ],
   ),
 );

我希望每次点击 FAB 时都使用相同的内容构建卡片。有人可以帮我吗?

【问题讨论】:

  • 您需要检查“listsview”状态完整小部件并设置状态。

标签: flutter flutter-layout flutter-widget


【解决方案1】:

首先声明一个小部件类型列表

List<Widget> _cardList = [];

然后创建您想要在按钮单击时添加的小部件,例如

  Widget _card() {
    return Card(
      child: Column(
        children: [
          Text('name'),
          Text('standard'),
          Text('Roll No'),
        ],
      ),
    );
  }

在按钮单击时将您的小部件添加到列表中

FloatingActionButton(
            child: Icon(Icons.add),
            onPressed: () {
              setState(() {
                _cardList.add(_card());
              });
            },
          ),

现在使用ListView.builder 来创建小部件列表

 ListView.builder(
      shrinkWrap: true,
      itemCount: _cardList.length,
      itemBuilder: (context, index) {
        return _cardList[index];
      },
    )

【讨论】:

  • 谢谢它的工作。关于如何删除我们想要的卡片的任何想法?
  • 只要使用数组的remove方法`_cards.removeAt(index)`
  • 我明白了你的想法,但这里的问题是卡片小部件是在类之外定义的。因此,不能使用 setState()。我在卡片的右侧给出了一个取消图标,但我不能使用 cardList,因为它没有在这里定义。有什么建议吗?
  • 您在列表视图中拥有每个项目的索引,只需将要删除的任何索引存储在单独的变量中并在 removeAt 参数中使用此索引。
猜你喜欢
  • 1970-01-01
  • 2020-08-26
  • 2021-01-14
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 2019-06-27
  • 1970-01-01
  • 2022-11-04
相关资源
最近更新 更多