File Handling & REST API Networking
File Handling & REST API Networking
Modern applications rarely run in complete isolation. They need to persist data to the local disk and communicate with remote servers over the internet.
In this lesson, we will cover file input/output (I/O) operations using dart:io and HTTP communication using the popular http package.
1. File Handling in Dart
The dart:io library provides classes to interact with the local filesystem, including files and directories.
Reading Files
You can read a file entirely as a string or line-by-line (which is safer for large files).
dartimport 'dart:io'; void main() async { final file = File('data.txt'); if (await file.exists()) { // Read entire content String content = await file.readAsString(); print("Content: $content"); // Read line-by-line List<String> lines = await file.readAsLines(); for (var line in lines) { print("Line: $line"); } } else { print("File not found!"); } }
Writing Files
Writing to a file will create the file if it doesn't exist, and overwrite it if it does. To append content instead of overwriting, use the FileMode.append flag.
dartimport 'dart:io'; void main() async { final file = File('output.txt'); // Overwrite content await file.writeAsString('Hello, Dart Files!'); // Append content await file.writeAsString('\nAppended text.', mode: FileMode.append); }
2. REST API Networking with HTTP
To make HTTP requests, you should add the http package to your dependencies in your pubspec.yaml file:
yamldependencies: http: ^1.1.0
Performing a GET Request
Let's fetch a list of posts from a public mock REST API (JSONPlaceholder) and parse it.
dartimport 'dart:convert'; import 'package:http/http.dart' as http; // Data model representing the response object class Post { final int id; final String title; final String body; Post({required this.id, required this.title, required this.body}); factory Post.fromJson(Map<String, dynamic> json) { return Post( id: json['id'], title: json['title'], body: json['body'], ); } } Future<void> fetchPosts() async { final url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1'); try { final response = await http.get(url); if (response.statusCode == 200) { // Decode the raw JSON string final Map<String, dynamic> data = jsonDecode(response.body); // Parse to our strongly-typed Post object final post = Post.fromJson(data); print("Post Title: ${post.title}"); } else { print("Request failed with status: ${response.statusCode}"); } } catch (e) { print("An error occurred during request: $e"); } } void main() async { await fetchPosts(); }
3. Performing a POST Request
To send data to a server, perform a POST request and encode your request body as a JSON string.
dartimport 'dart:convert'; import 'package:http/http.dart' as http; Future<void> createPost() async { final url = Uri.parse('https://jsonplaceholder.typicode.com/posts'); final response = await http.post( url, headers: { 'Content-Type': 'application/json; charset=UTF-8', }, body: jsonEncode({ 'title': 'New Dart Post', 'body': 'This was created using http package.', 'userId': 1, }), ); if (response.statusCode == 201) { print("Post created successfully!"); print("Response: ${response.body}"); } else { print("Failed to create post. Status code: ${response.statusCode}"); } }
Summary
- Use the
dart:iolibrary to perform file operations likereadAsStringandwriteAsString. - Use the
httppackage to interact with REST APIs. - Always check the
response.statusCode(e.g.,200for OK,201for Created) before parsing. - Use
jsonDecode()fromdart:convertto parse JSON response strings into Dart Maps. - Handle networking errors safely with
try-catchblocks.