Search code examples
flutterdartstack

RangeError (RangeError (index): Invalid value: Valid value range is empty: -1)


class Stack<T> {
  final List<T> _items = [];
//_items declared as Private

  void push(T item) => _items.add(item);

  T pop() => _items.removeLast();

  @override
  String toString() => _items.toString();
}

void main() {
  final stack = Stack<int>();
  stack.push(1);
  stack.push(2);
  print(stack.pop());
  print(stack.pop());

  final names = Stack<String>();
  names.push('Adam');
  names.push('Rose');

  print(stack.pop());
}

Print command with the 'stack.pop()' method doesn't print the name values as it does with the int values, How can I fix this?


Solution

  • you need to do names.pop() instead of stack.pop()