Using Dart Language Core Libraries

Introduction to Dart Core Libraries

Dart is such a language used for web, mobile, and desktop applications, and one of its most used frameworks is

opment/" target="_blank" rel="noreferrer noopener">Flutter. One of the key strengths of Dart is its core libraries, which provide built-in functionalities for handling various common tasks such as data processing, file manipulation, networking, and asynchronous programming. These core libraries help developers build feature-rich applications efficiently by eliminating the need to rely heavily on third-party packages for basic operations.

This article will explore the most commonly used Dart core libraries, offering insight into their functionality, use cases, and how to effectively use them in real-world applications.

What is Dart Language Core Libraries?

The Dart Language Core Libraries are pre-packaged modules that offer essential functions and classes, enabling developers to work with collections, strings, numbers, dates, files, networking, and more. These libraries are automatically available in every Dart application and are divided into several key components.

Some of the most widely used libraries include:

  • dart: Provides core features such as numbers, collections, strings, and other data types.
  • dart: Supports asynchronous programming and concurrency, enabling the use of Future and Stream.
  • dart: Allows encoding and decoding of JSON, UTF-8, and other formats.
  • dart: Provides file I/O, sockets, HTTP, and process control for server and desktop applications.
  • dart: Offers mathematical operations and constants.
  • dart: Extends the base collection library with advanced collection types.

Now, let’s dive into the details of each of these libraries and understand how they enhance development in Dart.

dart– The Foundation of Dart

The dartlibrary is the fundamental building block of every Dart program. This library is automatically imported into every Dart application, meaning you can access its classes and functions without any additional imports.

Key Features:

  • Numbers: Dart supports int and double types for handling integers and floating-point numbers, respectively. The num class allows operations on both types.
int a = 10;
double b = 5.5;
num result = a + b; // result is 15.5

Strings: Dart provides a rich API for string manipulation, making it easy to create, concatenate, and manipulate text.

String greeting = 'Hello, ';
String name = 'Dart!';
String fullGreeting = greeting + name;
print(fullGreeting); // Output: Hello, Dart!

Collections: This library also includes basic collection types like List, Set, and Map for handling ordered lists, unique items, and key-value pairs.

List<int> numbers = [1, 2, 3, 4];
Map<String, int> fruits = {'apple': 3, 'banana': 2};

dart– Asynchronous Programming Made Easy

Modern applications often need to handle tasks asynchronously, such as fetching data from the internet or working with I/O. The dartlibrary makes asynchronous programming easy by providing the Future and Stream classes, which allow you to work with asynchronous operations and data streams.

Key Features:

  • Future: Represents a value that will be available at some point in the future. It’s commonly used when performing tasks like network requests or file reading.
Future<void> fetchData() async {
  await Future.delayed(Duration(seconds: 2));
  print('Data fetched!');
}

void main() {
  fetchData();
  print('Fetching data...');
}

Stream: Allows handling a sequence of asynchronous events. Streams are useful for tasks that produce multiple values over time, such as listening to user input or receiving messages from a web server.

Stream<int> countStream = Stream.periodic(Duration(seconds: 1), (count) => count).take(5);

void main() {
  countStream.listen((data) => print(data));
}

dart– Encoding and Decoding Data

With the rise of JSON in web services and APIs, it’s important to be able to easily encode and decode data. The dartlibrary helps you deal with popular data formats such as JSON, UTF-8, and Base64.

Key Features:

  • JSON Encoding/Decoding: The json module in the dart:convert library makes it easy to encode Dart objects into JSON and decode JSON into Dart objects.
import 'dart:convert';

void main() {
  String jsonString = '{"name": "Alice", "age": 30}';
  Map<String, dynamic> user = jsonDecode(jsonString);
  print(user['name']); // Output: Alice

  String encoded = jsonEncode(user);
  print(encoded); // Output: {"name":"Alice","age":30}
}

Base64 Encoding: Another popular feature is encoding/decoding data in Base64, commonly used for binary data transmission.

import 'dart:convert';

void main() {
String text = 'Hello, Dart!';
String encoded = base64Encode(utf8.encode(text));
print(encoded); // Output: SGVsbG8sIERhcnQh

String decoded = utf8.decode(base64Decode(encoded));
print(decoded); // Output: Hello, Dart!
}

dart– File and Network I/O

The dartlibrary is invaluable for building server-side applications, working with files, making HTTP requests, and controlling processes. This library is only available in non-browser environments, such as server-side applications or command-line tools.

Key Features:

  • File Handling: You can read, write, and manipulate files on the file system using the File class.
import 'dart:io';

void main() async {
  final file = File('example.txt');
  await file.writeAsString('Hello, Dart!');

  String contents = await file.readAsString();
  print(contents); // Output: Hello, Dart!
}
  • Networking: The HttpClient class allows you to make HTTP requests and handle responses, making it ideal for building REST APIs and web services.
import 'dart:io';

void main() async {
final url = 'https://jsonplaceholder.typicode.com/posts/1';
final httpClient = HttpClient();

final request = await httpClient.getUrl(Uri.parse(url));
final response = await request.close();

response.transform(utf8.decoder).listen((contents) {
print(contents);
});
}

dart– Mathematical Functions

For applications requiring advanced mathematical operations, the dartlibrary offers a variety of mathematical constants, functions, and random number generators.

Key Features:

  • Math Functions: Basic mathematical functions such as sin, cos, sqrt, and more are available.
import 'dart:math';

void main() {
  double angle = pi / 4;
  print(sin(angle)); // Output: 0.7071067811865475

  print(sqrt(16)); // Output: 4.0
}

Random Numbers: The Random class provides an easy way to generate random numbers for various use cases like games or simulations.

import 'dart:math';

void main() {
var random = Random();
print(random.nextInt(100)); // Output: Random number between 0 and 99
}

dart– Advanced Collections

While the dartlibrary provides basic collection types like List, Set, and Map, the dartlibrary offers additional collection types like Queue, LinkedHashMap, and LinkedList for more advanced use cases.

Key Features:

  • Queue: A double-ended queue that allows adding and removing elements from both ends.
import 'dart:collection';

void main() {
  Queue<int> queue = Queue<int>();
  queue.addAll([1, 2, 3]);
  queue.addFirst(0);
  print(queue); // Output: (0, 1, 2, 3)
}

SplayTreeMap: A self-balancing binary search tree that maintains order among its keys.

import 'dart:collection';

void main() {
SplayTreeMap<int, String> treeMap = SplayTreeMap();
treeMap[2] = 'two';
treeMap[1] = 'one';
treeMap[3] = 'three';

print(treeMap); // Output: {1: one, 2: two, 3: three}
}

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

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

Continue reading