【问题标题】:Dynamically Add/Remove Widget to list in Flutter onTap在 Flutter onTap 中动态添加/删除 Widget 列表
【发布时间】:2020-03-07 17:11:24
【问题描述】:

刚开始学习 Flutter 并通过课程学习并制作了一个简单的掷骰子。现在作为对自己的挑战,我正在尝试升级骰子滚轮以添加不同类型的骰子。我目前在我的 Stateful 小部件中有一个自定义骰子类列表

List<Dice> dice = [];

这是我的骰子课

class Dice extends StatelessWidget {
  Dice({@required this.diceType, @required this.onPress});

  final int diceType;
  final Function onPress;

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onPress,
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          Image.asset('images/d${diceType}_blank.png'),
          Text(diceType.toString()),
        ],
      ),
    );
  }
}

我有一排图标(使用 Dice 类),它们会将骰子添加到骰子列表中,如下所示:

Expanded(
  child: Dice(
    diceType: 4,
    onPress: () {
      setState(() {
        dice.add(Dice(
          diceType: 4,
          onPress: () {
            print('Tapped');
            setState(() {
              //What to put here to remove from dice list
            });
          },
        ));
      });
    },
  ),
)

setState 中的注释是我似乎找不到的。我知道我需要对 dice.remove() 做一些事情,但不确定如何引用 Expanded 小部件以将其作为对象传递给 remove 函数。

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    从列表中删除位置 [index] 处的元素。

    final index = dice.length;
    
    dice.add(
      Dice(
        diceType: 4,
        onPress: () {
          print('Tapped');
          setState(() {
            dice.removeAt(index);
          });
        },
      ),
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 2020-10-22
      • 1970-01-01
      相关资源
      最近更新 更多