Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading