Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial, we will learn how to auto create model class from json file by making use of json model dart package library.
What is Json Model package?
Flutter json model package library is been used to create a model class from a json file. In other words this Library will help you to convert json data to model class for your flutter application.
Ok so let’s begin
Flutter : Auto Create Model from JSON file | json model Dart Package
Step 1 : Add Required Dependencies
Create a new Flutter project and add the following 4 dependencies.
To do so open pubspec.yaml file and add those.
dependencies
json_annotation : to create code for JSON serialization and deserialization.
dev_dependencies
json_model: used to generate model
build_runner: concrete way of generating files using dart code.
json_serializable: helps provider builder for handling JSON request.
dependencies: flutter: sdk: flutter cupertino_icons: ^0.1.3 json_annotation: #to create code for JSON serialization and deserialization. dev_dependencies: flutter_test: sdk: flutter json_model: #used to generate json to model build_runner: ^1.0.0 #concrete way of generating files using Dart code json_serializable: ^2.0.0 #helps provides builder for handling JSON
JSON to Model class can be generated simple by using json_model but json model will also make use of json serializable for Mapping and all other Modeling Staff.
So just add the above 4 dependencies in your flutter project pubspec.yaml file.
Step 2 : Create folder and Create .json file
Then, after adding json model and other 3 dependencies, now you need to create a new folder by name “jsons” and inside that folder create a .json file and add some json data in it.
- Create a “jsons” directory in root of your flutter project.
- Create a json file under jsons directory.
- Add below json data in that json file.
json data for model
{ "name": "Flash", "power": "Speed Run : His connection to the Speed Force gives him plenty of abilities.", "url": "https://m.media-amazon.com/images/M/MVXSDS_.jpg" }
Check out my project structure in below image
Step 3 : Go to Terminal and Run the Flutter Command
Once, you have created .json file and some json data in it, Now open your terminal and run the below Flutter Command
flutter packages pub run json_model
as shown below
What this command will do is, It will auto detect json file from jsons directory and create model from json data into your flutter project as shown below
Conclusion
Ok so in this tutorial we checked out how to auto-generate data model class from JSON file by using JSON MODEL dart package library.
Recommended Post
fetching data in flutter and displaying in listview