Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a Dart class named User.
Flutter
class [1] { final String name; final int age; User(this.name, this.age); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different class name than the constructor.
✗ Incorrect
The class name must be User to match the constructor and usage.
2fill in blank
mediumComplete the factory constructor to create a User from JSON.
Flutter
factory User.fromJson(Map<String, dynamic> json) {
return User(
json['[1]'],
json['age'],
);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong JSON key that does not exist.
✗ Incorrect
The JSON key for the user's name is name, matching the class field.
3fill in blank
hardFix the error in the toJson method to return a Map.
Flutter
Map<String, dynamic> toJson() {
return {
'name': name,
'age': [1],
};
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Converting int to string unnecessarily.
Using method call syntax on a field.
✗ Incorrect
The age field is an int and should be returned directly, not converted to string or called as a method.
4fill in blank
hardFill both blanks to complete the User class with fromJson and toJson methods.
Flutter
class User { final String name; final int age; User(this.name, this.age); factory User.[1](Map<String, dynamic> json) { return User(json['name'], json['age']); } Map<String, dynamic> [2]() { return {'name': name, 'age': age}; } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'fromMap' or 'toMap' instead of 'fromJson' and 'toJson'.
✗ Incorrect
The factory constructor is named fromJson and the method to convert to JSON is toJson.
5fill in blank
hardFill all three blanks to create a list of User objects from JSON list.
Flutter
List<User> users = (jsonList as List).map(([1]) => User.[2]([3])).toList();
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using wrong factory constructor name.
✗ Incorrect
The variable name in the map function is item, used twice. The factory constructor is fromJson.