Home Blog Page 3

Dart String Interpolation with Code Example

0
dart string interpolation
dart string interpolation

Hi Guy’s Welcome to Proto Coders Point.

Understanding String Interpolation in Dart

In Dart Variable values can be embedded into string literals. This using Dart String Interpolation we can eliminate technique like we used to do i.e cumbersome string concatenation(Where we use + Operator to concate string), Here with String Interpolation feature in dart provide a clearer way to display String in dart.

By using String Interpolation in dart we can embed variable value or expression inside a string. Syntax looks like this ${expression} or $variableName.

Dart String Interpolation Example 1

Below are few Example by which you get better understanding about String Interpolations

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void main() {
String name = 'Alice';
int age = 30;
String greeting = 'Hello, $name! You are $age years old.';
print(greeting); // Output: Hello, Alice! You are 30 years old.
}
void main() { String name = 'Alice'; int age = 30; String greeting = 'Hello, $name! You are $age years old.'; print(greeting); // Output: Hello, Alice! You are 30 years old. }
void main() {
  String name = 'Alice';
  int age = 30;

  String greeting = 'Hello, $name! You are $age years old.';
  print(greeting); // Output: Hello, Alice! You are 30 years old.
}

Here in above source code, You can see name & age are two variable with values in it, are embedded into s string greeting by using $name & $age Syntax.

Example 2 – Embedding Expressing Dart String Interpolation

While performing any calculation or while using expression, You need to make use of ${} i.e. curly braces.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void main() {
int a = 5;
int b = 3;
String result = 'The sum of $a and $b is ${a + b}.';
print(result); // Output: The sum of 5 and 3 is 8.
}
void main() { int a = 5; int b = 3; String result = 'The sum of $a and $b is ${a + b}.'; print(result); // Output: The sum of 5 and 3 is 8. }
void main() {
  int a = 5;
  int b = 3;

  String result = 'The sum of $a and $b is ${a + b}.';
  print(result); // Output: The sum of 5 and 3 is 8.
}

Here a + b is performed and the final string result is embedded into the string.

Example 3 – Multi-Line Strings

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void main() {
String firstName = 'John';
String lastName = 'Doe';
String introduction = '''
My name is $firstName $lastName.
I am learning Dart.
''';
print(introduction);
// Output:
// My name is John Doe.
// I am learning Dart.
}
void main() { String firstName = 'John'; String lastName = 'Doe'; String introduction = ''' My name is $firstName $lastName. I am learning Dart. '''; print(introduction); // Output: // My name is John Doe. // I am learning Dart. }
void main() {
  String firstName = 'John';
  String lastName = 'Doe';

  String introduction = '''
  My name is $firstName $lastName.
  I am learning Dart.
  ''';

  print(introduction);
  // Output:
  // My name is John Doe.
  // I am learning Dart.
}

In dart by using triple quotes, we can create a multiline string & interpolate the variable into them.

Example 4 – Method & Properties access into String

In dart by using string interpolation syntax we can also include method & property access Example below.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void main() {
DateTime currentDate= DateTime.now();
String currentTime = 'Current time is: ${currentDate.hour}:${currentDate.minute}:${currentDate.second}';
print(currentTime);
// Output: Current time is: HH:MM:SS (actual time values)
}
void main() { DateTime currentDate= DateTime.now(); String currentTime = 'Current time is: ${currentDate.hour}:${currentDate.minute}:${currentDate.second}'; print(currentTime); // Output: Current time is: HH:MM:SS (actual time values) }
void main() {
  DateTime currentDate= DateTime.now();

  String currentTime = 'Current time is: ${currentDate.hour}:${currentDate.minute}:${currentDate.second}';
  print(currentTime);
  // Output: Current time is: HH:MM:SS (actual time values)
}

Here we are getting current DataTime by using DateTime.now() Class Object, It has several properties like hours, minutes & seconds that we can easily access into strings by using syntax ${currentDate.hours} , ${currentDate.minute} ${currentDate.second}.

Conclusion

String Interpolation in dart is the best way to access values to dynamic strings. By doing this your codes is much more readable & maintainable. Whether you are working with simple string concatenation or complex data representation String Interpolation technique is very must essential in Flutter Dart Programming.

Naming Conventions in Flutter:Best Practices for Clean & Maintainable Code

0
Flutter Naming Convention
Flutter Naming Convention

Hi Guy’s Welcome to Proto Coders Point. In this Flutter Article let’s learn about Naming Convention in Flutter Application development. As you all know that in the world of software development, Giving a Preper naming conventions plays a crucial role in maintaining a clean, understandable, and easily maintainable code. As Flutter, is Developed by Google’s it is a UI toolkit for building natively compiled applications that supports on all the platform may be it’s mobile, web, and desktop that too with a single codebase. By maintaining a proper naming conventions while developing Application in Flutter will not only enhance readability but also make it easier for developers to collaborate on projects. This article will take you to the best practice that you need to follow while using naming convention in flutter.

1. Files and Directories

Files:

  • Use lowercase_with_underscores for naming file names. This kind of format is way easier to read and avoids potential issues with case sensitivity across different operating systems.
  • Example: main.dart, home_screen.dart, user_profile.dart

Directories:

  • Similarly, while creating directories always use this naming convension “lowercase_with_underscores”
  • Example: assets, models, services, widgets

2. Classes

Then comes Classes in dart language. While creating classes names should be written in Pascal Case, where first letter of word starts with an uppercase letter and there sholuld be no spaces or underscores. This kind of naming convention format is mostly common in many programming languages like Java, JavaScript, Python.

  • Example: HomePage, UserProfile, ApiService

3. Methods and Functions

In Dart Methods and functions should be written in camelCase, Means here Method/ Function will start with first letter as lowercase, and can be give uppercase letter for subsequent word.

  • Example: fetchData(), getUserProfile(), handleButtonClick()

4. Variables

Instance variables and local variables:

  • For declaring variables in dart we make use of camelCase, starting with a lowercase letter and capitalizing subsequent words.
  • Example: userName, profilePicture, userAge

Constant variables:

  • For declaring constant variable what will never changed, Make use of Full uppercase letters and can use underscores separating words for better understanding the use case.
  • Example: MAX_USER_AGE, DEFAULT_PROFILE_PICTURE

5. Constants and Enums

Constants:

  • As mentioned above, constants should always be names with all uppercase letters with underscores if needed.
  • Example: const int MAX_RETRIES = 3;

Enums:

  • Enum names should be in PascalCase, and their values should be in camelCase.
  • Example:
    dart enum UserStatus { active, inactive, banned }

6. Widgets

StatelessWidget and StatefulWidget Classes:

  • For State Widget naming convension should be PascalCase convention widget classes.
  • Example: LoginButton, UserCard

State Classes:

  • When defining the state class for a StatefulWidget, This class name should be as Normal at said above and by appending State at the end of class name to make it as widget class name.
  • Example:
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class LoginButton extends StatefulWidget {
@override _LoginButtonState
createState() => _LoginButtonState();
} c
lass _LoginButtonState extends State<LoginButton>
{
// State implementation
}
class LoginButton extends StatefulWidget { @override _LoginButtonState createState() => _LoginButtonState(); } c lass _LoginButtonState extends State<LoginButton> { // State implementation }
class LoginButton extends StatefulWidget { 
@override _LoginButtonState 
createState() => _LoginButtonState(); 
} c
lass _LoginButtonState extends State<LoginButton> 
{
 // State implementation
 }

7. Private Members

Private Memebers in dart are always defined with _ at begin of the naming convension, This can be applied to variable, method or class to make it private member.

  • Example: _fetchData(), _userName, _UserService

8. Mixins

Mixin Variable are maded as PascalCase, At the end of theWord or suffix word Mixin for easily identify the Mixin Variable in dart.

  • Example: LoggingMixin, ValidationMixin

Guide to Docker: Commands, Use Cases, & Benefits

0
docker guide
docker guide

As you all know that Docker is an open-source platform that can be used by any one out their and Docker helps developers to automate their development, scaling, and management of applications through containerization. Basically Docker will encapsulate the applications and all their dependencies into containers, Once application is ready and been containerized Docker ensures that software will runs smoothly in any environments. Below are key benefits of Docker and some very useful commands to get you started as a docker beginner.

Benefits of Docker

Portability: Docker is easily portable on all the machine as it is lightweight and can run consistently across various machines weather it’s local machines to cloud servers.

Scalability: Docker more popular because it is easily scalable, Application wrapped using docker can be easily scaled up or down as per our requirement.

Isolation: Another thing why Docker popular because it can be executed on its own isolated environment, by doing this different applications do not interfere with each other.

Efficiency: Docker containers make use of the host OS kernel i.e it share the host of OS kernel the code, which automatically makes docker more efficient.

Version Control: Version Control is possible in Docker just like how we use Git & GITHUB, This allows developers to keep track all the changes made & roll back to previous versions when necessary.

Use Cases of Docker Commands

Understanding and utilizing Docker commands is very important for managing Docker containers effectively.

Below are few Docker Commands for Beginners level

docker run: Use this command when you need to instantiate a container from an image. It’s essential for testing and development environments.

Example: docker run -it ubuntu


docker ps: Use this command to monitor running containers and check their status. It’s basically useful for managing multiple containers.

Example: docker ps -a lists all containers, whether they are running or stopped, providing a comprehensive overview of container activity.


docker build: Used to create dockerFile of the application. will create a image file of your application in the current working directory and will be names as myapp.

Example: docker build -t myapp .


docker pull: Used to download the Docker File from it Hub, Just like we clone or pull any changed from githu repository. Here docker files will get pulled or downloaded from it HUB.

Example: docker pull postgres


docker exec: used to interact with the running docker container, is been basically used for real-time interacting with docker container that is running. below cmd will open a bash shell with point your running container.

Example: docker exec -it mycontainer bash


By using these commands, Software developers can more efficiently manage their application been wrapped in a Docker containers, streamline application deployment, and maintain robust version control.

Visual Studio Code: 47 Essential Shortcuts for Developers

0
Visual Studio Code shortcuts
vscode keyboard shortcuts for developers

Visual Studio Code (VS Code) has become one of the most popular editors used by programmer/developer due to it’s flexibility, powerful features, and wide range of extensions available in its marketplace. However, The very useful for the developer is the large number of keywords shortcuts that are available for free to use that significantly enhance productivity of software developer in IT field. Getting used to these shortcuts & mastering it can save your time in building any kind of application, reduce context switching, and keep your focus on your code.

In this article, Let’s explore 47 usefull Visual Studio Code shortcuts tricks that every developer should know. Whether you’re a beginner or an experienced user, these vscode keyboard shortcuts for developers surely help you in various things while coding for your projects.

General Shortcuts

  1. Command Palette: Ctrl + Shift + P or F1 – (Windows) | Cmd + Shift + P or F1 – (macOS)
  2. Quick Open: Ctrl + P – (Windows) | Cmd + P – (macOS)
  3. New Window: Ctrl + Shift + N – (Windows) | Cmd + Shift + N(macOS)
  4. Close Window: Ctrl + Shift + W – (Windows) | Cmd + Shift + W(macOS)
  5. Settings: Ctrl + , – (Windows) | Cmd + , – (macOS)
  6. User Preferences: Ctrl + Shift + , – (Windows) | Cmd + Shift + , – (macOS)
  7. Toggle Sidebar: Ctrl + B – (Windows)| Cmd + B – (macOS)
  8. Toggle Full Screen: F11 – (Windows)| Cmd + Ctrl + F – (macOS)
  9. Zen Mode: Ctrl + K Z – (Windows)| Cmd + K Z – (macOS)
  10. Toggle Terminal: Ctrl + (backtick) – (Windows) | Cmd + (backtick) – (macOS)

File Management

  1. New File: Ctrl + N | Cmd + N
  2. Open File: Ctrl + O | Cmd + O
  3. Save: Ctrl + S | Cmd + S
  4. Save As: Ctrl + Shift + S | Cmd + Shift + S
  5. Save All: Ctrl + K S | Cmd + Option + S
  6. Close Editor: Ctrl + W | Cmd + W
  7. Reopen Closed Editor: Ctrl + Shift + T | Cmd + Shift + T
  8. Close Folder: Ctrl + K F | Cmd + K F

Navigation

  1. Go to Line: Ctrl + G | Cmd + G
  2. Go to File: Ctrl + P | Cmd + P
  3. Go to Symbol: Ctrl + Shift + O | Cmd + Shift + O
  4. Go to Definition: F12 | F12
  5. Peek Definition: Alt + F12 | Option + F12
  6. Navigate Back: Alt + Left Arrow | Cmd + Left Arrow
  7. Navigate Forward: Alt + Right Arrow | Cmd + Right Arrow
  8. Toggle Breadcrumbs: Ctrl + Shift + . | Cmd + Shift + .

Editing

  1. Cut Line: Ctrl + X | Cmd + X
  2. Copy Line: Ctrl + C | Cmd + C
  3. Move Line Up/Down: Alt + Up/Down Arrow | Option + Up/Down Arrow
  4. Duplicate Line: Shift + Alt + Up/Down Arrow | Shift + Option + Up/Down Arrow
  5. Delete Line: Ctrl + Shift + K | Cmd + Shift + K
  6. Insert Line Below: Ctrl + Enter | Cmd + Enter
  7. Insert Line Above: Ctrl + Shift + Enter | Cmd + Shift + Enter
  8. Select Line: Ctrl + L | Cmd + L
  9. Select All Occurrences: Ctrl + Shift + L | Cmd + Shift + L
  10. Undo: Ctrl + Z | Cmd + Z
  11. Redo: Ctrl + Y | Cmd + Shift + Z
  12. Toggle Comment: Ctrl + / | Cmd + /
  13. Block Comment: Shift + Alt + A | Shift + Option + A
  14. Format Document: Shift + Alt + F | Shift + Option + F
  15. Format Selection: Ctrl + K Ctrl + F | Cmd + K Cmd + F

Search and Replace

  1. Find: Ctrl + F | Cmd + F
  2. Replace: Ctrl + H | Cmd + H
  3. Find Next: F3 | Cmd + G
  4. Find Previous: Shift + F3 | Cmd + Shift + G
  5. Toggle Case Sensitive: Alt + C | Cmd + Alt + C
  6. Toggle Regex: Alt + R | Cmd + Alt + R

Simple by using these shortcuts into your workflow will boost your coding speed, As you will be navigate & manipulate your program or code more efficiently, making the development process smoother and more enjoyable. Happy coding!

Concurrency in Dart Programming Language

0
Asynchronous programming in Dart
Async/await Dart

As a developer, you might be knowing what concurrency exactly means. Concurrency is the ability to execute more then one task at a given time, means Executing multiple tasks simultaneously, By running multiple task concurrently will enhance the performance & responsiveness of the application. Let’s check out concurrency in dart programming language.

Asynchronous Programming in dart

Basically to perform non-blocking I/O operations & execute task concurrently without affecting or blocking the main thread developer make use of asynchronous programming model that let’s us to run multiple task simultaneously. Async programming in dart will enable responsive & to build scalable dart application.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void main() {
print("Start");
Future.delayed(Duration(seconds:2),()=>{
print("Delayed Task 2 second")
});
print("End");
}
void main() { print("Start"); Future.delayed(Duration(seconds:2),()=>{ print("Delayed Task 2 second") }); print("End"); }
void main() {
 print("Start");
  
  Future.delayed(Duration(seconds:2),()=>{
    print("Delayed Task 2 second")
  });
  
  print("End");
}

Output

Start
End
Delayed Task 2 second

Here, Start and End print statement will execute immediately and then after 2 second Delayed Task 2 second will get printed.


Future & Async/await

To work with asynchronous operation in dart we have Future function with async/await. Developer can make use of Future object to represent asynchronous computations and async/await syntax to write asynchronous code sequentially.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void main() async {
print("Start");
await delayedTask(); // waits here for task to complete
print("End");
}
Future<void> delayedTask() async {
await Future.delayed(Duration(seconds:2),()=>{
print("Delayed Task 2 second")
});
}
void main() async { print("Start"); await delayedTask(); // waits here for task to complete print("End"); } Future<void> delayedTask() async { await Future.delayed(Duration(seconds:2),()=>{ print("Delayed Task 2 second") }); }
void main() async {
 print("Start");
  
  await delayedTask(); // waits here for task to complete
  
  print("End");
}

Future<void> delayedTask() async {
  await Future.delayed(Duration(seconds:2),()=>{
    print("Delayed Task 2 second")
  });
}

Isolates in dart

There is another concept been provided by dart i.e. Isolates an lightweight concurrent execution unit that run in seperate memory spaces, with enables a the true parallel processing in dart and isolation of state. Isolate communicate via message passing making them ideal for CPU-bound tasks.

Check out this article on Isolate iin dart – Flutter Isolate – Run Task in Background – MultiThreading for example

Here is simple example on Isolate

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import 'dart:isolate';
void main() async {
ReceivePort receivePort = ReceivePort();
await Isolate.spawn(isolateFunction, receivePort.sendPort);
receivePort.listen((data)=>{
print('Received: ${data}')
});
}
void isolateFunction(SendPort sendPort){
sendPort.send("Message fron Isolate");
}
import 'dart:isolate'; void main() async { ReceivePort receivePort = ReceivePort(); await Isolate.spawn(isolateFunction, receivePort.sendPort); receivePort.listen((data)=>{ print('Received: ${data}') }); } void isolateFunction(SendPort sendPort){ sendPort.send("Message fron Isolate"); }
import 'dart:isolate';
void main() async {
 ReceivePort receivePort = ReceivePort();
  await Isolate.spawn(isolateFunction, receivePort.sendPort);
  receivePort.listen((data)=>{
    print('Received: ${data}')
  });
}

void isolateFunction(SendPort sendPort){
  sendPort.send("Message fron Isolate");
}

Working with Streams in dart

Stream-based concurrency model is avalilable in dart language that allows developers to process data asynchronously handling streams of data efficiently. Streams in dart facilitate development of event-driven application.

check out this article on streams Flutter Dart Stream Basic Example – Fetch Crypto Currency API Data

Basic Code Example on Streams in dart

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import 'dart:async';
void main() async {
StreamController<int> controller = StreamController<int>();
controller.stream.listen((data){
print('Received: $data');
});
controller.add(1);
controller.add(3);
controller.add(5);
}
import 'dart:async'; void main() async { StreamController<int> controller = StreamController<int>(); controller.stream.listen((data){ print('Received: $data'); }); controller.add(1); controller.add(3); controller.add(5); }
import 'dart:async';
void main() async {
 StreamController<int> controller = StreamController<int>();
  
  controller.stream.listen((data){
    print('Received: $data');
  });
  
  controller.add(1);
  controller.add(3);
  controller.add(5);
}

Dart Concurrency model

Dart’s concurrency model revolves around isolates event loops and asynchronous programming primitives. leveraging isolates & async programming, developer can built a super responsive and scalable & high performance application in flutter.

Managing Concurrent Tasks

To manage concurrent task in Dart programming language will involves a proper handling of asynchronous operation, mangaing errors.

Techniques like error handling, cancellation & timeouts are essentials for robust concurrent programming.

Conclusion

Concurrency operation/task in dart programming language are basically used to execute multiple tasks simutaneously using async nature without blocking the main thread.

Integrating Dart with Data Structures and Algorithms (DSA)

0
dsa in dart
Data Structure & Algorithm in dart

Introduction: Building a robust & efficient solutions to real-world programs we can combine Dart Programming language with Data Structures & Algorithms (DSA).

Creating a Dart project for DSA integration

Dart project for integrating with DSA:

  • Install Dart SDK (if not already installed).
  • Create a new Directory for Dart project.
  • open the folder into terminal
  • Now in terminal RUN ‘dart create my_first_dart_dsa_project to create a new dart project into the opened folder/directory.
  • Navigate into the project ‘my_first_dart_dsa_project‘ & start code.

Implementing Data Structure in dart language

You all know that Implementing a good Data Structure will give your dart code a better backbone. Let’s implement essential data structure like lists, Stacks, Queue, Trees etc. that to by using Dart Programming Language.

Below is an example to create Stack in dart:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
class Stack<T>{
List<T> _items = [];
void push(T value){
_items.add(value);
}
T pop(){
if(_items.isEmpty) throw Exception('Stack is Empty');
return _items.removeLast();
}
bool get isEmpty => _items.isEmpty;
// Optional: Peek at the top item without removing it
T get top {
if (_items.isEmpty) throw Exception('Stack is Empty');
return _items.last;
}
}
class Stack<T>{ List<T> _items = []; void push(T value){ _items.add(value); } T pop(){ if(_items.isEmpty) throw Exception('Stack is Empty'); return _items.removeLast(); } bool get isEmpty => _items.isEmpty; // Optional: Peek at the top item without removing it T get top { if (_items.isEmpty) throw Exception('Stack is Empty'); return _items.last; } }
class Stack<T>{
    List<T> _items = [];
  
    void push(T value){
      _items.add(value);
    }
  
   T pop(){
     if(_items.isEmpty) throw Exception('Stack is Empty');
     return _items.removeLast();
   }
  
  
  bool get isEmpty => _items.isEmpty;

 // Optional: Peek at the top item without removing it
  T get top {
    if (_items.isEmpty) throw Exception('Stack is Empty');
    return _items.last;
  }

}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void main() {
// Create a stack of integers
Stack<int> intStack = Stack<int>();
// Push data onto the stack
intStack.push(10);
intStack.push(20);
intStack.push(30);
print('Popped: ${intStack.pop()}'); // Should print: Popped: 30
print('Popped: ${intStack.pop()}'); // Should print: Popped: 20
// Check if the stack is empty
print('Is the stack empty: ${intStack.isEmpty}'); // Should print: Is the stack empty? false
// Push more data onto the stack
intStack.push(40);
intStack.push(50);
// Peek at the top item
print('Top item: ${intStack.top}'); // Should print: Top item: 50
// Pop the remaining items
print('Popped: ${intStack.pop()}'); // Should print: Popped: 50
print('Popped: ${intStack.pop()}'); // Should print: Popped: 40
print('Popped: ${intStack.pop()}'); // Should print: Popped: 10
// Check if the stack is empty again
print('Is the stack empty? ${intStack.isEmpty}'); // Should print: Is the stack empty? true
// Attempt to pop from an empty stack (will throw an exception)
try {
intStack.pop();
} catch (e) {
print('Error: ${e.toString()}'); // Should print: Error: Exception: Stack is Empty
}
}
void main() { // Create a stack of integers Stack<int> intStack = Stack<int>(); // Push data onto the stack intStack.push(10); intStack.push(20); intStack.push(30); print('Popped: ${intStack.pop()}'); // Should print: Popped: 30 print('Popped: ${intStack.pop()}'); // Should print: Popped: 20 // Check if the stack is empty print('Is the stack empty: ${intStack.isEmpty}'); // Should print: Is the stack empty? false // Push more data onto the stack intStack.push(40); intStack.push(50); // Peek at the top item print('Top item: ${intStack.top}'); // Should print: Top item: 50 // Pop the remaining items print('Popped: ${intStack.pop()}'); // Should print: Popped: 50 print('Popped: ${intStack.pop()}'); // Should print: Popped: 40 print('Popped: ${intStack.pop()}'); // Should print: Popped: 10 // Check if the stack is empty again print('Is the stack empty? ${intStack.isEmpty}'); // Should print: Is the stack empty? true // Attempt to pop from an empty stack (will throw an exception) try { intStack.pop(); } catch (e) { print('Error: ${e.toString()}'); // Should print: Error: Exception: Stack is Empty } }
void main() {
  // Create a stack of integers
  Stack<int> intStack = Stack<int>();

  // Push data onto the stack
  intStack.push(10);
  intStack.push(20);
  intStack.push(30);

  print('Popped: ${intStack.pop()}'); // Should print: Popped: 30
  print('Popped: ${intStack.pop()}'); // Should print: Popped: 20

  // Check if the stack is empty
  print('Is the stack empty: ${intStack.isEmpty}'); // Should print: Is the stack empty? false

  // Push more data onto the stack
  intStack.push(40);
  intStack.push(50);

  // Peek at the top item
  print('Top item: ${intStack.top}'); // Should print: Top item: 50

  // Pop the remaining items
  print('Popped: ${intStack.pop()}'); // Should print: Popped: 50
  print('Popped: ${intStack.pop()}'); // Should print: Popped: 40
  print('Popped: ${intStack.pop()}'); // Should print: Popped: 10

  // Check if the stack is empty again
  print('Is the stack empty? ${intStack.isEmpty}'); // Should print: Is the stack empty? true

  // Attempt to pop from an empty stack (will throw an exception)
  try {
    intStack.pop();
  } catch (e) {
    print('Error: ${e.toString()}'); // Should print: Error: Exception: Stack is Empty
  }
  
}

Output

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Popped: 30
Popped: 20
Is the stack empty? false
Top item: 50
Popped: 50
Popped: 40
Popped: 10
Is the stack empty? true
Error: Exception: Stack is Empty
Popped: 30 Popped: 20 Is the stack empty? false Top item: 50 Popped: 50 Popped: 40 Popped: 10 Is the stack empty? true Error: Exception: Stack is Empty
Popped: 30
Popped: 20
Is the stack empty? false
Top item: 50
Popped: 50
Popped: 40
Popped: 10
Is the stack empty? true
Error: Exception: Stack is Empty

Implementing of Algorithms

Algorithms are specially designed to logically manipulate & process the data efficiently.

Dart Code Example on implement Binary Search algorithm:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Function to perform binary search on a sorted list
int binarySearch(List<int> list, int searchKey) {
int low = 0;
int high = list.length - 1;
while (low <= high) {
// Calculate the middle index
int mid = low + ((high - low) ~/ 2);
// Check if the searchKey is present at mid
if (list[mid] == searchKey) {
return mid;
}
// If searchKey is greater, ignore the left half
else if (list[mid] < searchKey) {
low = mid + 1;
}
// If searchKey is smaller, ignore the right half
else {
high = mid - 1;
}
}
// If the searchKey is not present in the list
return -1;
}
// Function to perform binary search on a sorted list int binarySearch(List<int> list, int searchKey) { int low = 0; int high = list.length - 1; while (low <= high) { // Calculate the middle index int mid = low + ((high - low) ~/ 2); // Check if the searchKey is present at mid if (list[mid] == searchKey) { return mid; } // If searchKey is greater, ignore the left half else if (list[mid] < searchKey) { low = mid + 1; } // If searchKey is smaller, ignore the right half else { high = mid - 1; } } // If the searchKey is not present in the list return -1; }
// Function to perform binary search on a sorted list
int binarySearch(List<int> list, int searchKey) {
  int low = 0;
  int high = list.length - 1;
  
  while (low <= high) {
    // Calculate the middle index
    int mid = low + ((high - low) ~/ 2);
    
    // Check if the searchKey is present at mid
    if (list[mid] == searchKey) {
      return mid;
    }
    // If searchKey is greater, ignore the left half
    else if (list[mid] < searchKey) {
      low = mid + 1;
    }
    // If searchKey is smaller, ignore the right half
    else {
      high = mid - 1;
    }
  }
  
  // If the searchKey is not present in the list
  return -1;
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
void main() {
List<int> sortedList = [2, 3, 4, 10, 40];
int searchKey = 10;
int result = binarySearch(sortedList, searchKey);
if (result != -1) {
print("Element found at index: $result");
} else {
print("Element not found in the list");
}
}
void main() { List<int> sortedList = [2, 3, 4, 10, 40]; int searchKey = 10; int result = binarySearch(sortedList, searchKey); if (result != -1) { print("Element found at index: $result"); } else { print("Element not found in the list"); } }
void main() {
  

  List<int> sortedList = [2, 3, 4, 10, 40];
  int searchKey = 10;
  
  int result = binarySearch(sortedList, searchKey);
  
  if (result != -1) {
    print("Element found at index: $result");
  } else {
    print("Element not found in the list");
  }
}

Output

Element found at index: 3


Conclusion

You’ve have successfully build a dart code that utilize Data Structure & Algorithms (DSA). By implement DSA in Dart we can create a super powerful dart application that can solve complex problems very efficiently.