0
0
Fluttermobile~10 mins

Model classes from JSON in Flutter - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AModel
BPerson
CData
DUser
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different class name than the constructor.
2fill in blank
medium

Complete 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'
Ausername
Bname
CfullName
Duser
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong JSON key that does not exist.
3fill in blank
hard

Fix 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'
Aage
B'age'
Cage.toString()
Dthis.age()
Attempts:
3 left
💡 Hint
Common Mistakes
Converting int to string unnecessarily.
Using method call syntax on a field.
4fill in blank
hard

Fill 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'
AfromJson
BtoJson
CfromMap
DtoMap
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'fromMap' or 'toMap' instead of 'fromJson' and 'toJson'.
5fill in blank
hard

Fill 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'
Aitem
BfromJson
Delement
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Using wrong factory constructor name.