Home > Mobile >  How can I print the last item in the stack? (using dart)
How can I print the last item in the stack? (using dart)

Time:10-25

class CustomStack<T> {
  final _list = <T>[];
  void push(T value) => _list.add(value);
  T pop() => _list.removeLast();
  T get top => _list.last;
  bool get isEmpty => _list.isEmpty;
  bool get isNotEmpty => _list.isNotEmpty;
  int get length => _list.length;
  @override
  String toString() => _list.toString();
}

void main() {
  CustomStack<String> plates = CustomStack();
//Add plates into the stack
  plates.push("Plate1");
  plates.push("Plate2");
  plates.push("Plate3");
  plates.push("Plate Extra");
  print(plates);
  print(plates[plates.length-1]);
}



I get an error in the last line "The operator '[]' isn't defined for the type 'CustomStack'." How can I control the index in the stack. I want to print only "Plate Extra" on the screen.

CodePudding user response:

There is no need to use that structure plates[plates.length-1] if getting the last element is possible with the built function. If you want to get the last item in Custom Stack, you can define a function in your Custom Stack.

T get peek => _list.last;

  • Related