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
Dart is such a language used for web, mobile, and desktop applications, and one of its most used frameworks is
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.
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:
Future
and Stream
.Now, let’s dive into the details of each of these libraries and understand how they enhance development in 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.
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};
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.
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));
}
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.
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!
}
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.
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!
}
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);
});
}
For applications requiring advanced mathematical operations, the dartlibrary offers a variety of mathematical constants, functions, and random number generators.
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
}
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.
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}
}
Subscribe to get the latest posts sent to your email.