1

Just starting to learn Flutter and working thru a course and made a simple dice roller. Now as a challenge to myself Im trying to upgrade the dice roller to add different types of dice. I currently have a list of custom dice class in my Stateful widget

List<Dice> dice = [];

This is my dice class

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()),
        ],
      ),
    );
  }
}

I have a row of icons (using the Dice class) that will add a dice to the dice list like this:

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
            });
          },
        ));
      });
    },
  ),
)

The comment in the setState is what I cant seem to find. I know I need to do something with dice.remove() but not sure how to reference the Expanded widget to pass it in as an object for the remove function.

1 Answer 1

1

Remove a element at position [index] from a list.

final index = dice.length;

dice.add(
  Dice(
    diceType: 4,
    onPress: () {
      print('Tapped');
      setState(() {
        dice.removeAt(index);
      });
    },
  ),
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.