Home > front end >  Show json widgets in flutter
Show json widgets in flutter

Time:11-08

I'm working on a project where there is a website and i'm developing a phone application for it. In the website the user could create his own form and this form is save to database as json and after that this json file converted to react components and shown in the page I want to convert this json file to Flutter widgets and show it in my app,How can I do it?

There is some flutter package but didn't work with my json

CodePudding user response:

This concept is basically used to render the App UI from backend. Hence it's called as Server Driven UI. In this case, we parse the json data that comes from server and map it to the widgets. The simple example is here backend-to-ui-parser

CodePudding user response:

I think your json model is too different from the package you want to use. I understand that you cant change it because it work on your other website. So you need to recreate the builder it from scratch.

I think you can create a class that take a json and create the Form with a getter to get all your controller to submit form value.

Here my example:

class _FormCreatorState extends State<FormCreator> {
  late Widget formWidget;
  final Map<String, dynamic> _formController = {};


  @override
  void initState() {
    Map<String, dynamic> form = jsonDecode(widget.jsonForm);
    for (var field in form["form"]["fields"]) {
      _formController.addAll({
        field["name"]: field["value"] == "text"
            ? TextEditingController()
            : null // you can add else if (..) to handle more controller
      });
    }
    formWidget = Column(
      children: [
        for (var field in form["form"]["fields"])
          if (field["type"] == "text")
            TextFormField(
              keyboardType: TextInputType.text,
              decoration: InputDecoration(
                labelText: field["label"],
              ),
              initialValue: field["value"],
              controller: _formController[field["name"]],
            )
          //you can add else if (..) to handle more field
          else
            Container()
      ],
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return (Column(
      children: [
        formWidget,
        Center(
            child: TextButton(onPressed: () {
              //do something to get value of your controller with the _formController variable
            }, child: const Text("Submit"))),
      ],
    ));
  }
}

If have many problem, try to give us an example of your json !

  • Related