Model Class Sample
1. With private field
Dart
class TodoModel { int ? _userId; int ? _id; String? _title; bool ? _completed; TodoModel({ int ? userId, int ? id, String? title, bool ? completed}) { if (userId != null) { this ._userId = userId; } if (id != null) { this ._id = id; } if (title != null) { this ._title = title; } if (completed != null) { this ._completed = completed; } } int ? get userId => _userId; set userId( int ? userId) => _userId = userId; int ? get id => _id; set id( int ? id) => _id = id; String? get title => _title; set title(String? title) => _title = title; bool ? get completed => _completed; set completed( bool ? completed) => _completed = completed; TodoModel.fromJson(Map<String, dynamic> json) { _userId = json[ 'userId' ]; _id = json[ 'id' ]; _title = json[ 'title' ]; _completed = json[ 'completed' ]; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data[ 'userId' ] = this ._userId; data[ 'id' ] = this ._id; data[ 'title' ] = this ._title; data[ 'completed' ] = this ._completed; return data; } } |
2. Without a Private Field
Dart
class TodoModel { int ? userId; int ? id; String? title; bool ? completed; TodoModel({ this .userId, this .id, this .title, this .completed}); TodoModel.fromJson(Map<String, dynamic> json) { userId = json[ 'userId' ]; id = json[ 'id' ]; title = json[ 'title' ]; completed = json[ 'completed' ]; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data[ 'userId' ] = this .userId; data[ 'id' ] = this .id; data[ 'title' ] = this .title; data[ 'completed' ] = this .completed; return data; } } |
Flutter – Convert JSON to Model Class in Dart
Many times you are receiving API data but it is difficult to create a model class manually for some data that are too big. So we can make a model with just 2 steps. Let’s take sample data for which we want to create a model class.
{ "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false }
Step-by-Step Implementation
Step 1: Just Copy the Data you want to create a model class for.
Step 2: Go to this website.
Step 3: Paste it and give a name to the model class.
Step 4: Copy the Model class and use it in your flutter or dart projects.
Contact Us