In Flutter, deserializing object lists from JSON is a common requirement, especially when handling network requests and responses. We can implement this functionality through several steps. Below, I will describe this process in detail and provide a specific example.
Step 1: Define the Data Model
First, we define a class to represent the JSON data structure. Suppose we have a JSON object list where each object represents a user, including the user's ID, name, and email address.
dartclass User { final int id; final String name; final String email; User({this.id, this.name, this.email}); // Deserialize from JSON factory User.fromJson(Map<String, dynamic> json) { return User( id: json['id'], name: json['name'], email: json['email'], ); } }
Step 2: Write the Parsing Function
Next, we write a function to parse the JSON array and convert it into a list of User objects.
dartList<User> parseUsers(String responseBody) { final parsed = json.decode(responseBody).cast<Map<String, dynamic>>(); return parsed.map<User>((json) => User.fromJson(json)).toList(); }
Step 3: Use the Parsing Function
Finally, use the above function to deserialize the JSON string into a list of User objects. This is typically done within the callback of a network request.
dartimport 'dart:convert'; import 'package:http/http.dart' as http; Future<List<User>> fetchUsers() async { final response = await http.get('https://api.example.com/users'); if (response.statusCode == 200) { return parseUsers(response.body); } else { throw Exception('Failed to load users'); } }
Example Explanation
In this example, we first create a User class that can be constructed from JSON. Then, we define a parseUsers function that accepts the API response body, uses json.decode to parse the JSON data, and maps it to the User.fromJson factory constructor, ultimately generating a list of User objects.
By doing this, we can easily handle JSON-formatted data from the network and convert it effectively into data models for Flutter applications. This is crucial for developing modern mobile applications with network interactions.