Form is so far the commonly used UI component used in a mobile application. Last week, we came across the requirement where we had to render different forms in our Flutter app based on JSON data fetched from the server. Today, I’m going to share my experience with the same.
Prepare JSON file
We will keep all our JSON data fetched from server in the .json file inside assets folder like:
So we request API for the JSON data, encode the response as a String, then write the output string to our json file. Making API requests and writing output to the json file is beyond the scope of this article. The main point to note here are:
.json file which will hold the structure of our form to be rendered.
JSON data needs to be in specific format with specific keys.
The Package: json_to_form
We will make use of json_to_form package for rendering form. It can be installed using pubspec.yaml file and ‘pub get’ command, but I don’t recommend this way for this package because I found some areas of improvement in it to make our JSON data more simple. The package is no more than a single file – json_schema.dart, which can be dropped in our project directly and extend it as per our requirement. Thats cool!
As mentioned earlier, JSON data must be in specific format for the package to accept it. I’m writing that data directly into our .json file for this article. Open up the sample_form.json file inside assets and write down the following lines into it.
Here we mentioned 6 types of fields: Input, Phone, Email, RadioButton, Select, and Switch. Well, we can have more according to what can be accept by json_schema.dart file. So if you need your own control to be render, first code it in json_schema.dart file, then specify the data accordingly into json file(or on server side if you’re fetching JSON from API).
IMPORTANT: I’ve modified json_schema.dart file in order for JsonSchema widget to accept above json data and render a form accordingly. Just download the modified file below and replace the previously added one with this file.
i am getting error at JsonSchema and CoreFormState.can you please tell me what the reason.
The file download for the json_schema.dart doesn’t go anywhere, is there somewhere else where that can be accessed?
It is not a download, the intention of the statement is that you need to create a file named json_schema.dart in the specified folder structure.