Understanding dart:io – Files, Sockets, HTTP, Processes, and Streams in Dart
This article introduces the dart:io library, explaining its purpose, how to import and use it for file and directory manipulation, networking with HttpServer/HttpClient, process management, WebSocket communication, and standard I/O streams, accompanied by practical code examples for Dart and Flutter developers.
The dart:io library provides APIs for non‑web Dart applications to perform file, socket, HTTP, and other I/O operations, making it essential for server‑side scripts, command‑line tools, and Flutter mobile apps.
Importing the library is straightforward: import 'dart:io'; File and directory operations are performed using classes such as File, Directory, and Link. For example, renaming a file:
File myFile = new File('我的文件.txt');
myFile.rename('新的文件名.txt').then((_) => print('文件被重命名'));The abstract class FileSystemEntity is the superclass of these types and offers static methods like isDirectory, isFile, and exists to query file system information:
FileSystemEntity.isDirectory(myPath).then((isDir) {
if (isDir) {
print('$myPath 是目录');
} else {
print('$myPath 不是目录');
}
});Networking is supported via HttpServer and HttpClient. A simple HTTP server bound to IPv6 port 80 can be created as follows:
import 'dart:io';
main() {
HttpServer.bind(InternetAddress.anyIPv6, 80).then((server) {
server.listen((HttpRequest request) {
request.response.write('Hello, world!');
request.response.close();
});
});
}Clients can use HttpClient to send requests:
HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://www.example.com/"))
.then((HttpClientRequest request) => request.close())
.then((HttpClientResponse response) {
// Process response
});Process management is handled by the Process class. Starting a process and streaming its output:
Process.start('ls', ['-R', 'web']).then((process) {
stdout.addStream(process.stdout);
stderr.addStream(process.stderr);
process.exitCode.then(print);
});Running a command and obtaining the result:
Process.run('ls', ['-l']).then((ProcessResult results) {
print(results.stdout);
});WebSocket support allows full‑duplex communication. A server can upgrade an HTTP request to a WebSocket:
runZoned(() async {
var server = await HttpServer.bind('127.0.0.1', 4040);
server.listen((HttpRequest req) async {
if (req.uri.path == '/ws') {
var socket = await WebSocketTransformer.upgrade(req);
socket.listen(handleMsg);
}
});
}, onError: (e) => print('An error occurred.'));Clients connect with:
var socket = await WebSocket.connect('ws://127.0.0.1:4040/ws');
socket.add('Hello, World!');ServerSocket and Socket provide TCP communication. A server listening on a port:
ServerSocket.bind('127.0.0.1', 4041).then((serverSocket) {
serverSocket.listen((socket) {
socket.transform(utf8.decoder).listen(print);
});
});A client connecting to the server:
Socket.connect('127.0.0.1', 4041).then((socket) {
socket.write('Hello, World!');
});The library also exposes standard streams stdout, stderr, and stdin. Writing to stdout: stdout.writeln('Hello, World!'); Writing multiple values to stderr:
stderr.writeAll(['That ', 'is ', 'an ', 'error.', '
']);Reading a line synchronously from stdin: String inputText = stdin.readLineSync(); Overall, dart:io equips Dart developers with a comprehensive set of tools for file system access, network communication, process control, and standard I/O, making it a cornerstone for backend and Flutter mobile development.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
